docs: plan 2b-2 review round 1 fixes and Paul's rulings
Root-owned admission from a console-signed ready.json, every start path gated, separate boot input, queued edge start, firewall ordering, update-safe reboots, key failures reported by heartbeat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+309
−210
docs/superpowers/plans/2026-11-08-managed-fleets-2b2-box-side.md+309 −210
diff --git a/docs/superpowers/plans/2026-11-08-managed-fleets-2b2-box-side.md b/docs/superpowers/plans/2026-11-08-managed-fleets-2b2-box-side.md| index 9ff1d1ffc..a079f0787 100644 |
| --- a/docs/superpowers/plans/2026-11-08-managed-fleets-2b2-box-side.md |
| +++ b/docs/superpowers/plans/2026-11-08-managed-fleets-2b2-box-side.md |
| @@ -2,16 +2,16 @@ |
| > **For agentic workers:** Follow the controller's execution contract task-by-task; implementers do not spawn subagents. Steps use checkbox (`- [ ]`) syntax for tracking. |
| -**Goal:** A console-launched managed box boots from frozen cloud-init, verifies everything it executes, trades its one-time token once, holds a durable joining gate that runs nothing until the console writes its ready.json, establishes the fleet's secrets key, passes real `storage` and `router_probe` checks, and is wired for production behind an off-by-default switch, with a concrete dev drill card ready for Paul. |
| +**Goal:** A console-launched managed box boots from frozen cloud-init, verifies everything it executes, trades its one-time token once, holds a root-owned joining gate that runs nothing until root has verified a console-signed ready.json, establishes the fleet's secrets key, passes real `storage` and `router_probe` checks, and is wired for production behind an off-by-default switch, with a concrete dev drill card ready for Paul. |
| -**Architecture:** A new provider-neutral `internal/managedboot` package holds the frozen boot inputs, the cloud-init renderer, wire types and the durable joining state; the console renders user data from frozen box fields and serves the seed binary to an unused token. Box-side code in `internal/host` runs as root once per boot (`carlos system managed-boot`) and hands off to the installed stable binary's ordinary `bootstrap`; the agent, activator, root execution door and edge consult one live joining predicate. Readiness probes travel console → hub (mesh-key HMAC) → the exact `<fleet>/<label>` channel → box responder, and are bridged into 2a's `managedExtraChecks`. |
| +**Architecture:** A new provider-neutral `internal/managedboot` package holds the frozen boot inputs, the cloud-init renderer, wire types, the signed ready record and the root admission record. The console renders user data from frozen box fields, serves the seed binary to an unused token, and signs ready.json with its existing pointer-signing key. Box-side code runs as root once per boot (`carlos system managed-boot`), hands off to the installed stable binary's `bootstrap`, then queues the first carlos-edge start. Admission authority lives with root: the agent only relays ready.json to the root execution door, which verifies the signature and commits a root-only record that every root and agent start path consults. Readiness probes travel console → hub (mesh-key HMAC) → the exact `<fleet>/<label>` channel → box responder and are bridged into 2a's `managedExtraChecks`. |
| -**Tech Stack:** Go, SQLite, `text/template` + `embed` for the boot script, nftables, systemd, Ed25519 signed system pointers, ECDH P-256 secrets keys, existing `release.Store` create-only PUT, AWS SDK v2 only inside `internal/awsmanaged` (2b-1), mocked transport in tests. |
| +**Tech Stack:** Go, SQLite, `text/template` + `embed` for the boot script, nftables, systemd, Ed25519 signed wrappers (`{payload, sig}`, as `release/production.go:117`), ECDH P-256 secrets keys, `release.Store` create-only PUT, AWS SDK v2 only inside `internal/awsmanaged` (2b-1), mocked transport in tests. |
| -**Spec:** `docs/superpowers/specs/2026-10-28-managed-fleets-design.md` §4 Phase 2 (enrolment, secrets key, born examined, ready means ready, diagnostics) and "Phase 2 addendum (Paul, 2026-11-01)", §5 provider boundary, §6 request budget, §7 switch-on, §8 acceptance. Binding split/rulings: `/home/paulca/.cache/managed-fleets-2b-notes/decisions.md` ("2b-2" = recon tasks 6-11). Recon: `/home/paulca/.cache/managed-fleets-2b-notes/recon.md` §§3, 4, 6, 7, 9, 10, 11. Sibling: `docs/superpowers/plans/2026-11-08-managed-fleets-2b1-console-aws.md`. Predecessor: `docs/superpowers/plans/2026-11-01-managed-fleets-2a-core.md` "Deferred to 2b-2d"; ledger `docs/superpowers/notes/managed-fleets-2a-ledger.md`. |
| +**Spec:** `docs/superpowers/specs/2026-10-28-managed-fleets-design.md` §4 Phase 2 (enrolment, secrets key, born examined, ready means ready, diagnostics) and "Phase 2 addendum (Paul, 2026-11-01)", §5 provider boundary, §6 request budget, §7 switch-on, §8 acceptance. Binding split/rulings: `/home/paulca/.cache/managed-fleets-2b-notes/decisions.md` ("2b-2" = recon tasks 6-11; Paul's rules 9-11). Recon: `/home/paulca/.cache/managed-fleets-2b-notes/recon.md` §§3, 4, 6, 7, 9, 10, 11. Sibling: `docs/superpowers/plans/2026-11-08-managed-fleets-2b1-console-aws.md`. Predecessor: `docs/superpowers/plans/2026-11-01-managed-fleets-2a-core.md` "Deferred to 2b-2d"; ledger `docs/superpowers/notes/managed-fleets-2a-ledger.md`. |
| Source baseline is main `9622c65a159480a687f066f7a24e28a31c68360d` plus the 2b-1 plan as written (its branch is being built now). |
| -Existing signatures cited below were rechecked in that checkout on 2026-11-08. Declarations marked **new** are this plan's decisions. |
| +Existing signatures cited below were rechecked in that checkout on 2026-11-08, including every seam added in review round 1. Declarations marked **new** are this plan's decisions. |
| Every 2b-1 interface consumed is named exactly as the 2b-1 plan defines it (section "Consumed from 2b-1"). |
| This draft writes only this file; it runs no tests, makes no commits and dispatches no agents. |
| @@ -21,27 +21,29 @@ Execution facts (controller brief, 2026-11-08; these supersede decisions.md rule |
| - One branch, `managed-fleets-2b2`, cut from main after 2b-1 merges. Tasks commit in order; one reviewed squash merge at the end, on Paul's explicit go. |
| - Opus implements. Astra reviews; Fable also reviews the security and termination tasks (Tasks 2, 3, 4, 5 and Task 6's wiring/diagnostics). Stop at the first review round with no P1; three rounds maximum; two rounds in one fault family go to Paul. |
| -- Carry 2a's closed rounds 1-3, the C01-C14 pre-flight rulings and 2b-1's closed review in every brief. Splitting 2b resets nothing and reopens neither the joining gate nor C08. |
| +- Carry 2a's closed rounds 1-3, the C01-C14 pre-flight rulings, 2b-1's closed review and this plan's review history in every brief. Splitting 2b resets nothing and reopens neither the joining gate nor C08. |
| - Commit subjects under 80 characters (79 max) with a blank line before the body. |
| - No tenant names. Neutral examples only: shop, example.com, production; the drill fleet is `drill-2b`. |
| - Member-facing copy (refusals, readiness reasons, show text, docs) is marked `COPY` by implementers and goes through the controller's copy review before merge. Breadcrumb codes and log lines are not member copy. |
| - Provider-neutral core: no AWS SDK import outside `internal/awsmanaged`; `TestManagedCoreImports` (`internal/compute/imports_test.go:13`) is extended to `internal/managedboot`. |
| -- Request budget (spec §6): no new steady-state per-box polling. Joining-only reads are bounded: ready.json at most one GET per observed serial change or per 60 s while joining, zero after admission. Readiness probes: at most one console → hub probe per enrolled box per 60 s (the existing readiness cadence), each costing the box three fleet-bucket requests. Boot: one seed fetch, one stable pointer GET, one artifact GET, at most two key-object GETs and one create-only PUT per box boot. Idle console worker stays at zero calls. |
| +- Request budget (spec §6): no new steady-state per-box polling; numbers in "Request budget" below. Joining-only reads are bounded; zero ready reads after admission. |
| - Verification budget: targeted `-run` selections on touched packages, `-count=1`; never run the whole `internal/console` package locally; at most ~10 mutation checks per risky task (Tasks 2-5); one `-race` run over touched packages in Task 6; CI owns full suites and darwin/windows/linux-arm64 cross-builds. |
| - Go: `GOFLAGS=-buildvcs=false`; leave GOCACHE at its default. Socket-path tests use an owned short directory on disk under `$TMPDIR` or `~/.cache`, never `/tmp`. |
| - Census: every task names whether it touches root-binary units, refusal doors, record-write or authority inventories. `make census-card` / `make census-propose NAME=managed-fleets-2b2 CLAIMS=<owned-file>`; an independent reviewer's approval is recorded on discussion #280 at the reviewed tip. |
| -- No live AWS anywhere until Paul approves the Task 7 drill card: no SDK calls, IAM simulation, tofu apply or EC2 experiments. Mock clients/transport; disable IMDS in tests. |
| +- No live AWS mutation before Paul approves the Task 7 drill card. The only live AWS calls allowed earlier are Task 7's read-only preflight (AMI/subnet/VPC describes, `tofu plan`) needed to fill the card. Tests use mocked clients/transport with IMDS disabled. |
| - `enabled` stays false in every deployment until the approved drill; production providers are constructed only when the operator opts in (Task 6). |
| -- `CARLOS_HOST_CLAIM` stays an explicit refusal for every managed path, including the two new console doors (decisions rule 7). No gated-SQL escape hatch. |
| +- `CARLOS_HOST_CLAIM` stays an explicit refusal for every managed path, including the new console doors (decisions rule 7). No gated-SQL escape hatch. |
| - Preserve C08: a matching published ready.json may already have admitted the box; console uncertainty never revokes, overwrites, deletes or terminates it, and the box never returns to joining. |
| -- Managed boxes have no instance profile, SSH key or SSM agent; diagnostics are console-output breadcrumbs and readiness reasons only (decisions rule 1). |
| +- Managed boxes have no instance profile, SSH key or SSM agent; diagnostics are console-output breadcrumbs, heartbeat fields and readiness reasons only (decisions rule 1). |
| +- Paul's rulings (decisions 9-11): the first binary comes only through the console seed door to an unused token (no public URL, no custom AMI); the owner `carlos fleets secrets-key` door refuses on managed fleets until 2c; the drill deletes every AWS resource and keeps the dev console's `drill-2b` records for 2d, with no hand DB edits. |
| +- Admission authority is root's. No root decision reads a file the service UID (carlos) can create, replace or link. |
| - Implementers stop at local checks, commit, census proposal and report. The controller owns copy review, reviews, #280, push, CI and landing. |
| ## Review Focus |
| 1. **Reboot between the trade and durable staging.** The console has consumed the token and released credentials, but the box restarts before its staged commit is durable. Expected: no partially written credentials or host.env survive, no second credential release, the box runs nothing and ends at breadcrumb `enrol_failed`, and the console's 20-minute deadline cleans it up. A reboot after the commit resumes with zero further enrol calls. Owner: Task 2 `TestManagedBootRebootBoundaries`. |
| -2. **The box consumes ready.json, then console verification fails (C08).** The PUT succeeded, the box admitted itself, and the console's verifying GET is lost or reads a mismatch. Expected: the box stays admitted and makes zero further ready reads; the console stays `publishing`/uncertain, holds quota, and never revokes or terminates. Owners: Task 3 `TestManagedJoinAdmissionOneWay`; Task 6 `TestManaged2B2ConsumedPublicationUncertain`. |
| -3. **A tampered or unsigned stable binary.** The pointer has a bad or scoped-key signature, the artifact hash differs, the linux-arm64 artifact is missing, or the installed file changes between install and exec. Expected: nothing executes, breadcrumb `bootstrap_failed`, joining state stays durable. Owner: Task 2 `TestManagedBootStableTrust` (seed side: Task 1 `TestManagedCloudInitVerifyHelper`). |
| +2. **The box consumes ready.json, then console verification fails (C08).** The PUT succeeded, root committed admission, and the console's verifying GET is lost or reads a mismatch. Expected: root's admission record stays, the box keeps serving and makes zero further ready reads; the console stays `publishing`/uncertain, holds quota, and never revokes or terminates. Owners: Task 3 `TestManagedAdmissionOneWay`; Task 6 `TestManaged2B2ConsumedPublicationUncertain`. |
| +3. **A tampered or unsigned stable binary.** The pointer has a bad or scoped-key signature, the artifact hash differs, the linux-arm64 artifact is missing, or the staged file changes between fetch and first exec. Expected: nothing executes, breadcrumb `bootstrap_failed`, no admission. Owner: Task 2 `TestManagedBootStableTrust` (seed side: Task 1 `TestManagedCloudInitScriptRun`). |
| 4. **Two first boxes race to mint the fleet key.** A `--boxes 3` create launches three boxes with no key yet. Expected: exactly one private object exists, every box installs that key, the registry fingerprint equals the object's, and no box ever overwrites or registers a different key. Owner: Task 4 `TestManagedFleetKeyFirstWriterWins`. |
| 5. **A router probe answered by a sibling box.** The target channel is disconnected while siblings are connected, or a misrouted request reaches another box. Expected: the hub never falls back to another channel; a box answers only probes naming its own fleet/label/op; the console passes `router_probe` only on an exact echo with the hub's channel attestation. Owner: Task 5 `TestFleetProbeExactChannel`. |
| @@ -63,18 +65,19 @@ Execution facts (controller brief, 2026-11-08; these supersede decisions.md rule |
| | 6 | `managedReadyObjectKey(fleet, key string) bool`: store door denies PUT/DELETE of every `fleets/<fleet>/boxes/<label>/ready.json`; GET remains | |
| If 2b-1 lands with a different name for any of these, the implementer stops and reports; the plan is amended by the controller, not adapted silently. |
| +Task 3 changes the ready object's encoding (2a's `managedReadyObject`, `managedworker.go:569`) to a signed wrapper; 2b-1's publication and freshness logic is otherwise consumed unchanged. |
| ## File map |
| | Task | Files / responsibility | |
| |---|---| |
| | 1 | New `internal/managedboot/{frozen,userdata,breadcrumb}.go`, `cloudinit_v1.sh.tmpl`, `testdata/userdata-v1.golden`; console `managedworker.go`, `managedstore.go`, `managedenrol.go`, new `managedseed.go`, `server.go` route | |
| -| 2 | New `internal/managedboot/{enrolwire,state,hostenv}.go`; new `internal/host/{managedboot,managedboot_linux,managedboot_other,managedstable}.go`; `system.go` verb | |
| -| 3 | `internal/provision/reconcile.go`; new `internal/host/managedjoin.go`; `internal/host/agent.go` wiring; `internal/host/claimstop_run.go`; `internal/instancectl/server.go` | |
| -| 4 | New `internal/managedboot/fleetkey.go`; new `internal/host/managedkey.go`; console `fleetsecretskey.go` (extract core), new `managedfleetkey.go`, `server.go` route | |
| +| 2 | New `internal/managedboot/{enrolwire,identity,hostenv}.go`; new `internal/host/{managedboot,managedboot_linux,managedboot_other,managedstable}.go`; `system.go` verb | |
| +| 3 | New `internal/managedboot/{ready,admission}.go`; console `managedworker.go` (signed ready object); `internal/provision/reconcile.go`; new `internal/host/managedjoin.go`; `internal/host/agent.go`, `rootrestart.go`, `unitops.go`, `namedrecovery.go`, `claimstop_run.go`; `internal/instancectl/{server,client}.go` | |
| +| 4 | New `internal/managedboot/fleetkey.go`; new `internal/host/managedkey.go`; `internal/status/snapshot.go` (heartbeat field); console `fleetsecretskey.go` (extract core), new `managedfleetkey.go`, `managedready.go`, `server.go` route | |
| | 5 | New `internal/managedboot/probe.go`; new `internal/edge/fleetprobe.go`, `edge.go` dispatch, `mesh.go` domain; `internal/tunnelclient/tunnelclient.go` header; new `internal/host/managedprobe.go`; new console `managedprobe.go` | |
| | 6 | `cmd/console/main.go`, console `server.go` (`NewServer`), `managedworker.go` diagnostics; `internal/awsmanaged/integration_2b2_test.go`; console `managed_e2e`/`managedbudget` tests | |
| -| 7 | New `docs/superpowers/notes/managed-fleets-2b2-drill-card.md` (approval card), drill log after approval only | |
| +| 7 | New `docs/superpowers/notes/managed-fleets-2b2-drill-card.md` (approval card after read-only preflight), drill log after approval only | |
| ## Request budget (spec §6 numbers this plan commits to) |
| @@ -85,8 +88,8 @@ If 2b-1 lands with a different name for any of these, the implementer stops and |
| | Console seed door | 1 artifact stream per box boot (+ retries within expiry) | Task 1 `TestManagedSeedDoor` | |
| | Box first contact | 1 trade (+ 503/429 retries), 1 pointer GET, 1 artifact GET via store door | Task 2 `TestManagedBootTradeRetry`, reboot matrix | |
| | Box fleet key | first box ≤2 GET + 1 create-only PUT; later box 1 GET | Task 4 key tests | |
| -| Joining box, ready.json | 1 GET at arming, ≤1 per observed serial change, else ≤1 per 60 s | Task 3 `TestManagedJoinReadyLeg` | |
| -| Admitted box, ready.json | 0, forever, including after reboot | Task 3 `TestManagedJoinAdmissionOneWay` | |
| +| Joining box, ready.json | 1 GET at arming, ≤1 per observed serial change, else ≤1 per 60 s; relay to root is a local socket call | Task 3 `TestManagedJoinReadyLeg` | |
| +| Admitted box, ready.json | 0, forever, including after reboot and binary updates | Task 3 `TestManagedAdmissionOneWay`; Task 2 `TestManagedBootUpdateReboot` | |
| | Enrolled box readiness | ≤1 heartbeat GET + ≤1 hub probe per 60 s; probe = 3 fleet-bucket requests | Task 5 `TestManagedProbeBudget` | |
| | Ready/failed boxes | 0 probes, 0 heartbeat reads by the managed worker | Task 5, Task 6 | |
| | Failed launched box | exactly 1 ConsoleOutput at the deadline | Task 6 `TestManaged2B2Diagnostics` | |
| @@ -97,7 +100,7 @@ The serial read every ~2 s and the status heartbeat are existing BYO fleet-box t |
| - 2a plan :922 "current verified stable binary": Task 2. :923 durable marker incl. statics, bootstrap/status/probes still run: Tasks 2-3. :924 ready GET bounds: Task 3. :926 allowlists, digest before exec, IMDS barrier, scrub, genuine directory inspection: Tasks 1-2. :927 storage, router, first-box key, approved drill: Tasks 4, 5, 7. :928 first-box private-key persistence: Task 4. |
| - Recon §3 "freeze what empty covers": the attested set is `/data` only (absent or an empty directory, not a symlink), scanned before anything writes under it. |
| -- Recon §3 "gate absent must mean known admitted/BYO": identity file present + state missing is joining (Task 2/3 fail-closed tests). |
| +- Recon §3 "gate absent must mean known admitted/BYO": identity present + no valid root admission record is joining (Task 3 fail-closed tests). |
| - 2b-1 Task 1: the client contract is 503/429 retried within the original expiry, 403 terminal; Task 2 implements it. |
| - 2a T7 M5 (client cancellation after claim can sacrifice a box) stays accepted: the client never cancels a trade mid-request; a lost reply ends at `enrol_failed` and deadline cleanup. |
| - 2a final-review :108 (short transport-only CLI retry window) is a CLI item, untouched here. |
| @@ -107,23 +110,24 @@ The serial read every ~2 s and the status heartbeat are existing BYO fleet-box t |
| **Files:** |
| - Create: `internal/managedboot/frozen.go`, `userdata.go`, `breadcrumb.go`, `cloudinit_v1.sh.tmpl`, `testdata/userdata-v1.golden`, `userdata_test.go`, `userdata_linux_test.go`. |
| -- Modify: `internal/console/managedstore.go` (managedBox field, AdvanceManagedBox invariant), `managedworker.go` (`managedLaunchRequest` at :236, reserved→launching at :296), `managedenrol.go` (reply fields), `server.go` (route beside `POST /api/fleet/enrol` at :2234). |
| +- Modify: `internal/console/managedstore.go` (managedBox field, AdvanceManagedBox invariant at :374), `managedworker.go` (`managedLaunchRequest` at :236, reserved→launching at :296), `managedenrol.go` (reply fields), `server.go` (route beside `POST /api/fleet/enrol` at :2234). |
| - Create: `internal/console/managedseed.go`, `managedseed_test.go`; extend `managedenrol_test.go`, `internal/compute/imports_test.go`. |
| **Interfaces:** |
| - Consumes: existing `(*Server).managedLaunchRequest(b managedBox) (compute.LaunchSpec, error)`; `deriveManagedEnrolToken` (`managedstore.go:74`); `(*Server).managedStable(ctx context.Context) (*release.SystemPointer, error)` (`managedready.go:27`); `Config.Origin`, `Config.TunnelHost`, `Config.ReleasePub`, `Config.Releases`; 2b-1 `launchManagedBox(..., firstDispatch bool)`. |
| - Produces (**new**, package `managedboot`): |
| - `const FormatV1 = 1`; `const MaxUserDataBytes = 12288`; `const SeedArtifactPlatform = "linux-arm64"`. |
| + - `const BootDir = "/var/lib/carlos-managed-boot"`; `BootInputPath = BootDir + "/boot-input.json"` (full LaunchInput, root 0600); `SeedRequestPath = BootDir + "/seed-request.json"` (token only, root 0600, deleted after the seed is verified). |
| - `type Frozen struct { Format int "format"; ConsoleOrigin string "console_origin"; TunnelHost string "tunnel_host"; ReleasePubkey string "release_pubkey"; SeedVersion string "seed_version"; SeedKey string "seed_key"; SeedSHA256 string "seed_sha256" }` (JSON tags as quoted). |
| - `func (f Frozen) Validate() error`; `func (f Frozen) IsZero() bool`. |
| - - `type LaunchInput struct { Frozen Frozen; Fleet, Label, Op, Token string; Expires time.Time }`. |
| + - `type LaunchInput struct { Frozen Frozen "frozen"; Fleet, Label, Op, Token string; Expires time.Time }` with JSON `fleet`, `label`, `op`, `token`, `expires`; `func DecodeLaunchInput(b []byte) (LaunchInput, error)` (strict, unknown fields refused). |
| - `func RenderUserData(in LaunchInput) (string, error)`: pure; refuses any field failing its allowlist or output above MaxUserDataBytes. |
| - Breadcrumb codes `CodeSeedVerified`, `CodeEnrolPending`, `CodeEnrolFailed`, `CodeStableVerified`, `CodeJoining`, `CodeBootstrapFailed` with values exactly 2b-1's six codes; `func Breadcrumb(code string) string` returns `"CARLOS_BOOT:" + code`. |
| -- Produces (**new**, console): managedBox field `Boot managedboot.Frozen` JSON `boot`; `(*Server).managedBootFrozen(ctx context.Context) (managedboot.Frozen, error)`; `(*Server).handleManagedSeed(w http.ResponseWriter, r *http.Request)` on `POST /api/fleet/enrol/seed`; `(*Server).managedSeedFor(ctx context.Context, token string, now time.Time) (managedboot.Frozen, error)`; managedEnrolReply gains `Bucket string "bucket"`, `BucketRegion string "bucket_region"`, `Operation string "op"`. |
| +- Produces (**new**, console): managedBox field `Boot managedboot.Frozen` JSON `boot`; `(*Server).managedBootFrozen(ctx context.Context) (managedboot.Frozen, error)`; `(*Server).handleManagedSeed(w http.ResponseWriter, r *http.Request)` on `POST /api/fleet/enrol/seed` with strict body `{"token"}` only; `(*Server).managedSeedFor(ctx context.Context, token string, now time.Time) (managedboot.Frozen, error)`; managedEnrolReply gains `Bucket string "bucket"`, `BucketRegion string "bucket_region"`, `Operation string "op"`. |
| -**Census/review:** New public refusal door (`/api/fleet/enrol/seed`) and a changed enrol reply: refusal-door and authority census. `internal/managedboot` enters the root binary (Task 2 imports it): root-unit census. Reviewed with Task 2 as one security unit. |
| +**Census/review:** New public refusal door (`/api/fleet/enrol/seed`, Paul rule 9) and a changed enrol reply: refusal-door and authority census. `internal/managedboot` enters the root binary (Task 2 imports it): root-unit census. Reviewed with Task 2 as one security unit. |
| -- [ ] **Step 1: Write the failing renderer, freeze and seed-door tests.** |
| +- [ ] **Step 1: Write the failing renderer, script, freeze and seed-door tests.** |
| ```text |
| TestManagedUserDataGolden: fixed LaunchInput => bytes equal testdata/userdata-v1.golden; |
| @@ -134,11 +138,22 @@ TestManagedUserDataAllowlist: each field rejected when invalid, nothing rendered |
| pubkey not std-base64 of 32 bytes; seed key not ^bootstrap/router/[0-9A-Za-z._-]+/carlos-linux-arm64$; |
| sha not 64 lowercase hex; expires zero or non-UTC; Format != 1. |
| Injection probes (quote, $(), backtick, newline, NUL, unicode line separator) in every field => error. |
| -TestManagedUserDataSecrets: token appears exactly once, only inside the root-only input file |
| - heredoc; never on a command line, URL, log/echo line or breadcrumb; set -x absent. |
| +TestManagedUserDataSecrets: token appears exactly twice, only inside the two root-only heredocs |
| + (boot-input.json, seed-request.json); never on a command line, URL, log/echo line or breadcrumb; |
| + set -x absent; seed-request.json contains exactly {"token":...}; boot-input.json decodes with |
| + DecodeLaunchInput to the input that was rendered. |
| +TestManagedCloudInitScriptRun (linux; under unshare -r, skipped with a reason only when user |
| + namespaces are unavailable): run the RENDERED script with a root prefix, PATH shims for |
| + apt-get/nft/systemctl/useradd/id/chown/timeout (shims log argv), real curl against an |
| + httptest TLS server running the real handleManagedSeed (CA via CURL_CA_BUNDLE): |
| + re-exec under `timeout 900 /bin/sh <script>` happens once; curl writes to seed.part with |
| + -o and the body sent is the token-only file; wrong seed bytes => helper refuses, no exec, |
| + bootstrap_failed breadcrumb, no unit started; right bytes => seed renamed to seed, 0700, |
| + verify helper runs immediately before the `systemctl start carlos-managed-boot.service`; |
| + seed-request.json removed; unit and drop-in texts written exactly (see Step 3). |
| TestManagedCloudInitVerifyHelper (linux, python3): extracted verify helper refuses wrong |
| owner/mode dir, noexec mount flag, symlink, hardlink count 2, non-regular file, |
| - malformed digest and one-byte mismatch; accepts exact bytes; runs immediately before each exec line. |
| + malformed digest and one-byte mismatch; accepts exact bytes. |
| TestManagedBootFrozenAtLaunch: reserved->launching commit persists Boot from the verified |
| stable pointer's linux-arm64 artifact + cfg.Origin/TunnelHost/ReleasePub before any Launch call; |
| stable unavailable/unsigned/no linux-arm64 => stays reserved, zero Launch calls, 30-min deadline unchanged; |
| @@ -147,8 +162,9 @@ TestManagedBootFrozenAtLaunch: reserved->launching commit persists Boot from the |
| TestManagedSeedDoor: valid unused token in launching/booting window => 200 octet-stream of the |
| frozen SeedKey bytes, Content-Length set, Cache-Control no-store; token NOT consumed (enrol still 200 after); |
| unknown/used/expired/before-launch token => identical 403; store failure => 503 Retry-After 5; |
| - IP limiter before deployment limiter (shared with enrol); HostClaim => 409; >4 KiB or unknown field => 400; |
| - more than 4 concurrent streams => 503 Retry-After 5; response never contains the token. |
| + IP limiter before deployment limiter (shared with enrol); HostClaim => 409; >4 KiB, unknown field |
| + (a full LaunchInput included) => 400; more than 4 concurrent streams => 503 Retry-After 5; |
| + response never contains the token. |
| TestManagedEnrolReplyFields: 200 reply carries bucket, bucket_region, op equal to the box's |
| frozen Storage and OpID; existing fields unchanged; 403/503 bodies unchanged. |
| TestManagedCoreImports: internal/managedboot added; still no AWS SDK import. |
| @@ -156,14 +172,23 @@ TestManagedCoreImports: internal/managedboot added; still no AWS SDK import. |
| - [ ] **Step 2: Run the targeted failing tests.** |
| -Run `GOFLAGS=-buildvcs=false go test ./internal/managedboot ./internal/compute -run 'TestManagedUserData|TestManagedCloudInitVerifyHelper|TestManagedCoreImports' -count=1` and `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManaged(BootFrozenAtLaunch|SeedDoor|EnrolReplyFields)' -count=1`. |
| -Expected: FAIL on undefined symbols and missing behavior, not on environment. |
| +Run `GOFLAGS=-buildvcs=false go test ./internal/managedboot ./internal/compute -run 'TestManagedUserData|TestManagedCloudInit|TestManagedCoreImports' -count=1` and `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManaged(BootFrozenAtLaunch|SeedDoor|EnrolReplyFields)' -count=1`. |
| +Expected: FAIL on undefined symbols and missing behavior, not on environment. The script-run test lives in `internal/console` if it needs the real handler (it imports managedboot to render), keeping managedboot free of console imports. |
| - [ ] **Step 3: Implement `managedboot.Frozen`, `RenderUserData` and the v1 template.** |
| The template is `#!/bin/sh`, embedded with `//go:embed`, rendered by `text/template` with values already allowlisted; each value is emitted single-quoted. Plain text only (no gzip), so output never depends on a compressor version. |
| `Format` selects the template; a later template change adds a new format and keeps v1 rendering for frozen boxes. The golden file is the change detector. |
| -Script order, each step failing to breadcrumb `bootstrap_failed`: `set -eu`, `umask 077`, `exec timeout 900`; root-owned 0700 staging `/var/lib/carlos-managed-boot` via the group-init ancestor walk (`infra/modules/region-host/group-init.sh.tftpl:18`); apt over the HTTPS Debian mirror only (`nftables curl ca-certificates python3`); create the `carlos` system user; install table `inet carlos_managed_imds` with group-init's rule shape (`group-init.sh.tftpl:104-140`: metadata reachable by uid 0 and carlos only, forwarded traffic rejected), persist it and verify `nft list table`; write `input.json` (0600) by heredoc; `curl --proto =https --tlsv1.2 -fsS --retry 20 --retry-max-time 600 --max-filesize 100663296 --data @input.json` to `<origin>/api/fleet/enrol/seed`; write `seed.sha256`; run the verify helper; emit `seed_verified`; install and start `carlos-managed-boot.service` (Type=oneshot, RemainAfterExit=yes, ExecStart = verify helper then `seed system managed-boot --input /var/lib/carlos-managed-boot/input.json`, enabled for every boot). |
| +Script order, each step failing to breadcrumb `bootstrap_failed`: |
| +1. `set -eu`, `umask 077`; bound the whole run with group-init's pattern (`group-init.sh.tftpl:12-15`): if `CARLOS_MANAGED_BOOT_BOUNDED` is unset, export it and `exec timeout 900 /bin/sh "$0"`. |
| +2. Root-owned 0700 `BootDir` via the group-init ancestor walk (`:18-45`). |
| +3. apt over the HTTPS Debian mirror only (`nftables curl ca-certificates python3`); create the `carlos` system user. |
| +4. Install table `inet carlos_managed_imds` with group-init's rule shape (`:104-140`: metadata reachable by uid 0 and carlos only, forwarded traffic rejected); persist it to `/etc/nftables.conf`, `systemctl enable nftables.service`, verify `nft list table`. |
| +5. Write `boot-input.json` (full LaunchInput) and `seed-request.json` (`{"token":"..."}`) by heredoc, both 0600. |
| +6. `curl --proto =https --tlsv1.2 -fsS --retry 20 --retry-max-time 600 --max-filesize 100663296 -H 'Content-Type: application/json' --data-binary @seed-request.json -o BootDir/seed.part <origin>/api/fleet/enrol/seed`; write `seed.sha256`; run the verify helper against `seed.part`; rename to `seed`; delete `seed-request.json`; emit `seed_verified`. |
| +7. Write `/etc/systemd/system/carlos-managed-boot.service`: `[Unit] Requires=nftables.service`, `After=nftables.service`, `Before=carlos-edge.service`; `[Service] Type=oneshot`, `RemainAfterExit=yes`, `ExecStart=` verify helper then `BootDir/seed system managed-boot --input BootDir/boot-input.json`; `[Install] WantedBy=multi-user.target`. Write drop-in `carlos-managed-boot.service.d/10-enrol.conf` with `Wants=network-online.target` and `After=network-online.target` (removed by Task 2 at completion). Write `carlos-edge.service.d/60-managed.conf` with `Requires=` and `After=carlos-managed-boot.service`. |
| +8. `systemctl daemon-reload`, `systemctl enable carlos-managed-boot.service`, verify helper, `systemctl start carlos-managed-boot.service`. |
| + |
| Do not copy group-only pieces: lifecycle hook, `Restart=no`, group marker, SSM fetches, awscli. |
| - [ ] **Step 4: Freeze Boot at the reserved→launching commit and render user data from it.** |
| @@ -171,47 +196,50 @@ Do not copy group-only pieces: lifecycle hook, `Restart=no`, group marker, SSM f |
| `managedBootFrozen` reads the pass's verified stable pointer once, takes `Current.Artifacts["linux-arm64"]`, base64-encodes `Config.ReleasePub`, and validates the result. |
| Persist it in the same CAS that sets `LaunchStartedAt`/`EnrolExpires`; 2b-1's firstDispatch call happens only after that commit. |
| AdvanceManagedBox: once `before.Boot` is nonzero it must equal `after.Boot`; `after.Launch.UserData` stays empty in SQL (the token is never stored). |
| -`managedLaunchRequest` returns an error for zero Boot and otherwise sets `spec.UserData` from `RenderUserData` with the derived token; JSON user data from 2a is removed. |
| +`managedLaunchRequest` returns an error for zero Boot and otherwise sets `spec.UserData` from `RenderUserData` with the derived token; 2a's JSON user data is removed. |
| - [ ] **Step 5: Add the seed door and the additive enrol reply fields.** |
| Strict 4 KiB `{"token"}` decode; HostClaim refusal; reuse `s.cli.managedEnrolIP` then `managedEnrolGlobal`. |
| Token lookup is the enrol lookup's hash path with the same state/window predicate (`managedenrol.go:82`) but no CAS and no state change. |
| -Stream via `release.Opener` when the store implements it, else Get, capped at 96 MiB; the box verifies the digest, the console does not vouch for bytes. |
| +Stream via `release.Opener` (`S3Store.Open`, `store.go:930`) when the store implements it, else Get, capped at 96 MiB; the box verifies the digest, the console does not vouch for bytes. |
| A package-level semaphore of 4 bounds concurrent streams. Refusal bodies are COPY. |
| -The door never reveals whether a token exists: unknown, used, expired and not-yet-launched answer the same 403 body and timing class as enrolment. |
| +The door never reveals whether a token exists: unknown, used, expired and not-yet-launched answer the same 403 body as enrolment. |
| Log lines name the fleet/label and outcome only; the token, its hash and the request body are never logged. |
| - [ ] **Step 6: Repeat Step 2 to PASS; run `TestManagedFrozenLaunchRetryAcrossConfigChange` and `TestManagedEnrolReplayAndRace` once; commit.** |
| -Mutation checks (≤6): drop one allowlist regex; render the token into the curl argv; skip the Boot immutability check; consume the token in the seed door; skip the verify helper before exec; allow zero Boot launch. |
| +Mutation checks (≤7): drop one allowlist regex; render the token into the curl argv; send boot-input.json as the seed body; skip the Boot immutability check; consume the token in the seed door; skip the verify helper before exec; allow zero Boot launch. |
| Commit subject: `feat: frozen managed cloud-init and token-bound seed door`. |
| -### Task 2: Run first contact: gate, attest, trade once, stage durably, install stable |
| +### Task 2: Run first contact: gate, attest, trade once, stage durably, install stable, start edge |
| **Files:** |
| -- Create: `internal/managedboot/enrolwire.go`, `state.go`, `hostenv.go` and tests. |
| +- Create: `internal/managedboot/enrolwire.go`, `identity.go`, `hostenv.go` and tests. |
| - Create: `internal/host/managedboot.go` (state machine, platform-neutral), `managedboot_linux.go` (fs, nft, systemd), `managedboot_other.go` (refuses), `managedstable.go`; tests `managedboot_test.go`, `managedboot_linux_test.go`, `managedstable_test.go`. |
| - Modify: `system.go` (`systemVerb` list at :56, `runSystem` switch) to add `managed-boot`. |
| **Interfaces:** |
| -- Consumes: `managedboot.LaunchInput`, `Frozen`, `Breadcrumb`; `release.GetSystemPointer(ctx context.Context, s Store, pub ed25519.PublicKey, component, channel string) (*SystemPointer, string, error)` (`systempointer.go:259`); `release.FetchToFile(ctx context.Context, s Store, key, dst string, limit int64, wantSHA256 string) error` (`fetch.go:22`); `openFleetDoorStore(getenv func(string) string, identity FleetIdentity) (release.Store, error)` (`agent.go:5472`); `rootaws.ParseStaticCredentials(body []byte) (aws.Credentials, error)` (`credentials.go:15`); `hostenv.Render`/`Parse` (`hostenv.go:267`, :316); bootstrap exec pattern of `installGroup` (`hostenv/group.go:170`). |
| +- Consumes: Task 1 `LaunchInput`, `DecodeLaunchInput`, `Frozen`, `Breadcrumb`, `BootDir`; `release.GetSystemPointer(ctx context.Context, s Store, pub ed25519.PublicKey, component, channel string) (*SystemPointer, string, error)` (`systempointer.go:259`); `release.FetchToFile(ctx context.Context, s Store, key, dst string, limit int64, wantSHA256 string) error` (`fetch.go:22`); `openFleetDoorStore(getenv func(string) string, identity FleetIdentity) (release.Store, error)` (`agent.go:5472`); `rootaws.ParseStaticCredentials(body []byte) (aws.Credentials, error)` (`credentials.go:15`); `hostenv.Render`/`Parse` (`hostenv.go:267`, :316); bootstrap exec pattern of `installGroup` (`hostenv/group.go:170`). Bootstrap enables but does not start carlos-edge (`bootstrap.go:247-250`, `systemctlPlanArming` :274-281, message :697). |
| - Produces (**new**, package `managedboot`): |
| - `type EnrolRequest struct { Token string "token"; DataDirEmpty bool "data_dir_empty"; DataDirEntries int "data_dir_entries" }` and `type EnrolReply struct { Fleet, Label, TunnelURL, TunnelToken string; Credentials struct{ ID string "id"; Secret []byte "secret" } "credentials"; Joining bool; Bucket, BucketRegion, Operation string }` with the console's JSON names; a console test pins both against `managedEnrolRequest`/`managedEnrolReply`. |
| - - `const IdentityPath = "/etc/carlos/managed-box.json"`; `const StateDir = "/var/lib/carlos-managed"`; `const StatePath = StateDir + "/state.json"`. |
| - - `type Identity struct { Fleet, Label, Op string }` (root 0644, written once). |
| - - `type State struct { Schema int "schema"; Phase string "phase"; Fleet, Label, Op string; ReadyAt time.Time "ready_at"; AdmittedAt time.Time "admitted_at" }` with `PhaseJoining = "joining"`, `PhaseAdmitted = "admitted"`. |
| - - `func LoadState(root string) (Identity, State, bool, error)`: bool is "this is a managed box"; identity present + state missing/malformed/mismatched ⇒ joining with error. |
| - - `func WriteState(root string, s State) error`: temp file, fsync, rename, directory fsync; refuses admitted→joining and identity changes. |
| + - `const IdentityPath = "/etc/carlos/managed-box.json"`; `type Identity struct { Fleet, Label, Op, ReleasePubkey string }` (JSON `fleet`, `label`, `op`, `release_pubkey`), root:root 0644 in root-owned `/etc/carlos`, written once. |
| + - `func LoadIdentity(root string) (Identity, bool, error)`: bool is "this is a managed box"; opens with an O_NOFOLLOW ancestor walk and refuses any component not owned by root or writable by group/other. |
| + - `const RootAdmissionDir = "/var/lib/carlos-managed-root"` (root:root 0700, created at commit; Task 3 owns its contents). |
| + - `const KeyStatusPath = "/etc/carlos/managed-key-status.json"` (root 0644; Task 4 writes it). |
| - `func ManagedHostEnv(id Identity, r EnrolReply, f Frozen, secretsKey string) (map[string]string, error)`: exactly CARLOS_REGION=`fleet/<fleet>`, CARLOS_FLEET, CARLOS_FLEET_BOX, CARLOS_TUNNEL_NAME, CARLOS_TUNNEL_URL, CARLOS_TUNNEL_TOKEN, CARLOS_RELEASE_PUBKEY, CARLOS_HIBERNATE_BUCKET, CARLOS_HIBERNATE_REGION, CARLOS_HIBERNATE_PREFIX=`instances`, AWS_SHARED_CREDENTIALS_FILE=`/etc/carlos/credentials`, and CARLOS_SECRETS_KEY when nonempty. Never CARLOS_DEPLOYMENT_BUCKET/DIR, CARLOS_HOST_CLAIM or CARLOS_GROUP_ADMISSION. |
| -- Produces (**new**, package `host`): `func RunSystemManagedBoot(args []string)`; `type managedBoot struct` with injected `root string`, `http *http.Client`, `now func() time.Time`, `run func(ctx context.Context, argv []string, env []string) error`, `breadcrumb func(code string)`; `func (m *managedBoot) Run(ctx context.Context, in managedboot.LaunchInput) error`; `func installManagedStable(ctx context.Context, s release.Store, pub ed25519.PublicKey, root string) (version string, err error)`. |
| +- Produces (**new**, package `host`): `func RunSystemManagedBoot(args []string)`; `type managedBoot struct` with injected `root string`, `http *http.Client`, `now func() time.Time`, `run func(ctx context.Context, argv []string, env []string) error`, `systemctl func(ctx context.Context, args ...string) error`, `breadcrumb func(code string)`; `func (m *managedBoot) Run(ctx context.Context, in managedboot.LaunchInput) error`; `func installManagedStable(ctx context.Context, s release.Store, pub ed25519.PublicKey, root string) (version string, err error)`. |
| -**Census/review:** Root-binary units (host, managedboot, system verb). Security review (Astra + Fable): verified execution, credential staging, scrubbing. |
| +**Census/review:** Root-binary units (host, managedboot, system verb). Security review (Astra + Fable): verified execution, credential staging, scrubbing, service ordering. |
| - [ ] **Step 1: Write failing first-contact tests against a fake root and fake console/store.** |
| ```text |
| -TestManagedBootIMDSGate: nft table absent or unreadable => bootstrap_failed, zero HTTP calls. |
| +TestManagedBootFirewallOrdering: unit text has Requires=/After=nftables.service and the enrol |
| + drop-in Wants=/After=network-online.target; table absent at start but present after 5 s |
| + (fake clock) => proceeds; table never appears within 60 s => bootstrap_failed, zero HTTP |
| + calls, edge start never queued; nft list errors => same; enrol drop-in removed (daemon-reload) |
| + only after the complete marker is durable. |
| TestManagedBootAttestation: /data absent => empty,0; empty dir => empty,0; one entry (incl. dotfile, |
| lost+found) => not empty, exact count, trade still sent honestly, console 403 => enrol_failed; |
| /data symlink or non-directory => not empty; scan happens before any write under /data. |
| @@ -221,47 +249,52 @@ TestManagedBootTradeRetry: 503 Retry-After 5 and 429 retried until Expires, then |
| bucket => refused, nothing staged, enrol_failed; secret never in logs/errors/breadcrumbs. |
| TestManagedBootRebootBoundaries: crash injected after each durable step: |
| (a) before trade => next boot trades once; (b) after request sent, before reply => next boot |
| - retries, console 403 => enrol_failed, nothing staged, no workloads, edge never started; |
| + retries, console 403 => enrol_failed, nothing staged, no workloads, edge never queued; |
| (c) reply received, staging partially written => next boot removes the partial staging dir |
| (shredded), does not reuse partial credentials, 403 => enrol_failed; |
| (d) after commit rename => next boot makes ZERO enrol calls and continues; |
| - (e) after scrub, key, stable install, bootstrap each => resume, no repeated network step that |
| - already completed, joining state present and unchanged throughout. |
| + (e) after scrub, key, stable install, bootstrap, complete marker each => resume without |
| + repeating a completed network step; no root admission record exists at any point. |
| +TestManagedBootStartPlan: recorded systemctl argv after a first successful boot is exactly |
| + daemon-reload, (bootstrap's own enable plan), daemon-reload after drop-in removal, |
| + `start --no-block carlos-edge.service`, in that order, after the complete marker fsync; |
| + the oneshot never runs a blocking `start carlos-edge`; crash between complete marker and |
| + queueing => next boot's complete path queues `start --no-block carlos-edge.service` once. |
| +TestManagedBootUpdateReboot: complete box; /opt/carlos/carlos replaced by a later signed |
| + version (as systemapply.go:676 renames it) => reboot: managed-boot complete path succeeds |
| + without reading /opt/carlos/carlos, queues edge, makes zero enrol/store/ready calls; |
| + interrupted update then the existing root recovery/rollback path restores a binary => |
| + reboot => same; admission record (Task 3) untouched in both. |
| TestManagedBootStagingModes: host.env root:root 0600; credentials root:carlos 0640 parseable |
| - by ParseStaticCredentials; managed-box.json root 0644; StateDir root:carlos 0770 and |
| - state.json carlos 0600 phase=joining; carlos-edge drop-in 60-managed.conf has |
| - ReadWritePaths=/var/lib/carlos-managed, Requires= and After=carlos-managed-boot.service. |
| + by ParseStaticCredentials; managed-box.json root 0644 with release_pubkey equal to the frozen |
| + key; RootAdmissionDir root:root 0700 and empty; no file under any carlos-writable path is |
| + read by managed-boot. |
| TestManagedBootScrub: after commit, sentinel token/secret absent from every file under the fake |
| - root except host.env and credentials: input.json token removed, cloud-init user-data copies |
| - (instance/user-data.txt, user-data.txt.i, scripts/part-001, instances/<id>/...) shredded, |
| - seed request body removed; scrub failure => bootstrap_failed before bootstrap runs. |
| + root except host.env and credentials: boot-input.json rewritten without the token, |
| + seed-request.json absent, cloud-init user-data copies (instance/user-data.txt, user-data.txt.i, |
| + scripts/part-001, instances/<id>/...) shredded; scrub failure => bootstrap_failed before bootstrap. |
| TestManagedBootStableTrust: pointer signed by another key, scoped-key grant, wrong component/ |
| - channel, missing linux-arm64, artifact sha mismatch, oversize artifact, installed file swapped |
| - or re-linked between install and exec => nothing executed, bootstrap_failed, state joining; |
| + channel, missing linux-arm64, artifact sha mismatch, oversize artifact, staged file swapped |
| + or re-linked between fetch and first exec => nothing executed, bootstrap_failed, no admission; |
| valid pointer => /opt/carlos/carlos root 0755 equals signed sha, stable_verified emitted, |
| - bootstrap argv run with clean env and cwd /, re-hashed immediately before exec. |
| + bootstrap argv run with clean env and cwd /, re-hashed immediately before that first exec. |
| TestManagedBootNoDeploymentAuthority: staged env and child env never contain deployment bucket, |
| deployment dir, HOST_CLAIM, GROUP_ADMISSION, AWS profile selectors or the enrol token. |
| -TestManagedStateFailClosed: identity present + state missing/malformed/foreign fleet/label/op |
| - => LoadState reports joining with error; WriteState admitted->joining refused; no identity => BYO. |
| TestManagedEnrolWireMatchesConsole (console package): managedboot wire types round-trip the |
| console's managedEnrolRequest/managedEnrolReply JSON exactly. |
| ``` |
| - [ ] **Step 2: Run the failing tests.** |
| -Run `GOFLAGS=-buildvcs=false go test ./internal/managedboot ./internal/host -run 'TestManagedBoot|TestManagedState' -count=1` and `GOFLAGS=-buildvcs=false go test ./internal/console -run TestManagedEnrolWireMatchesConsole -count=1`; expect FAIL. |
| +Run `GOFLAGS=-buildvcs=false go test ./internal/managedboot ./internal/host -run 'TestManagedBoot' -count=1` and `GOFLAGS=-buildvcs=false go test ./internal/console -run TestManagedEnrolWireMatchesConsole -count=1`; expect FAIL. |
| - [ ] **Step 3: Implement the state machine in the order the tests pin.** |
| -Order per boot: root check → IMDS table check → `committed/` present? skip to install : attest → trade (retry contract above, never past `Expires`) → write `staging.<random>/` (host.env, credentials, identity, state, each fsynced) → fsync dir → rename to `committed/` → fsync parent → install committed files into final paths (idempotent) → scrub → fleet key (Task 4 inserts here; until then CARLOS_SECRETS_KEY is absent) → stable install → drop-ins → `systemctl daemon-reload` → run `/opt/carlos/carlos bootstrap` → emit `joining` → write `complete` marker. |
| -A boot that finds `complete` re-verifies the installed binary digest record and exits 0 with no network calls. |
| +Order per boot: root/euid check and `--input` must be a root-owned 0600 regular file in `BootDir` → wait up to 60 s for the IMDS table (systemd ordering normally guarantees it) → `complete` marker present? go to the complete path : → `committed/` present? skip to install : attest → trade (retry contract below, never past `Expires`) → write `staging.<random>/` (host.env, credentials, identity, each fsynced) → fsync dir → rename to `committed/` → fsync parent → install committed files into final paths and create `RootAdmissionDir` (idempotent) → scrub → fleet key (Task 4; never fails the boot) → stable install → `run /opt/carlos/carlos bootstrap` (first exec, re-hashed just before) → write and fsync `complete` → remove the enrol drop-in and daemon-reload → `systemctl start --no-block carlos-edge.service` → emit `joining`. |
| +Complete path: no network, no digest check of `/opt/carlos/carlos` (after first install its integrity belongs to the existing root update/rollback path, `systemapply.go:676`); ensure the enrol drop-in is gone; queue `start --no-block carlos-edge.service`; exit 0. |
| Any partial `staging.*` directory is shredded and removed on start. Breadcrumbs go to `/dev/console`, one line each, never with values. |
| -Retry backoff for the trade: honour `Retry-After` (5 s for 503, the header value for 429), jittered 1-30 s for transport errors, stop at `Expires`; emit `enrol_pending` once when the first retry starts. |
| -The overall boot deadline is `Expires`; after it, the only remaining action is `enrol_failed` and exit non-zero. |
| -Because the carlos-edge drop-in `Requires=` the boot unit, a failed boot leaves the agent stopped; the box then runs nothing and the console's 20-minute deadline terminates it. |
| -Automatic platform updates later replace `/opt/carlos/carlos`; the boot unit keeps running the verified seed, whose `complete` path needs no network, so later updates do not depend on the seed's version. |
| -`RunSystemManagedBoot` refuses unless euid is 0 and `--input` names a root-owned 0600 regular file inside `/var/lib/carlos-managed-boot`. |
| +Trade retry: honour `Retry-After` (5 s for 503, the header value for 429), jittered 1-30 s for transport errors, stop at `Expires`; emit `enrol_pending` once when the first retry starts. After `Expires` the only remaining action is `enrol_failed` and a non-zero exit. |
| +Because carlos-edge `Requires=` the boot unit, a failed boot leaves the agent stopped; the box runs nothing and the console's 20-minute deadline terminates it. The seed binary is never updated; it runs only this state machine, whose complete path needs nothing newer. |
| Trust chain the tests must keep intact (recon §3 "bootstrap trust cycle"): |
| @@ -270,115 +303,145 @@ Trust chain the tests must keep intact (recon §3 "bootstrap trust cycle"): |
| | User data (token, seed digest, release pubkey, origins) | written by the console through RunInstances; readable afterwards only by uid 0/carlos via the IMDS gate | |
| | Seed binary | its SHA-256 equals the frozen `SeedSHA256`, checked by the root-only helper immediately before each exec; TLS to the console is transport only | |
| | Enrol reply | HTTPS to the frozen console origin, bound to the single-use token; cross-checked against frozen fleet/label/op/tunnel host | |
| -| Stable pointer and artifact | Ed25519 signature under the frozen root pubkey (`GetSystemPointer` rejects scoped grants), artifact SHA from the signed pointer, re-hashed before exec | |
| +| Stable pointer and artifact | Ed25519 signature under the frozen root pubkey (`GetSystemPointer` rejects scoped grants), artifact SHA from the signed pointer, re-hashed before first exec; later updates by systemapply | |
| +| Ready object (Task 3) | console signature under the same frozen pubkey, verified by root from the root-owned identity file | |
| | Fleet key object | create-only write under the fleet's own IAM user; validated public/private/fingerprint consistency; registered fingerprint must match | |
| - [ ] **Step 4: Implement `installManagedStable` over the store door.** |
| Open the store with `openFleetDoorStore` using the committed identity env; channel `stable`, component `router`. |
| -Fetch into the root-only staging dir with the 96 MiB limit (`systemstate.go:29`) and the signed SHA; rename to `/opt/carlos/carlos`; record the digest root-only; re-hash before every exec. |
| +Fetch into the root-only staging dir with the 96 MiB limit (`systemstate.go:29`) and the signed SHA; rename to `/opt/carlos/carlos`. |
| Reuse verification primitives only; do not invoke `system install-channel` (its group/floor checks assume a deployment-bucket identity). |
| - [ ] **Step 5: Repeat Step 2 to PASS and commit.** |
| -Mutation checks (≤8): skip IMDS check; re-trade after commit; reuse partial staging; skip scrub of one cloud-init copy; skip pointer signature verify; skip pre-exec re-hash; let an empty reply bucket through; write state before credentials in the commit. |
| +Mutation checks (≤10): skip the IMDS wait; re-trade after commit; reuse partial staging; skip scrub of one cloud-init copy; skip pointer signature verify; skip pre-exec re-hash; let an empty reply bucket through; blocking `start carlos-edge`; complete path re-checks the initial digest; keep the enrol drop-in after completion. |
| Commit subject: `feat: managed box first contact with verified install`. |
| -### Task 3: Hold every workload behind the joining gate until ready.json |
| +### Task 3: Root-owned admission behind every start surface |
| **Files:** |
| -- Modify: `internal/provision/reconcile.go` (`ReconcileConfig` at :38, `ownsRecord` at :549, `Reconcile` at :1423) and `reconcile_test.go`. |
| -- Create: `internal/host/managedjoin.go`, `managedjoin_test.go`. |
| -- Modify: `internal/host/agent.go` (`runAgent` :264, `BoxProvisionConfig` :3893, `fastTick` :3160 via `fastDeps` :2670, `makeStartRoute` :5168 wiring), `internal/host/group_admission.go` (composition only), `internal/host/claimstop_run.go` (`RunInstanceControl` :23). |
| -- Modify: `internal/instancectl/server.go` (mux at :507-518) and tests; `internal/edge/group_admission.go` consumer unchanged. |
| +- Create: `internal/managedboot/ready.go`, `admission.go` and tests. |
| +- Modify: console `internal/console/managedworker.go` (`managedReadyObject` :569, publication :576-638) and `managedready_test.go`; 2b-1's freshness and C08 behaviour unchanged. |
| +- Modify: `internal/provision/reconcile.go` (`ReconcileConfig` :38, `ownsRecord` :549, `Reconcile` :1423) and tests. |
| +- Create: `internal/host/managedjoin.go`, `managedjoin_test.go`, `managedjoin_root_linux_test.go`. |
| +- Modify: `internal/host/agent.go` (`runAgent` :264, `BoxProvisionConfig` :3893, `fastTick` :3160 via `fastDeps` :2670, `makeStartRoute` :5168, `adoptLoop` :1701, `configSyncLoop` :1796, root pass `runAdoptUnderRootRelease` :5619 incl. SyncUnits :5817 and `rootStartRoute` :5923), `rootrestart.go` (`rootStartRoute` :524, `rootSelectedRestart` :529), `unitops.go` (`productionUnitOps` :27), `namedrecovery.go` (`productionNamedUnitRecovery` :31), `claimstop_run.go` (`RunInstanceControl` :23). |
| +- Modify: `internal/instancectl/server.go` (mux :507-526), `client.go` (`NewClient` :50) and tests. |
| **Interfaces:** |
| -- Consumes: Task 2 `managedboot.LoadState`, `WriteState`, `Identity`, `State`; `release.ReadSerial` (`serial.go:32`, `SerialDoc.Serial int64`); activator hooks `Service.TenantAdmittedFunc`, `Service.TenantExempt`, `ExecBackend.TenantStartAllowed`, `Service.tenantStartRefusal` (`activator/group_admission.go:11-34`); `(*ExecBackend).Start` :2092, `StartGen` :2136, `StartGenExe` :2163, `StartSidecar` :3294, `StartWorkerStaged` :3433; `(*Service).doWakeOnce` (`activator.go:2501`); edge `HAAdmission{ TenantAdmitted() bool }`; `runWorkerBootPassAfterAdmission` (`host/group_admission.go:301`). |
| -- Produces (**new**): |
| +- Consumes: Task 2 `LoadIdentity`, `Identity.ReleasePubkey`, `RootAdmissionDir`; `Config.Key` (console Ed25519 private key that signs channel pointers, `server.go:674-677`; public half is `Config.ReleasePub` / `CARLOS_RELEASE_PUBKEY`) and the existing `{payload, sig}` wrapper convention (`release/release.go:487`, signing at `release/production.go:117`, verify at :160); `release.ReadSerial` (`serial.go:32`, `Serial int64`); activator hooks `Service.TenantAdmittedFunc`, `Service.TenantExempt`, `ExecBackend.TenantStartAllowed` (`activator/group_admission.go:11-34`); `(*ExecBackend).Start` :2092, `StartGen` :2136, `StartGenExe` :2163, `StartSidecar` :3294, `StartWorker` :3397, `StartWorkerStaged` :3433; `(*Service).doWakeOnce` (`activator.go:2501`); edge `HAAdmission{ TenantAdmitted() bool }` (`edge/group_admission.go:8`); `appconfig.UnitOps.Restart` call at `appconfig/unitsync.go:459`. |
| +- Produces (**new**, package `managedboot`): |
| + - `type ReadyRecord struct { Schema int "schema"; Kind string "kind"; Fleet, Label, Op string; ReadyAt time.Time "ready_at" }`, `const ReadyKind = "managed-ready"`. |
| + - `func SignReady(priv ed25519.PrivateKey, r ReadyRecord) ([]byte, error)`: wrapper `{"payload": base64(json), "sig": base64(ed25519.Sign(priv, payloadB64))}`, deterministic. |
| + - `func VerifyReady(pub ed25519.PublicKey, wire []byte, want Identity) (ReadyRecord, error)`: strict wrapper and payload decode, `Kind == ReadyKind`, schema 1, fleet/label/op equal, nonzero UTC ReadyAt; scoped grants refused. |
| + - `const AdmissionPath = RootAdmissionDir + "/admission.json"`. |
| + - `func CommitAdmission(root string, wire []byte) error`: euid 0 only; `LoadIdentity`; `VerifyReady` with `Identity.ReleasePubkey`; dir must be root:root 0700 opened O_NOFOLLOW; write temp, fsync, rename, fsync dir; an existing valid record is kept (idempotent, never replaced). |
| + - `func RootAdmission(root string) (managed, admitted bool, err error)`: identity absent ⇒ (false, true, nil) BYO; identity present ⇒ admitted only if `AdmissionPath` is a root-owned 0600 single-link regular file in a root 0700 dir, opened O_NOFOLLOW, whose bytes re-verify; any doubt ⇒ (true, false, err). |
| +- Produces (**new**, host/instancectl/provision): |
| - `ReconcileConfig.Joining func() bool`: when true, `ownsRecord` returns false for every record (labelled, unlabelled, static, replica-assigned, sidecar) before the replica branch, and `Reconcile` returns nil before listing, minting or removing. |
| - - `type managedJoin struct` with `func newManagedJoin(root string) (*managedJoin, error)` (nil for BYO), `func (j *managedJoin) Joining() bool`, `func (j *managedJoin) TenantAdmitted() bool`, `func (j *managedJoin) TenantAdmissionExempt(registry.Route) bool` (always false while joining), `func (j *managedJoin) TenantAdmissionStarting() bool` (true), `func (j *managedJoin) readyLeg(ctx context.Context, s release.Store, now time.Time, serial int64, serialOK bool) bool` (true when this call admitted the box). |
| - - `const managedReadyBackstop = 60 * time.Second`. |
| - - `fastDeps.managedReady func(ctx context.Context, now time.Time, serial int64, serialOK bool)`. |
| - - `instancectl.Server.Joining func() bool`; refused verbs answer 409 with body `box is joining its fleet` (COPY). |
| + - Root door routes `POST /managed-admit` (body ≤4 KiB, the raw ready object) → `CommitAdmission`; `GET /managed-admission` → `{"managed":bool,"admitted":bool}`. `instancectl.Server` fields `ManagedAdmit func(wire []byte) error`, `ManagedAdmission func() (managed, admitted bool, err error)`; client methods `(*Client).ManagedAdmit(ctx context.Context, wire []byte) error`, `(*Client).ManagedAdmission(ctx context.Context) (managed, admitted bool, err error)`. |
| + - Root door refuses POST `/start`, `/seed`, `/cmd`, `/tty`, `/parent`, `/demo-build`, `/demo-snapshot` with 409 `box is joining its fleet` (COPY) while `RootAdmission` is not admitted. |
| + - `func managedRootGate(root string) func() error`: used by every root-pass execution callback. |
| + - `type managedJoin struct` (agent side, advisory) with `func newManagedJoin(c *instancectl.Client) (*managedJoin, error)` (nil for BYO), `Joining() bool`, `TenantAdmitted() bool`, `TenantAdmissionExempt(registry.Route) bool` (false while joining), `TenantAdmissionStarting() bool` (true), `readyLeg(ctx context.Context, s release.Store, now time.Time, serial int64, serialOK bool) bool`; `const managedReadyBackstop = 60 * time.Second`; `fastDeps.managedReady func(ctx context.Context, now time.Time, serial int64, serialOK bool)`. |
| -**Census/review:** Root-binary units (provision, host, instancectl, activator wiring); authority inventory (start/serve surfaces). Security review (Astra + Fable). |
| +**Census/review:** Root-binary units (provision, host, instancectl, activator wiring); authority inventory (start/serve surfaces, root admission door); the console ready-object writer changes (record-write census). Security review (Astra + Fable). |
| -- [ ] **Step 1: Write failing gate and admission tests.** |
| +- [ ] **Step 1: Write failing admission and gate tests.** |
| ```text |
| +TestManagedReadySigned (console): published ready.json is SignReady(Config.Key, record); |
| + verify GET decodes and verifies with Config.ReleasePub; foreign-key, unsigned, other-kind or |
| + mismatched object => uncertainty exactly as 2a's mismatch (no PUT, no revoke, no terminate); |
| + Config.Key nil => no PUT, publishing stays pending with a COPY reason; C08/N4 witnesses |
| + (TestManagedPublishDeadline, TestManagedDelayedPublicationFreshness) still pass. |
| +TestManagedRootAdmissionForgery (linux, as root in a user namespace, service UID = carlos): |
| + carlos cannot create, replace, rename into or symlink RootAdmissionDir/admission.json |
| + (EACCES); a pre-placed symlink, hardlink, wrong owner, mode 0644, or dir mode 0770 => |
| + RootAdmission (true,false,err); a carlos-owned file anywhere else claiming admission has no |
| + effect; /start, /cmd, root pass start route all refuse in each case. |
| +TestManagedRootAdmitVerify: POST /managed-admit with unsigned, wrong-key, scoped-grant, other |
| + kind, other fleet/label/op, trailing JSON or >4 KiB body => 4xx, no file written; valid object |
| + => record written, GET /managed-admission admitted=true; replay => 200, file unchanged; |
| + identity file tampered (not root-owned or group-writable parent) => refuse. |
| TestReconcileJoiningOwnsNothing: Joining()=true => ownsRecord false for labelled-own, unlabelled, |
| static, ReplicaAssignment containing box, sidecar records; Reconcile returns nil with zero |
| - registry writes and zero store LISTs; a row pre-seeded in the local registry is neither removed |
| - nor started and its data dir untouched; Joining()=false => existing ownsRecord results unchanged. |
| -TestManagedJoinStartSurfaces: while joining each surface refuses with ErrTenantAdmission or the |
| - root 409 and launches nothing: Service wake (request-triggered and background), ExecBackend |
| - Start/StartGen/StartGenExe/StartSidecar/StartWorker/StartWorkerStaged, named-unit startRoute, |
| - worker boot pass, root door POST /start (legacy, gen, rootfs), /seed, /cmd, /tty, /parent, |
| - /demo-build, /demo-snapshot; edge returns 503 "starting" for any route; exemptions inherited |
| - from group admission do not apply; /stop, /sweep, GET /ready and /size still answer. |
| -TestManagedJoinLiveServices: while joining the status heartbeat (fleets/<f>/status/boxes/<l>.json), |
| - tunnel dial, store-door reads, system pointer leg and probe responder (Task 5) all run. |
| -TestManagedJoinReadyLeg: absent/403/5xx/malformed/trailing JSON/unknown field/zero ready_at/ |
| - wrong fleet, label or op => stays joining, state file unchanged; |
| - reads: one at arming, one per changed serial, else at most one per 60 s; serial read error => |
| - backstop only; valid object => state admitted fsynced BEFORE the in-memory flip, then one full |
| - reconcile and worker boot pass requested; WriteState failure => stays joining, retried next due. |
| -TestManagedJoinAdmissionOneWay: after admission, 1000 ticks with serial changes => zero ready GETs; |
| - ready object later deleted, rewritten with another op, or store unreachable => box stays admitted; |
| - restart with state admitted => no ready reads, normal reconcile; state file deleted while |
| - identity present => joining again (fail closed) and reported, never silently admitted. |
| -TestManagedJoinRebootMatrix: restart before ready, after ready GET before WriteState, after |
| - WriteState before flip, after flip before reconcile => final state consistent; no start before |
| - the durable admitted record; no lost admission after it. |
| -TestManagedJoinBYOUnchanged: no identity file => Joining nil/false, zero ready reads, group |
| - admission behavior and exemptions exactly as on main; identity + CARLOS_GROUP_ADMISSION=1 => |
| - agent refuses to arm tenant work (config error) rather than mixing gates. |
| + registry writes and zero store LISTs; Joining()=false => existing results unchanged. |
| +TestManagedJoinStartSurfaces: with a valid named-unit declaration and pre-seeded routes |
| + (native, rootfs, sidecar, worker, named unit, static) in the local registry while joining, |
| + every surface refuses and launches nothing: Service wake (request and background), |
| + ExecBackend Start/StartGen/StartGenExe/StartSidecar/StartWorker/StartWorkerStaged, |
| + makeStartRoute, worker boot pass, adoptLoop adoption, configSyncLoop restart, root pass |
| + rootStartRoute (agent.go:5923 -> systemctlStartUnit), rootSelectedRestart, rollback restart, |
| + SyncUnits' UnitOps.Restart (unitsync.go:459), named-unit recovery, root door /start (legacy, |
| + gen, rootfs) /seed /cmd /tty /parent /demo-*; edge returns 503 "starting" for any route. |
| + Platform maintenance keeps working: system update apply/rollback of /opt/carlos/carlos and |
| + restarts of carlos-edge, carlos-instance-control and nftables; /stop /sweep GET /ready /size answer. |
| +TestManagedJoinLiveServices: while joining the status heartbeat, tunnel dial, store-door reads, |
| + system pointer leg and probe responder (Task 5) all run. |
| +TestManagedJoinReadyLeg: absent/403/5xx/malformed/unsigned/wrong-key/wrong fleet, label or op |
| + => no relay or a root refusal, stays joining; reads: one at arming, one per changed serial, |
| + else at most one per 60 s; serial read error => backstop only; valid object => relayed to |
| + POST /managed-admit; only a 200 flips the agent and requests one full reconcile and worker |
| + boot pass; root refusal or socket error => stays joining, retried next due. |
| +TestManagedAdmissionOneWay: after admission, 1000 ticks with serial changes => zero ready GETs; |
| + ready object later deleted, rewritten or store unreachable => box stays admitted (root record |
| + is authoritative); agent restart => GET /managed-admission, no ready reads; reboot => same; |
| + admission record deleted by root-level tampering => joining again, reported, never silently admitted. |
| +TestManagedJoinRebootMatrix: restart before ready, after ready GET before relay, after root |
| + commit before the agent flip, after flip before reconcile => final state consistent; no start |
| + before root's durable record; no lost admission after it. |
| +TestManagedJoinBYOUnchanged: no identity file => no managedJoin, zero ready reads, root door |
| + routes answer managed=false, group admission and exemptions exactly as on main; identity + |
| + CARLOS_GROUP_ADMISSION=1 => agent refuses to arm tenant work (config error). |
| ``` |
| - [ ] **Step 2: Run the failing tests.** |
| -Run with an owned short socket dir: `TMPDIR=<owned-short-dir> GOFLAGS=-buildvcs=false go test ./internal/provision ./internal/host ./internal/instancectl -run 'TestReconcileJoining|TestManagedJoin' -count=1`; expect FAIL. |
| +Run with an owned short socket dir: `TMPDIR=<owned-short-dir> GOFLAGS=-buildvcs=false go test ./internal/managedboot ./internal/provision ./internal/host ./internal/instancectl -run 'TestReconcileJoining|TestManagedJoin|TestManagedRootAdmi|TestManagedAdmission' -count=1` and `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedReadySigned|TestManagedPublishDeadline|TestManagedDelayedPublicationFreshness' -count=1`; expect FAIL. |
| -- [ ] **Step 3: Gate ownership and every start surface on one live predicate.** |
| +- [ ] **Step 3: Sign the ready object on the console.** |
| -Pass `join.Joining` as a func into BoxProvisionConfig's configure list so every loop (`instancesLoop` :4324 retains cfg) sees the live value, never a snapshot bool. |
| -Bind the activator: `TenantAdmittedFunc = join.TenantAdmitted`, `TenantExempt` false while joining, `ExecBackend.TenantStartAllowed` refuses while joining; the late `admissionBefore` check catches a flip just before exec. |
| -Wrap `makeStartRoute` and the worker boot pass with the same refusal. Hand the edge `join` as its `HAAdmission`. |
| -In `RunInstanceControl`, set `Server.Joining` to a per-request `managedboot.LoadState("/")` check (root-readable, fail closed) and wrap the listed verbs before dispatch. |
| -The root door's check is independent of the agent: a compromised or buggy agent path that reaches `/start` while joining is still refused at the execution boundary. |
| -On a BYO box (`newManagedJoin` returns nil) every hook keeps its current value, so `fixedAdmission` (`host/group_admission.go:55`) and its exemptions behave exactly as on main. |
| -A managed box never constructs `fixedAdmission`; group exemptions for platform, named-unit and backing routes (`:81`) therefore never apply while joining. |
| -`runAgent` creates `managedJoin` before any loop starts (beside the fixed admission at `agent.go:271`) and logs one line when it arms in joining or admitted state. |
| +Replace `managedReadyObject`'s plain JSON with `SignReady(s.cfg.Key, ...)`; the create-only PUT, GET-verify, original ReadyAt and C08 classification stay as 2a/2b-1 define them. Ed25519 and the payload encoding are deterministic, so a re-issued PUT carries identical bytes. |
| +`Kind` separates this payload from every other object the same key signs; strict decoding rejects pointer, production-flag or door-key payloads. |
| -- [ ] **Step 4: Add the joining-only ready leg to fastTick.** |
| +- [ ] **Step 4: Make root the admission authority.** |
| -Call `d.managedReady(ctx, now, doc.Serial, err == nil)` after the serial read on every tick; it returns at once when not joining. |
| -It tracks its own last-seen serial so the 2-second clamp on `runFull` never suppresses or repeats a read. Path: `fleets/<fleet>/boxes/<label>/ready.json` via the store door; strict decode of exactly `fleet`, `label`, `ready_at`, `op`. |
| -On success: `WriteState(admitted)`, then flip, then `d.fullDue.Store(true)`. |
| +`RunInstanceControl` sets `ManagedAdmit`/`ManagedAdmission` from `CommitAdmission`/`RootAdmission("/")` and wraps the listed start verbs; the root door's existing PeerOK (carlos-edge MainPID) still guards the socket. |
| +`runAdoptUnderRootRelease` computes `managedRootGate("/")` once per pass and wraps `rootStartRoute`, both `rootSelectedRestart` callbacks, `rollbackUnitRestart`, `productionUnitOps.Restart` and `productionNamedUnitRecovery`; system binary apply/rollback and fixed platform units are not wrapped. |
| +The agent never writes admission state. `managedJoin` asks `GET /managed-admission` at arming and after each successful relay; its predicate is advisory defence in depth for agent-side surfaces. |
| +On a BYO box every hook keeps its current value, so `fixedAdmission` (`host/group_admission.go:55`) behaves as on main; a managed box never constructs it, so group exemptions (`:81`) never apply while joining. |
| -- [ ] **Step 5: Repeat Step 2 to PASS and commit.** |
| +- [ ] **Step 5: Gate agent-side surfaces and add the joining-only ready leg.** |
| + |
| +Pass `join.Joining` as a func into BoxProvisionConfig's configure list so every loop (`instancesLoop` :4324 retains cfg) sees the live value. Bind `TenantAdmittedFunc`, `TenantExempt`, `ExecBackend.TenantStartAllowed`; wrap `makeStartRoute`, the worker boot pass, adoptLoop's start path and configSyncLoop's restarts; hand the edge `join` as its `HAAdmission`. |
| +In `fastTick` call `d.managedReady(ctx, now, doc.Serial, err == nil)` after the serial read on every tick; it returns at once when not joining and tracks its own last-seen serial so the 2-second `runFull` clamp never suppresses or repeats a read. Path `fleets/<fleet>/boxes/<label>/ready.json` via the store door. |
| +On a root 200: flip, then `d.fullDue.Store(true)`. |
| + |
| +- [ ] **Step 6: Repeat Step 2 to PASS and commit.** |
| -Mutation checks (≤10): ownsRecord joining check after the replica branch; Reconcile not short-circuited; one ExecBackend start variant ungated; root /cmd ungated; exemption kept while joining; flip before WriteState; ready read after admission; missing state treated as admitted; op not compared; backstop at every tick. |
| -Commit subject: `feat: hold managed boxes behind a durable joining gate`. |
| +Mutation checks (≤10): root trusts a carlos-writable path; CommitAdmission skips signature; follow symlinks on read; ownsRecord joining check after the replica branch; rootStartRoute ungated; UnitOps.Restart ungated; one ExecBackend start variant ungated; agent flips before root 200; ready read after admission; platform unit restart wrongly gated. |
| +Commit subject: `feat: root-owned admission gate for managed boxes`. |
| ### Task 4: Mint and register the fleet's first secrets key |
| **Files:** |
| - Create: `internal/managedboot/fleetkey.go`, `fleetkey_test.go`; `internal/host/managedkey.go`, `managedkey_test.go`. |
| -- Modify: `internal/host/managedboot.go` (insert the key step after scrub). |
| -- Modify: `internal/console/fleetsecretskey.go` (extract core from `handleAPIFleetSecretsKey` at :72), `server.go` route; create `internal/console/managedfleetkey.go`, `managedfleetkey_test.go`; extend `fleetsecretskey_test.go`. |
| +- Modify: `internal/host/managedboot.go` (insert the key step after scrub); `internal/status/snapshot.go` (`Box` :846, additive field) and the agent's heartbeat writer. |
| +- Modify: `internal/console/fleetsecretskey.go` (extract core from `handleAPIFleetSecretsKey` at :72), `managedready.go` (storage check reads the heartbeat field), `server.go` route; create `internal/console/managedfleetkey.go`, `managedfleetkey_test.go`; extend `fleetsecretskey_test.go`. |
| **Interfaces:** |
| -- Consumes: `appconfig.GenerateKey() (privB64, pubB64 string, err error)` (`crypto.go:96`), `ParsePrivateKey`, `ParsePublicKey`, `KeyFingerprint(pub *ecdh.PublicKey) string` (`fingerprint.go:16`); `lease.NewFilesStore(ctx context.Context, bucket, region string) (release.Store, error)` (`lease/endpoint.go:182`) as the fleet-bucket store; `release.Store.Put(ctx, key, body, "")` is create-only and maps 412 to `release.ErrCASConflict` (`store.go:1001`, :37); `fleetIdentityOK(reg consoleRegistry, name, token, wantFleet, wantAccount string) bool` (`apiinteractivebox.go:117`); `recordFleetKeyFP`, `reg.SetFleetSecretsKey`, `registry.ErrFleetKeyInUse`, `expectedSecretsFP`, `lockAccount`. |
| +- Consumes: `appconfig.GenerateKey() (privB64, pubB64 string, err error)` (`crypto.go:96`), `ParsePrivateKey`, `ParsePublicKey`, `KeyFingerprint(pub *ecdh.PublicKey) string` (`fingerprint.go:16`); `lease.NewFilesStore(ctx context.Context, bucket, region string) (release.Store, error)` (`lease/endpoint.go:182`) as the fleet-bucket store; `release.Store.Put(ctx, key, body, "")` is create-only and maps 412 to `release.ErrCASConflict` (`store.go:1001`, :37); `fleetIdentityOK(reg consoleRegistry, name, token, wantFleet, wantAccount string) bool` (`apiinteractivebox.go:117`); `recordFleetKeyFP`, `reg.SetFleetSecretsKey`, `registry.ErrFleetKeyInUse`, `expectedSecretsFP`, `lockAccount`; Task 2 `KeyStatusPath`. |
| - Produces (**new**): |
| - `const FleetKeyObject = "system/fleet-secrets-key.json"` (2b-1's policy path). |
| - - `type FleetKey struct { Schema int "schema"; Fleet string "fleet"; Public string "public"; Private string "private"; Fingerprint string "fingerprint"; MintedBy string "minted_by"; Op string "op" }`; `func (k FleetKey) Validate(fleet string) error` (private parses, derived public equals `Public`, fingerprint equals `KeyFingerprint`, schema 1). |
| + - `type FleetKey struct { Schema int "schema"; Fleet string "fleet"; Public string "public"; Private string "private"; Fingerprint string "fingerprint"; MintedBy string "minted_by"; Op string "op" }`; `func (k FleetKey) Validate(fleet string) error`. |
| + - `type KeyStatus struct { Code string "code" }` with codes `ok`, `object_invalid`, `object_unreadable`, `registration_refused`, `registration_unavailable` (fixed codes; console maps them to COPY reasons). |
| - `func ensureFleetKey(ctx context.Context, s release.Store, id managedboot.Identity) (managedboot.FleetKey, error)`: GET; absent ⇒ mint + create-only PUT; ErrCASConflict or ambiguous PUT ⇒ GET and adopt the stored object; never a second PUT over an existing object. |
| - `func registerFleetKey(ctx context.Context, c *http.Client, origin, tunnelToken string, id managedboot.Identity, pub string) error`. |
| + - `status.Box.ManagedKey string` JSON `managed_key,omitempty` (the agent copies `KeyStatus.Code` from the root-owned file). |
| - Console: `type fleetKeyOutcome struct { Fleet, Fingerprint string; Changed bool }`; `(*Server).registerFleetSecretsKey(ctx context.Context, acct *Account, reg consoleRegistry, fleet string, key *ecdh.PublicKey, actor string, initialOnly bool) (fleetKeyOutcome, error)` with typed errors `errFleetKeyPlatformKey`, `errFleetKeyReplaceRefused`, `errFleetKeyInUse`, `*fleetKeySealedApps`, `*fleetKeyInstances`, `*fleetKeyNotRecorded{Status int}`. |
| - Console route `POST /api/fleet/managed/secrets-key` → `(*Server).handleManagedFleetKey(w, r)`; body `{"fleet","label","op","pubkey"}`, `Authorization: Bearer <tunnel token>`. |
| -**Census/review:** New public refusal door; record-write census for the registry key mutation via a second caller; authority inventory (box token gains initial-key-only registration). Security review (Astra + Fable). |
| +**Census/review:** New public refusal door; record-write census for the registry key mutation via a second caller; authority inventory (box token gains initial-key-only registration); owner door refusal on managed fleets (Paul rule 10). Security review (Astra + Fable). |
| - [ ] **Step 1: Write failing key tests.** |
| @@ -387,62 +450,67 @@ TestManagedFleetKeyFirstWriterWins: three boxes, empty bucket, barrier before PU |
| PUT returns success, two get ErrCASConflict, all three install the same private key, one object |
| exists, registry fingerprint equals its fingerprint; replay registration => changed=false. |
| TestManagedFleetKeyAmbiguousPut: PUT times out but succeeded => GET finds own object, adopts it; |
| - PUT times out and failed => GET absent => one retry create-only; GET error => no proceed, |
| - bootstrap_failed after the boot deadline; object never deleted or overwritten. |
| -TestManagedFleetKeyLaterBox: object present => zero mint, zero PUT, one GET; installs key; |
| - malformed, foreign-fleet, mismatched public/fingerprint object => refuse, state joining, |
| - no CARLOS_SECRETS_KEY written, reason surfaces through the Task 5 probe. |
| + PUT times out and failed => GET absent => one retry create-only; GET keeps failing => |
| + key status object_unreadable; object never deleted or overwritten. |
| +TestManagedFleetKeyLaterBox: object present => zero mint, zero PUT, one GET; installs key. |
| +TestManagedFleetKeyFailureContinues: malformed, foreign-fleet or mismatched public/fingerprint |
| + object, registration 409/403, or registration unreachable past the boot deadline => key status |
| + written (root 0644), no CARLOS_SECRETS_KEY, managed-boot still completes and queues the edge, |
| + root admission still absent; agent starts joining and its heartbeat carries managed_key=<code>. |
| TestManagedFleetKeyHostEnv: CARLOS_SECRETS_KEY written atomically into host.env before bootstrap; |
| - private key absent from logs, breadcrumbs, errors, console requests and probe replies. |
| + private key absent from logs, breadcrumbs, errors, console requests, heartbeat and probe replies. |
| +TestManagedReadinessKeyStatus (console): heartbeat managed_key other than "" or "ok" => storage |
| + check State "fail" with the code's COPY reason, regardless of the probe; show/CLI status |
| + displays it through the existing readiness view; "ok" => probe decides (Task 5). |
| TestManagedFleetKeyDoor: valid active token for fleet/label, managed fleet, box in enrolled or |
| publishing state of op => 200; first key => changed=true, owner record + registry updated; |
| same key => changed=false, zero writes; different key already registered => 409, zero writes; |
| platform's own key => 400; key used by another fleet => 409; wrong/expired/revoked token, |
| BYO fleet, wrong op, box ready/failed/terminated, other account's fleet => identical 403; |
| - HostClaim => 409; rate-limited before any lookup; owner-door messages byte-identical to main. |
| -TestFleetSecretsKeyCoreParity: owner door through the extracted core keeps every existing |
| - response code/body/audit line; initialOnly=false still allows replacement exactly as before. |
| + HostClaim => 409; rate-limited before any lookup. |
| +TestFleetSecretsKeyCoreParity: owner door on BYO fleets through the extracted core keeps every |
| + existing response code/body/audit line; replacement still allowed exactly as before. |
| TestFleetSecretsKeyOwnerDoorManaged: owner door on a managed fleet => 409 (COPY), zero writes. |
| ``` |
| - [ ] **Step 2: Run the failing tests.** |
| -Run `GOFLAGS=-buildvcs=false go test ./internal/managedboot ./internal/host -run 'TestManagedFleetKey' -count=1` and `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedFleetKeyDoor|TestFleetSecretsKey(CoreParity|OwnerDoorManaged)|TestAPIFleetSecretsKey' -count=1`; expect FAIL. |
| +Run `GOFLAGS=-buildvcs=false go test ./internal/managedboot ./internal/host -run 'TestManagedFleetKey' -count=1` and `GOFLAGS=-buildvcs=false go test ./internal/console -run 'TestManagedFleetKeyDoor|TestManagedReadinessKeyStatus|TestFleetSecretsKey(CoreParity|OwnerDoorManaged)|TestAPIFleetSecretsKey' -count=1`; expect FAIL. |
| -- [ ] **Step 3: Extract the validation core without changing the owner door.** |
| +- [ ] **Step 3: Extract the validation core; refuse the owner door on managed fleets.** |
| Move fingerprint, platform-key, account-lock reread, sealed-values/instances replacement checks, owner record, registry write and audit into `registerFleetSecretsKey`; the handler maps typed errors back to today's exact bodies. |
| `initialOnly=true` refuses any registered fingerprint other than the presented one before the sealed-value checks run. |
| -The owner door refuses managed fleets with a COPY message naming that the fleet's first box registers its key. |
| +Per Paul rule 10 the owner door refuses managed fleets with a COPY message saying the fleet's first box registers its key; 2c designs replacement. |
| - [ ] **Step 4: Add the operation-bound managed door.** |
| Order: HostClaim refusal → limiter (reuse the enrol IP/global pair) → strict 4 KiB decode → registry fleet row (managed, owner account) → `fleetIdentityOK` → SQL box row `(fleet, label, op)` in `enrolled` or `publishing` → `registerFleetSecretsKey(..., initialOnly=true)` with actor `managed-box <fleet>/<label> op <op>`. |
| No general fleet-token access to owner routes; no key replacement authority. Bodies are COPY. |
| -- [ ] **Step 5: Implement box-side ensure + register and wire it into managed-boot.** |
| +- [ ] **Step 5: Implement box-side ensure + register; never fail the boot on it.** |
| -Runs as root after scrub. Root loads the committed fleet key from the fixed file `/etc/carlos/credentials` through `rootaws.LoadDefaultConfig` (`rootaws/config.go:17`, :38); no environment profile or shared-file selector is involved. |
| +Runs as root after scrub. Root loads the committed fleet key from the fixed file `/etc/carlos/credentials` through `rootaws.LoadDefaultConfig` (`rootaws/config.go:17`, :38). |
| Open the fleet bucket with `lease.NewFilesStore(ctx, bucket, bucketRegion)`; it carries no change index, so a key PUT bumps nothing in the deployment store. |
| -Register after the object is confirmed; 503/429 retried, 409/403 stop the key step and leave the box joining without CARLOS_SECRETS_KEY. |
| -Without the key the agent's config sync stays disabled (`agent.go:1797`) and `storage` stays pending with the Task 5 fingerprint reason, so a fleet whose key cannot be established never reaches ready. |
| +Register after the object is confirmed; 503/429 retried within the boot deadline. Any key failure writes `KeyStatusPath` and continues: boot completes, the agent starts with workload admission closed (no root admission exists), and the heartbeat carries the code so the console's storage check reports `fail` with a reason through the existing CLI status path. |
| +Without the key the agent's config sync stays disabled (`agent.go:1797`), and the box can never reach ready, so a fleet whose key cannot be established never runs workloads. |
| The object holds the private half in plaintext under SSE-S3, which Paul accepted in addendum P2; the policy grants no delete on it. |
| - [ ] **Step 6: Repeat Step 2 to PASS and commit.** |
| -Mutation checks (≤8): unconditional PUT; trust local mint after a CAS conflict; register before object confirmation; initialOnly ignored; skip op/state check; accept BYO fleet; skip fingerprint/public consistency; owner door left open on managed fleets. |
| +Mutation checks (≤8): unconditional PUT; trust local mint after a CAS conflict; register before object confirmation; initialOnly ignored; skip op/state check; accept BYO fleet; key failure aborts the boot; owner door left open on managed fleets. |
| Commit subject: `feat: first managed box mints and registers the fleet key`. |
| ### Task 5: Prove storage and the router path to the exact box |
| **Files:** |
| - Create: `internal/managedboot/probe.go`, `probe_test.go`. |
| -- Create: `internal/edge/fleetprobe.go`, `fleetprobe_test.go`; modify `internal/edge/edge.go` (tunnel-host branch at :1994, header scrub near :2055), `internal/edge/mesh.go` (new domain), `internal/tunnelclient/tunnelclient.go` (header beside :272). |
| +- Create: `internal/edge/fleetprobe.go`, `fleetprobe_test.go`; modify `internal/edge/edge.go` (tunnel-host branch at :1994, header scrub at :2056 and :3857), `internal/edge/mesh.go` (new domain), `internal/tunnelclient/tunnelclient.go` (header beside :272). |
| - Create: `internal/host/managedprobe.go`, `managedprobe_test.go`. |
| -- Create: `internal/console/managedprobe.go`, `managedprobe_test.go`; modify `managedready.go` only if a reason string changes (COPY). |
| +- Create: `internal/console/managedprobe.go`, `managedprobe_test.go`. |
| **Interfaces:** |
| -- Consumes: `(*TunnelHub).transportFor(name string) http.RoundTripper` (`tunnel.go:487`, exact channel, no fallback); `tunnelclient.FromTunnel`; mesh keys via `(*Server).edgeProofKeys(ctx context.Context) (current, next []byte)` (`console/edgeproof.go:126`) and the edge's mirrored current/next keys; `managedExtraChecks.Checks(context.Context, managedBox) (storage, router managedCheck, err error)` (`managedready.go:14`); 2b-1 `managed_fleet_delivered_keys`; Task 3 `managedJoin` identity/state; Task 4 `FleetKeyObject`; `lease.NewFilesStore`. |
| +- Consumes: `(*TunnelHub).transportFor(name string) http.RoundTripper` (`tunnel.go:487`, exact channel, no fallback); `tunnelclient.FromTunnel`; mesh keys via `(*Server).edgeProofKeys(ctx context.Context) (current, next []byte)` (`console/edgeproof.go:126`) and the edge's mirrored current/next keys (`mesh.go:163`, `signingKey` :172); `managedExtraChecks.Checks(context.Context, managedBox) (storage, router managedCheck, err error)` (`managedready.go:14`); 2b-1 `managed_fleet_delivered_keys`; Task 2 `Identity`; Task 3 `managedJoin`; Task 4 `FleetKeyObject`, heartbeat `managed_key`; `lease.NewFilesStore`. |
| - Produces (**new**): |
| - `type ProbeRequest struct { Fleet, Label, Op, Nonce string; Storage bool }`; `type ProbeReply struct { Fleet, Label, Op, Nonce string; Storage ProbeStorage; SecretsKeyFP string "secrets_key_fp" }`; `type ProbeStorage struct { OK bool "ok"; KeyID string "key_id"; Code string "code" }`; strict decoders, 1 KiB request / 4 KiB reply caps. |
| - Edge: `const fleetProbePath = "/__carlos/fleet-probe"`, `const managedProbePath = "/__carlos/managed-probe"`, `const fleetProbeDomain = "carlos-fleet-probe\x00"`, `const fleetProbeAuthHeader = "X-Carlos-Fleet-Probe-Auth"`, `const fleetProbeChannelHeader = "X-Carlos-Probe-Channel"`; `func signFleetProbe(key []byte, channel string, body []byte, now time.Time) string`; `func verifyFleetProbeEitherKey(current, next []byte, channel, header string, body []byte, now time.Time) bool`; `func (e *Edge) serveFleetProbe(w http.ResponseWriter, r *http.Request)`; `func (e *Edge) serveManagedProbe(w http.ResponseWriter, r *http.Request)`; `type ManagedProbeResponder interface { Respond(ctx context.Context, req managedboot.ProbeRequest) (managedboot.ProbeReply, error) }` set by an `edge.RunOption`. |
| @@ -470,12 +538,13 @@ TestManagedProbeResponder: joining box answers before any route exists and befor |
| not FromTunnel or header absent => 404; storage=true => PUT/GET/DELETE of |
| _carlos/probes/<label>/<nonce> with the delivered credentials, body round-trip compared, |
| KeyID = credentials file access key ID (never the secret); S3 failure => ok=false with code; |
| - SecretsKeyFP from the installed key; one probe at a time per box. |
| + SecretsKeyFP from the installed key ("" when absent); one probe at a time per box. |
| TestManagedProbeChecks (console): router pass only on 200 + channel header + exact echo; |
| storage pass only when ok=true, key_id in managed_fleet_delivered_keys for fleet/account, and |
| - secrets_key_fp nonempty and equal to the registry fleet fingerprint; independent results |
| - (router pass + storage pending, and reverse); hub unreachable => both pending, err nil; |
| - replayed reply with old nonce => pending; reasons COPY; HostClaim => no probe. |
| + secrets_key_fp nonempty and equal to the registry fleet fingerprint; a Task 4 key-status |
| + failure keeps storage "fail" whatever the probe says; independent results (router pass + |
| + storage pending, and reverse); hub unreachable => both pending, err nil; replayed reply with |
| + old nonce => pending; reasons COPY; HostClaim => no probe. |
| TestManagedProbeBudget: enrolled box, 10 readiness passes inside 60 s => one probe; ready or |
| failed boxes => zero probes; idle worker => zero; each probe => exactly 3 fleet-bucket calls. |
| ``` |
| @@ -487,16 +556,16 @@ Run `TMPDIR=<owned-short-dir> GOFLAGS=-buildvcs=false go test ./internal/edge ./ |
| - [ ] **Step 3: Add the hub endpoint and box responder.** |
| Hub branch: only on the reserved tunnel host, `POST`, clean path, before `e.tunnels.ServeHTTP`; verify MAC over channel, timestamp and body; forward with `transportFor(channel)` to `managedProbePath` carrying `ManagedProbeHeader: 1`; never call `fleetChannelFor` (its `ConnectedOfFleet` fallback, `edge.go:3898`, is exactly the sibling hazard). |
| -Box branch: before demo/route lookup and before `admissionRefuses`, only when `FromTunnel(ctx)` and the header is set; responder checks fleet/label against identity and op against the managed state. |
| -The agent passes the responder to the edge through a new `edge.RunOption` only when `managedJoin` is non-nil; BYO boxes keep answering the path with the ordinary 404. |
| -The responder runs as the carlos user, so its S3 client uses the normal SDK chain with `AWS_SHARED_CREDENTIALS_FILE=/etc/carlos/credentials` (root:carlos 0640), the same file the hibernate lease uses. |
| -Strip `ManagedProbeHeader` and `fleetProbeChannelHeader` from every inbound request next to the existing `ReplicaProbeHeader` scrub (`edge.go:2056`) and from proxied requests (`:3857`), so neither a visitor nor an app can set them. |
| +Box branch: before demo/route lookup and before `admissionRefuses`, only when `FromTunnel(ctx)` and the header is set; responder checks fleet/label against identity and op against it too. |
| +The agent passes the responder to the edge through a new `edge.RunOption` only on a managed box; BYO boxes keep answering the path with the ordinary 404. |
| +The responder runs as the carlos user; its S3 client uses the normal SDK chain with `AWS_SHARED_CREDENTIALS_FILE=/etc/carlos/credentials` (root:carlos 0640), the file the hibernate lease uses. |
| +Strip `ManagedProbeHeader` and `fleetProbeChannelHeader` from every inbound request next to the existing `ReplicaProbeHeader` scrub (`edge.go:2056`) and from proxied requests (`:3857`). |
| The mesh key's existing rotation (current/next) applies unchanged; the new MAC domain keeps probe signatures unusable as hop or door marks and vice versa. |
| - [ ] **Step 4: Bridge into readiness.** |
| `Checks` builds a fresh 32-byte hex nonce, signs with the edge's signing-key rule over the console's mirrored keys, POSTs to `https://<TunnelHost>/__carlos/fleet-probe` with a 10 s timeout and no redirects, and maps results as the tests pin. |
| -Transport/hub failures return pending checks with `err == nil` so 2a's existing "pending unless pass" handling applies. |
| +Transport/hub failures return pending checks with `err == nil` so 2a's "pending unless pass" handling applies. |
| - [ ] **Step 5: Repeat Step 2 to PASS and commit.** |
| @@ -508,7 +577,7 @@ Commit subject: `feat: real storage and router readiness for managed boxes`. |
| **Files:** |
| - Modify: `cmd/console/main.go` (Config at :482; provider construction beside the app-store backend at :1065); `internal/console/server.go` (`NewServer` :1783 sets `managedExtra`); `internal/console/managedworker.go` (one console-output read at failure). |
| - Create: `internal/awsmanaged/integration_2b2_test.go` (package `awsmanaged_test`, uses 2b-1's `NewComputeWith`/`NewStorageWith`); `internal/console/managed2b2_test.go`; extend `managedbudget_test.go`, `managed_e2e_test.go`. |
| -- Docs: `docs/site/cli.md` gains no command; add a short operator note on the opt-in variables in the existing self-hosting/operator doc that lists console env (COPY), stating managed fleets stay off by default. |
| +- Docs: `docs/site/cli.md` gains no command; add a short operator note on the opt-in variables in the existing operator doc that lists console env (COPY), stating managed fleets stay off by default. |
| **Interfaces:** |
| - Consumes: 2b-1 `awsmanaged.NewCompute`, `NewStorage`, configs and module outputs; Tasks 1-5. |
| @@ -521,22 +590,27 @@ Commit subject: `feat: real storage and router readiness for managed boxes`. |
| ```text |
| TestManagedProvidersFromEnv: backend unset => nil, nil, "" (admission keeps 503); |
| backend=aws with any variable missing/invalid (non-12-digit account, empty boundary, root |
| - user path, empty prefix, region not in list) => error naming the variable, console start |
| - fails like the app-store backend; valid => both providers non-nil, ManagedDeployment set; |
| - backend=fake or other value => error. No real network: rootaws with dummy creds, IMDS off. |
| + user path, empty prefix, region not in list) or CARLOS_RELEASE_KEY absent (no signing key for |
| + ready.json) => error naming the variable, console start fails like the app-store backend; |
| + valid => both providers non-nil, ManagedDeployment set; backend=fake or other => error. |
| + No real network: rootaws with dummy creds, IMDS off. |
| TestManagedExtraWired: NewServer with TunnelHost + providers => managedExtra is the probe bridge; |
| without TunnelHost => nil (storage/router stay pending). |
| TestManaged2B2OneBox (console fakes + real handlers + real managedboot/host code against a fake |
| - root, fake hub, fake fleet bucket): create --boxes 1 => Boot frozen => UserData rendered => |
| - seed fetched => trade => staged => key minted/registered => stable installed => joining |
| - heartbeat => six checks pass => ready.json create-only PUT => box admits on serial bump => |
| - shop (native) record placed after ready reconciles and starts; nothing started before. |
| + root, fake hub, fake fleet bucket, fake root door): create --boxes 1 => Boot frozen => UserData |
| + rendered => seed fetched => trade => staged => key minted/registered => stable installed => |
| + edge queued => joining heartbeat => six checks pass => signed ready.json create-only PUT => |
| + agent relays => root commits => shop (native) record placed after ready reconciles and starts; |
| + nothing started before root's record. |
| +TestManaged2B2KeyFailureStatus: malformed key object in the fake bucket => boot completes, agent |
| + joining, heartbeat managed_key=object_invalid, `carlos fleets show` (CLI against the handler) |
| + prints storage failed with the COPY reason; no ready.json, no workloads; deadline cleanup. |
| TestAWSManaged2B2Recovery (awsmanaged_test, mocked transport): lost RunInstances reply => |
| same instance found, UserData bytes identical across adapter reconstruction; storage prepared |
| once; credentials delivered once and recorded in the delivered set. |
| -TestManaged2B2ConsumedPublicationUncertain: PUT succeeds, console verify GET fails/mismatches => |
| - console stays publishing+uncertain, quota held, zero revoke/terminate calls; box admitted and |
| - serving; next verify pass resolves to ready with no second PUT. |
| +TestManaged2B2ConsumedPublicationUncertain: PUT succeeds, root commits admission, console verify |
| + GET fails/mismatches => console stays publishing+uncertain, quota held, zero revoke/terminate |
| + calls; box admitted and serving; next verify pass resolves to ready with no second PUT. |
| TestManaged2B2Diagnostics: box fails at the 20-minute deadline => exactly one ConsoleOutput call, |
| sanitized codes persisted, show reports the last code; enrol/tunnel/access/private-key |
| sentinels absent from show, progress, logs and persisted rows; no ConsoleOutput while healthy. |
| @@ -553,7 +627,7 @@ Run `GOFLAGS=-buildvcs=false go test ./cmd/console ./internal/console -run 'Test |
| - [ ] **Step 3: Construct providers only on explicit opt-in.** |
| -Follow the app-store backend's precedent (`main.go:1065-1072`): opted-in but incomplete configuration is a fatal start error with a precise message (COPY); not opted in leaves both providers nil. |
| +Follow the app-store backend's precedent (`main.go:1065-1072`): opted-in but incomplete configuration, including a missing `Config.Key`, is a fatal start error with a precise message (COPY); not opted in leaves both providers nil. |
| Never substitute a fake. `enabled` in `system/managed-fleets.json` remains the admission switch. |
| - [ ] **Step 4: Record breadcrumbs once on failure.** |
| @@ -562,14 +636,14 @@ When a launched box fails its readiness or enrolment deadline, call `ConsoleOutp |
| - [ ] **Step 5: Repeat Step 2 to PASS, then run the final local gate once.** |
| -`TMPDIR=<owned-short-dir> GOFLAGS=-buildvcs=false go test -race ./internal/managedboot ./internal/host ./internal/provision ./internal/instancectl ./internal/edge ./internal/console ./internal/awsmanaged ./cmd/console -run 'TestManaged|TestReconcileJoining|TestFleetProbe|TestFleetSecretsKey|TestAWSManaged2B2|TestManagedCoreImports|TestStoreDoorManagedReady' -count=1`. |
| +`TMPDIR=<owned-short-dir> GOFLAGS=-buildvcs=false go test -race ./internal/managedboot ./internal/host ./internal/provision ./internal/instancectl ./internal/edge ./internal/status ./internal/console ./internal/awsmanaged ./cmd/console -run 'TestManaged|TestReconcileJoining|TestFleetProbe|TestFleetSecretsKey|TestAWSManaged2B2|TestManagedCoreImports|TestStoreDoorManagedReady' -count=1`. |
| `GOFLAGS=-buildvcs=false go build -o <owned-disk-scratch>/carlos .` and `./cmd/console`; targeted `go vet` on touched packages; gofmt on touched files. |
| Full suites and cross-builds run on amadan CI before landing. Report real failures; do not loop full suites. |
| - [ ] **Step 6: Census, copy inventory and commit.** |
| -`make census-card`; per-unit CLAIMS in owned scratch; `make census-propose NAME=managed-fleets-2b2 CLAIMS=<file>` covering host/edge/provision/instancectl/activator wiring/managedboot units, the seed/key/probe doors, registry key writes and the box-token authority change. |
| -Hand the controller the COPY inventory (refusals, readiness reasons, show text, operator doc lines). |
| +`make census-card`; per-unit CLAIMS in owned scratch; `make census-propose NAME=managed-fleets-2b2 CLAIMS=<file>` covering host/edge/provision/instancectl/activator wiring/managedboot/status units, the seed/key/probe/root-admission doors, registry key writes, the signed ready-object writer and the box-token authority change. |
| +Hand the controller the COPY inventory (refusals, readiness reasons, key-status reasons, show text, operator doc lines). |
| Commit subject: `feat: wire managed fleet providers behind an opt-in switch`. |
| ### Task 7: Prepare the dev drill card; run it only after Paul approves |
| @@ -580,31 +654,37 @@ Commit subject: `feat: wire managed fleet providers behind an opt-in switch`. |
| **Interfaces:** |
| - Consumes: everything above, released; 2b-1 Task 5 module variables/outputs; `system/managed-fleets.json` shape (`internal/release/managedfleets.go:7`). |
| -- Produces: one approved, executed and cleaned-up drill, or a card awaiting approval. Nothing live happens before Paul's explicit approval of the card as written. |
| +- Produces: a card with every value filled from read-only preflight, then (after Paul's approval only) one executed and cleaned-up drill. |
| **Census/review:** No code. The card itself gets one Astra read for completeness before it goes to Paul. |
| -- [ ] **Step 1: Write the card with every value concrete (fresh read-only checks are part of approval, not done before it).** |
| +- [ ] **Step 1: Run the read-only preflight needed to fill the card.** |
| + |
| +Allowed before approval, all with `--profile kass` and read-only: `aws ec2 describe-images` for the current Debian 13 arm64 AMI (pin its ID and root device), `describe-vpcs`/`describe-subnets`/`describe-route-tables` for the VPC/subnet below, `describe-security-groups` to confirm the drill SG name is free, and `tofu plan` (no apply) in platform-infrastructure dev with the release ref and `managed_fleets_enabled = true`; attach the inspected plan output to the card. Read the dev console's `CARLOS_HOST_CLAIM` setting. |
| +Nothing that creates, modifies or deletes anything runs before Paul's approval: no apply, no SG creation, no config write, no release roll, no launch. |
| + |
| +- [ ] **Step 2: Write the card with every value concrete.** |
| | Item | Value on the card | |
| |---|---| |
| | Account / profile | dev deployment account 640012953448, AWS profile `kass` (always named explicitly) | |
| -| Region / network | eu-west-1; default VPC vpc-02212d67a9fca3b20; subnet-0975dda9ac0e65347 (eu-west-1c); verify both exist and the subnet has an internet-gateway default route before launch | |
| -| Image | current Debian 13 arm64 EBS AMI, pinned by ID on the card after a fresh describe (historical ami-071babd89cea53fa3 is only a starting point) | |
| +| Region / network | eu-west-1; default VPC vpc-02212d67a9fca3b20; subnet-0975dda9ac0e65347 (eu-west-1c); preflight confirms existence and an internet-gateway default route | |
| +| Image | the Debian 13 arm64 EBS AMI ID pinned by the preflight describe (historical ami-071babd89cea53fa3 is only a starting point) | |
| | Box | one t4g.small, 30 GiB encrypted gp3, IMDSv2 hop 1, no instance profile, no key pair, no SSM | |
| | Security group | new `carlos-managed-drill` in that VPC: no inbound; egress tcp/443 to 0.0.0.0/0 and ::/0 only (console, hub, store, S3, Debian HTTPS mirror); NTP/DNS use link-local VPC services | |
| | Fleet / config | fleet `drill-2b` in an ops-owned dev account; `system/managed-fleets.json` enabled=true, ceiling=1, account_limit=1, size `small` → t4g.small, that image/subnet/SG, root_gb 30 | |
| -| IAM / infra | platform-infrastructure dev: module ref bump to the release containing 2b-1 + 2b-2, `managed_fleets_enabled = true`, inspected `tofu plan` attached to the card before apply | |
| -| Console | dev console on sophie (console.service) with the Task 6 env; confirm `CARLOS_HOST_CLAIM` is off there (decisions rule 7) or the drill stops | |
| +| IAM / infra | platform-infrastructure dev: module ref bump to the release containing 2b-1 + 2b-2, `managed_fleets_enabled = true`; the inspected `tofu plan` from Step 1 is attached | |
| +| Console | dev console on sophie (console.service) with the Task 6 env and `CARLOS_RELEASE_KEY` present; `CARLOS_HOST_CLAIM` off there (decisions rule 7) or the drill stops | |
| | Release | release tag; dev stable pointer must name that release (its linux-arm64 artifact is the seed and the installed binary); roll order dev boxes → dev console | |
| | Cost cap / TTL | ≤ US$5 total; window ≤ 4 h attended; abort and clean up at TTL whatever the state | |
| | Isolation | r10r and every existing fleet untouched; no shared SG, role or bucket | |
| -- [ ] **Step 2: Write the exact verification list.** |
| +- [ ] **Step 3: Write the exact verification list.** |
| ```text |
| V1 CLI: carlos fleets create drill-2b --managed --region eu-west-1 --size small --boxes 1 |
| - returns an op; show reports each phase; six checks reach pass; ready.json exists once. |
| + returns an op; show reports each phase; six checks reach pass; ready.json exists once, |
| + signed, and verifies with the deployment's release public key. |
| V2 Console output contains only CARLOS_BOOT codes, ending at joining; no token/secret text. |
| V3 Before ready.json: box heartbeat shows the stable version; no instance unit ever started. |
| V4 shop (native) and a rootfs sample placed after ready serve at their public URLs. |
| @@ -616,7 +696,7 @@ V7 Fleet key object exists once; registry fingerprint equals it. |
| V8 Request counts from the console's budget counters match Task 6's numbers for the window. |
| ``` |
| -- [ ] **Step 3: Write the exact cleanup list (part of the approval).** |
| +- [ ] **Step 4: Write the exact cleanup list (part of the approval, Paul rule 11).** |
| ```text |
| C1 system/managed-fleets.json enabled=false (admission off first). |
| @@ -626,14 +706,14 @@ C3 Fleet bucket: delete every object version and delete marker (list-object-ver |
| abort multipart uploads, then delete the bucket; confirm 404. |
| C4 IAM user: list and delete every access key, delete the inline policy, delete the user. |
| C5 Delete the drill SG after the ENI is gone. |
| -C6 Console/registry rows for drill-2b remain until 2d removal exists (see decision for Paul); |
| - record them in the log; no raw SQL edits. |
| +C6 The dev console keeps the drill-2b fleet and box rows; record them in the drill log; they |
| + are removed through 2d's removal path. No hand DB edits. |
| C7 Leave infra at managed_fleets_enabled=true or revert per Paul's instruction on the card. |
| ``` |
| -- [ ] **Step 4: Hand the card to the controller for Paul; stop.** |
| +- [ ] **Step 5: Hand the card to the controller for Paul; stop.** |
| -Do not run any step of the drill without Paul's explicit approval of this card. After approval, execute V1-V8 then C1-C7, log each command and result in the drill log, and remove local scratch. |
| +Do not run any mutating step without Paul's explicit approval of this card. After approval, execute V1-V8 then C1-C7, log each command and result in the drill log, and remove local scratch. |
| Commit subject (card only): `docs: managed fleets 2b-2 dev drill approval card`. |
| ## Landing (controller) |
| @@ -649,55 +729,74 @@ Merge only on Paul's go with `amadan branch merge carlos/platform managed-fleets |
| | Rule 1: no profile/SSH/SSM, dedicated egress-only SG | 2b-1 adapter request; Task 2 never needs IMDS credentials; Task 7 SG | |
| | Rule 7: HOST_CLAIM refusal stays | Tasks 1, 4, 6 refusal tests on every new door | |
| | Rule 8 pairing | Superseded for 2b-2 by the controller brief (Opus implements; Astra/Fable review) | |
| -| §4 enrolment: one-time token, no long-lived secret in user data/logs | Task 1 renderer/secrets test; Task 2 trade, scrub, wire | |
| -| §4 port #183 hardening: allowlists, IMDS gate, shredding cloud-init copies | Task 1 allowlist + nft in template; Task 2 IMDS check + scrub | |
| +| Rule 9: console seed door to an unused token | Task 1 seed door, script-run test | |
| +| Rule 10: owner door refuses on managed fleets until 2c | Task 4 `TestFleetSecretsKeyOwnerDoorManaged` | |
| +| Rule 11: drill deletes all AWS resources, keeps console rows, no DB edits | Task 7 C1-C7 | |
| +| §4 enrolment: one-time token, no long-lived secret in user data/logs | Task 1 renderer/secrets tests; Task 2 trade, scrub, wire | |
| +| §4 port #183 hardening: allowlists, IMDS gate, shredding cloud-init copies | Task 1 allowlist + nft in template; Task 2 firewall ordering + scrub | |
| | §4 fetch binary through the store door and verify as platform boxes do | Task 2 stable pointer + artifact via store door; Task 1 seed by digest | |
| | 2a hard req: install current verified stable, never stale bootstrap | Task 2 `installManagedStable`, `TestManagedBootStableTrust` | |
| -| 2a hard req: durable marker before any reconcile/start; survives reboot | Task 2 commit includes joining state; Task 3 gate + reboot matrix | |
| -| 2a hard req: ownsRecord false for labelled/unlabelled/static; every start path refuses | Task 3 `TestReconcileJoiningOwnsNothing`, `TestManagedJoinStartSurfaces` | |
| +| 2a hard req: durable marker before any reconcile/start; survives reboot | Task 2 identity commit; Task 3 root record + reboot matrix | |
| +| 2a hard req: ownsRecord false for labelled/unlabelled/static; every start path refuses | Task 3 `TestReconcileJoiningOwnsNothing`, `TestManagedJoinStartSurfaces` incl. root adoption/config-sync/recovery | |
| | 2a hard req: ready GET only while joining, per serial or 60 s; zero after | Task 3 ready leg tests; Task 6 budget | |
| -| 2a hard req: ready.json console-written only | 2b-1 Task 6 ACL consumed; Task 7 V6 live check | |
| -| Gate absent must not fail open | Task 2 `TestManagedStateFailClosed`; Task 3 deleted-state test | |
| +| 2a hard req: ready.json console-written only | 2b-1 Task 6 ACL; Task 3 console signature verified by root; Task 7 V6 | |
| +| Gate absent must not fail open; root never trusts agent-written state | Task 3 `RootAdmission`, `TestManagedRootAdmissionForgery` | |
| | §4 born examined: first report lists data dir empty | Task 2 attestation before any /data write | |
| -| §4 ready means ready: six checks incl. storage and router probe | Task 5 real checks bridged into `managedExtraChecks` | |
| -| §4 diagnostics: breadcrumbs, launch errors, failed check visible | Task 2 codes; Task 6 one ConsoleOutput read + show; Task 5 reasons | |
| +| §4 ready means ready: six checks incl. storage and router probe | Task 5 real checks; Task 4 key status into storage | |
| +| §4 diagnostics: breadcrumbs, launch errors, failed check visible | Task 2 codes; Task 4 heartbeat key status; Task 6 ConsoleOutput + show | |
| +| Box actually starts serving after boot | Task 2 `TestManagedBootStartPlan` (`--no-block` edge start) | |
| +| Reboot after platform self-update | Task 2 `TestManagedBootUpdateReboot` | |
| | Addendum P1: key once in enrolment reply, never user data | Task 1 secrets test; Task 2 staging; Task 6 recovery test | |
| -| Addendum P2: first box mints, registers via existing door, private half in fleet bucket; later boxes read it | Task 4 (later-box read covered by `TestManagedFleetKeyLaterBox`; many-box add flows 2c) | |
| +| Addendum P2: first box mints, registers via existing door, private half in fleet bucket; later boxes read it | Task 4 (later-box read covered; many-box add flows 2c) | |
| | "No parallel key path" | Task 4 extracted core shared by both doors | |
| | §5 provider boundary + import test | managedboot added to `TestManagedCoreImports`; AWS only via 2b-1 | |
| -| §6 request budget with stated numbers and a counting test | Global Constraints numbers; Tasks 3, 5, 6 budget tests | |
| +| §6 request budget with stated numbers and a counting test | "Request budget" table; Tasks 3, 5, 6 budget tests | |
| | §7 switch-on after an approved dev drill | Task 7 card; enabled stays false until then | |
| | §8.1 checks shown passing (one box here; three in 2c) | Task 6 `TestManaged2B2OneBox`; Task 7 V1 | |
| | §8.2 apps serve after ready (custom domain 2c) | Task 6 composed; Task 7 V4 | |
| | §8.4 box credentials cannot reach deployment/other fleet bucket | 2b-1 policy fixtures; Task 7 V6 live | |
| | §8.5 secrets never in logs/progress/pages | Tasks 1, 2, 4, 6 sentinel tests; Task 7 V2 | |
| -| §8.6 reboot recovery (managed box) | Task 2/3 reboot matrices; Task 7 V5 | |
| +| §8.6 reboot recovery (managed box) | Tasks 2/3 reboot matrices; Task 7 V5 | |
| | §8.8 docs and copy review | Task 6 operator note; COPY inventory to controller | |
| | C08 consumed publication | Review Focus 2; Tasks 3 and 6 | |
| | Frozen retry bytes | Task 1 golden + `TestManagedBootFrozenAtLaunch`; Task 6 adapter recovery | |
| -Type check: `managedboot.Frozen`, `LaunchInput`, `State`, `Identity`, `FleetKey`, `ProbeRequest`/`ProbeReply` are defined once (Tasks 1, 2, 4, 5) and consumed by later tasks with the same names. |
| +Type check: `managedboot.Frozen`, `LaunchInput`, `Identity`, `ReadyRecord`, `FleetKey`, `KeyStatus`, `ProbeRequest`/`ProbeReply` are defined once (Tasks 1-5) and consumed by later tasks with the same names; the earlier agent-writable `State` type is gone. |
| Every Review Focus line names a test in its owning task. No implementation bodies are prescribed; tests list observable assertions. |
| Not covered here by design: hub fallback for unlabelled routes can pick a joining box (`fleetChannelFor`, `edge.go:3889`); harmless with one box and no prior apps, listed for 2c. |
| -Dependency order: Task 1 defines the frozen inputs and wire the box consumes; Task 2 produces the durable identity/state Task 3 gates on; Task 4 runs inside Task 2's state machine and needs Task 3 only for the box staying joining on failure; Task 5 needs Task 3's identity and Task 4's fingerprint; Task 6 composes all of them with 2b-1's adapters; Task 7 needs a release containing both slices. |
| -Proportion: seven tasks for roughly 11 recon requirements; code blocks are test assertions only. |
| +Dependency order: Task 1 defines the frozen inputs and wire the box consumes; Task 2 produces the root-owned identity Task 3 verifies against; Task 4 runs inside Task 2's state machine and relies on Task 3 keeping the box closed on failure; Task 5 needs Task 2's identity and Task 4's fingerprint; Task 6 composes all of them with 2b-1's adapters; Task 7 needs a release containing both slices. |
| -## Decisions only Paul can make |
| +## Paul's rulings recorded (decisions.md 9-11, 2026-11-08) |
| -1. **Seed delivery.** The first executable must come from somewhere before the box holds any credential. This plan has the console stream the frozen stable artifact to an unused, unexpired enrolment token (Task 1). Alternatives: a public artifact URL, or an operator-baked AMI. Recommendation: the token-bound console seed door; it adds no public binary endpoint and no image pipeline. |
| -2. **Owner key registration on managed fleets.** If the owner registers a key with `carlos fleets secrets-key` before the first box does, no box can ever hold its private half. This plan refuses the owner door on managed fleets until 2c designs replacement. Recommendation: refuse. |
| -3. **Drill residue.** Removal is 2d, so after the drill the dev console keeps the `drill-2b` fleet and box rows (box shown ready but terminated). Recommendation: keep them, recorded in the drill log, and delete them through 2d's removal path; clean every AWS resource fully; no raw SQL. |
| +1. **Seed delivery (rule 9).** The console streams the frozen signed stable binary through `POST /api/fleet/enrol/seed` to an unused enrolment token without consuming it; no public URL and no custom AMI. Implemented in Task 1. |
| +2. **Owner key registration on managed fleets (rule 10).** `carlos fleets secrets-key` refuses on managed fleets until 2c designs key replacement. Implemented in Task 4. |
| +3. **Drill leftovers (rule 11).** Every AWS resource is deleted (instance, bucket including all versions, IAM user and keys, SG); the dev console keeps the `drill-2b` fleet and box records, noted in the drill log and removed via 2d; no hand DB edits. Implemented in Task 7. |
| ## Deferred to 2c/2d |
| - **2c:** Many real boxes and `boxes add` with key consumption at scale; three-box §8.1 acceptance; partial-capacity drill; custom-domain serving. |
| - **2c:** Hub fallback (`fleetChannelFor` step 2) must skip joining boxes so a second box joining an active fleet cannot receive unlabelled app traffic it will refuse. |
| - **2c:** Multiple hubs behind one tunnel hostname: a probe landing on a hub without the channel reports pending; hub-to-hub probe forwarding is not built. |
| -- **2c:** Fleet secrets-key replacement or recovery for managed fleets (owner door stays refused on managed fleets here); re-credentialing boxes stranded by 2b-1's needs-operator state. |
| -- **2c:** Full bootstrap diagnostics beyond the six breadcrumb codes; richer show output. |
| +- **2c:** Fleet secrets-key replacement or recovery for managed fleets (owner door stays refused, rule 10); re-credentialing boxes stranded by 2b-1's needs-operator state. |
| +- **2c:** Full bootstrap diagnostics beyond the six breadcrumb codes and the key-status codes; richer show output. |
| - **2d:** Member box and fleet removal, drain/wait/terminate/detach; deletion of drill-era console rows through that path. |
| - **2d:** 30-day last-box bucket retention, revival by add, version/delete-marker reaping by the platform rather than by hand. |
| - **2d:** Hourly regional orphan sweep with 24-hour grace. |
| - **Later:** `CARLOS_HOST_CLAIM` support through a trusted gated BEGIN IMMEDIATE seam; baked managed AMI instead of boot-time apt; phase 3 billing and VPC peering. |
| -- Carry N2 and the accepted 2a/2b-1 minors as follow-ups; this plan opens no review round. |
| +- Carry N2 and the accepted 2a/2b-1 minors as follow-ups. |
| + |
| +## Review history |
| + |
| +Round 1 (Astra, `/home/paulca/.cache/managed-fleets-2b-notes/review-2b2-r1.md`, verdict NOT READY): 6 P1, 2 P2, all accepted by the controller and fixed in this plan. This revision does not reset the round count. |
| + |
| +- P1-1 root admission authority: Fixed. Admission is a root-owned record in root-only `RootAdmissionDir` (0700), committed by the root door only after verifying the console's signed ready.json (`Config.Key`, the pointer-signing key; `{payload, sig}` wrapper) against the release public key in root-owned `managed-box.json`; the agent only relays. Task 3 `TestManagedRootAdmissionForgery`, `TestManagedRootAdmitVerify`, `TestManagedReadySigned`. |
| +- P1-2 complete start gating: Fixed. Task 3 gates `rootStartRoute` (`agent.go:5923` → `rootrestart.go:524-526`), `rootSelectedRestart`, rollback restart, `UnitOps.Restart` (`unitops.go:35`, `unitsync.go:459`), named-unit recovery, adoptLoop and configSyncLoop, preserving platform maintenance units; witnesses use valid named-unit declarations and pre-seeded routes. |
| +- P1-3 first-contact wire contract: Fixed. Task 1 separates `boot-input.json` (full LaunchInput) from token-only `seed-request.json`; the bounded re-exec runs `timeout 900 /bin/sh "$0"`; curl writes with `-o seed.part`; `TestManagedCloudInitScriptRun` runs the rendered script against the real seed handler with mocked system commands. |
| +- P1-4 boot completion: Fixed. Task 2 queues `systemctl start --no-block carlos-edge.service` after the durable complete marker, and again on every complete-path boot; `TestManagedBootStartPlan` covers interruption between completion and queueing. |
| +- P1-5 update-compatible reboot: Fixed. The complete path does not re-verify `/opt/carlos/carlos`; the initial digest applies only to first install, and integrity afterwards belongs to systemapply. `TestManagedBootUpdateReboot` covers update→reboot and interrupted update→recovery→reboot. |
| +- P1-6 reboot prerequisites: Fixed. The boot unit has `Requires=`/`After=nftables.service`, plus `Wants=`/`After=network-online.target` in an enrol drop-in removed at completion; `TestManagedBootFirewallOrdering` covers delayed restoration and failure. |
| +- P2-7 failure diagnostics: Fixed. Key failures never fail the boot; root writes `managed-key-status.json`, the agent starts closed and reports `managed_key` in its heartbeat, and the storage check fails with a reason in CLI status. Task 4 `TestManagedFleetKeyFailureContinues`, `TestManagedReadinessKeyStatus`; Task 6 `TestManaged2B2KeyFailureStatus`. |
| +- P2-8 concrete approval scope: Fixed. Task 7 Step 1 allows the read-only preflight (AMI and network describes, `tofu plan`) needed to fill the card; mutations and the drill wait for Paul's approval. |
| + |
| +Paul's rulings on this plan's three open questions are recorded above as decisions 9-11. |