carlos / platform Public

managed-fleets-1c-451

Squashed from managed-fleets-1c-451 into main.
claude agent, operated by paul@keymail.dev 4029ac561cc03327d6de078568b33800c4d30c6c parent a67f377
16 files changed, +1,069 −14
  • docs/superpowers/notes/census-proposal-managed-fleets-1c-451.md +27 −0
  • docs/superpowers/plans/2026-10-30-managed-fleets-1c-reboot-lease.md +221 −0
  • docs/superpowers/plans/CODEX-FINDINGS-MANAGED-FLEETS-1C-R1.md +26 −0
  • docs/superpowers/plans/CODEX-REVIEW-BRIEF-MANAGED-FLEETS-1C.md +39 −0
  • docs/superpowers/specs/2026-10-28-managed-fleets-design.md +406 −0
  • docs/superpowers/specs/CODEX-BUILDER-CHECK-MANAGED-FLEETS.md +11 −0
  • internal/activator/control.go +23 −3
  • internal/activator/control_test.go +29 −0
  • internal/hafresh/owner.go +37 −9
  • internal/hafresh/owner_boot_test.go +75 −0
  • internal/host/haself.go +17 −1
  • internal/host/haself_test.go +49 −0
  • internal/lease/legacytake.go +9 −1
  • internal/lease/previousboot_test.go +84 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-managed-fleets-1c-451.tsv +15 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-managed-fleets-1c-451.md b/docs/superpowers/notes/census-proposal-managed-fleets-1c-451.md
new file mode 100644
index 000000000..cd4c128c3
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-managed-fleets-1c-451.md
@@ -0,0 +1,27 @@
+# Census approval: managed-fleets-1c-451
+
+Ruling `census-ruling-managed-fleets-1c-451`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/activator/control.go` `systemctlControlGroup` | body | unchanged (1) | error path only: a failed systemctl show now returns unitStateError(err), appending systemctl's own stderr (<=200 bytes) to the error text for the log; the command, its arguments, the unit name and the parsing of a successful answer are unchanged |
+| `internal/activator/control.go` `systemctlUnitMainExit` | body | unchanged (1) | error path only: as systemctlControlGroup, unitStateError(err) on a failed systemctl show; command, arguments, unit name and parsing unchanged |
+| `internal/activator/control.go` `systemctlUnitState` | body | unchanged (1) | error path only: as systemctlControlGroup, unitStateError(err) on a failed systemctl show; command, arguments, unit name and parsing unchanged (#451 diagnosis: tells a lost D-Bus at shutdown from other failures) |
+
+Envelopes re-pinned: `internal/activator`, `internal/hafresh`, `internal/host`, `internal/lease`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/activator/control.go` `systemctlControlGroup`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input (J4, as systemctlUnitState): new (rootfs Plan 2 Task 9): runs systemctl show -p ControlGroup --value <unit> as carlos, an unprivileged query of PID 1, for a unit name built by unitNameFor from the row's host; the answer is systemd's own; it starts and stops nothing; no root decision
+- `internal/activator/control.go` `systemctlUnitMainExit`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-worker-exit;basis=new: runs `systemctl show -p InvocationID,ExecMainCode,ExecMainStatus,SuccessExitStatus <unit>` as the agent (no privilege), the same shape as systemctlUnitState and systemctlControlGroup; the unit name is the handle's own (unitNameFor/rootfsUnitFor), not tenant input; output parsed as four key=value strings into MainExit (Astra R1 P2: SuccessExitStatus is the unit's clean-exit policy as systemd loaded it from the shipped template)
+- `internal/activator/control.go` `systemctlUnitState`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/host/haself.go:readBootID`: reads +file:ReadFile; written legacy, accepted-legacy, frozen
+
+Seal: `8f6a1865b0abcea9d4fb68232cc2a25263a106ec87f73bd4b3f2fb388971ebe5` → `af326671321edda76c7e6217a47892605a9e3b886fa880ad6d049c2f28f63873`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-managed-fleets-1c-451.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-10-30-managed-fleets-1c-reboot-lease.md b/docs/superpowers/plans/2026-10-30-managed-fleets-1c-reboot-lease.md
new file mode 100644
index 000000000..0b3e1a442
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-30-managed-fleets-1c-reboot-lease.md
@@ -0,0 +1,221 @@
+# Managed fleets 1c: a rebooted box takes back its own lease (#451) Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** After a reboot, a box wakes its instances at once instead of waiting up to 15 minutes for the lock its own previous boot left behind.
+
+**Architecture:** The legacy (non-HA) lease owner string gains the kernel boot id. When a starting agent meets an unexpired non-HA lock written by this same EC2 instance under a different boot, it takes it, conditional on the ETag it read, exactly as it takes an expired lock today. Nothing from an earlier boot can still be running under a new kernel, so that lock is provably dead. Every other unexpired lock is still refused.
+
+**Tech Stack:** Go; `internal/hafresh` (owner vocabulary), `internal/lease` (acquire), `internal/host` (identity), `internal/activator` (diagnostic only).
+
+**Spec:** `docs/superpowers/specs/2026-10-28-managed-fleets-design.md` §4 Phase 1, item 1c. Bug: amadan #451. Investigation: §"Findings" below.
+
+## Findings (main d3908d93)
+
+- Owner string: `hafresh.OwnerFor` (`internal/hafresh/owner.go:34-45`) writes `box/v1;ref=<ref>;iid=<iid>;pid=<pid>[;ha=1]`. `ParseOwner` (`:52-97`) is strict.
+- `lease.currentOwner` (`internal/lease/self.go`) fills it with `os.Getpid()`; the agent names itself with `lease.SetSelf(haSelfNow(...))` (`internal/host/haself.go:25-28`, `agententry.go:47-48`). `iid` comes from IMDS, `ref` from `metricsBoxLabel`.
+- `LeaseTTL` is 15 min (`internal/lease/lease.go:40`).
+- The non-HA take is `takeLegacy` (`internal/lease/legacytake.go:55-66`): any unexpired lock is `*HeldError`; ownership is never compared. That is the 15 minutes.
+- #451 affects native instances too (leo on dev, 2026-10-26, ~13 min dark; `docs/superpowers/notes/dev-claim-trial-undo-log.md` on `design-live-moves-ha`, fdf30876).
+- Why shutdown can't prove the stop is unconfirmed. The leading guess: `systemctlUnitState` (`internal/activator/control.go:100-117`) runs as `carlos`, needs D-Bus, and D-Bus stops in parallel at shutdown; the error's stderr is discarded. Task 4 makes the next occurrence say so. The unit-ordering fix is a follow-up once confirmed; the takeover rule is needed regardless (power loss, kernel panic).
+
+## Global Constraints
+
+- Non-HA locks only. An HA owner (`;ha=1`) never carries `boot=`, and HA locks keep every current rule (`*HALockError` on the legacy path). Old binaries would misread an HA owner with an extra field as non-HA, so HA needs two releases and is out of scope.
+- Take only when ALL hold: the lock is not HA; `self.IID != ""` and equals the owner's `iid`; `self.Ref` equals the owner's `ref`; both boot ids are non-empty; they differ.
+- The take stays conditional on the classified ETag (`classifyAndTake`), at generation + 1. No new write path.
+- A box off EC2 (empty `iid`) or one that can't read its boot id behaves exactly as today.
+- Boot id source: `/proc/sys/kernel/random/boot_id`, trimmed. No build tags (on non-Linux the read fails and the field stays empty).
+- Local tests: only touched packages, with `-run` (AGENTS.md; CI runs the full suite). Cross-compile gate: darwin and windows must still build.
+- Copy: the one new log line is operator diagnostics, not copy-reviewed.
+
+## Review Focus
+
+1. **The agent restarts within one boot** (`systemctl restart carlos-edge`, a crash): the new process has a new pid but the same boot id, and its old instance units may still be running. Must stay `*HeldError`. Test in Task 3.
+2. **Two boxes cloned from one disk image** share `/etc/machine-id` (so maybe `ref`) but not `iid`. Must stay `*HeldError`. Test in Task 3.
+3. **A lock written by an older binary** (no `boot=` field) after an upgrade-and-reboot: no takeover (waits the TTL, as today). Test in Tasks 1 and 3.
+4. **An older binary on another box** reading a new owner string: it must still classify the lock as non-HA and held. Test in Task 1 (the string keeps `ha=` last and `HAOn()` false).
+5. **EC2 stop/hibernate-resume** keeps the boot id, so a hibernated box's lock is never taken. Covered by rule (same boot), asserted in Task 1's table.
+
+---
+
+### Task 1: The owner string carries the boot, and the previous-boot rule
+
+**Files:**
+- Modify: `internal/hafresh/owner.go`
+- Test: `internal/hafresh/owner_test.go`
+
+**Interfaces:**
+- Produces: `hafresh.Self` gains `Boot string` (NOT part of `Complete()`); `hafresh.Owner` gains `Boot string`; `func PreviousBoot(o Owner, self Self) bool`.
+
+- [ ] **Step 1: Write the failing tests**
+
+`TestOwnerForWritesBootOnlyWhenLegacy`:
+- `OwnerFor(Self{Ref: "r", IID: "i-1", Boot: "b1"}, 7, false)` == `"box/v1;ref=r;iid=i-1;pid=7;boot=b1"`.
+- `OwnerFor(Self{Ref: "r", IID: "i-1", Boot: "b1"}, 7, true)` == `"box/v1;ref=r;iid=i-1;pid=7;ha=1"` (no boot on HA).
+- `OwnerFor(Self{Ref: "r", Boot: ""}, 7, false)` == `"box/v1;ref=r;pid=7"`.
+
+`TestParseOwnerBoot`: round trip of the first string gives `Owner{Ref:"r", IID:"i-1", PID:7, Boot:"b1"}`; `"box/v1;ref=r;pid=7;boot=b1;ha=1"` is rejected (`ok == false`); `"box/v1;ref=r;pid=7;boot="` is rejected; every string the existing owner tests accept still parses identically; `hafresh.View{Lock: ...Owner: "box/v1;ref=r;iid=i-1;pid=7;boot=b1"}.HAOn()` is false.
+
+`TestPreviousBoot` (table, `self = Self{Ref:"r", IID:"i-1", Boot:"b2"}` unless stated):
+| owner | want |
+|---|---|
+| `{Ref:"r", IID:"i-1", Boot:"b1"}` | true |
+| `{Ref:"r", IID:"i-1", Boot:"b2"}` (same boot, any pid) | false |
+| `{Ref:"r", IID:"i-2", Boot:"b1"}` | false |
+| `{Ref:"x", IID:"i-1", Boot:"b1"}` | false |
+| `{Ref:"r", IID:"", Boot:"b1"}` | false |
+| `{Ref:"r", IID:"i-1", Boot:""}` (old binary) | false |
+| `{Ref:"r", IID:"i-1", Boot:"b1", HA:true}` | false |
+| self with `IID:""` | false |
+| self with `Boot:""` | false |
+
+- [ ] **Step 2: Run them to see them fail**
+
+Run: `go test ./internal/hafresh/ -run 'TestOwnerForWritesBootOnlyWhenLegacy|TestParseOwnerBoot|TestPreviousBoot'`
+Expected: FAIL (unknown field `Boot`, undefined `PreviousBoot`).
+
+- [ ] **Step 3: Implement**
+
+`OwnerFor` appends `;boot=<s.Boot>` after `pid` when `!ha && s.Boot != ""`. `ParseOwner` accepts an optional `boot` field after `pid` and before `ha`, but rejects `boot` together with `ha`. Update both doc comments to show the new shape. `PreviousBoot` implements the Global Constraints rule, with a comment saying why it is safe (a new kernel means no process of the old boot survives) and why HA is excluded.
+
+- [ ] **Step 4: Run them to see them pass**
+
+Run: `go test ./internal/hafresh/`
+Expected: PASS (whole package, including the existing owner and keep tests).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/hafresh/owner.go internal/hafresh/owner_test.go
+git commit -m "hafresh: legacy owners carry the boot id; PreviousBoot names a lock this box's earlier boot left (#451)"
+```
+
+### Task 2: The agent knows its boot
+
+**Files:**
+- Modify: `internal/host/haself.go`
+- Test: `internal/host/haself_test.go` (create if absent; else add)
+
+**Interfaces:**
+- Consumes: `hafresh.Self.Boot` (Task 1).
+- Produces: `haSelfNow` fills `Boot`; `var bootIDPath = "/proc/sys/kernel/random/boot_id"` (package var, for tests); `func readBootID(path string) string` returning the trimmed contents or `""` on any error.
+
+- [ ] **Step 1: Write the failing tests**
+
+`TestReadBootID`: a temp file containing `"3f1c...\n"` gives `"3f1c..."`; a missing path gives `""`; an empty file gives `""`.
+`TestHASelfNowCarriesTheBoot`: with `bootIDPath` pointed at a temp file holding `b9` and IMDS unreachable (the existing tests' pattern for `haSelfNow` with a client that fails), the result has `Boot == "b9"` and `Complete()` unchanged by `Boot`. Do not call `t.Parallel()` (the test sets a package var).
+
+- [ ] **Step 2: Run them to see them fail**
+
+Run: `go test ./internal/host/ -run 'TestReadBootID|TestHASelfNowCarriesTheBoot'`
+Expected: FAIL (undefined).
+
+- [ ] **Step 3: Implement**
+
+`haSelfNow` sets `Boot: readBootID(bootIDPath)`. Check `haSelfRetry`/`startHASelfRetry`: any `Self` it rebuilds goes through `haSelfNow`, so `Boot` is carried; if anything builds a `Self` another way, carry `Boot` there too.
+
+- [ ] **Step 4: Run them to see them pass**
+
+Run: `go test ./internal/host/ -run 'TestReadBootID|TestHASelfNowCarriesTheBoot|HASelf'`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/host/haself.go internal/host/haself_test.go
+git commit -m "host: the lease identity carries the kernel boot id (#451)"
+```
+
+### Task 3: The legacy take accepts this box's previous boot
+
+**Files:**
+- Modify: `internal/lease/legacytake.go:55-66`
+- Test: `internal/lease/ha_test.go`
+
+**Interfaces:**
+- Consumes: `hafresh.ParseOwner`, `hafresh.PreviousBoot` (Task 1), `lease.CurrentSelf()`.
+- Produces: nothing new exported.
+
+- [ ] **Step 1: Write the failing tests**
+
+All with `leasetest.NewLockFixture(t)`, `lease.SetSelf(hafresh.Self{Ref:"r", IID:"i-1", Boot:"b2"})` and a `t.Cleanup` that restores the previous self (follow `self_test.go`). Each puts an UNEXPIRED lock (`time.Now().Add(10*time.Minute)`) at generation 9 via `leaseBody`.
+
+- `TestLegacyTakeTakesThePreviousBootsLock`: owner `OwnerFor(Self{Ref:"r",IID:"i-1",Boot:"b1"}, 41, false)`. `lease.Acquire` succeeds; the lock is generation 10, owned by `OwnerFor(CurrentSelf(), os.Getpid(), false)`; the take went through `classifyAndTake` (generation 10 on an unexpired lock can only come from there; no new write path).
+- `TestLegacyTakeRefusesTheSameBoot`: owner boot `b2`, pid 41. `*lease.HeldError`, lock unchanged.
+- `TestLegacyTakeRefusesAnotherInstance`: owner `IID:"i-2"`, boot `b1`. `*lease.HeldError`.
+- `TestLegacyTakeRefusesAnOldOwner`: owner `"box/v1;ref=r;iid=i-1;pid=41"` (no boot). `*lease.HeldError`.
+- `TestLegacyTakeStillRefusesHALocks`: owner `OwnerFor(Self{Ref:"r",IID:"i-1"}, 41, true)`. `*lease.HALockError`.
+
+- [ ] **Step 2: Run them to see them fail**
+
+Run: `go test ./internal/lease/ -run 'TestLegacyTake'`
+Expected: the first FAILs with `*HeldError`; the other four pass already (they pin today's behaviour).
+
+- [ ] **Step 3: Implement**
+
+In `takeLegacy`'s decide, before returning `*HeldError` for an unexpired lock: if `o, ok := hafresh.ParseOwner(v.Lock.Owner); ok && hafresh.PreviousBoot(o, CurrentSelf())`, log once `lease: taking <key> from this box's previous boot (<old boot> -> <new boot>), lock would have expired at <time>` and return nil. Update `takeLegacy`'s doc comment list with the new bullet.
+
+- [ ] **Step 4: Run them to see them pass**
+
+Run: `go test ./internal/lease/`
+Expected: PASS (whole package).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/lease/legacytake.go internal/lease/ha_test.go
+git commit -m "lease: a box takes the unexpired lock its own previous boot left, at once (#451)"
+```
+
+### Task 4: A failed unit-state check says why
+
+**Files:**
+- Modify: `internal/activator/control.go:100-117`
+- Test: `internal/activator/control_test.go` (add; create if absent)
+
+**Interfaces:**
+- Produces: `func unitStateError(err error) error`, wrapping an `*exec.ExitError` as `fmt.Errorf("%w: %s", err, <stderr trimmed, cut to 200 bytes>)`, other errors unchanged.
+
+- [ ] **Step 1: Write the failing test**
+
+`TestUnitStateErrorCarriesStderr`: an `*exec.ExitError` built by running `sh -c 'echo "Failed to connect to bus" >&2; exit 1'` with `.Output()` gives an error whose text contains `Failed to connect to bus` and which still `errors.As` to `*exec.ExitError`; a 1 KB stderr is cut to 200 bytes; a non-exit error is returned as is.
+
+- [ ] **Step 2: Run it to see it fail**
+
+Run: `go test ./internal/activator/ -run TestUnitStateErrorCarriesStderr`
+Expected: FAIL (undefined).
+
+- [ ] **Step 3: Implement**
+
+`systemctlUnitState` (and `UnitMainExit`'s systemctl call beside it, if it discards stderr the same way) returns `unitStateError(err)`. `exec.Cmd.Output` already fills `ExitError.Stderr` when `Stderr` is nil.
+
+- [ ] **Step 4: Run it to see it pass**
+
+Run: `go test ./internal/activator/ -run 'TestUnitStateErrorCarriesStderr|UnitState'`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add internal/activator/control.go internal/activator/control_test.go
+git commit -m "activator: a failed systemctl state read logs systemctl's own reason (#451 diagnosis)"
+```
+
+### Task 5: Census and branch review
+
+`internal/hafresh`, `internal/lease` and `internal/host` compile into the root binary, so `TestPlan14RootReadCensus` will fail.
+
+- [ ] **Step 1:** Run `go test . -run TestPlan14RootReadCensus`. Expected: FAIL naming the changed units.
+- [ ] **Step 2:** Follow AGENTS.md "The census": `make census-card`, write the CLAIMS (this code runs in the agent as `carlos`; root's behaviour is unchanged), `make census-propose`. The reviewer decides the ruling (never Paul) and it is recorded on #280.
+- [ ] **Step 3:** Whole-branch Astra review from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, round 1 of 3. This branch touches lease takeover (termination and production storage), so it gets that review even though the tasks are small. Focus: the five Review Focus items; that no path takes an HA lock or a same-boot lock.
+- [ ] **Step 4:** CI green on the branch tip; merge with `amadan branch merge carlos/platform <branch> -squash` on Paul's go.
+
+### Task 6: Prove it on dev
+
+Live action: needs Paul's go with the scoped plan (AGENTS.md). Account dev, the dev fleet box (r10r box-1), one reboot, about 10 minutes, nothing created.
+
+- [ ] **Step 1:** After the release carrying this is rolled to dev (roll order: dev boxes, then dev console), reboot box-1 with a rootfs resident and a native instance on it, while probing each public URL every second.
+- [ ] **Step 2:** Pass: both serve again within 2 minutes of the box's tunnel reconnecting (was ~15 min), and the box's log shows the `taking ... from this box's previous boot` line for each.
+- [ ] **Step 3:** Read the previous boot's journal for the `unit state:` lines (Task 4 now carries systemctl's reason). If it is `Failed to connect to bus`, file the unit-ordering follow-up (`After=dbus.service` on the edge unit; a census unit) on #451; otherwise post what it says.
+- [ ] **Step 4:** Post the result on #451 and close it if the takeover held.
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-MANAGED-FLEETS-1C-R1.md b/docs/superpowers/plans/CODEX-FINDINGS-MANAGED-FLEETS-1C-R1.md
new file mode 100644
index 000000000..a4add8614
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-FINDINGS-MANAGED-FLEETS-1C-R1.md
@@ -0,0 +1,26 @@
+Round 1 of 3, commit `f6a309bf67d5a45f0f7ee72ff349fd5349c38e97`.
+
+**Findings:** P1: none. P2: none. P3: none.
+
+The takeover preserves all required exclusions: same boot, different instance or reference, missing identity, older owners without a boot ID, and HA locks. It still uses the classified ETag and increments the generation once.
+
+Mixed-version readers remain safe: old readers classify boot-bearing owners as legacy and respect expiry; HA owners retain their existing format. The legacy wake retains the local database. Release obligations remain conditional on ETags, without dependence on the previous PID or boot.
+
+The boot read fails conservatively to an empty value and introduces no platform-specific API. The edge unit’s sandbox leaves the kernel path readable. Error wrapping preserves callers’ decisions and limits appended stderr to 200 bytes.
+
+Census verdicts:
+
+| Unit or envelope | Verdict and evidence |
+|---|---|
+| `systemctlControlGroup` | **APPROVE** — command, arguments and successful parsing unchanged; only error wrapping changes. `control.go:168` |
+| `systemctlUnitMainExit` | **APPROVE** — same query and exit-policy parsing; no weakened check. `control.go:135` |
+| `systemctlUnitState` | **APPROVE** — same query; failures remain failures. `control.go:101` |
+| `readBootID` | **APPROVE**, including `legacy/accepted-legacy` disposition — production reads a fixed kernel path, with no tenant-controlled path selection. `haself.go:27` |
+| `internal/activator` | **APPROVE** — bounded diagnostic wrapping adds no authority or root input. `control.go:199` |
+| `internal/hafresh` | **APPROVE** — boot serialization excludes HA; takeover requires the approved identity conditions. `owner.go:40`, `owner.go:122` |
+| `internal/host` | **APPROVE** — startup and identity retry carry the fixed-path boot read; cloud identity completeness is unchanged. `haself.go:27`, `haself.go:70` |
+| `internal/lease` | **APPROVE** — HA refusal precedes the exception; conditional-write and generation safeguards remain intact. `legacytake.go:58`, `legacytake.go:90` |
+
+Validation limits: changed Go files pass formatting checks; the scoped diff passes whitespace checks. Targeted tests could not start because the sandbox denied Go’s work directory. Cross-compilation and census execution remain unverified. Network restrictions prevented reading #451 or recording verdicts on #280. No files changed.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-MANAGED-FLEETS-1C.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-MANAGED-FLEETS-1C.md
new file mode 100644
index 000000000..5499b2e45
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-MANAGED-FLEETS-1C.md
@@ -0,0 +1,39 @@
+# Review brief: managed fleets 1c branch (#451 reboot lease) and its census, round 1 of 3
+
+Repo carlos/platform, branch `managed-fleets-1c-451`, tip: the commit that adds this brief (`git log -1` on the branch).
+Under review: the code diff `d3908d930a..HEAD` excluding `docs/` (ten files: `internal/hafresh/owner.go`, `internal/host/haself.go`, `internal/lease/legacytake.go`, `internal/activator/control.go`, their tests, and the census overlay under `internal/provision/testdata/`).
+Authorities: the plan `docs/superpowers/plans/2026-10-30-managed-fleets-1c-reboot-lease.md` and spec `docs/superpowers/specs/2026-10-28-managed-fleets-design.md` §4 item 1c (both approved by Paul, on this branch), amadan #451 (`amadan discuss show carlos/platform 451`), AGENTS.md "The census". The ledger of rulings is `.superpowers/sdd/2026-10-30-managed-fleets-1c-reboot-lease/progress.md` if present; the three rulings are also in the commit messages' neighbourhood (tests moved to a new file, a fourth wrapped systemctl call, boot pinned to "" in four existing identity tests).
+
+You are an independent reviewer. Read the diff, then the code it touches and reaches, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul approved the spec and plan (2026-10-30). The design: after a reboot, a box takes an UNEXPIRED legacy (non-HA) lock immediately when the lock's owner is this same EC2 instance (same non-empty iid, same ref) under a different, known kernel boot id. HA locks and HA owners are out of scope and must be untouched; an HA owner never carries `boot=`.
+- Unit-ordering fixes for shutdown (`After=dbus.service`) are a follow-up, not this branch.
+
+## What to check
+
+1. **Safety of the takeover.** Can any path take a lock whose writer might still be alive: the same boot with a different pid (agent restart while instance units run), another instance sharing a machine id (cloned disk), an owner with no `boot=` (older binary), an HA lock, a self with an empty iid or boot, EC2 hibernate-resume (same boot id)? Is the take still the single conditional write in `classifyAndTake` on the classified ETag, at generation+1?
+2. **Mixed versions.** A box running main without this branch reads a lock written by this branch: `;boot=` on a legacy owner. Does any existing reader (grep `ParseOwner`, `HAOn`, `DecideKeep`, `hafresh.View` users, the release marker and tombstone paths, `origin/region-ha-p1b2-forwarding`'s haforward callers act only on HA owners per its author) misbehave on a string it can no longer parse? And the reverse: this branch reading main's owners.
+3. **After the take.** Does the wake that follows treat the local database as this box's own (it was the last holder), and is anything else keyed on the old pid or boot (obligation store `owed`, release markers, `currentOwner`) left inconsistent?
+4. **The boot id read.** `readBootID` and `bootIDPath`: failure modes, non-Linux builds (darwin and windows must cross-compile), and whether the edge's systemd sandbox could hide `/proc/sys/kernel/random/boot_id` (check the unit template under `internal/host/units`).
+5. **`unitStateError`.** No caller compares these errors by identity or type-asserts `*exec.ExitError` directly, so wrapping changes no decision; stderr is bounded.
+6. **Census approval.** The card is `docs/superpowers/notes/census-proposal-managed-fleets-1c-451.md`. Give a verdict for every unit (three `systemctl*` readers: body change on the error path only; new `readBootID`) and every re-pinned envelope (`internal/activator`, `internal/hafresh`, `internal/host`, `internal/lease`), using the card's own review question: does any root read now open, run, query or follow a path or input a tenant, an app or a box agent can create, write or name, or is a check weakened? Approve or reject per unit.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The census, and review of any newly changed security, root, termination or production-storage behaviour, still check the fix; see AGENTS.md, "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the file, the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant or trust boundary it breaks (that is its fault family). Then the census verdicts, one line per unit and envelope. End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites; targeted `go test -run` is fine if your sandbox allows it.
diff --git a/docs/superpowers/specs/2026-10-28-managed-fleets-design.md b/docs/superpowers/specs/2026-10-28-managed-fleets-design.md
new file mode 100644
index 000000000..ccd16fa67
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-28-managed-fleets-design.md
@@ -0,0 +1,406 @@
+# Managed fleets: boxes a member rents from the deployment's operator
+
+Status: draft for Paul's read, 2026-10-30, after an Astra builder check
+(findings in `CODEX-BUILDER-CHECK-MANAGED-FLEETS.md`). Discussion: amadan #457.
+Branch: `design-managed-fleets-457`.
+
+## 1. Intent
+
+A member should be able to say "give me three boxes of this size, ready
+for my apps" and get them, from the CLI, without AWS credentials, SSH,
+SSM, OpenTofu, hand-minted tokens or an operator writing routes.
+
+The first user is a team moving an existing app (Rails first, but
+anything that runs as a rootfs app) onto CARLOS without rewriting it.
+They run the existing app on rented boxes behind the CARLOS router, then
+move pieces of it to native CARLOS apps over time. Native CARLOS apps can
+be placed on the same boxes. A managed fleet is an ordinary fleet whose
+boxes the platform created.
+
+The boxes live in the cloud account of whoever operates the CARLOS
+deployment. On carloku.com that is carloku. On a self-hosted deployment
+it is that operator's own account, which is where its databases already
+are. This is the first case to ship: an operator runs their own CARLOS
+deployment, their app's database is in RDS and its caches in
+ElastiCache in the same AWS account, and they want boxes for the app
+inside that network.
+
+## 2. Goals, non-goals, anti-goals
+
+Goals:
+
+- A member creates, inspects and removes a managed fleet's boxes through
+ the console API and `carlos` CLI, and gets every diagnostic there too,
+ including bootstrap failures.
+- Rootfs apps and native apps placed on a managed fleet get a public
+ CARLOS URL (and custom domains and certificates) with no hand-written
+ route.
+- Creation is safe to interrupt and retry. A lost connection, a console
+ restart or an ambiguous cloud response never launches a duplicate box
+ and never leaves a box running that the console does not know about.
+- Boxes are useful only to the account that owns the fleet. Nothing on a
+ managed box can read the platform's deployment bucket or another
+ account's data.
+- On carloku, boxes are paid for monthly, before they are handed over.
+
+Non-goals (later, separately):
+
+- Autoscaling, automatic box replacement, several regions per fleet,
+ other clouds.
+- Running one app on several boxes for load or availability. Three boxes
+ give capacity. Replicas are other work (rootfs replicas, region HA).
+- Roles that restrict who in an account may create boxes (Paul,
+ 2026-10-28: "any member for now and we do roles etc. later").
+- Moving an *existing* app onto a fleet. `carlos apps place` is cut once
+ the hostname history is active (nearest-region-without-claims spec
+ §5), so phase 1 places apps at creation with `carlos apps create
+ --place fleet/<f>`. Moving existing apps is a later item. (My call.)
+- Operator-supplied hosted databases. The member's databases stay where
+ they are.
+
+Anti-goals (would make this a failure even if it works):
+
+- A member, or a bug, can make the operator pay for boxes nobody tracks.
+- A managed box gains reach into the platform or another tenant: the
+ deployment bucket, other fleets, the operator's own VPC resources
+ beyond what the operator listed.
+- Self-service that quietly needs an operator step (a manual route, a
+ hostname-history rescan, a token pasted over SSM).
+- A first version that only works on AWS by baking AWS into core
+ packages. AWS is an adapter (provider-neutral core rule).
+
+## 3. What already exists (recon, main at 674fec48)
+
+- **Fleets** (`fleets.go`, `internal/console/fleets.go`,
+ `internal/registry/fleets.go`, `internal/fleetapi/`). Account-owned;
+ the owner record is `accounts/<acct>/fleets/` (`fleetowner.go`). A box
+ joins with a bearer token from `carlos fleets add-box` (sha256 stored,
+ plaintext printed once) and dials a reverse tunnel to the hub edge.
+ Fleet boxes have no deployment-bucket credentials; they read and write
+ only through the edge store door (`internal/edge/storedoor.go`), which
+ scopes them to `accounts/<sqid>/`, `apps/<sqid>/` and `fleets/<fleet>/`.
+ The fleet's data bucket is supplied by the customer
+ (`fleets create --bucket`).
+- **Rootfs apps** (#366). Plans 1–4 are merged. A box is rootfs-ready
+ per `internal/host/rootfsplacement.go`; the console admits a rootfs
+ placement only when every fresh active box in the fleet reports
+ `rootfs_ready` on v0.29.0 or later (`internal/console/rootfs.go`).
+- **Plans and billing** (`internal/plans`, `internal/billing`,
+ `internal/billingstripe`). Yearly plans and packs as quantities on one
+ Stripe subscription; raises charged now with `pending_if_incomplete`;
+ reductions take effect at renewal; ops recorded before the first send.
+ Fleets are paid-only (`checkFleets`).
+- **PR #183** (`trust-placement`, GitHub only, 1,564 commits behind
+ main). Built most of an earlier version of this: `internal/compute`
+ (a provisioner interface, an EC2 adapter and a fake), a hardened
+ first-boot script (`internal/console/userdata.go`), tag-identified
+ terminate, an orphan sweep. Its hourly `box_hours` billing and
+ "re-run to repair" recovery are superseded. The earlier approved
+ design is
+ `platform-infrastructure/platform-design/superpowers/specs/2026-08-12-private-instances-design.md`.
+- **Nothing on main launches or terminates cloud instances.** EC2 is
+ used read-only (`internal/awsinv`, `internal/termfence`).
+
+## 4. Phases
+
+Each phase is useful on its own and gets its own plan.
+
+### Phase 1: fleet apps work without an operator
+
+Three blockers that stop *any* fleet, managed or not, being
+self-service today. 1a is the visible first slice (stopping rule 6):
+the sample app on the dev fleet box serves at its public URL with no
+hand-written route. 1b and 1c follow it.
+
+**1a. Public routes for fleet-placed apps.** Pulled out as its own
+spec and APPROVED by Paul 2026-10-30:
+`docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md` rev 4
+on `design-fleet-public-routes` (06b4d79e), owned by another session.
+The hub (the console's box) writes a `forward` row for each
+fleet-placed record whose fleet the account owns, and `fleetProxy`
+serves it. This design depends on it and does not repeat it. Managed
+fleets need nothing from 1a beyond what that spec gives BYO fleets.
+
+**1b. Box choice within a fleet.** A fleet of three boxes must put each
+instance on exactly one box, spread instances across the boxes, keep
+one writer per instance database (the Litestream lease), and tell the
+hub which box serves it (`fleetChannelFor`'s `boxLabel`). The recon
+found no per-instance box choice for multi-box fleets on main: the
+claim-based box placement was shelved (#404). The builder's first task
+is to establish what a multi-box fleet does today. If it already
+spreads instances with one writer each, 1b is a test. If it doesn't, 1b
+is a small placement rule, owned by the console and recorded on the
+instance (my guess: least-loaded ready box at create, fixed after).
+This is the largest unknown in the design.
+
+**1c. A reboot doesn't cost 15 minutes (#451).** After a rootfs box
+reboots, the agent can't recognise the lease its own previous boot
+held, because the lease owner names the pid but not the boot id, so the
+instance waits out the lease. Fix #451: a lease is recognisable as this
+box's earlier boot and released at start. Verify by rebooting a dev
+fleet box under load.
+
+### Phase 2: managed fleets, no billing
+
+The core feature, first on a self-hosted deployment with no plan
+catalog (so nothing is billed).
+
+**Member experience** (illustrative syntax; copy review settles the
+words):
+
+ carlos fleets create production --managed --region eu-west-1 --size large --boxes 3
+ carlos fleets show production # each box: state, version, ready checks, last error
+ carlos apps create shop --place fleet/production
+ carlos fleets boxes add production --boxes 1
+ carlos fleets boxes remove production box-3
+ carlos fleets remove production
+
+`create` prints what will be launched (and, on carloku, the monthly
+price), returns an operation the CLI follows, and keeps working if the
+CLI goes away. `carlos fleets show` re-attaches. Re-running the same
+command while an operation is open joins that operation; it never buys
+more boxes.
+
+**Operator configuration.** The operator turns the feature on and
+decides, per region: the size list (a short list of ARM instance
+types, each with a name like `large`), the pinned machine image, the
+subnets and security groups boxes launch into, and a deployment-wide
+ceiling on managed boxes. On a self-hosted deployment the subnets are
+the ones that can already reach the operator's RDS and ElastiCache, so
+no peering is needed. Configuration is operator-written, not
+member-writable. Where it lives (system config, `host.env`, a signed
+catalog object) is the builder's call; it must not add per-box bucket
+polling (see §6).
+
+**Who may create boxes.** Any member of an account (Paul). Limits: the
+deployment-wide ceiling and a per-account box limit (on carloku, from
+the plan catalog; on self-hosted, defaulting to the ceiling). Both are
+checked under a lock that makes two concurrent creates unable to exceed
+them together.
+
+**Provisioning.**
+
+- Every create is a durable console operation, recorded before anything
+ is launched. Each box gets its identity (fleet, label, operation)
+ first, and that identity goes to the cloud as the launch's
+ idempotency token (EC2 `ClientToken`) and as tags. A retry, a restart
+ or an ambiguous response re-asks with the same identity and finds the
+ same box.
+- A console-side worker drives open operations to an end, after
+ restarts too. This replaces the 2026-08-12 design's "synchronous
+ handler, repaired by re-run" model, which #457 asked to revisit: a
+ member who closes their laptop must not leave an operation stuck
+ half-way.
+- A periodic sweep lists cloud resources carrying the deployment's tags
+ and reports (and, past a grace period, terminates) any the console has
+ no record of. Terminate refuses any instance whose tags don't name
+ the fleet and box it was asked to end (#183's identity-checked
+ terminate).
+- Partial failure: if some boxes come up and others don't, the fleet
+ keeps the boxes that are ready, the operation reports which failed and
+ why, and failed boxes are terminated. The member can retry the
+ missing count.
+- The provisioner sits behind an interface (`internal/compute` from
+ #183 is the starting point) with a fake for tests. The AWS adapter
+ loads through `internal/rootaws`.
+
+**The fleet's storage.** A managed fleet gets a data bucket the console
+creates for it, the way object storage creates a store
+(`objstore.Provisioner`). Boxes reach only that bucket. How a box gets
+credentials for it (an instance profile per fleet, or a per-fleet IAM
+user like `objstore.EnsureUser`) is the builder's call, with one
+constraint: the console role's new IAM authority is no broader than it
+needs, and gets its own security review. #183 created a role per fleet,
+which needs `iam:CreateRole` and `PassRole` on the console; prefer a
+design that needs less.
+
+**Enrolment.** A box joins its fleet without any long-lived secret
+appearing in user data, logs, progress output or the console's pages.
+My guess at the mechanism: user data carries a one-time enrolment token
+that expires within minutes and that the box trades, on first contact,
+for its ordinary fleet token; the trade is refused after first use. The
+box fetches the binary through the store door (`bootstrap/carlos`) and
+verifies it as platform boxes do. Port #183's first-boot hardening
+(parameter allowlists, IMDS gate, shredding cloud-init copies).
+
+**The fleet's secrets key.** Each fleet has its own secrets key, and
+the deployment's key never reaches a fleet box
+(`docs/superpowers/specs/2026-10-29-fleet-secrets-key-design.md`,
+merged ea01d831, in v0.31.0). For a managed fleet the provisioner
+mints the key on the first box and registers its public half through
+the same door `carlos fleets secrets-key` uses, so the owner never
+handles it (that spec's §8). The private key reaches the fleet's later
+boxes without passing through the console in plain form; how is the
+builder's call. No parallel key path.
+
+**Born examined.** The hostname history (nearest-region-without-claims
+spec) refuses data-kind creates on a fleet it has not examined, and
+refuses new boxes on a fleet it has (`fleetGrowthRefusal`, N9). Both
+exist because a BYO box may already hold an app's data. A managed box
+was launched by the console from a pinned image onto fresh volumes, so
+it cannot. A managed fleet is therefore recorded as examined when it is
+created, and a managed box may join it, on one condition: the box's
+first report, before it accepts any work, lists its data directory as
+empty. A box that reports anything else is refused and terminated. BYO
+fleets keep the operator flow unchanged.
+
+**Ready means ready.** A box counts as ready, and the operation as
+done, only when all of these hold: it is registered and active in the
+fleet; it runs the deployment's expected platform version; it reports
+`rootfs_ready`; the fleet owner record names the member's account; it
+can write and read its fleet bucket; and a probe through the router
+reaches it over its tunnel. "Running" in EC2 or a bare heartbeat is not
+enough. Each check's state shows in `carlos fleets show`.
+
+**Diagnostics.** Every failure a member can hit, bootstrap included,
+is visible through the API and CLI: the cloud's launch errors, the
+box's first-boot breadcrumbs (posted through the store door, or read by
+the console from the instance console output), the readiness check that
+failed. No AWS console, SSH or SSM for the member.
+
+**Removal.**
+
+- Removing a box stops new placements on it at once. While it still
+ runs instances, the removal is refused with a message naming the
+ apps. (My call.) Moving instances between a fleet's boxes is not
+ built today: moves refuse fleet routes (`apiinstancemove.go:65`). If
+ 1b's placement makes an in-fleet move cheap (the instance hibernates
+ to the fleet bucket and wakes on another box), removal drains instead
+ of refusing; the builder decides once 1b is known.
+- Removing a fleet is refused while any app is placed on it.
+- Termination is checked against tags. The fleet bucket is kept while
+ any box still uses it. After the last box goes it is kept 30 days,
+ then deleted, and `carlos fleets show` says when. (Carried from the
+ 2026-08-12 design.) Within those 30 days, adding a box to the fleet
+ brings it back on the same bucket and cancels the deletion; that is
+ the only recovery path, and no separate export command is built. (My
+ call.)
+- **A box that is lost for good** (terminated by the cloud, failed
+ hardware) must not lose its instances. They come back on the fleet's
+ surviving boxes from the fleet bucket, and the member restores
+ capacity by adding a box. No automatic replacement. 1b's placement
+ rule must deliver this; if instances are fixed to one box, it needs a
+ reassignment path for a box the console has confirmed gone. (My
+ call; builder check Q2.)
+- On carloku, a removed box keeps running until the end of its paid
+ month, then is terminated (phase 3). On self-hosted, at once once
+ drained.
+
+### Phase 3: carloku layers
+
+**Monthly billing.** Boxes are billed monthly, per box, priced per size.
+Paul, 2026-10-28: monthly is easier. The yearly subscription can't carry
+them: Stripe Checkout can't create mixed-interval subscriptions, a
+renewal stop ends at the earliest item's period, a failed box invoice
+would take the plan with it, and the pinned API version predates mixed
+intervals (billing recon; `internal/billingstripe/prepared.go:148`,
+`client.go:34`). So boxes go on a separate monthly subscription with
+its own role, beside the plan subscription.
+
+- Buying: the console launches the boxes in a held state (not yet
+ available to the member), then charges. The first purchase goes
+ through Checkout; later boxes are prorated raises with
+ `pending_if_incomplete`, using the existing op machinery. Boxes are
+ handed over when the charge applies. A failed or abandoned charge
+ terminates the held boxes, and nothing was charged. A box that fails
+ to come up is never charged. Holding first avoids needing refunds,
+ which billing doesn't do today. (Recon's recommendation; my call.)
+- Removing: a reduction at renewal, as packs and seats already do. The
+ box runs until the paid month ends. (Paul: "I don't really mind";
+ this matches the existing "leaver comes off at renewal".)
+- Box compute is not metered on top. Managed boxes must not accrue on
+ `fleet_box_hours_*` (`internal/usage/usage.go:24-25`).
+- Bandwidth and storage stay under the member's plan and packs.
+- Unpaid renewal: while Stripe retries, the boxes run (past due counts
+ as paid today). When the box subscription ends unpaid, the boxes get
+ the plans spec's 7-day grace for paid-only features, are then
+ terminated, and the fleet bucket follows the 30-day retention above.
+ (My call, matching the existing lapse rules.)
+- Plan lapse while boxes are paid: fleets are paid-only, so the box
+ subscription is set not to renew. The boxes run to the end of the
+ month already paid, then follow the unpaid path. No refunds. (My
+ call.)
+
+**Reaching the member's own databases.** On carloku, the member's
+databases are in their AWS account, not carloku's. Each managed fleet
+gets its own VPC in carloku's account with an address range the member
+chooses, sealed off from other fleets and from the platform's own boxes
+except the tunnel to the router. It is peered with the member's VPC;
+the member accepts the peering request, adds a route to the fleet's
+range in their route tables, and opens their security groups. AWS
+needs routes on both sides of a peering. CARLOS takes no access to the
+member's account: it does its own side and the CLI prints the member's
+three steps exactly, with the values filled in, and checks the
+connection afterwards. (My call; builder check Q4.) This is phase 3,
+not phase 2: on a self-hosted deployment the boxes already launch in
+the operator's network.
+
+## 5. Provider boundary
+
+- **Core** (no cloud SDK): operations, box records, quotas, readiness,
+ enrolment, born-examined, removal, billing, the CLI. Tested end to end
+ against the fake provisioner.
+- **AWS adapter**: launch, describe, terminate, tag listing, the fleet
+ bucket and its credentials, and (phase 3) VPC and peering. Loaded
+ through `internal/rootaws`. The console role gets launch and
+ terminate on resources tagged for this deployment, in the operator's
+ configured regions, with only the configured image, subnets and
+ security groups.
+- **A deployment without AWS** gets no managed fleets (the feature
+ stays off) and keeps BYO fleets unchanged. An import test keeps the
+ AWS SDK out of core packages.
+
+## 6. Request budget
+
+A managed box is a fleet box: its steady-state store traffic is the
+same as a BYO fleet box today, through the store door, and this feature
+adds no per-box bucket polling. The provisioning worker calls the cloud
+API (EC2 describe calls) only while an operation is open. The orphan
+sweep is one list call per configured region per hour. Operator
+configuration is read on a change-index generation change, not on a
+timer. Each plan states its numbers and has a test counting store
+calls.
+
+## 7. Switch-on (stopping rule 5)
+
+- Phase 1: who asks is Paul, for the Rails migration case. On when merged
+ and rolled to dev; proved by the Rails sample on the dev fleet box
+ with no hand route and a reboot drill.
+- Phase 2: on for the first self-hosted deployment after a dev
+ drill, with Paul's approval of the live test plan (account, region,
+ resources, cost, duration, cleanup) as AGENTS.md requires.
+- Phase 3: on carloku once phase 2 has run on the self-hosted deployment
+ and the monthly price per size is set by Paul.
+
+## 8. Acceptance checks
+
+1. Three boxes requested from the CLI all become ready, with every
+ readiness check shown passing.
+2. A Rails rootfs app and a native app, placed on the fleet at creation,
+ serve at their public URLs (and a custom domain), with no hand route.
+3. Fake-provisioner tests: interrupted create, console restart mid-
+ operation, ambiguous launch response, retry of the same command,
+ partial capacity failure, two concurrent creates at the quota edge.
+ None leaves a duplicate or untracked box.
+4. Cross-account refusals: another account can't place on, inspect or
+ remove the fleet; a managed box's credentials can't reach the
+ deployment bucket or another fleet's bucket.
+5. Enrolment secrets never appear in logs, progress output or pages.
+6. Reboot recovery (1c); removal with active workloads (drain, or
+ refusal); the fleet keeps serving on surviving boxes; the bucket is
+ retained as stated.
+7. Phase 3: buying, failed charge, failed launch and removal each charge
+ exactly what this spec says and nothing twice.
+8. Commands documented in `docs/site/cli.md`; copy review for every
+ member-facing string.
+
+## 9. Left to the builder
+
+- Command and flag names (copy review settles words).
+- Where operator configuration lives, within §6's budget.
+- Instance profile versus per-fleet IAM user for bucket access, within
+ §4's constraint.
+- The enrolment token's exact form.
+- Table and record shapes, the worker's schedule, the sweep's grace
+ period.
+- What to port from #183 versus rewrite.
diff --git a/docs/superpowers/specs/CODEX-BUILDER-CHECK-MANAGED-FLEETS.md b/docs/superpowers/specs/CODEX-BUILDER-CHECK-MANAGED-FLEETS.md
new file mode 100644
index 000000000..bdecfbfa8
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-BUILDER-CHECK-MANAGED-FLEETS.md
@@ -0,0 +1,11 @@
+1. **What happens when a monthly box renewal fails—or the annual plan lapses while boxes remain paid?**
+ Phase 3 defines failed purchases and voluntary removal, but not these cases. The existing plans spec allows payment retries, then grace and eventual deletion. Applying that unchanged could leave unpaid machines running or disable paid capacity. The answer determines subscription coordination, shutdown deadlines and data retention.
+
+2. **Must v1 support member-initiated recovery after a box is permanently lost?**
+ Automatic replacement is excluded, but manual recovery is unspecified. With console-assigned placement, adding a replacement box does not necessarily recover existing instances; current fleet moves are refused. The answer determines whether the plan needs safe reassignment and restoration of existing instances, beyond the explicitly discretionary draining of healthy boxes.
+
+3. **What can a member do with the fleet’s data during the 30-day retention window after its last box goes?**
+ Can they restore the fleet by adding boxes, export the data through CARLOS, or only see the deletion date? If they restore it, does deletion stop? Keeping a bucket alone does not provide recovery through the CLI. The answer changes the removal lifecycle, recovery commands and acceptance checks.
+
+4. **May the customer configure return routes when connecting their VPC, or must CARLOS do that through delegated access?**
+ Phase 3 limits customer setup to accepting peering and opening security groups. AWS also requires routes on both sides of the connection. The answer changes the promised onboarding flow and whether the adapter needs authority in the customer’s account. See [https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-routing.html](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-routing.html).
\ No newline at end of file
diff --git a/internal/activator/control.go b/internal/activator/control.go
index 0ca06618b..3e929f59d 100644
--- a/internal/activator/control.go
+++ b/internal/activator/control.go
@@ -3,6 +3,7 @@ package activator
import (
"context"
"errors"
+ "fmt"
"os"
"os/exec"
"path/filepath"
@@ -100,7 +101,7 @@ type UnitState func(ctx context.Context, unit string) (active, invocation string
func systemctlUnitState(ctx context.Context, unit string) (string, string, error) {
out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "ActiveState,InvocationID", unit).Output()
if err != nil {
- return "", "", err
+ return "", "", unitStateError(err)
}
var active, inv string
for _, line := range strings.Split(string(out), "\n") {
@@ -134,7 +135,7 @@ type MainExit struct {
func systemctlUnitMainExit(ctx context.Context, unit string) (MainExit, error) {
out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "InvocationID,ExecMainCode,ExecMainStatus,SuccessExitStatus", unit).Output()
if err != nil {
- return MainExit{}, err
+ return MainExit{}, unitStateError(err)
}
var m MainExit
for _, line := range strings.Split(string(out), "\n") {
@@ -167,7 +168,7 @@ type ControlGroupOf func(ctx context.Context, unit string) (string, error)
func systemctlControlGroup(ctx context.Context, unit string) (string, error) {
out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "ControlGroup", "--value", unit).Output()
if err != nil {
- return "", err
+ return "", unitStateError(err)
}
return strings.TrimSpace(string(out)), nil
}
@@ -190,3 +191,22 @@ func readCgroupEvents(path string) (exists, populated bool, err error) {
}
return true, !strings.Contains(string(b), "populated 0"), nil
}
+
+// unitStateError is a failed systemctl read's error with systemctl's own
+// stderr appended, cut to 200 bytes: "exit status 1" alone could not tell
+// a lost D-Bus at shutdown from a missing unit (#451). An error that is
+// not an exit is returned unchanged.
+func unitStateError(err error) error {
+ var ee *exec.ExitError
+ if !errors.As(err, &ee) {
+ return err
+ }
+ msg := strings.TrimSpace(string(ee.Stderr))
+ if msg == "" {
+ return err
+ }
+ if len(msg) > 200 {
+ msg = msg[:200]
+ }
+ return fmt.Errorf("%w: %s", err, msg)
+}
diff --git a/internal/activator/control_test.go b/internal/activator/control_test.go
new file mode 100644
index 000000000..88dc96156
--- /dev/null
+++ b/internal/activator/control_test.go
@@ -0,0 +1,29 @@
+package activator
+
+import (
+ "errors"
+ "os/exec"
+ "strings"
+ "testing"
+)
+
+// #451: a systemctl that fails at shutdown said only "exit status 1"; its
+// own reason (a lost D-Bus, say) is what tells the cause apart.
+func TestUnitStateErrorCarriesStderr(t *testing.T) {
+ _, err := exec.Command("sh", "-c", `echo "Failed to connect to bus: No such file or directory" >&2; exit 1`).Output()
+ got := unitStateError(err)
+ var ee *exec.ExitError
+ if !strings.Contains(got.Error(), "Failed to connect to bus") || !errors.As(got, &ee) {
+ t.Fatalf("%v", got)
+ }
+
+ _, err = exec.Command("sh", "-c", `head -c 1024 /dev/zero | tr '\0' q >&2; exit 1`).Output()
+ if got := unitStateError(err).Error(); strings.Count(got, "q") != 200 {
+ t.Fatalf("stderr not cut to 200 bytes: %d", strings.Count(got, "q"))
+ }
+
+ plain := errors.New("context deadline exceeded")
+ if got := unitStateError(plain); got != plain {
+ t.Fatalf("a non-exit error changed: %v", got)
+ }
+}
diff --git a/internal/hafresh/owner.go b/internal/hafresh/owner.go
index 22a7c657b..e78e8c258 100644
--- a/internal/hafresh/owner.go
+++ b/internal/hafresh/owner.go
@@ -10,11 +10,13 @@ import (
// Self is this box's identity as a lease owner: its reference (the label
// it publishes metrics under), its cloud instance id ("" until known),
-// and the cloud account and region it runs in. OwnerFor writes only the
-// reference and the instance id.
-type Self struct{ Ref, IID, Account, Region string }
+// the cloud account and region it runs in, and the kernel boot id ("" when
+// it can't be read). OwnerFor writes the reference, the instance id and,
+// on a legacy lock only, the boot.
+type Self struct{ Ref, IID, Account, Region, Boot string }
-// Complete reports whether all four fields are known.
+// Complete reports whether the four cloud identity fields are known. The
+// boot is not one of them.
func (s Self) Complete() bool {
return s.Ref != "" && s.IID != "" && s.Account != "" && s.Region != ""
}
@@ -23,14 +25,18 @@ func (s Self) Complete() bool {
type Owner struct {
Ref, IID string
PID int
+ Boot string
HA bool
}
const ownerPrefix = "box/v1;"
// OwnerFor is the owner string a box writes into a lock:
-// box/v1;ref=<ref>;iid=<instance id>;pid=<pid>, with ;ha=1 on an HA
-// lock. iid= is left out while the instance id is unknown.
+// box/v1;ref=<ref>;iid=<instance id>;pid=<pid>, then ;boot=<boot id> on a
+// legacy lock or ;ha=1 on an HA lock. iid= is left out while the instance
+// id is unknown, boot= while the boot id is (#451). An HA owner never
+// carries a boot: a binary that predates the field cannot parse it and
+// would read the HA lock as a legacy one.
func OwnerFor(s Self, pid int, ha bool) string {
var b strings.Builder
b.WriteString(ownerPrefix + "ref=" + s.Ref)
@@ -38,6 +44,9 @@ func OwnerFor(s Self, pid int, ha bool) string {
b.WriteString(";iid=" + s.IID)
}
b.WriteString(";pid=" + strconv.Itoa(pid))
+ if !ha && s.Boot != "" {
+ b.WriteString(";boot=" + s.Boot)
+ }
if ha {
b.WriteString(";ha=1")
}
@@ -45,8 +54,8 @@ func OwnerFor(s Self, pid int, ha bool) string {
}
// ParseOwner reads an owner string OwnerFor wrote, strictly: ref, iid
-// (optional), pid and ha (optional, only "1"), in that order, each with a
-// non-empty value, pid a positive decimal with no sign or leading zero,
+// (optional), pid, then either boot (optional) or ha (optional, only "1"),
+// never both, in that order, each with a non-empty value, pid a positive decimal with no sign or leading zero,
// nothing else. Any other string (a legacy host:pid owner, a tombstone's
// moved:<id>, a release marker's owner) is not a box owner: ok is false.
func ParseOwner(s string) (Owner, bool) {
@@ -84,7 +93,12 @@ func ParseOwner(s string) (Owner, bool) {
return Owner{}, false
}
o.PID = n
- if len(fields) > 0 {
+ if len(fields) > 0 && strings.HasPrefix(fields[0], "boot=") {
+ if o.Boot, ok = next("boot"); !ok {
+ return Owner{}, false
+ }
+ }
+ if len(fields) > 0 && o.Boot == "" {
if v, ok := next("ha"); !ok || v != "1" {
return Owner{}, false
}
@@ -95,3 +109,17 @@ func ParseOwner(s string) (Owner, bool) {
}
return o, true
}
+
+// PreviousBoot reports whether o is a legacy lock this same box wrote under
+// an earlier kernel boot (#451): the same non-empty instance id and the
+// same reference, and two known boot ids that differ. Such a lock is dead
+// even while it is unexpired, since no process of an earlier boot survives
+// into a new kernel, so the box may take it at once instead of waiting out
+// the lease. The same boot (an agent restart, whose instance units may
+// still run), another instance (a box cloned from this one's disk shares
+// its machine id, not its instance id), an owner or a self with no boot
+// id, and every HA owner answer false.
+func PreviousBoot(o Owner, self Self) bool {
+ return !o.HA && self.IID != "" && o.IID == self.IID && o.Ref == self.Ref &&
+ o.Boot != "" && self.Boot != "" && o.Boot != self.Boot
+}
diff --git a/internal/hafresh/owner_boot_test.go b/internal/hafresh/owner_boot_test.go
new file mode 100644
index 000000000..daee95886
--- /dev/null
+++ b/internal/hafresh/owner_boot_test.go
@@ -0,0 +1,75 @@
+package hafresh_test
+
+import (
+ "testing"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+)
+
+// #451: a legacy owner names the kernel boot it was written under, so a
+// box can recognise the lock its own previous boot left. An HA owner
+// never does: an older binary reading an HA owner with an extra field
+// would take it for a legacy one.
+func TestOwnerForWritesBootOnlyWhenLegacy(t *testing.T) {
+ s := hafresh.Self{Ref: "r", IID: "i-1", Boot: "b1"}
+ for _, c := range []struct {
+ self hafresh.Self
+ ha bool
+ want string
+ }{
+ {s, false, "box/v1;ref=r;iid=i-1;pid=7;boot=b1"},
+ {s, true, "box/v1;ref=r;iid=i-1;pid=7;ha=1"},
+ {hafresh.Self{Ref: "r"}, false, "box/v1;ref=r;pid=7"},
+ } {
+ if got := hafresh.OwnerFor(c.self, 7, c.ha); got != c.want {
+ t.Errorf("OwnerFor(%+v, ha=%v) = %q, want %q", c.self, c.ha, got, c.want)
+ }
+ }
+}
+
+func TestParseOwnerBoot(t *testing.T) {
+ s := "box/v1;ref=r;iid=i-1;pid=7;boot=b1"
+ o, ok := hafresh.ParseOwner(s)
+ if want := (hafresh.Owner{Ref: "r", IID: "i-1", PID: 7, Boot: "b1"}); !ok || o != want {
+ t.Fatalf("%q: %+v %v, want %+v", s, o, ok, want)
+ }
+ for _, bad := range []string{
+ "box/v1;ref=r;pid=7;boot=b1;ha=1", // boot only on legacy owners
+ "box/v1;ref=r;pid=7;ha=1;boot=b1",
+ "box/v1;ref=r;pid=7;boot=",
+ "box/v1;ref=r;pid=7;boot=b1;boot=b2",
+ "box/v1;ref=r;boot=b1;pid=7",
+ } {
+ if o, ok := hafresh.ParseOwner(bad); ok {
+ t.Errorf("parsed %q as %+v", bad, o)
+ }
+ }
+ v := hafresh.View{Lock: hafresh.Lock{Owner: s}}
+ if v.HAOn() {
+ t.Fatal("a legacy owner with a boot reads as HA")
+ }
+}
+
+func TestPreviousBoot(t *testing.T) {
+ self := hafresh.Self{Ref: "r", IID: "i-1", Boot: "b2"}
+ for _, c := range []struct {
+ name string
+ o hafresh.Owner
+ self hafresh.Self
+ want bool
+ }{
+ {"this box, earlier boot", hafresh.Owner{Ref: "r", IID: "i-1", PID: 41, Boot: "b1"}, self, true},
+ {"this boot (agent restart)", hafresh.Owner{Ref: "r", IID: "i-1", PID: 41, Boot: "b2"}, self, false},
+ {"another instance", hafresh.Owner{Ref: "r", IID: "i-2", PID: 41, Boot: "b1"}, self, false},
+ {"another ref", hafresh.Owner{Ref: "x", IID: "i-1", PID: 41, Boot: "b1"}, self, false},
+ {"owner without iid", hafresh.Owner{Ref: "r", PID: 41, Boot: "b1"}, self, false},
+ {"owner from an older binary", hafresh.Owner{Ref: "r", IID: "i-1", PID: 41}, self, false},
+ {"HA owner", hafresh.Owner{Ref: "r", IID: "i-1", PID: 41, Boot: "b1", HA: true}, self, false},
+ {"self without iid", hafresh.Owner{Ref: "r", IID: "i-1", PID: 41, Boot: "b1"}, hafresh.Self{Ref: "r", Boot: "b2"}, false},
+ {"self without boot", hafresh.Owner{Ref: "r", IID: "i-1", PID: 41, Boot: "b1"}, hafresh.Self{Ref: "r", IID: "i-1"}, false},
+ } {
+ if got := hafresh.PreviousBoot(c.o, c.self); got != c.want {
+ t.Errorf("%s: PreviousBoot = %v, want %v", c.name, got, c.want)
+ }
+ }
+}
diff --git a/internal/host/haself.go b/internal/host/haself.go
index 71930b2ac..a40ddcede 100644
--- a/internal/host/haself.go
+++ b/internal/host/haself.go
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net/http"
+ "os"
"strings"
"time"
@@ -25,7 +26,22 @@ var haIMDSClient = &http.Client{Timeout: haIdentityRead}
// label is its resolved group reference.
func haSelfNow(getenv func(string) string, client *http.Client) hafresh.Self {
iid, account, region, _ := readIdentity(client, imdsBase)
- return hafresh.Self{Ref: metricsBoxLabel(getenv, readMachineID()), IID: iid, Account: account, Region: region}
+ return hafresh.Self{Ref: metricsBoxLabel(getenv, readMachineID()), IID: iid, Account: account, Region: region, Boot: readBootID(bootIDPath)}
+}
+
+// bootIDPath is where the kernel publishes this boot's id; a test points
+// it elsewhere.
+var bootIDPath = "/proc/sys/kernel/random/boot_id"
+
+// readBootID is the kernel boot id at path, trimmed, "" when it can't be
+// read (off Linux, say). A legacy lock names it, so the next boot can tell
+// its own earlier boot's lock from a live one (#451).
+func readBootID(path string) string {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return ""
+ }
+ return strings.TrimSpace(string(b))
}
// startHASelfRetry is RunAgent's rule for the retry: a startup identity
diff --git a/internal/host/haself_test.go b/internal/host/haself_test.go
index 771cebf81..d5d8f5807 100644
--- a/internal/host/haself_test.go
+++ b/internal/host/haself_test.go
@@ -3,6 +3,8 @@ package host
import (
"context"
"net/http"
+ "os"
+ "path/filepath"
"slices"
"testing"
"time"
@@ -36,6 +38,7 @@ func TestAgentEntrySetsOwnerBeforeRun(t *testing.T) {
// The box's reference is its metrics label; its instance id, account and
// region come from one identity-document read, "" when that read fails.
func TestHASelfNowNamesTheBox(t *testing.T) {
+ withBootID(t, "") // these assert the IMDS identity; the boot has its own test
f := &fakeIMDS{doc: `{"accountId":"111122223333","instanceId":"i-0a61f580df1acfa65","region":"eu-west-1"}`}
getenv := envOf(map[string]string{"CARLOS_FLEET": "pi", "CARLOS_FLEET_BOX": "pi-box"})
want := metricsBoxLabel(getenv, readMachineID())
@@ -70,6 +73,7 @@ func (f *failingFor) RoundTrip(r *http.Request) (*http.Response, error) {
// until it answers, then set once, with the reference; the retry ends
// there, or when its context does.
func TestHASelfRetrySetsALateInstanceID(t *testing.T) {
+ withBootID(t, "") // these assert the IMDS identity; the boot has its own test
f := &failingFor{fakeIMDS: &fakeIMDS{doc: `{"accountId":"111122223333","instanceId":"i-0abc","region":"eu-west-1"}`}, n: 2}
getenv := envOf(map[string]string{"CARLOS_FLEET": "pi", "CARLOS_FLEET_BOX": "pi-box"})
var set []hafresh.Self
@@ -110,6 +114,7 @@ func (d *docSwitch) RoundTrip(r *http.Request) (*http.Response, error) {
// A document with an instance id but no region is not an identity yet:
// the retry waits for the tick that brings all of it, and sets it once.
func TestHASelfRetryWaitsForTheWholeIdentity(t *testing.T) {
+ withBootID(t, "") // these assert the IMDS identity; the boot has its own test
d := &docSwitch{fakeIMDS: &fakeIMDS{}, docs: []string{
`{"accountId":"111122223333","instanceId":"i-0abc"}`,
`{"accountId":"111122223333","instanceId":"i-0abc"}`,
@@ -138,6 +143,7 @@ func TestHASelfRetryWaitsForTheWholeIdentity(t *testing.T) {
// starts the retry, and a later complete document reaches the lease
// identity. A complete startup identity starts nothing.
func TestAgentRetriesAPartialIdentity(t *testing.T) {
+ withBootID(t, "") // these assert the IMDS identity; the boot has its own test
t.Cleanup(func() { lease.SetSelf(hafresh.Self{}) })
getenv := envOf(map[string]string{"CARLOS_FLEET": "pi", "CARLOS_FLEET_BOX": "pi-box"})
ref := metricsBoxLabel(getenv, readMachineID())
@@ -161,3 +167,46 @@ func TestAgentRetriesAPartialIdentity(t *testing.T) {
t.Fatal("a complete identity started the retry")
}
}
+
+// withBootID points the boot id read at a file holding id for one test.
+// Tests that use it set a package var, so they never run in parallel.
+func withBootID(t *testing.T, id string) {
+ t.Helper()
+ p := filepath.Join(t.TempDir(), "boot_id")
+ if err := os.WriteFile(p, []byte(id+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ was := bootIDPath
+ bootIDPath = p
+ t.Cleanup(func() { bootIDPath = was })
+}
+
+// #451: the kernel boot id, trimmed; "" for a missing or empty file.
+func TestReadBootID(t *testing.T) {
+ dir := t.TempDir()
+ p := filepath.Join(dir, "boot_id")
+ os.WriteFile(p, []byte("3f1c0e2a-9b7d-4c1e-8f00-1a2b3c4d5e6f\n"), 0o600)
+ if got := readBootID(p); got != "3f1c0e2a-9b7d-4c1e-8f00-1a2b3c4d5e6f" {
+ t.Fatalf("%q", got)
+ }
+ if got := readBootID(filepath.Join(dir, "missing")); got != "" {
+ t.Fatalf("missing: %q", got)
+ }
+ empty := filepath.Join(dir, "empty")
+ os.WriteFile(empty, nil, 0o600)
+ if got := readBootID(empty); got != "" {
+ t.Fatalf("empty: %q", got)
+ }
+}
+
+// The lease identity carries the boot, with IMDS answering or not, and the
+// boot does not make an identity Complete.
+func TestHASelfNowCarriesTheBoot(t *testing.T) {
+ withBootID(t, "b9")
+ getenv := envOf(nil)
+ f := &fakeIMDS{status: http.StatusInternalServerError}
+ got := haSelfNow(getenv, imdsClient(f))
+ if got.Boot != "b9" || got.IID != "" || got.Complete() {
+ t.Fatalf("IMDS failing: %+v", got)
+ }
+}
diff --git a/internal/lease/legacytake.go b/internal/lease/legacytake.go
index 6ac445018..4d41042b1 100644
--- a/internal/lease/legacytake.go
+++ b/internal/lease/legacytake.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
+ "log"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
@@ -41,7 +42,9 @@ const takeRounds = 3
// leniently and would take an expired one):
//
// - an HA-format lock: *HALockError, nothing written;
-// - unexpired (leaseFree is false): *HeldError, nothing written;
+// - unexpired, written by this box under an earlier kernel boot
+// (hafresh.PreviousBoot): taken at once, as an expired one is (#451);
+// - unexpired otherwise (leaseFree is false): *HeldError, nothing written;
// - expired, or gone again since createLease: the next generation under
// this leaser's owner, conditional on the exact ETag classified
// (If-None-Match: * when it was gone).
@@ -60,6 +63,11 @@ func takeLegacy(ctx context.Context, client lss3.S3API, l *lss3.Leaser) (*litest
return &HALockError{View: v}
}
if !leaseFree(v.Lock.ExpiresAt, time.Now()) {
+ if o, ok := hafresh.ParseOwner(v.Lock.Owner); ok && hafresh.PreviousBoot(o, CurrentSelf()) {
+ log.Printf("lease: taking %s from this box's previous boot (%s -> %s); the lock would have expired at %s",
+ key, o.Boot, CurrentSelf().Boot, v.Lock.ExpiresAt.UTC().Format(time.RFC3339))
+ return nil
+ }
return &HeldError{Owner: v.Lock.Owner, ExpiresAt: v.Lock.ExpiresAt}
}
return nil
diff --git a/internal/lease/previousboot_test.go b/internal/lease/previousboot_test.go
new file mode 100644
index 000000000..cfea17254
--- /dev/null
+++ b/internal/lease/previousboot_test.go
@@ -0,0 +1,84 @@
+package lease_test
+
+import (
+ "errors"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ leasetest "github.com/carlosframework/platform/internal/lease/locktest"
+)
+
+// #451. This box, booted as b2, meets an UNEXPIRED legacy lock at
+// generation 9. Only one its own earlier boot wrote is taken at once.
+func previousBootBox(t *testing.T) *leasetest.LockFixture {
+ t.Helper()
+ lease.ResetForTest()
+ t.Cleanup(lease.ResetForTest)
+ lease.SetSelf(hafresh.Self{Ref: "r", IID: "i-1", Boot: "b2"})
+ return leasetest.NewLockFixture(t)
+}
+
+func unexpired() time.Time { return time.Now().Add(10 * time.Minute) }
+
+func TestLegacyTakeTakesThePreviousBootsLock(t *testing.T) {
+ fx := previousBootBox(t)
+ fx.PutLock("instances/h", leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "r", IID: "i-1", Boot: "b1"}, 41, false), unexpired()))
+ h, err := lease.Acquire(ctx, fx.Bucket, "instances/h", "")
+ if err != nil {
+ t.Fatalf("the previous boot's lock was not taken: %v", err)
+ }
+ defer h.Release(ctx)
+ v, _ := hafresh.DecodeLock(fx.LockBody("instances/h"), "")
+ if v.Lock.Generation != 10 {
+ t.Fatalf("generation %d, want 10", v.Lock.Generation)
+ }
+ if got, want := v.Lock.Owner, hafresh.OwnerFor(lease.CurrentSelf(), os.Getpid(), false); got != want {
+ t.Fatalf("owner %q, want %q", got, want)
+ }
+}
+
+func TestLegacyTakeRefusesTheSameBoot(t *testing.T) {
+ refusesHeld(t, hafresh.OwnerFor(hafresh.Self{Ref: "r", IID: "i-1", Boot: "b2"}, 41, false))
+}
+
+func TestLegacyTakeRefusesAnotherInstance(t *testing.T) {
+ refusesHeld(t, hafresh.OwnerFor(hafresh.Self{Ref: "r", IID: "i-2", Boot: "b1"}, 41, false))
+}
+
+func TestLegacyTakeRefusesAnOldOwner(t *testing.T) {
+ refusesHeld(t, "box/v1;ref=r;iid=i-1;pid=41")
+}
+
+func TestLegacyTakeStillRefusesHALocks(t *testing.T) {
+ fx := previousBootBox(t)
+ body := leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "r", IID: "i-1", Boot: "b1"}, 41, true), unexpired())
+ fx.PutLock("instances/h", body)
+ _, err := lease.Acquire(ctx, fx.Bucket, "instances/h", "")
+ var ha *lease.HALockError
+ if !errors.As(err, &ha) {
+ t.Fatalf("an HA lock: %v", err)
+ }
+ if string(fx.LockBody("instances/h")) != string(body) {
+ t.Fatal("the HA lock was written")
+ }
+}
+
+// refusesHeld puts an unexpired lock owned by owner and checks the
+// acquire is refused as held, with the lock untouched.
+func refusesHeld(t *testing.T, owner string) {
+ t.Helper()
+ fx := previousBootBox(t)
+ body := leaseBody(owner, unexpired())
+ fx.PutLock("instances/h", body)
+ _, err := lease.Acquire(ctx, fx.Bucket, "instances/h", "")
+ var held *lease.HeldError
+ if !errors.As(err, &held) || held.Owner != owner {
+ t.Fatalf("owner %q: %v", owner, err)
+ }
+ if string(fx.LockBody("instances/h")) != string(body) {
+ t.Fatalf("owner %q: the lock was written", owner)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 12f796b46..de1d867b4 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -40,3 +40,4 @@ plan14-root-reads-rootfs-worker-exit.tsv 7ebc3871ee3c93ff168bfa62d23d6be5a970786
plan14-root-reads-region-ha-p1b2.tsv 5b559ba7a42084908cb0fec08083bb2b9b3c9d960036fd10418f81e56304bb64
plan14-root-reads-analytics-agents.tsv 5b559ba7a42084908cb0fec08083bb2b9b3c9d960036fd10418f81e56304bb64
plan14-root-reads-region-ha-dead-holder-backoff.tsv 8f6a1865b0abcea9d4fb68232cc2a25263a106ec87f73bd4b3f2fb388971ebe5
+plan14-root-reads-managed-fleets-1c-451.tsv af326671321edda76c7e6217a47892605a9e3b886fa880ad6d049c2f28f63873
diff --git a/internal/provision/testdata/plan14-root-reads-managed-fleets-1c-451.tsv b/internal/provision/testdata/plan14-root-reads-managed-fleets-1c-451.tsv
new file mode 100644
index 000000000..092432a2c
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-managed-fleets-1c-451.tsv
@@ -0,0 +1,15 @@
+# Census overlay managed-fleets-1c-451, written by census-propose (#369). census-ruling-managed-fleets-1c-451, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-managed-fleets-1c-451.md.
+# 3 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy ad9bcce3338389507602740f11794371f7c5707753300679e3db3b36ed885f10 internal/activator/control.go systemctlControlGroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input (J4, as systemctlUnitState): new (rootfs Plan 2 Task 9): runs systemctl show -p ControlGroup --value <unit> as carlos, an unprivileged query of PID 1, for a unit name built by unitNameFor from the row's host; the answer is systemd's own; it starts and stops nothing; no root decision;rev3=census-ruling-managed-fleets-1c-451;basis=error path only: a failed systemctl show now returns unitStateError(err), appending systemctl's own stderr (<=200 bytes) to the error text for the log; the command, its arguments, the unit name and the parsing of a successful answer are unchanged file:CommandContext@92 0bd6628708731566c788752ab638489e17f61203c9ad5682bb0591a2e047138a
+@legacy 9d32d7eba47f2efa8cd6bc0193f7bb27090d2d50ddd36eecfe652a23c19e3dbb internal/activator/control.go systemctlUnitMainExit legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-worker-exit;basis=new: runs `systemctl show -p InvocationID,ExecMainCode,ExecMainStatus,SuccessExitStatus <unit>` as the agent (no privilege), the same shape as systemctlUnitState and systemctlControlGroup; the unit name is the handle's own (unitNameFor/rootfsUnitFor), not tenant input; output parsed as four key=value strings into MainExit (Astra R1 P2: SuccessExitStatus is the unit's clean-exit policy as systemd loaded it from the shipped template);rev3=census-ruling-managed-fleets-1c-451;basis=error path only: as systemctlControlGroup, unitStateError(err) on a failed systemctl show; command, arguments, unit name and parsing unchanged file:CommandContext@94 f6240e84056f6a594f3fcc4a942a4f0756076f875511a4582b29f7554d1193c8
+@legacy 89805171101a29ceabea1c828faba6e8833d78da52b2d057262ddc4e1cf71c06 internal/activator/control.go systemctlUnitState legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-managed-fleets-1c-451;basis=error path only: as systemctlControlGroup, unitStateError(err) on a failed systemctl show; command, arguments, unit name and parsing unchanged (#451 diagnosis: tells a lost D-Bus at shutdown from other failures) file:CommandContext@97 d94db59c4f3c92e4a72973ff30093b8e3ad869ffb6b32dc8287f09a36c0afdc8
+@legacy f2763cd6c8a4295b13ce6ac9a22887d25a50f8c1dc7af4a3edf27fda6da478e2 internal/host/haself.go readBootID legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-1c-451;basis=new: reads the fixed kernel path /proc/sys/kernel/random/boot_id (package var bootIDPath, set only by tests) as the agent (carlos), trimmed, "" on any error; the value goes only into the agent's legacy lease owner string (;boot=) and hafresh.PreviousBoot's comparison; no tenant, app or box agent names the path file:ReadFile@49 eaf14ea5c9b36e47ac5c5e642a9780e8bffe1353828864ca7c590fe3c58932f2
+internal/activator/control.go systemctlControlGroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input (J4, as systemctlUnitState): new (rootfs Plan 2 Task 9): runs systemctl show -p ControlGroup --value <unit> as carlos, an unprivileged query of PID 1, for a unit name built by unitNameFor from the row's host; the answer is systemd's own; it starts and stops nothing; no root decision;rev3=census-ruling-managed-fleets-1c-451;basis=error path only: a failed systemctl show now returns unitStateError(err), appending systemctl's own stderr (<=200 bytes) to the error text for the log; the command, its arguments, the unit name and the parsing of a successful answer are unchanged file:CommandContext@92 0bd6628708731566c788752ab638489e17f61203c9ad5682bb0591a2e047138a
+internal/activator/control.go systemctlUnitMainExit legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-worker-exit;basis=new: runs `systemctl show -p InvocationID,ExecMainCode,ExecMainStatus,SuccessExitStatus <unit>` as the agent (no privilege), the same shape as systemctlUnitState and systemctlControlGroup; the unit name is the handle's own (unitNameFor/rootfsUnitFor), not tenant input; output parsed as four key=value strings into MainExit (Astra R1 P2: SuccessExitStatus is the unit's clean-exit policy as systemd loaded it from the shipped template);rev3=census-ruling-managed-fleets-1c-451;basis=error path only: as systemctlControlGroup, unitStateError(err) on a failed systemctl show; command, arguments, unit name and parsing unchanged file:CommandContext@94 f6240e84056f6a594f3fcc4a942a4f0756076f875511a4582b29f7554d1193c8
+internal/activator/control.go systemctlUnitState legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-managed-fleets-1c-451;basis=error path only: as systemctlControlGroup, unitStateError(err) on a failed systemctl show; command, arguments, unit name and parsing unchanged (#451 diagnosis: tells a lost D-Bus at shutdown from other failures) file:CommandContext@97 d94db59c4f3c92e4a72973ff30093b8e3ad869ffb6b32dc8287f09a36c0afdc8
+internal/host/haself.go readBootID legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-1c-451;basis=new: reads the fixed kernel path /proc/sys/kernel/random/boot_id (package var bootIDPath, set only by tests) as the agent (carlos), trimmed, "" on any error; the value goes only into the agent's legacy lease owner string (;boot=) and hafresh.PreviousBoot's comparison; no tenant, app or box agent names the path file:ReadFile@49 eaf14ea5c9b36e47ac5c5e642a9780e8bffe1353828864ca7c590fe3c58932f2
+@coverage internal/activator 5f545d3f5fb8632dfc196d5513c1e8689424e15d818e578f4980a748b735d9ca
+@coverage internal/hafresh 27a69bbba984e1ad62c326da63cb68ddb332336fc96d1f8f7f5a9d8efa44fdf2
+@coverage internal/host c0a330a760956175bd038005e2a139f49d6912707e8ee7f975031b989353f36e
+@coverage internal/lease 1de7eda9c51c4309e3c8cb43e64fdbbec118e70827f36fb27a4f36ffa01fbda8