carlos / platform Public

Nearest-region never-reuse, merge A: record every hostname that holds data

Plan Tasks 2-4 (docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md,
spec rev 5 accepted 2026-10-26): a create-only hostname history in the control
store, a data-kind predicate with kind immutability, the mark written by every
data writer before any replayable creation intent (instance door, seeds and
imports, sidecars, lifetime allocation and recovery), and
'carlos system hosts-used status'. Mode stays 'incomplete': nothing is refused
for reuse yet and nearest-region stays off. An unwritable history answers 503
with S2. Astra: Task 2 READY at round 2, Task 3 and the branch READY AFTER FIXES
at round 1, fixes applied; census approved on #280.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from nearest-region-a into main.
claude agent, operated by paul@keymail.dev 70d3767265fa52b596285152480bd230a0cc23b2 parent 25bfb7a
42 files changed, +2,836 −16
  • docs/superpowers/notes/census-proposal-nearest-region-a.md +21 −0
  • docs/superpowers/notes/copy/nearest-region-never-reuse.md +12 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-branch-r1.md +26 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task2-r1.md +16 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task2-r2.md +7 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task3-r1.md +12 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r1.md +55 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r2.md +81 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r3.md +46 −0
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-r1.md +50 −0
  • docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-branch.md +87 −0
  • docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task2-R2.md +97 −0
  • docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task2.md +78 −0
  • docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task3.md +96 −0
  • docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md +252 −0
  • docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md +134 −0
  • internal/console/apiinstances.go +3 −1
  • internal/console/apiinstances_test.go +5 −2
  • internal/console/apiinstanceseed.go +3 −2
  • internal/console/apisidecars.go +8 −1
  • internal/console/apisidecars_test.go +5 −2
  • internal/console/authcli.go +3 −0
  • internal/console/browserupdates_test.go +22 −2
  • internal/console/claim_invariant_fixtures_test.go +1 −0
  • internal/console/claim_invariant_probes_read_test.go +2 −1
  • internal/console/hostsused.go +244 −0
  • internal/console/hostsused_writers_test.go +591 −0
  • internal/console/lifetimes.go +4 −0
  • internal/console/lifetimes_create.go +9 −0
  • internal/console/server.go +3 −0
  • internal/console/svcroutes_test.go +5 −2
  • internal/console/testdata/claim-routes.txt +1 −0
  • internal/provision/hostsused.go +241 −0
  • internal/provision/hostsused_test.go +278 −0
  • internal/provision/nearest_region_a_census_test.go +73 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/record_sequence.go +13 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-nearest-region-a.tsv +7 −0
  • system.go +7 −1
  • system_hostsused.go +98 −0
  • system_hostsused_test.go +138 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-nearest-region-a.md b/docs/superpowers/notes/census-proposal-nearest-region-a.md
new file mode 100644
index 000000000..9c98d5ac3
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-nearest-region-a.md
@@ -0,0 +1,21 @@
+# Census approval: nearest-region-a
+
+Ruling `census-ruling-nearest-region-a`. Every change below keeps the disposition it already has, so it needs an approval, not a decision.
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `system.go` `runSystem` | body | unchanged (0) | adds the hosts-used family to the system dispatch (carlos system hosts-used status, one GET of a console door as the operator); every existing command branch unchanged; no read added |
+| `system.go` `systemVerb` | body | unchanged (0) | adds "hosts-used" to the verb list, routed to runSystemHostsUsedVerb; no read added |
+
+Envelopes re-pinned: `.`, `internal/console`, `internal/provision`.
+
+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. Escalate 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. An escalation goes to the census owner as a decision.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `system.go` `runSystem`: authority, task B,C,D,F,G,J4. Basis: rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops the claims case (host.RunSystemClaims, deleted); every other branch unchanged; no read added
+- `system.go` `systemVerb`: authority, task B,C,D,F,G,J4. Basis: rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops "claims" from the verb list, so it now falls to the unknown-verb message; no read added
+
+Seal: `798a1ee3d8c8b775f963b9ae1dbc45e18628fa0c1e63404f46606601766ad66c` → `798a1ee3d8c8b775f963b9ae1dbc45e18628fa0c1e63404f46606601766ad66c`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-nearest-region-a.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/copy/nearest-region-never-reuse.md b/docs/superpowers/notes/copy/nearest-region-never-reuse.md
new file mode 100644
index 000000000..bb8f307fc
--- /dev/null
+++ b/docs/superpowers/notes/copy/nearest-region-never-reuse.md
@@ -0,0 +1,12 @@
+# Nearest-region never-reuse: approved copy
+
+Approved by Paul in copy review on 2026-10-26, unedited. Apply verbatim; `<host>` and `<target>` are placeholders.
+
+- **S1**: <host> is in use or has held an app's data before, so it can't be created. Choose another address.
+- **S2**: Could not check whether <host> is free. Try again.
+- **S3**: An app's placement can't be changed once it exists.
+- **S4**: New instances can't be created on <target> yet. Choose another region.
+- **S5**: New instances can't be created right now. Try again later.
+- **S6**: <host>: not migrated. Its destination record is gone, and recreating it would reuse a hostname that held data.
+- **S7**: Moves and placement are paused for maintenance. Try again later.
+- **S8**: New instances can't be created during maintenance. Try again in a few minutes.
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-branch-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-branch-r1.md
new file mode 100644
index 000000000..6dba71f51
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-branch-r1.md
@@ -0,0 +1,26 @@
+No P1 findings.
+
+**P2 — Task 4: the CLI witness bypasses command execution.**
+[system_hostsused_test.go:12](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/system_hostsused_test.go:12) tests `systemVerb`, then calls the request and printing helpers directly with a fake getter. It never exercises `runSystem` or `runSystemHostsUsedVerb`.
+
+Removing the dispatch at [system.go:97](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/system.go:97), or breaking session wiring, would leave this witness passing while the command fails.
+
+**Fix:** invoke the real command against a local HTTP fixture using isolated operator credentials. Assert the GET path, bearer token, output and failure exit. For a subprocess, use `carlosTestEnv` and a scratch working directory.
+
+**Fault family:** entry-point witness coverage; brief check 4 requires the CLI witness to exercise the real entry point.
+
+**Census approvals**
+
+For commit `7eb8354c2d23523c545cb10f34255f57b7c2472a`:
+
+- **APPROVE — `system.go:runSystem`.** The [new dispatch](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/system.go:97) retains explicit operator invocation and leaves existing branches unchanged. No direct root read added.
+- **APPROVE — `system.go:systemVerb`.** The [verb addition](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/system.go:54) only selects dispatch; its recorded authority basis remains intact.
+- **APPROVE — envelope `.`.** The [new command](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/system_hostsused.go:79) uses existing session resolution and performs a GET to a fixed endpoint. Response decoding and formatting introduce no additional root authority.
+- **APPROVE — envelope `internal/console`.** The [marking helpers](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/console/hostsused.go:93) preserve existing create checks and record destinations. The [status handler](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/console/hostsused.go:204) uses `apiSystemRoller`, lists a fixed prefix and reads existing SQLite tables. Its [route registration](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/console/authcli.go:1072) excludes every service role. No root trust boundary is widened.
+- **APPROVE — envelope `internal/provision`.** [History keys](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/provision/hostsused.go:61) validate hostnames or use fixed metadata names. The [kind guard](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/provision/record_sequence.go:163) checks supplied bytes without adding reads or weakening existing checks.
+
+`gofmt -l .` is clean. Targeted tests could not start because the read-only sandbox denied Go’s temporary build directory; builds, vet and executable census checks remain unverified. `git diff --check` reports whitespace in review Markdown. No files changed; `GOCACHE` remained unset.
+
+Fix the P2 without reopening this review, under the brief’s stopping rule.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task2-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task2-r1.md
new file mode 100644
index 000000000..4929ca825
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task2-r1.md
@@ -0,0 +1,16 @@
+- **P1 — Task 2 / check 4: kind immutability uses different decoding rules from record readers.**
+ **Fault family:** an exempt record must never become a live data-kind record in place.
+
+ [`kindOfFields`](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/provision/hostsused.go:213) reads only lowercase `"kind"`. [`DecodeRecord`](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/provision/maintenance.go:73) uses Go’s case-insensitive field matching, where later matching fields overwrite earlier ones.
+
+ **Failure scenario:** a stored record containing `"kind":"instance","Kind":"static"` is read as **static**. Lifetime migration calls [`MarkMigrating`](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/provision/lifetime_migration.go:87), which marshals the fields in sorted order: `"Kind":"static"` now precedes `"kind":"instance"`. The resulting record reads as **instance**. The new guard sees lowercase `"kind":"instance"` on both sides and permits the change through [`migrationMarkLocked`](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/console/lifetimes_migrate.go:273). An exempt record therefore becomes a data-kind record without passing through creation and marking.
+
+ The same mismatch also rejects legitimate same-kind updates when an existing record uses only `"Kind":"static"` and a typed updater writes canonical `"kind":"static"`.
+
+ **Fix:** decode the effective kind from the original JSON using the same rules as `DecodeRecord`. Check the final bytes after sequence re-encoding, which can also reorder aliases. Add regression coverage for mixed spellings, migration, sequence advancement, and same-kind typed updates.
+
+No separate P2 or P3 findings.
+
+Targeted tests could not start because the read-only sandbox refused Go’s temporary build directory. This finding is source-verified. `GOCACHE` remained unset; no files were edited.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task2-r2.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task2-r2.md
new file mode 100644
index 000000000..fd585f126
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task2-r2.md
@@ -0,0 +1,7 @@
+Round 1 P1 — **resolved**: kind comparison now uses record-reader decoding rules and checks the bytes after sequence re-encoding ([hostsused.go:205](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/provision/hostsused.go:205), [record_sequence.go:163](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/provision/record_sequence.go:163)). No round 1 P2s.
+
+No new P1, P2, or P3 findings within Task 2’s scope. Reviewed store conflict handling, hostname validation, modes, data-kind classification, tombstone handling, existing callers, nested wrappers, and census changes.
+
+Targeted tests could not start because the read-only sandbox denied Go’s temporary build directory. This verdict is based on source review. `GOCACHE` remained unset; no files were edited.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task3-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task3-r1.md
new file mode 100644
index 000000000..2a22e3448
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task3-r1.md
@@ -0,0 +1,12 @@
+No P1 findings.
+
+**P2 — Task 3: temporary-site exemption witness never creates a record.** At [hostsused_writers_test.go:400](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/console/hostsused_writers_test.go:400), the subtest calls `createTemporary` and immediately checks `noMarks`. That helper only registers the temporary app; it does not create its static instance record.
+
+A regression that marks temporary-site records would therefore escape this subtest. Extend it to create the temporary app’s static platform-host record through the real instance door, assert that the record exists, then assert no marks—with lifetimes both off and on.
+
+Fault family: exemption witness coverage (brief checks 5 and 8).
+
+Targeted tests could not start because the read-only sandbox prevented Go from creating its build directory under `$TMPDIR`. `git diff --check` passed. No files changed; GOCACHE remained unset.
+
+**READY AFTER FIXES**
+
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r1.md
new file mode 100644
index 000000000..ca6364ef5
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r1.md
@@ -0,0 +1,55 @@
+NOT READY
+
+1. **P1 — The in-region allowance still permits predecessor data and processes to be reused.** The rail checks bucket LTX files only; it skips entirely when `HibernateBucket` is unset ([createleftovers.go:43](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/createleftovers.go:43), [:69](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/createleftovers.go:69)). An existing local DB wins without an ownership check ([backend_exec.go:819](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/activator/backend_exec.go:819)). An already-awake process can also win without another restore ([activator.go:1509](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/activator/activator.go:1509), [:1534](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/activator/activator.go:1534)). Sidecars use the same hostname-derived DB layout ([sidecar_reconcile.go:131](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/provision/sidecar_reconcile.go:131)).
+
+ **Fix:** a clean bucket must not authorize reuse by itself. Retaining the exception requires proving the predecessor’s processes and replicators stopped, removing or safely parking its local data on every box that could serve it, and preventing stale admission during that transition. Refuse when the bucket is unconfigured or evidence is unavailable. A README purge procedure does not enforce this. The smallest safe scope cut is to refuse used hostnames at home too.
+
+2. **P1 — The proposed marking sites miss actual record writers.** Seeds and imports return from the instance handler before its two listed write arms ([apiinstances.go:1613](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apiinstances.go:1613)); `createSeedRecord` independently dispatches both writes ([apiinstanceseed.go:82](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apiinstanceseed.go:82)). Lifetime-enabled attach bypasses `domainattach.go:259` and writes through `createRecordWithLifetimeLocked` ([domainattach.go:227](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/domainattach.go:227), [:680](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/domainattach.go:680)). Recovery can publish an allocation without re-entering any HTTP create door ([lifetimes_recovery.go:202](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/lifetimes_recovery.go:202)).
+
+ The shared validation point does cover instance creates, canary, deploy’s first create, explicit regions, app-region placement, seeds and imports. That does **not** make their write sites shared.
+
+ **Fix:** explicitly include `createSeedRecord`, lifetime attach, and allocation recovery in the marking invariant. Mark before persisting replayable creation intent; settle pre-upgrade pending allocations before declaring history complete. For `accounts migrate`, preserve an existing hostname mark or create it before copying a record: claims-off migration currently writes directly to the store ([accounts_record_sequence.go:17](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/accounts_record_sequence.go:17)).
+
+3. **P1 — Create-only history is atomic evidence of use, but does not serialize reuse.** The store’s conditional PUT protects one key ([store.go:39](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/release/store.go:39)). Instance record keys are app-scoped; the code explicitly documents that concurrent creates from different apps can both pass hostname checks and write records ([apiinstances.go:1175](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apiinstances.go:1175)).
+
+ Two requests can pass those checks before either writes. One wins the history PUT; the other counts the host as used but remains eligible for the home-region exception. An empty home bucket does not prove that the winner has finished or owns no record elsewhere.
+
+ **Fix:** refuse a request that loses a fresh-marker PUT; do not turn that conflict into immediate home-region reuse. Any retained reuse path needs hostname exclusion and ownership revalidation through record publication, including lifetimes-off operation. Refusing all reuse avoids adding another ownership protocol. A successful mark followed by a failed record write or crash is conservatively safe; its permanent refusal is an availability tradeoff.
+
+4. **P1 — Backfill and import cannot establish completeness as specified.** The import names non-console buckets and pool directories, but omits local-only data on ordinary regional boxes and customer fleet boxes ([design:49](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md:49)). Those local databases can later be accepted directly. “Existing record listing” is also insufficient: even `ListAllRecordsStrict` excludes records under missing or soft-deleted accounts ([reconcile.go:2509](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/provision/reconcile.go:2509)); ordinary instance and sidecar listings skip malformed records ([provision.go:2980](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/provision/provision.go:2980), [sidecar.go:353](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/provision/sidecar.go:353)).
+
+ **Fix:** inventory raw record keys, including Trash/orphans; configured replica prefixes; staging; and local storage on every relevant platform, pool and fleet box. Define a stable inventory window covering legacy deletions and pending writes. Keep provider discovery in the adapter.
+
+ If an operator cannot list a required bucket or inspect a required box, **`complete` must refuse**. Every host continues to count as used: all non-console, pool and fleet creates remain refused. Home creates still need finding 1 resolved. Naming every region is not evidence that every inventory succeeded.
+
+5. **P1 — The rollback remedy loses deleted history, and restore has no defined boundary.** The disposition says to rerun backfill after an old console ([design:132](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md:132)). A hostname created **and deleted** during that downgrade is absent from backfill, while its data can remain. A persisted or cached `@complete` then authorizes it as new.
+
+ **Fix:** prohibit creation by pre-marking console binaries after activation. State that history is monotonic: restoring only console SQLite is safe for this invariant while the control-store history remains intact; restoring that store backwards is not. Recovery must preserve the union of marks or restart every console in incomplete mode and repeat the full inventory before admitting remote creates. Backfill alone cannot repair this. Account migration within the same store preserves history only if its source hosts were already marked.
+
+6. **P1 — `apps place` bypasses the proposed placement restriction.** It updates local route placement and rewrites existing instance records’ regions directly ([fleets.go:679](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/fleets.go:679), [:702](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/fleets.go:702)). It does not run the create gate or offline landing cleanup.
+
+ A hostname recreated at home can therefore be placed onto a fleet holding an older lifetime’s database despite the design’s “not on a customer fleet” rule.
+
+ **Fix:** refuse placement changes for populated apps under this design, before writing placement or routes. Preserve placement of empty apps followed by properly gated first creates. Do not add another move protocol here.
+
+7. **P1 — Offline landing prevents target contamination, but the blanket safety claim includes data loss.** Parking warm files and verifying staging are real ([movesoffline_land.go:550](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/host/movesoffline_land.go:550), [:700](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/host/movesoffline_land.go:700)). With a valid source, successful promotion replaces the target replica. However, it deletes destination-only objects ([mirror.go:332](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/lease/mirror.go:332)); it does not preserve an older lifetime’s potentially sole remaining bucket copy. Local parking does not protect that copy.
+
+ Moreover, a recreated source admitted over an old warm DB can checkpoint that DB **before its first wake** ([movesoffline_seal.go:398](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/host/movesoffline_seal.go:398)). Correct target mirroring would then faithfully transfer predecessor data.
+
+ **Fix:** close source reuse first, and refuse dirty destinations before staging can overwrite them. The cited self-serve cleanliness rule is a design requirement, not an implemented safeguard at this commit. Keep that dependency explicit; do not call arbitrary older-lifetime destinations safe.
+
+8. **P2 — “Create here, then `carlos move`” is not an available general escape route.** Offline mutations require an operator’s CLI token ([apiinstancemove_offline.go:90](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apiinstancemove_offline.go:90)). Move gates read instance records and reject static, pooled and fleet routes ([apiinstancemove.go:65](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apiinstancemove.go:65)). They do not move sidecars.
+
+ **Fix:** make choosing another hostname the supported remedy for this release. Mention moving only where an implemented, authorized offline path applies. Do not make this small plan depend implicitly on shipping self-serve moves.
+
+9. **P2 — One plan is appropriate, but its finish lines do not prove its safety claims.** Tasks 1–7 omit concurrent creates, recovery writers, inaccessible inventories, history restore, migration, placement bypasses and local-only leftovers ([design:165](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md:165)). Task 3 explicitly treats a clean bucket as sufficient.
+
+ **Fix:** retain one plan and require those refusal witnesses, plus mark-before-publication assertions for every writer with lifetimes on/off. Verify canary, deploy, explicit/app regions, temporary static creates, seeds/imports, sidecars and both attach arms through their real entry points.
+
+ Correct two supporting claims: sidecars currently use the request region or fleet placement, not the app-region default ([apisidecars.go:269](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apisidecars.go:269)). Also specify how a console started before completion observes `@complete`: restart after completion, or request-time rereads with the additional cost stated. No new box polling is necessary.
+
+10. **P2 — The round-1 disposition table closes unresolved findings.** At [design:127](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md:127): #1’s lifetime dependency is removed, but sidecar safety remains subject to findings 1–4 above; #2’s proposed archive is removed, but local residue is not limited to operator purges; #3 and #7 are removed; #4 and #5 remain open; #6’s new box-format concern disappears, but console rollback remains open; #8’s counter issue disappears, but restore and migration require explicit guarantees; #9’s old capability gate disappears, but completion-cache costs need correction; #10 remains open.
+
+ **Fix:** record these as removed mechanisms versus unresolved safety obligations. Also label the next revision **Option B, round 2 of 3**; this review is its round 1, separately from the discarded lifetime design.
+
+Reviewed against `2f1f5589`. Read-only; no files changed, tests run, or live operations performed.
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r2.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r2.md
new file mode 100644
index 000000000..72bf368fa
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r2.md
@@ -0,0 +1,81 @@
+NOT READY
+
+1. **P1 — `accounts migrate` retains a recreation exception.**
+
+ The spec allows an existing mark to count as success for migration ([spec:28](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md:28)). But migration performs a create-only copy whenever the destination key is absent ([accounts_record_sequence.go:17](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/accounts_record_sequence.go:17)), and deliberately retains the source objects ([accounts.go:69](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/accounts.go:69)). Rerunning it after deleting the destination can therefore republish saved record bytes. Neither the copy loop nor the proposed mark conflict establishes that this is a continuing live instance rather than a resurrection.
+
+ **Fix:** after activation, refuse migration that would create a data-kind record at an absent destination. Permit an already-present, identical destination and migration of unrelated objects. This cuts the exception without adding a migration protocol. Task 5 must witness **migrate → delete destination → migrate again → refusal**, with lifetimes on and off.
+
+2. **P1 — Inventory still cannot establish the global “ever used” claim.**
+
+ Three gaps remain in [§3](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md:36):
+
+ - **Closing an unreadable fleet is insufficient.** It prevents creates there, but leaves its historical hostnames unknown. Those names can still be accepted elsewhere. “Every target succeeded **or was closed**” is weaker than the chosen global rule. The same problem returns when a previously unexamined fleet joins after completion.
+ - **Present objects are not complete historical evidence.** Records can be deleted outright ([provision.go:2860](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/provision/provision.go:2860)). Ordinary store listings use `ListObjectsV2`, not historical versions ([store.go:1055](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/release/store.go:1055)). Data-bucket noncurrent versions also expire, with a seven-day default ([bucket lifecycle:95](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/infra/modules/deployment-buckets/main.tf:95)). A fully removed pre-marking hostname cannot be reconstructed from the specified sources.
+ - **The scan names default layouts, without defining their interpretation or a stable scan window.** Replica prefixes are configurable ([activator.go:147](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/activator/activator.go:147)); nested directory names can be hashes, with the full hostname inside ([provision.go:3140](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/provision/provision.go:3140)). Deletion/purge during the scan can remove unmarked evidence. Terminal allocation/retirement checks alone do not freeze those sources.
+
+ **Fix:** remove the “closed target permits completion” alternative. An uninventoryable fleet means this deployment cannot complete this global inventory; nearest-region stays ineffective, as Paul specified. Define the authoritative target roster, configured paths/prefixes, historical evidence and a short operator-controlled inventory window. Refuse completion for missing, unmappable or irrecoverable history, and refuse admission of unexamined existing targets afterward. Tasks 6 and 10 need these refusal witnesses—not merely successful directory listings.
+
+3. **P1 — The populated-app placement refusal is still vulnerable to concurrent creation.**
+
+ The proposed check precedes writes, but the retained mechanism changes app placement, then registry routes, then instance records ([fleets.go:665](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/fleets.go:665), [:679](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/fleets.go:679), [:702](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/fleets.go:702)). Instance creation reads placement earlier and publishes later ([apiinstances.go:1217](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apiinstances.go:1217), [:1702](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apiinstances.go:1702)).
+
+ An “empty” check can pass, a create can publish and begin serving at the old location, and placement can then repoint it without moving its data. Checking only bucket records also misses existing hand-added data routes that `SetPlacement` will mutate.
+
+ **Fix:** for this round’s scope cut, disable placement changes under Option B rather than retaining the existing repointing loops behind a preflight check. If empty-app placement remains, specify exclusion against every create/recovery writer and cover existing registry routes. Task 8 needs a barrier-controlled create-versus-place witness through the API and both page entry points.
+
+4. **P1 — A procedural rollback floor is acceptable, but its scope and breach cost are understated.**
+
+ A trusted-operator floor is reasonable for this design; it does not require new box enforcement. However, it must cover **every record-writing binary**, including the standalone `carlos accounts migrate`, not just the console.
+
+ The inspected external script at `carloku-infrastructure` commit `cb460ae5` currently checks cleanliness and builds the supplied checkout’s HEAD ([roll-console.sh:39](/home/paulca/github.com/carlosframework/carloku-infrastructure/scripts/roll-console.sh:39)). The proposed floor is therefore implementation work that must land before completion, with a refusal test—not only documentation reviewed under task 11.
+
+ A breach costs more than another scan:
+
+ - An old writer can admit reuse before the next startup tripwire.
+ - A create-and-delete during the breach leaves no current record to detect.
+ - Re-inventory cannot reconstruct evidence that has disappeared, as finding 2 explains.
+ - Reverting to the spec’s ordinary incomplete mode permits used names again ([spec:47–52](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md:47)); that is not a safe recovery mode for a previously activated deployment.
+
+ **Fix:** document and enforce the minimum release for console and migration CLI. Distinguish **initial incomplete**, where today’s behaviour remains, from **history invalidated after activation**, where data-kind creates are refused. Re-enable only when history can actually be recovered; otherwise keep that deployment outside the feature’s scope. A rescan cannot undo data exposure or overwriting that already happened.
+
+5. **P2 — The exemptions are supported, but the plan’s witnesses and response promises need correction.**
+
+ **Exemptions:** valid provisioned `static` and `service` records do not acquire platform database paths: `DerivesPaths` requires an addressless instance, and `RouteFor` derives paths only under that predicate ([provision.go:456](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/provision/provision.go:456), [reconcile.go:505](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/provision/reconcile.go:505)). Validation refuses static hibernation, requires service upstreams, and refuses upstream hibernation. It also rejects a replica role on either exempt kind ([provision.go:656](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/provision/provision.go:656)). Seed/import requests reject both kinds ([apiinstanceseed.go:90](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apiinstanceseed.go:90)). Updates revalidate shape. Task 1’s explicit kind-immutability guard remains appropriate. Sidecars correctly remain data kinds.
+
+ **Writer coverage:** the revised sites cover the live ordinary claims-off paths. Instance creates dispatch to lifetime creation or direct creation; seeds/imports dispatch independently through `createSeedRecord`. The lifetime mark belongs before `BeginAllocation`, not merely before record publication ([lifetimes_create.go:107](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/lifetimes_create.go:107)). Recovery publishes through `allocRecordLocked`, so its mark check must cover both replay branches ([lifetimes_recovery.go:202](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/lifetimes_recovery.go:202)). Sidecars use the direct writer with claims off even when lifetimes are on. Attach’s two arms and deploy’s automatic first record are static and exempt. The migration exception remains finding 1.
+
+ **Keep the one plan, but amend its eleven tasks:**
+
+ | Task | Required correction or witness |
+ |---|---|
+ | 1 | Keep; test shape restrictions and kind immutability through real updates. |
+ | 2 | Separate data writers from exempt attach/deploy/temporary-static cases. Exempt cases must **not** mark. Explicitly cover sidecars with lifetimes on too. |
+ | 3 | Assert one successful publication and one refusal. Do not require U2 specifically: existing ownership checks can refuse before the marker PUT. |
+ | 4 | Cover missing/erroring marks during recovery, both replay branches, pre-upgrade pending work, and work spanning completion. |
+ | 5 | Add the migration resurrection refusal from finding 1. |
+ | 6 | Add unknown/closed targets, historical-only names, scan races and incomplete target rosters. |
+ | 7 | Cover post-activation history invalidation and a downgrade create/delete invisible to the startup tripwire. |
+ | 8 | Add the placement race and route-only case—or test the scope-cut refusal. |
+ | 9 | Test an **already stored non-home app region** before completion. Creation currently reads it independently of `appRegionsOn` ([apiinstances.go:1232](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apiinstances.go:1232)). |
+ | 10 | Verify configured layouts, hashed directories, pagination and explicit failures against the full target roster. |
+ | 11 | Implement and test the external floor before activation; document all writers and the actual breach cost. |
+
+ Also simplify U1/U2 to one marker-conflict refusal: the conditional PUT returns the same conflict for an old mark and a concurrent winner ([store.go:34](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/release/store.go:34)). The promised duplicate-first read is currently skipped outside the home-bucket rail ([createleftovers.go:136](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/createleftovers.go:136)). Finally, startup needs body reads to distinguish unmarked exempt records; two key listings alone cannot implement that tripwire. Correct the cost statement.
+
+The round-1 disposition table should therefore read:
+
+| Round-1 finding | Round-2 disposition |
+|---|---|
+| 1 — Home reuse | **Fixed at the policy root**, subject to establishing history. |
+| 2 — Missing writers | **Coverage corrected; still open for migration’s recreation exception.** |
+| 3 — Concurrent reuse | **Fixed for ordinary post-activation creates** by refusing marker conflicts. |
+| 4 — Inventory | **Still open, P1.** Closing an unknown target does not establish global history. |
+| 5 — Rollback/restore | **Still open, P1.** Floor scope and recovery after lost history remain incomplete. |
+| 6 — Placement bypass | **Still open, P1.** Sequential refusal does not cover concurrent creates or route-only state. |
+| 7 — Offline moves | **Scoped out for previously reused hosts; addressed for genuinely fresh post-activation hosts.** Version recovery is time-limited, not permanent preservation. |
+| 8 — Move as remedy | **Fixed.** Choosing another hostname is the supported remedy. |
+| 9 — Plan/witnesses | **Partially fixed, P2.** Completion observation is specified; witness corrections remain above. |
+| 10 — Overclosed table | **Still open, P2.** Several “answered” entries remain conditional or incomplete. |
+
+Reviewed against `fd47a8d6`. Read-only; no files changed, tests run, or live operations performed.
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r3.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r3.md
new file mode 100644
index 000000000..319010e95
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r3.md
@@ -0,0 +1,46 @@
+NOT READY
+
+1. **P1 — A marked, pre-activation allocation can publish over old data after `complete`.**
+
+ Rev 4 blocks completion only for pending rows **from a pre-marking console** ([spec:43](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md:43)). But the marking console still admits today’s creates during initial incomplete mode, including non-home creates without a leftover-data check ([createleftovers.go:43](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/createleftovers.go:43)).
+
+ Concrete sequence: a deleted hostname H retains its former owner’s replica in a non-home region. Before inventory, a new create for H successfully writes its previously absent mark and begins a lifetime allocation. The slot write succeeds; record publication fails, leaving the allocation pending ([lifetimes_create.go:107](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/lifetimes_create.go:107), [:370](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/lifetimes_create.go:370)). Inventory finds H’s data and retains its mark. `complete` nevertheless passes because this allocation came from the marking console.
+
+ After activation, recovery’s “our slot, absent record” branch publishes it ([lifetimes_recovery.go:204](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/lifetimes_recovery.go:204)). Rev 4’s proposed mark-exists check passes. The new instance can restore the predecessor’s replica ([backend_exec.go:853](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/activator/backend_exec.go:853)). This is an actual post-activation data-exposure path; “never an unmarked publication” does not prevent it.
+
+ **Concrete cut to discuss with Paul:** require a maintenance boundary for activation: stop admitting data creates, drain in-flight writers, and refuse completion while **any** allocation or retirement remains pending, regardless of writer version. Resume only after every console observes active mode. Add a witness for the sequence above. Per the round limit, stop here for that scope decision.
+
+2. **P2 — The inventory-window freeze needs an executable boundary.**
+
+ Refusing move API requests does not pause moves already running on unchanged boxes. The worker independently dispatches offline moves ([movespass.go:1149](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/host/movespass.go:1149)); staging, sealing and landing continue from record state ([movesoffline.go:416](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/host/movesoffline.go:416)). Likewise, a placement request already past the proposed top-of-function refusal can still reach its writes.
+
+ **Fix:** make `begin` exclude new move/placement admissions and wait for admitted operations to finish; refuse to open the scan window with an unfinished move. Specify how consoles observe `begin`, `complete` and invalidation. This can accompany finding 1’s maintenance cut without changing boxes. The current “move attempted during the window” witness does not cover work already admitted.
+
+3. **P2 — The reader premise is substantially correct for ordinary Option B operation, but its version-read explanation is inaccurate.**
+
+ The inspected paths support current-data inventory:
+
+ | Reader | Evidence |
+ |---|---|
+ | Litestream restore | [lease.go:533](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/lease/lease.go:533); its client uses [ListObjectsV2](/home/paulca/go/pkg/mod/github.com/benbjohnson/litestream@v0.5.14/s3/replica_client.go:1405) and [GET without VersionId](/home/paulca/go/pkg/mod/github.com/benbjohnson/litestream@v0.5.14/s3/replica_client.go:657). |
+ | Promotion/mirror | [mirror.go:616](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/lease/mirror.go:616) lists current objects; [:683](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/lease/mirror.go:683) copies without a version ID. |
+ | `db pull/query`, forwarding and dbreads | The console uses [ReadReplicaClient](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apidb.go:492); the forwarding box wires [the same client](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/host/dbreads.go:154). |
+ | Seeds | [seeddoer.go:28](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/seeddoer.go:28) reads replica coordinates; snapshot placement uses [storeSeedObjects.Open](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/host/seedwiring.go:27), ultimately [an unversioned GET](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/release/store.go:924). |
+ | Offline stage/seal/land | [Stage](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/host/movesoffline_stage.go:174) mirrors current objects; [seal](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/host/movesoffline_seal.go:473) records the current listing; [landing](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/host/movesoffline_land.go:700) checks and restores that listing. |
+ | Warm cache | [backend_exec.go:819](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/activator/backend_exec.go:819) requires a present database; absent-database metadata is purged before restoration. |
+
+ However, **some readers can read noncurrent versions**: `SealedClient.OpenLTXFile` explicitly opens a pinned version ([sealedclient.go:147](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/moves/sealedclient.go:147)). That belongs to the generation/Phase 1 machinery, not the offline path described above. Claims and Phase 1 also have separate switches.
+
+ **Fix:** explicitly bound Option B to the supported claims/Phase 1 configuration and correct §1’s attribution. Do not present current-only reads as a repository-wide property. I found no noncurrent-version fallback in the ordinary paths listed above.
+
+4. **P2 — The current-object inventory omits seed snapshots.**
+
+ Source 2 names configured replica prefixes and `moves/`, but boxes also read `seeds/<host>/<id>/snapshot.db` ([seedwiring.go:25](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/host/seedwiring.go:25)). Current seed records normally mark their hosts, so this omission alone is **not a demonstrated cross-owner leak**.
+
+ **Fix:** include `seeds/` in the conservative inventory and test orphan snapshots. Otherwise document and prove why every surviving seed reference is necessarily covered by another inventoried source.
+
+The round-2 migration exception is **cut correctly**. The placement cut fixes its steady-state bypass, subject to the transition boundary above. The broader inventory and rollback policy address their earlier root problems, but completion is not yet safe because of finding 1. Closing fleets is defensible for isolation: reconciliation separates placements, and both [database access](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apidb.go:64) and [moves](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/console/apiinstancemove.go:83) refuse fleet routes.
+
+**The plan is not buildable safely as written.** The remaining P1 calls for the activation scope cut with Paul, not another design-review round.
+
+Reviewed at `62f019680df5abb5c143e7f36e3382311745499a`. Read-only; no files changed, tests run or live operations performed.
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-r1.md
new file mode 100644
index 000000000..f49ddfb46
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-r1.md
@@ -0,0 +1,50 @@
+NOT READY
+
+1. **P1 — Sidecars do not use the lifetime protocol.** The design’s claim that Plan 1 already supplies every creation path with a lifetime is false (`design:64–70`, `223–225`). `SidecarRecord` has neither `Incarnation` nor `ReplicaScope` (`internal/provision/sidecar.go:71`); its create door calls `CreateSidecarRecord` directly (`internal/console/apisidecars.go:390`), and lifetime retirement explicitly applies only to instances (`internal/console/hostclaimops.go:19`). Recreating a deterministic sidecar name therefore still reaches its predecessor’s storage.
+
+ **Fix:** explicitly design sidecar allocation, retirement, legacy adoption, recovery and route propagation. Include app purge and temporary-app expiry. Stamping `createRecordWithLifetimeLocked` cannot implement this by itself.
+
+2. **P1 — The proposed local archive remains readable by the replacement tenant.** The in-place rename in `design:102–106` leaves the archived database beside the replacement’s database. That entire directory is mounted read-write into the tenant (`internal/instancectl/gen.go:66–71`). A fresh database does not prevent the replacement app from opening the archived file directly. The existing layout code documents this exact hazard and deliberately archives outside the instance tree: [preflight.go:74](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-nearest-region-199/internal/layout/preflight.go:74).
+
+ **Fix:** keep the archive in-region but outside every tenant-visible mount, using existing agent-owned storage and safe rename operations. Verify that a replacement tenant cannot list or read its predecessor’s archive.
+
+3. **P1 — `<db>.life` is tenant-writable identity evidence.** The acceptance rule in `design:102–103` trusts a file inside that same writable directory. An old tenant can write the predictable next lifetime number before deletion; the replacement then accepts the old database as its own. Safe filesystem traversal alone does not authenticate the stamp.
+
+ **Fix:** store the authoritative local ownership evidence outside the tenant namespace. Bind it to the actual database installation and update it durably with replacement. Test forged, removed and symlinked tenant-side stamps. This can use existing agent authority; it does not require a new root operation.
+
+4. **P1 — A recreated record can continue using its predecessor’s running process without reaching restore.** Reconciliation installs the successor lifetime onto an existing unheld row (`internal/provision/reconcile.go:1435`, `2305–2331`). The activator indexes entries by hostname and returns an already-awake entry without comparing lifetimes (`internal/activator/activator.go:1509`, `1534–1557`). Even `wakeRouteChanged` checks account, app, address and seed identity, but not incarnation (`internal/activator/wakeidentity.go:36–51`). The proposed `restorePlain` check never runs in this case.
+
+ **Fix:** make lifetime replacement an ordered local transition: block new admission, cancel or finish an outstanding wake, prove the previous process and replicator stopped, set aside its data, then expose the successor. Check incarnation on awake admission, queued wakes and worker respawns. The lease remains sufficient for one writer **per lifetime**; separate lifetime leases do not serialize access to the shared local pathname.
+
+5. **P1 — Offline checkpoints and initial seed placement bypass the proposed local ownership check.** Changing bucket prefixes does not cover every local database consumer:
+
+ - Offline sealing checkpoints an existing local DB when its position is not behind the replica (`internal/host/movesoffline_seal.go:386–410`). The production checkpoint callback takes only `dbPath`, derives the host from its filename and starts replication (`internal/host/movespass.go:315–322`). After recreation, a predecessor’s local DB could therefore be uploaded into the successor’s scoped prefix without a wake.
+ - Initial seeded restore can purge the previous database and place the seed without calling `restorePlain` (`internal/activator/seedplace.go:172–207`). Its purge deletes the DB, WAL and metadata (`:341–355`), contrary to the archive requirement.
+
+ **Fix:** require verified local ownership before every checkpoint, replication start, seed replacement and warm-cache acceptance. Pass the judged record/route identity into checkpoint callbacks. Put archival before seed-marker cleanup. Test “recreate, then move before first wake” and “recreate with seed/import over an old local DB.”
+
+6. **P1 — A README floor does not protect existing records from rollback, and the console also needs protection.** The design explicitly admits that a downgraded box serves predecessor data (`design:180–183`). Stopping new placements cannot protect records already present. An old console is also dangerous: record updates decode into the old `Record` type and marshal it back (`internal/provision/provision.go:1051–1097`), dropping an unknown `replica_scope`; `WriteRecord` preserves sequence semantics, not unknown fields (`internal/provision/record_sequence.go:120–156`). Even upgraded boxes would subsequently interpret that record as legacy.
+
+ **Fix:** enforce a minimum release for boxes **and every record-writing console/process**, covering update, recovery, boot and retained binaries, before stamping begins. Existing floor machinery already addresses these activation paths (`internal/host/movesfloor.go:20–53`); specify how it is reused within the no-new-root-powers/no-new-poll constraints. Turning nearest-region off must leave scope handling and the floor enforced.
+
+7. **P2 — The quarantine operation lacks crash recovery and a disk bound.** `design:104–106` describes several renames but no durable operation record or recovery ordering. A crash after moving the DB but before moving its WAL leaves a split archive; today’s missing-DB restore subsequently purges remaining artifacts (`internal/activator/backend_exec.go:824–831`). A Unix timestamp is not itself a non-overwriting guarantee. Seven-day retention (`design:247–249`) also does not bound bytes accumulated within seven days, and neither plan implements cleanup.
+
+ **Fix:** specify a recoverable archive transaction, collision-proof destinations, durable completion and handling of partial renames. Add a byte/free-space limit and a defined refusal when exhausted. Assign cleanup to an existing housekeeping pass, with tests that protect incomplete archives and any sole recoverable copy.
+
+8. **P2 — “Never reused” needs a precise recovery boundary and migration policy.** For ordinary instance creation, the foundation is sound: allocation uses `max(console history, durable hostname slot)+1`, with overflow refusal (`internal/console/lifetimes_create.go:81–96`). Slots are hostname-global, so changing accounts does not reset the counter (`internal/provision/lifetime.go:46–52`). A console SQLite restore alone does not rewind an intact slot. Trash restore intentionally retains the same lifetime; seed/import creation enters the allocator (`internal/console/apiinstanceseed.go:82–87`; `apiinstanceimport.go:179`).
+
+ But unused void allocations may reuse numbers (`internal/console/lifetimes_store.go:185–191`), and `accounts migrate` bypasses its record-copy restrictions when claims are off (`accounts_record_sequence.go:17–40`). It can also change local route ownership directly (`accounts.go:457–471`). The design does not define that operation after cutover, or recovery when authoritative slots are restored backwards.
+
+ **Fix:** state the guarantee as “no lifetime that could have served data is reused, provided durable slots never regress.” Preserve slots and the cutover marker across restores; explicitly refuse or define lifetime-aware account migration. Add stale-console-DB recovery, cross-account recreation and migration tests.
+
+9. **P2 — The capability gate and request budget are underspecified.** The claimed “picker’s cached edges listing” (`design:143`) does not exist here: `liveEdges` performs a fresh read (`internal/console/regioncandidates.go:203`), comprising an edges LIST plus per-file GETs (`internal/edgesfile/snapshot.go:225–248`) and a status snapshot load (`:123–137`). The existing picker also always accepts home and excludes stale boxes from eligibility calculations (`internal/console/regioncandidates.go:81–82`, `101–117`), which is not equivalent to proving every potential reader understands the scope.
+
+ **Fix:** define one capability predicate for home, explicit regions, automatic placement, sidecars and move destinations. Specify missing/stale/incomplete evidence behavior. Reuse a request’s existing snapshot where available and state additional LIST/GET costs where it is not. No new per-box polling or AWS-specific core logic is inherently required by scoped names, but the proposed zero-additional-request claim is not yet demonstrated.
+
+10. **P2 — The plans’ finish lines do not prove complete path coverage or safe activation.** Removing two helpers and compiling (`design:205–209`) cannot prove that every caller supplied the correct scope. Several interfaces currently discard the needed identity: checkpoint takes only a path (`movespass.go:315`), seed replica deletion takes only a host (`seedwiring.go:242`), and hibernate verification carries only host/DB path (`ops/hibernate_verify.go:59`). Claim-based park discovery separately hard-codes flat namespaces (`internal/park/sweep.go:224–231`); it must be explicitly classified as unreachable with claims off, rather than assumed converted.
+
+ The **move naming itself is viable**: `MirrorPrefix` copies relative keys between explicit directory boundaries (`internal/lease/mirror.go:185–216`). Passing the same scope through stage, seal, land and promotion preserves it in either direction. However, the acceptance test must include A→B→A, stale same-lifetime replicas, predecessor leftovers, abort/retry, tombstones and local stamps—not only a successful outbound move.
+
+ **Fix:** retain two delivery phases if useful, but split their work into independently testable identity, local-transition, replica-consumer, move and floor tasks. Require exact-prefix witnesses for acquire/restore/promote, seeds, pull/query/forward, dbreads, verification, checkpoint, mirror and cleanup. Ordinary instance creates, canary (`canary.go:591`), deploy (`deploy.go:1023`) and explicit-region creates share the instance door (`apiinstances.go:1698–1703`); test those wrappers plus temporary/automatic placement and the separate sidecar protocol. Complete dev validation before flagship activation, enforce both capabilities and the rollback floor before stamping, and include rollback/restart witnesses before enabling nearest-region.
+
+`design` references identify `docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md`. All evidence is from `c49129d5`. Review was read-only; no tests or live operations were run.
\ No newline at end of file
diff --git a/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-branch.md b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-branch.md
new file mode 100644
index 000000000..0bdad1dc5
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-branch.md
@@ -0,0 +1,87 @@
+# Review brief: branch nearest-region-a (merge A of the nearest-region never-reuse plan), round 1 of 3
+
+Repo carlos/platform, branch `nearest-region-a`, commit 15f0ba08 (the brief's own commit follows it; review the code at that commit).
+Under review: the diff `b1d00ca7..15f0ba08` (`git diff b1d00ca7 15f0ba08`; b1d00ca7 is `origin/main`).
+Authorities: the accepted spec `docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md`
+(rev 5, accepted by Paul 2026-10-26) and the plan `docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md`,
+Tasks 2, 3 and 4 (merge A in its "Delivery and review sizing" table). Both are carried unchanged on this
+branch from `design-nearest-region-199` and land with it; treat them as fixed authorities, not unmerged
+work. Approved copy: `docs/superpowers/notes/copy/nearest-region-never-reuse.md`. AGENTS.md on main.
+
+You are an independent reviewer. Read the document, then the code it
+names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings in the spec (§1-§5, §3a). Report only mechanisms that fail to honour them.
+- Tasks 2 and 3 had their own reviews and are closed: Task 2 round 1 NOT READY (one P1, fixed), round 2
+ READY (`ASTRA-FINDINGS-nearest-region-a-task2-r1.md`, `-r2.md`); Task 3 round 1 READY AFTER FIXES (one
+ P2, applied in 15f0ba08; `ASTRA-FINDINGS-nearest-region-a-task3-r1.md`). Raise something in their code
+ again only with new evidence, such as an interaction with Task 4 or a merge-level effect.
+- Merge A scope: nothing changes what a user sees on create beyond Tasks 2-4, and the nearest-region
+ switch stays off (`appRegionsOn` is untouched). Merge B work (the activation window, inventory,
+ enforcement in recovery, tripwire, `apps place` and `accounts migrate` cuts, README) is out of scope.
+- The `carlos system hosts-used status` output lines and usage text are drafts; their copy review comes
+ with merge B. Report wording only if it is wrong about what the code does.
+- The status door answers `inflight_creates` and `unfinished_moves` as null until Task 5 can count them
+ (a deliberate deviation from the plan's "0 until then": a zero would claim a drain the console cannot
+ see).
+
+## What to check
+
+1. Task 4: the door is operator-only (`apiSystemRoller`), closed to every service credential, read-only,
+ and leaks no store error text. The mark count counts marks only (not `@mode`, `@floor` or anything
+ else under the prefix). Request cost: one listing of the prefix plus SQLite reads, per call.
+2. The CLI verb is wired into `systemVerb`/`runSystem`, uses the operator session, and prints only what
+ the door answered.
+3. Merge-level: the branch as a whole keeps every create door's existing answers in `incomplete` mode,
+ apart from the unwritable-bucket case (503 S2), and the root-read census changes (`runSystem`,
+ `systemVerb`: body) add no root read.
+4. Tests: each new witness goes through a real entry point and would fail without its implementation.
+5. Anything in the branch that would fail CI: build on linux, darwin and windows, vet, gofmt, the
+ record-write and root-read censuses, the route inventories (`claim_invariant_*`, `svcroutes_test.go`).
+
+## Census approval (separate from the verdict above)
+
+AGENTS.md, "The census: an approval, not a decision". The card is
+`docs/superpowers/notes/census-proposal-nearest-region-a.md`. For every unit on it (`system.go`
+`runSystem`, `system.go` `systemVerb`) and every re-pinned envelope (`.`, `internal/console`,
+`internal/provision`), give APPROVE or ESCALATE, citing the lines you read: compare a unit with its
+recorded disposition and basis on the card; for an envelope, read every changed function in that
+package in the diff and what it reaches. Escalate 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. Put these verdicts in their own section after the findings.
+
+## 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 section or task, 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). 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.
+
+In round 3, a NOT READY also says whether the P1s share one cause, and
+whether refusing the case up front or cutting the feature would remove
+them.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task2-R2.md b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task2-R2.md
new file mode 100644
index 000000000..618b7d7b5
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task2-R2.md
@@ -0,0 +1,97 @@
+# Review brief: nearest-region never-reuse, Task 2 (hostname history store, data-kind predicate, kind immutability), round 2 of 3
+
+Repo carlos/platform, branch `nearest-region-a`, commit da9f765e (the brief's own commit follows it; review the code at that commit).
+Under review: Task 2's commits `b5660975` and `da9f765e` (the round 1 fix), that is:
+`internal/provision/hostsused.go` (new), `internal/provision/hostsused_test.go` (new),
+`internal/provision/record_sequence.go` (`WriteRecord`), and the census bookkeeping
+(`nearest_region_a_census_test.go`, `plan9_b8_census_test.go`, `testdata/plan14-root-reads-*`).
+Authorities: the accepted spec `docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md`
+(rev 5, accepted by Paul 2026-10-26) and its plan `docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md`,
+Task 2. Both were reviewed and accepted on `design-nearest-region-199` and are carried unchanged on this
+branch (commit 9ceae022), so they land with this merge; treat them as fixed authorities, not as unmerged
+work. AGENTS.md on main ("Stopping rules", "The census").
+
+You are an independent reviewer. Read the document, then the code it
+names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings in the spec (§1-§5, §3a): marks are create-only and never deleted; data kinds are every
+ record whose `KindOrDefault()` is not `static` or `service`, plus sidecars; an absent `@mode` means
+ `incomplete`; one console process per deployment. Report only mechanisms that fail to honour them.
+- This is merge A: nothing reads `@floor` yet and no door writes `@mode` yet (Tasks 5-10 are merge B).
+ Do not report missing merge-B behaviour.
+
+## What to check
+
+1. `MarkHostUsed` is create-only (`Put` with `ifMatch ""`), maps only `release.ErrCASConflict` to
+ `(false, nil)`, and passes every other store error through. Check `release.Store` implementations
+ (`DirStore`, `S3Store`, any wrapper the console uses) answer a create-only conflict with
+ `ErrCASConflict` and nothing else, so an outage can never read as "already marked".
+2. `HostsUsedKey` returns `""` for anything `controlname.ValidHostShape` refuses, and no valid hostname
+ can collide with `@mode` or `@floor`, or escape the prefix.
+3. `ReadHostsMode`: absent is `incomplete`; an unreadable or unknown body is an error and never a
+ default. `WriteHostsMode` refuses unknown modes.
+4. Kind immutability in `WriteRecord` (`checkKindUnchanged`): an in-place write that changes a record's
+ kind is refused with `ErrKindChange`; a create from `{}` may be any kind; `""` and `instance` are one
+ kind. The tombstone exemption: `provision.TombstoneBody` keeps no `kind`, so without the exemption
+ retiring a static record would be refused. Check the exemption cannot be used to turn a live exempt
+ record into a live data-kind record (is there any writer that writes a non-tombstone body over a
+ tombstone in place?), and that every existing `WriteRecord` caller (console lifetimes, hostops,
+ `accounts_record_sequence.go`, `provision` update paths, the nested prepared-record path for store
+ wrappers) still works: none of them may now be refused for a write that keeps the kind.
+5. `Record.DataKind` matches the spec's exemptions exactly (addr-backed `instance` is a data kind).
+6. The record-write census entries (`nearest_region_a_census_test.go`) classify the new `Put` sites
+ correctly (`nonrecord`), and nothing in the diff weakens a census.
+
+## Round 2
+
+Earlier rounds: round 1, `docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task2-r1.md`
+(one P1, no P2). The round number counts every earlier review of this change, under any file name
+or reviewer.
+
+First give one line per P1 and P2 from round 1: resolved, partly, or not. Carry every unresolved or
+partly resolved finding forward at its current severity, then add new findings. The verdict covers
+everything outstanding, earlier rounds included. The fix: `checkKindUnchanged` now decodes `before`
+and the exact bytes about to be written with `json.Unmarshal` into a struct tagged like `Record`
+(the rules `DecodeRecord` uses), after any sequence re-encoding, immediately before the `Put`. A
+body that does not decode is refused unless it is byte-identical to `before`. Regression test:
+`TestWriteRecordKindReadsAsReadersDo`. Fault family of round 1: an exempt record must never become a
+live data-kind record in place. A second finding in that family stops the review (AGENTS.md
+stopping rule 2), so name the family beside each finding.
+
+Commit `da9f765e` also leaves the root-read census overlay as it was at `b5660975`; the census is
+re-proposed once for the whole branch at its end. Do not report that.
+
+## 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 section or task, 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). 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.
+
+In round 3, a NOT READY also says whether the P1s share one cause, and
+whether refusing the case up front or cutting the feature would remove
+them.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task2.md b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task2.md
new file mode 100644
index 000000000..d38a490a8
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task2.md
@@ -0,0 +1,78 @@
+# Review brief: nearest-region never-reuse, Task 2 (hostname history store, data-kind predicate, kind immutability), round 1 of 3
+
+Repo carlos/platform, branch `nearest-region-a`, commit 9ceae022 (the brief's own commit follows it; review the code at that commit).
+Under review: the diff `b1d00ca7..b5660975` (one commit), that is:
+`internal/provision/hostsused.go` (new), `internal/provision/hostsused_test.go` (new),
+`internal/provision/record_sequence.go` (`WriteRecord`), and the census bookkeeping
+(`nearest_region_a_census_test.go`, `plan9_b8_census_test.go`, `testdata/plan14-root-reads-*`).
+Authorities: the accepted spec `docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md`
+(rev 5, accepted by Paul 2026-10-26) and its plan `docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md`,
+Task 2. Both were reviewed and accepted on `design-nearest-region-199` and are carried unchanged on this
+branch (commit 9ceae022), so they land with this merge; treat them as fixed authorities, not as unmerged
+work. AGENTS.md on main ("Stopping rules", "The census").
+
+You are an independent reviewer. Read the document, then the code it
+names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings in the spec (§1-§5, §3a): marks are create-only and never deleted; data kinds are every
+ record whose `KindOrDefault()` is not `static` or `service`, plus sidecars; an absent `@mode` means
+ `incomplete`; one console process per deployment. Report only mechanisms that fail to honour them.
+- This is merge A: nothing reads `@floor` yet and no door writes `@mode` yet (Tasks 5-10 are merge B).
+ Do not report missing merge-B behaviour.
+
+## What to check
+
+1. `MarkHostUsed` is create-only (`Put` with `ifMatch ""`), maps only `release.ErrCASConflict` to
+ `(false, nil)`, and passes every other store error through. Check `release.Store` implementations
+ (`DirStore`, `S3Store`, any wrapper the console uses) answer a create-only conflict with
+ `ErrCASConflict` and nothing else, so an outage can never read as "already marked".
+2. `HostsUsedKey` returns `""` for anything `controlname.ValidHostShape` refuses, and no valid hostname
+ can collide with `@mode` or `@floor`, or escape the prefix.
+3. `ReadHostsMode`: absent is `incomplete`; an unreadable or unknown body is an error and never a
+ default. `WriteHostsMode` refuses unknown modes.
+4. Kind immutability in `WriteRecord` (`checkKindUnchanged`): an in-place write that changes a record's
+ kind is refused with `ErrKindChange`; a create from `{}` may be any kind; `""` and `instance` are one
+ kind. The tombstone exemption: `provision.TombstoneBody` keeps no `kind`, so without the exemption
+ retiring a static record would be refused. Check the exemption cannot be used to turn a live exempt
+ record into a live data-kind record (is there any writer that writes a non-tombstone body over a
+ tombstone in place?), and that every existing `WriteRecord` caller (console lifetimes, hostops,
+ `accounts_record_sequence.go`, `provision` update paths, the nested prepared-record path for store
+ wrappers) still works: none of them may now be refused for a write that keeps the kind.
+5. `Record.DataKind` matches the spec's exemptions exactly (addr-backed `instance` is a data kind).
+6. The record-write census entries (`nearest_region_a_census_test.go`) classify the new `Put` sites
+ correctly (`nonrecord`), and nothing in the diff weakens a census.
+
+## 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 section or task, 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). 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.
+
+In round 3, a NOT READY also says whether the P1s share one cause, and
+whether refusing the case up front or cutting the feature would remove
+them.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task3.md b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task3.md
new file mode 100644
index 000000000..4a916bd7b
--- /dev/null
+++ b/docs/superpowers/notes/reviews/CODEX-REVIEW-BRIEF-nearest-region-a-task3.md
@@ -0,0 +1,96 @@
+# Review brief: nearest-region never-reuse, Task 3 (mark in every data-kind create writer), round 1 of 3
+
+Repo carlos/platform, branch `nearest-region-a`, commit 8d5c39e3 (the brief's own commit follows it; review the code at that commit).
+Under review: commit `8d5c39e3` (`git show 8d5c39e3`), that is `internal/console/hostsused.go` (new),
+`internal/console/hostsused_writers_test.go` (new), the call sites in `apiinstances.go`,
+`apiinstanceseed.go`, `apisidecars.go`, `lifetimes_create.go` (`createRecordWithLifetimeLocked`),
+`lifetimes.go` (`lifetimeCreateRefusal`), `server.go` (one field), two existing tests whose expected
+status changed (`TestAPIInstanceStoreFailure`, `TestAPISidecarStoreFailure`), and census bookkeeping.
+Task 2 (the provision primitives it calls: `MarkHostUsed`, `ReadHostsMode`, `Record.DataKind`) was
+reviewed separately and is READY; do not re-review it.
+Authorities: the accepted spec `docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md`
+(rev 5, accepted by Paul 2026-10-26; §2 is the writer table) and the plan
+`docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md`, Task 3. Both are carried unchanged on
+this branch from `design-nearest-region-199`; treat them as fixed authorities, not unmerged work. The
+approved strings are `docs/superpowers/notes/copy/nearest-region-never-reuse.md` (S1, S2, S5, S8 used
+here). AGENTS.md on main ("Stopping rules").
+
+You are an independent reviewer. Read the document, then the code it
+names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings in the spec: marks are create-only and never deleted; a mark followed by a failed write
+ or crash leaves the hostname refused for ever (accepted); exempt kinds are static and service; sidecars
+ always mark; attach, deploy's static first create and temporary static sites are exempt; a conflict in
+ active mode is S1 whoever wrote the mark; one console process per deployment, which reads `@mode` once.
+- This is merge A. Out of scope here, and not to be reported as missing: lifetime recovery's own marking
+ inside `allocRecordLocked` (Task 7), the activation window and admissions (Task 5), `accounts migrate`
+ (Task 10), the claims-on `hostops` writers (unreachable with claims off; spec §2), and the mode never
+ being anything but `incomplete` in production until merge B.
+- The private-storage walk and `bindEnvironmentCreate` run before the mark on purpose: the plan puts the
+ mark immediately before the persisting call, and a store walk that answers "pending approval" must not
+ burn the hostname. A store left behind by a refused create is the existing, accepted residue of
+ #412 (comment in `handleAPIInstanceCreate`).
+
+## What to check
+
+1. Every data-kind record create in `internal/console` marks before it persists anything, with lifetimes
+ off and on: instance door (all placements: plain, canary, `--region`, app region), seed (`--from`),
+ import, sidecar. Look for any create path the source-scan guard (`TestEveryCreateWriterMarksFirst`)
+ cannot see, for example a record created through another helper, package or store wrapper reachable
+ from a console door.
+2. The mark comes after the door's own record-exists read and every other refusal, so a create refused
+ for any other reason never burns its hostname. With lifetimes on, it sits after `planCreateLocked`
+ (step 2) and before `BeginAllocation`; check nothing between them can refuse.
+3. No path persists a data-kind record unmarked: a mark or mode read that fails refuses (S2) in every
+ mode; an `activating` or `invalidated` mode refuses (S8, S5). Check `hostsMode` never caches a failed
+ read and never defaults.
+4. Active mode: a conflict refuses with S1, except a create retried after its own record landed, which
+ gets the door's ordinary duplicate answer (`markBeforeCreate` reads the door's key only after a
+ conflicting mark). Check that read cannot let a create over another app's or another incarnation's
+ data through, and that a record deleted between that read and the write cannot slip a create through.
+ Two concurrent creates of one new host: exactly one may publish.
+5. Exempt creates never mark (`DataKind` false, attach first routes, temporary apps), and an exempt
+ create can never reach a data-kind record through these doors.
+6. User-visible change in `incomplete` mode: none except a bucket that cannot be written now answers 503
+ S2 instead of 502 (the plan's `TestMarkErrorRefusesInIncomplete`). Check nothing else a user sees on
+ create changed, and that no store error text reaches a response.
+7. Request budget (spec §3a, plan Global Constraints): one conditional PUT per data-kind create, one GET
+ of `@mode` per process, no per-request GET (the duplicate read only after a conflict).
+8. The witnesses go through the real doors with lifetimes off and on, and would fail without the
+ implementation (the author ran mutations removing each mark and the duplicate read; check the
+ assertions are not vacuous).
+
+## 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 section or task, 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). 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.
+
+In round 3, a NOT READY also says whether the P1s share one cause, and
+whether refusing the case up front or cutting the feature would remove
+them.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md b/docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md
new file mode 100644
index 000000000..9c427d97d
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md
@@ -0,0 +1,252 @@
+# Nearest-Region Never-Reuse 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:** No new data-kind record is ever created for a hostname whose earlier data may still exist, so `CONSOLE_APP_REGIONS` can be turned on without the host lifecycle claim (#199, #404).
+
+**Architecture:** A permanent create-only mark per hostname in the console's control store (`control/hosts-used/<host>.json`), written by every data-kind record writer before it persists anything. A one-time activation window drains in-flight work, inventories every place old data could live, and switches the console to `active`. In `active` mode a mark conflict refuses the create. Nothing on the box data path changes.
+
+**Tech Stack:** Go (console, provision, CLI), the release.Store control-store API, one AWS adapter script, one shell change in carloku-infrastructure.
+
+**Spec:** docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md (rev 5, accepted 2026-10-26). Read §1-§5 before any task.
+
+## Global Constraints
+
+- The rule applies only with claims off (`cfg.HostClaim` false) and Phase 1 off (`CARLOS_MOVES_PHASE1`, moves/switch.go:6). `complete` refuses otherwise.
+- Data kinds are every record whose `KindOrDefault()` is not `static` or `service`, plus every sidecar. Exempt creates never mark.
+- Marks are create-only (`Put` with `ifMatch ""`) and are never deleted by any code path.
+- Request budget: one conditional PUT per data-kind create; one GET of `@mode` per console start; tripwire at start = two listings plus one GET per unmarked record key. No per-request GET, no box changes, no polling.
+- One console process per deployment (spec §3a). No code may assume two.
+- Copy: every user-facing string comes verbatim from Task 1's approved list. No em dashes. Error fragments, diagnostics and JSON keys are out of copy review.
+- Witnesses go through real entry points (HTTP doors and the CLI), with the lifetimes cutover both off and on, as `lifetimes_create_test.go` does. No fixture-only proofs for gates.
+- Provider-neutral core: S3 and SSM appear only in the adapter script (Task 11) and the infra repo (Task 12).
+- Local tests: only the touched packages, with `-run`. CI runs the full suite.
+
+## Review Focus
+
+1. A create retried after its record landed: it must get the door's ordinary duplicate answer, not S1. Pinned in Task 3 (`TestRetryAfterLandedCreateIsDuplicate`).
+2. A host that differs only by a suffix (`app.example.co` vs `app.example.com`) in a bucket listing: it must map to its own host and never to the other. Pinned in Task 6 (`TestBucketListingSuffixHostsStayDistinct`).
+3. A store outage during a create in `incomplete` mode: refuse with S2, never create unmarked. Pinned in Task 3 (`TestMarkErrorRefusesInIncomplete`).
+4. A console restart during `activating`: it must come back still `activating`, with admissions stopped. Pinned in Task 5 (`TestActivatingSurvivesRestart`).
+5. Uppercase or trailing-dot hostnames in adapter output: they normalise exactly as `controlname.ValidHostShape` does, or count as unmapped. Pinned in Task 6 (`TestListingHostNormalisation`).
+
+## Delivery and review sizing
+
+| Merge | Tasks | What Paul can see |
+|---|---|---|
+| A | 1-4 | dev console: `carlos system hosts-used status` shows mode `incomplete` and the mark count growing as instances are created |
+| B | 5-10, 13 | the window, inventory and enforcement, all inert until `complete` |
+| infra | 11, 12 | the adapter script; `roll-console.sh` refuses below the floor |
+| ops | 14, 15 | switch-on, dev then flagship |
+
+**Own review (AGENTS.md rule 3, security gate or production storage):** Tasks 2, 3, 5, 6, 7, 8, 10, 12. Tasks 1, 4, 9, 11 and 13 are covered by one whole-branch review per merge. Each review has at most three rounds (stopping rule 1).
+
+## File map
+
+- Create `internal/provision/hostsused.go`: mark store, mode store, `DataKind`.
+- Create `internal/provision/hostsused_map.go`: pure listing-to-hostname mapping.
+- Modify `internal/provision/record_sequence.go:120` (`WriteRecord`): kind immutability.
+- Create `internal/console/hostsused.go`: gate state, `markForCreate`, admissions, doors.
+- Create `internal/console/hostsused_inventory.go`: roster, sources 1 and 4, import, `complete`.
+- Create `internal/console/hostsused_tripwire.go`: start-up check.
+- Modify `internal/console/apiinstances.go` (arms at :1702, :1706; region resolution :1225-1250), `apiinstanceseed.go:82-87`, `apisidecars.go:391`, `lifetimes_create.go:107` and `:370`, `fleets.go:578`, `regionconfig.go:10`, `regioncandidates.go`, and the offline move admission doors (`apiinstancemove_offline.go`).
+- Create `system_hostsused.go` (CLI). Modify `accounts_record_sequence.go:17-45`.
+- Create `scripts/hosts-used-scan-aws.sh` (adapter).
+- Modify `README.md` ("App regions rollback floor", "Turning app regions on").
+- carloku-infrastructure: `scripts/roll-console.sh`.
+
+---
+
+### Task 1: Copy review of every new string (Paul)
+
+Runs in parallel with Tasks 2-3. Blocks any task that writes a string.
+
+- [ ] Extract S1-S8 (spec §6), the operator log line, the `status` output lines (Task 4) and the README text (Task 13) into the copy-review skill's format.
+- [ ] Run copy review and apply Paul's edits verbatim to spec §6.
+- [ ] Commit the approved list as `docs/superpowers/notes/copy/nearest-region-never-reuse.md`.
+
+**Done when:** Paul has approved every string and the approved list is committed.
+
+### Task 2: History store, data-kind predicate, kind immutability (own review)
+
+**Files:** Create `internal/provision/hostsused.go` and `hostsused_test.go`. Modify `internal/provision/record_sequence.go:120`. Test `internal/provision/record_sequence_test.go`.
+
+**Interfaces (produces):**
+- `const HostsUsedPrefix = "control/hosts-used/"`
+- `func HostsUsedKey(host string) string`: `""` for a host failing `ValidHostShape`.
+- `type HostUse struct { Host, Account, App, Kind, Source string; At time.Time }` (json snake_case).
+- `func MarkHostUsed(ctx context.Context, s release.Store, u HostUse) (fresh bool, err error)`: `ErrCASConflict` gives `(false, nil)`.
+- `func HostIsUsed(ctx context.Context, s release.Store, host string) (bool, error)`
+- `func (r Record) DataKind() bool`
+- Mode: `HostsModeIncomplete`, `HostsModeActivating`, `HostsModeActive`, `HostsModeInvalidated`. `func ReadHostsMode(ctx, s) (mode, etag string, err error)` (absent gives incomplete). `func WriteHostsMode(ctx, s, mode, ifMatch string) (string, error)`. Key `control/hosts-used/@mode`.
+- `type HostsFloor struct { Version, Commit string }`, key `control/hosts-used/@floor`, with `ReadHostsFloor` and `WriteHostsFloor`.
+- `var ErrKindChange = errors.New("provision: a record's kind cannot change")`
+
+- [ ] Write the failing tests: `TestMarkHostUsedCreateOnly` (first call fresh, second not, body unchanged), `TestMarkHostUsedStoreError` (error passes through), `TestDataKindExemptsStaticAndService` (`""` and `instance` true, addr-backed `instance` true, `static` and `service` false), `TestHostsModeDefaultsIncomplete`, `TestWriteRecordRefusesKindChange` (`before` kind static, body kind instance gives `ErrKindChange`; same kind passes; `before` `{}` passes).
+- [ ] Run `go test ./internal/provision -run 'TestMarkHostUsed|TestDataKind|TestHostsMode|TestWriteRecordRefusesKindChange'`. Expect FAIL.
+- [ ] Implement. `WriteRecord` decodes only the `kind` field of `before` and `body` when `before` is not `{}`, with `""` read as `instance`.
+- [ ] Run the tests. Expect PASS. Run `go test ./internal/provision -run 'Update|Record'`. Expect PASS.
+- [ ] Commit `provision: hostname history store, data-kind predicate, kind immutability`.
+
+**Done when:** the five tests pass and every existing record-update test still passes.
+
+### Task 3: Mark in every create writer (own review)
+
+**Files:** Create `internal/console/hostsused.go` and `hostsused_writers_test.go`. Modify `apiinstances.go` (before :1702 and :1706), `apiinstanceseed.go:82-87`, `apisidecars.go:391`, `lifetimes_create.go` (before `BeginAllocation` at :107).
+
+**Interfaces:**
+- Consumes `provision.MarkHostUsed`, `Record.DataKind`, `ReadHostsMode`.
+- Produces `func (s *Server) markForCreate(ctx context.Context, u provision.HostUse) *doorRefusal`. With mode `incomplete`, a conflict passes and an error gives 503 S2. With mode `active`, a conflict gives 409 S1 and an error gives 503 S2. The `s.hostsMode()` accessor reads a field set at start (Task 5 adds transitions).
+
+- [ ] Write the failing tests, each through the real door with lifetimes off and on:
+ - `TestCreateDoorsMarkBeforePersisting`: a store wrapper records Put order, and for instances create, canary-shaped, `--region`, app-region, seed, import and sidecar the mark key's Put precedes the record Put (or the `BeginAllocation` row).
+ - `TestExemptCreatesDoNotMark`: attach (both arms), static first create and a temporary static create write no mark.
+ - `TestRetryAfterLandedCreateIsDuplicate`: the second identical create gets the door's existing duplicate answer.
+ - `TestMarkErrorRefusesInIncomplete`: a Put error gives 503 and no record.
+ - `TestUsedHostRefusedEverywhereWhenActive`: mode forced active, an existing mark, and every door and region (console's own included) gives 409 S1.
+ - `TestEveryCreateWriterMarksFirst`: a source-scan guard over `internal/console/*.go` lists every call of `provision.CreateRecord`, `provision.CreateSidecarRecord`, `provision.CreateRecordReplica` and `s.store.BeginAllocation`, and fails on any call site missing from the allowlist of sites Task 3 covers.
+- [ ] Run `go test ./internal/console -run 'TestCreateDoorsMark|TestExemptCreates|TestRetryAfterLanded|TestMarkError|TestUsedHostRefused|TestEveryCreateWriter'`. Expect FAIL.
+- [ ] Implement. The mark goes after the door's own record-exists read and every other check, immediately before the persisting call. Sidecars use the sidecar host name and kind `sidecar`.
+- [ ] Run the tests. Expect PASS. Run `go test ./internal/console -run 'Create|Sidecar|Seed|Import|Lifetime'`. Expect PASS.
+- [ ] Commit `console: every data-kind create writer marks its hostname first`.
+
+**Done when:** every listed door marks before persisting in both lifetimes states, exempt creates do not mark, and the guard fails on an unlisted writer.
+
+### Task 4: `hosts-used status` door and CLI (first visible slice)
+
+**Files:** Modify `internal/console/hostsused.go`. Create `system_hostsused.go` and `system_hostsused_test.go` (root CLI).
+
+**Interfaces:**
+- Produces operator door `GET /api/system/hosts-used/status`. It returns JSON `{mode, marks, inflight_creates, pending_allocations, pending_retirements, unfinished_moves}`, with the last four filled by Task 5 (0 until then). `marks` counts keys under `HostsUsedPrefix`, listed on request.
+- `carlos system hosts-used status` prints them with Task 1's approved lines.
+
+- [ ] Write the failing tests: `TestHostsUsedStatusDoor` (operator-only, counts marks), `TestSystemHostsUsedStatusCLI`.
+- [ ] Run them. Expect FAIL. Implement, using the existing `/api/system/*` operator auth. Run them. Expect PASS.
+- [ ] Commit, then open merge A (Tasks 1-4) for one branch review.
+
+**Done when:** on dev after merge A, `carlos system hosts-used status` shows `incomplete` and the mark count rises with each new data-kind instance.
+
+### Task 5: The activation window: modes, admissions, drain (own review)
+
+**Files:** Modify `internal/console/hostsused.go`, `apiinstancemove_offline.go` (admission doors) and `fleets.go:578`. Test `internal/console/hostsused_window_test.go`.
+
+**Interfaces:**
+- Produces `func (s *Server) admitDataCreate() (done func(), ref *doorRefusal)`: S8 in activating, S5 in invalidated, and an in-flight count otherwise.
+- Produces `func (s *Server) admitMoveOrPlace() (done func(), ref *doorRefusal)`: S7 in activating.
+- Produces doors `POST /api/system/hosts-used/begin` and `/cancel`. The console reads `@mode` once at start, and doors change it in process and in the store (`WriteHostsMode` with the read ETag) together.
+- Drain counts: in-flight from `admitDataCreate` and `admitMoveOrPlace`; any non-terminal `host_allocations` and `record_retirements` row of any writer version; every record whose `Move` is not terminal (one `apps/` listing plus a GET per record, on `status` only).
+
+- [ ] Write the failing tests: `TestBeginStopsAdmissions` (data-kind create S8, offline move start S7, place S7, static create allowed), `TestDrainWaitsForAdmittedMove` (a record with a non-terminal `Move` keeps `unfinished_moves` at 1 until it ends), `TestDrainCountsInflightCreate` (a create blocked inside its handler holds the count at 1), `TestActivatingSurvivesRestart`, `TestCancelReturnsToIncomplete`.
+- [ ] Run them. Expect FAIL. Implement. Wrap each data-kind create door's handler in `admitDataCreate` at its top, and the offline-move start doors and `placeAppTarget` in `admitMoveOrPlace`.
+- [ ] Run them. Expect PASS. Commit `console: the hostname-history activation window`.
+
+**Done when:** `begin` stops exactly those admissions, the counts fall to zero only when admitted work has finished, and the mode survives a restart.
+
+### Task 6: Inventory, import and `complete` (own review)
+
+**Files:** Create `internal/provision/hostsused_map.go` and its test, and `internal/console/hostsused_inventory.go` and its test.
+
+**Interfaces:**
+- `func HostsFromBucketListing(replicaPrefix string, keys []string) (hosts, unmapped []string)`. It maps `<replicaPrefix>/<host>/…`, `moves/<host>/…`, `moves/@offline/<host>/…` and `seeds/<host>/…`, ignores `moves/@lanes/…`, and reports any other key under those roots as unmapped.
+- `func HostsFromBoxListing(paths []string) (hosts, unmapped []string)`. Paths are relative to the box's data dir. It maps flat `<host>.db*`, `<host>.env`, `<host>.config.env` and `<host>/`, and `.offline-moves/<host>/…`. For `instances/<id>/…` and `.instances/<id>/…`, the host is the full host named by a file inside; an `id` starting with `_` and no host-named file inside is unmapped.
+- `type TargetListing struct { Target, Kind, Prefix, Error string; OK bool; Entries []string }`, the adapter's JSON line format. `Kind` is `bucket` or `box`.
+- Doors `POST /api/system/hosts-used/import` (body: TargetListing lines) and `POST /api/system/hosts-used/complete`. Roster: regions and pools from `control/edges/*.json`, fleets from the console's fleet table, and boxes from the edges files and fleet bindings, fixed at `begin`.
+- Console-side sources at `complete`: raw keys under `apps/` (every instance and sidecar key, a body decoding to an exempt kind skipped, an undecodable body marked) and every host in `host_allocations`, `record_retirements` and `record_migrations`.
+- `complete` refuses when: not activating, any drain count is non-zero, a roster target has no `OK` listing and is not a closed fleet, any unmapped entry exists, the roster changed since `begin`, or `HostClaim` or `MovesEnabled` is on. On success it writes every mark (`Source` = `records`, `tables`, `bucket:<target>` or `box:<target>`), `@floor` (this build's version and commit) and `@mode` = active.
+- `carlos system hosts-used import <file>|complete|close-fleet <name>`.
+
+- [ ] Write the failing tests: `TestBucketListingSuffixHostsStayDistinct`, `TestListingHostNormalisation`, `TestHashedInstanceDirMapsByInnerFile`, `TestHashedInstanceDirWithoutHostIsUnmapped`, `TestInventoryMarksOrphanSeedSnapshot`, `TestInventoryMarksRawRecordKeys` (Trash app, orphan, soft-deleted account, malformed body), `TestCompleteRefusesFailedSource`, `TestCompleteRefusesUnmappable`, `TestCompleteRefusesRosterChange`, `TestCompleteRefusesClaimsOrPhase1`, `TestCompleteRefusesPendingAllocationAnyVersion` (Astra round 3: mark H, begin an allocation, fail the record write, scan finds H's bucket data, so `complete` refuses until recovery ends the allocation), `TestLocalOnlyLeftoverRefused` (a box listing names H with no record and no bucket data, so after `complete` a create of H gets S1), `TestHistoricalOnlyNameAllowed` (H with no current data anywhere and no mark can be created).
+- [ ] Run `go test ./internal/provision -run 'Listing|Hashed' && go test ./internal/console -run 'Inventory|Complete|LocalOnly|HistoricalOnly'`. Expect FAIL.
+- [ ] Implement. Run the tests. Expect PASS. Commit `console: hostname inventory, import and complete`.
+
+**Done when:** every refusal above is witnessed and a clean inventory ends in `active` with the floor written.
+
+### Task 7: Enforcement in `active` (own review)
+
+**Files:** Modify `lifetimes_create.go:370` (`allocRecordLocked`), `apiinstances.go:1225-1250`, `regioncandidates.go` and `regionconfig.go:10`. Test `internal/console/hostsused_active_test.go`.
+
+**Interfaces:**
+- In `active`, `allocRecordLocked` publishes only when `HostIsUsed` is true for the allocation's host. An absent mark sets mode `invalidated` (store and process), pages through the existing alert path and leaves the allocation pending. In `incomplete`, it marks create-only and ignores a conflict.
+- `appRegionsOn()` becomes `s.cfg.AppRegions && s.cfg.HomeRegion != "" && s.hostsMode() == provision.HostsModeActive`.
+- A target (region, pool or fleet) not in the examined set from `complete`, or a closed fleet, refuses a data-kind create with S4 and is skipped by the picker. App creation with `--place` on it (apicli.go:411-445) also gets S4.
+
+- [ ] Write the failing tests: `TestConcurrentCreatesOneWins` (two apps, one new host, a barrier before the mark: exactly one publication and one refusal of any kind), `TestRecoveryRefusesUnmarkedPublication` (both replay branches, lifetimes_recovery.go:201 and :207), `TestStoredNonHomeRegionBeforeComplete` (an app with a stored non-home region creates there as today in `incomplete`, and the switch assigns no new non-home region), `TestNearestRegionAfterComplete`, `TestUnexaminedTargetRefused`, `TestClosedFleetRefused`.
+- [ ] Run them. Expect FAIL. Implement. Run them. Expect PASS.
+- [ ] Commit `console: enforce the hostname history once active`.
+
+**Done when:** all six witnesses pass with lifetimes off and on.
+
+### Task 8: Tripwire, invalidation and restore (own review)
+
+**Files:** Create `internal/console/hostsused_tripwire.go` and its test. Add the door `POST /api/system/hosts-used/invalidate`.
+
+**Interfaces:** `func (s *Server) hostsTripwire(ctx context.Context) error` runs at start when mode is `active`. It lists `apps/` and `HostsUsedPrefix`, GETs each record key with no mark, and enters `invalidated` on any data-kind body or undecodable body.
+
+- [ ] Write the failing tests: `TestTripwireInvalidatesOnUnmarkedRecord`, `TestTripwireIgnoresExemptUnmarked`, `TestRestoreDroppingMarksInvalidates` (delete one mark key from a test store and restart, so invalidated, S5 on data-kind creates, and the switch off), `TestReinventoryLeavesInvalidated` (begin, clean scans, complete, active).
+- [ ] Run them. Expect FAIL. Implement. Run them. Expect PASS. Commit `console: hostname-history tripwire and invalidated mode`.
+
+**Done when:** a dropped mark or an unmarked data-kind record found at start turns creates and the switch off until a full re-inventory completes.
+
+### Task 9: Cut `apps place`
+
+**Files:** Modify `internal/console/fleets.go:578`. Test `internal/console/fleets_place_cut_test.go`.
+
+- [ ] Write the failing test `TestPlaceRefusedAfterActivation`. Through `handleAPIPlace` (:729), `handleAppPlace` (:791) and `handleFleetPlacePage` (:834) in `active` or `invalidated`, an existing app gets S3, the registry is not opened and no record changes. In `incomplete`, behaviour is today's. `carlos apps create --place fleet/<f>` still succeeds.
+- [ ] Run it. Expect FAIL. Implement the refusal as the first statement of `placeAppTarget`. Run it. Expect PASS. Commit.
+
+**Done when:** all three entry points refuse with no write after activation.
+
+### Task 10: Cut `accounts migrate` resurrection, and the CLI floor (own review)
+
+**Files:** Modify `accounts_record_sequence.go:17-45` (`putMigrationObject`, `validateMigrationRecords`). Test `accounts_record_sequence_test.go`.
+
+- [ ] Write the failing tests: `TestMigrateRefusesResurrection` (migrate, delete the destination record, migrate again: S6, with lifetimes off and on), `TestMigrateIdenticalDestinationPasses`, `TestMigrateUnrelatedObjectsPass`, `TestMigrateMarksBeforeCopy` (in `incomplete`, a data-kind record copy marks first), `TestCLIRefusesBelowFloor` (an `@floor` naming a later version makes `accounts migrate` refuse before any write).
+- [ ] Run `go test . -run 'TestMigrate|TestCLIRefusesBelowFloor'`. Expect FAIL. Implement. Data-kind is decided by decoding the record body's `kind`. Run them. Expect PASS. Commit.
+
+**Done when:** a re-run can never recreate a deleted data-kind record after activation, and an old-floor CLI refuses.
+
+### Task 11: AWS adapter scan
+
+**Files:** Create `scripts/hosts-used-scan-aws.sh`.
+
+- [ ] Write the script. It takes `--profile`, the roster JSON from `status` and an output file. For each region bucket it lists current objects under the configured replica prefix, `moves/` and `seeds/` with `aws s3api list-objects-v2`, all pages. For each box it runs a read-only `find <data dir> -maxdepth 3` through `aws ssm send-command`. It emits one `TargetListing` JSON line per target with `ok:false` and the error on any failure. It never writes or deletes.
+- [ ] Dry run on dev with the operator profile. Import with `carlos system hosts-used import`, check `status`, then `cancel`.
+
+**Done when:** the dev dry run lists every roster target with `ok:true`, or a named failure, and the import reports no unmapped entries.
+
+### Task 12: `roll-console.sh` floor (carloku-infrastructure; own review)
+
+**Files:** carloku-infrastructure `scripts/roll-console.sh` and a test beside it in that repo's existing style.
+
+- [ ] Write the failing test: with a fake `@floor` naming commit C, rolling a checkout that does not contain C exits non-zero before building, and a checkout containing C proceeds.
+- [ ] Implement. Read `control/hosts-used/@floor` with the operator profile. If present, require `git merge-base --is-ancestor <commit> HEAD` in the checkout. Absent means no floor.
+- [ ] Run the test. Expect PASS. Open the infra PR and merge it **before** Task 14 step 3.
+
+**Done when:** the infra script refuses a below-floor console, with a passing test, merged.
+
+### Task 13: README
+
+**Files:** Modify `README.md`.
+
+- [ ] Add, from Task 1's approved text: the modes, the activation window runbook (announce, `begin`, `status` to zero, scan, import, `complete`), the one-console assumption, the floor for the console and `carlos accounts migrate`, the restore rule, closing a fleet, and to "Turning app regions on" a step 0 (window completed) and new probe hostnames on every run.
+- [ ] Commit. Open merge B (Tasks 5-10, 13) for its branch review once the own-review tasks are approved.
+
+**Done when:** merge B is reviewed and merged.
+
+### Task 14: Switch-on, dev (operator; Paul's go)
+
+- [ ] Roll the release with merges A and B to the dev console. Boxes are unchanged. Then update the operator's `carlos` CLI.
+- [ ] Announce the window. Run `begin`, then `status` until every count is 0.
+- [ ] Run Task 11's scan for every roster target, then `import` and `complete`. Check `status` says `active`.
+- [ ] Check: create a data-kind instance and a sidecar in each region, delete them, and recreate each host in every region (all S1). Create a new host through nearest-region and check its region.
+- [ ] Run README "Turning app regions on" steps 1-6 on dev, with new probe names, and `scripts/region-service-gate.sh <probe-host> <build> <other edge EIPs>` for every eligible region.
+
+**Done when:** dev is `active`, the recreation checks are refused, and every region passes the service gate.
+
+### Task 15: Switch-on, flagship (operator; Paul's go)
+
+- [ ] Confirm Task 12 is merged, then roll the flagship console.
+- [ ] Run the window as in Task 14.
+- [ ] Run README "Turning app regions on" step 5 (probes per eligible region, with the gate), then step 6 (switch on).
+
+**Done when:** flagship is `active`, every region's gate passes and `CONSOLE_APP_REGIONS=on` places new apps in their nearest region.
diff --git a/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md b/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md
new file mode 100644
index 000000000..97f1d50e8
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md
@@ -0,0 +1,134 @@
+# Nearest-region placement without claims: no new record over data that still exists
+
+Rev 5, 2026-10-26, **accepted 2026-10-26** (Paul). Branch `design-nearest-region-199`. Design review is over (AGENTS.md stopping rule 1): Option B had three Astra rounds (docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-optionB-r1.md, -r2.md, -r3.md). Round 3's P1, a marked allocation started before activation publishing after `complete`, is closed by the cut Paul accepted: a one-time activation maintenance window (§3a). Rev 5 adds that window and round 3's three P2 fixes and nothing else.
+
+## 1. The invariant
+
+**No new data-kind record can be created for a hostname whose data from an earlier record still exists anywhere a box could read it.**
+
+The hazard is data that still exists, not names ever used. **Option B is bound to claims off (`HostClaim` false) and Phase 1 off (`CARLOS_MOVES_PHASE1`, moves/switch.go:6, default off).** `complete` refuses with either on. In that configuration, once a hostname's data is gone it is harmless to reuse, because every reader sees current objects and present files only:
+- A wake restores through `lease.Restore` (lease.go:533). Its litestream S3 client lists with `ListObjectsV2` and GETs without a version id (litestream v0.5.14 `s3/replica_client.go:1405`, `:657`).
+- Staging promotion lists current objects and copies without a version id (mirror.go:616, :683).
+- `db pull`, `db query`, forwarding and dbreads use the same `ReadReplicaClient` (apidb.go:492, host/dbreads.go:154).
+- Seeds read replica coordinates (seeddoer.go:28) and place snapshots by an unversioned GET (seedwiring.go:27, release/store.go:924).
+- Offline stage, seal and land mirror, record and check current listings (movesoffline_stage.go:174, movesoffline_seal.go:473, movesoffline_land.go:700).
+- The warm cache needs a present database (backend_exec.go:819).
+
+Pinned-version reads exist (`SealedClient.OpenLTXFile`, moves/sealedclient.go:147), but they belong to the claims and Phase 1 generation machinery, which Option B excludes. This is not a repository-wide property.
+
+Noncurrent versions also expire after `data_noncurrent_days`, 7 by default (deployment-buckets/main.tf:95-100).
+
+**Mechanism.** A permanent create-only mark `control/hosts-used/<host>.json` means "this hostname may hold data". After activation, a data-kind create whose mark PUT conflicts is refused (S1), whether the conflict comes from an old mark or a concurrent winner, since the store gives one answer for both (release/store.go:34-46). Marks are never cleared: conservative and cheap.
+
+**No-data kinds (exempt, never marked):** `static` and `service`. `RouteFor` derives a DB path only when `DerivesPaths` holds, that is an addressless `instance` (provision.go:456-458, reconcile.go:505). `ValidateShape` refuses hibernate on `static` (provision.go:710-720), requires an upstream for `service` and refuses hibernate with one (:722, :731), and refuses the replica role on both (:656). Seed and import refuse both (apiinstanceseed.go:90). Updates revalidate shape. Plan task 1 adds `Kind` immutability. An addr-backed `instance` is not exempt, because its `Addrs` can change (apiinstances.go:2110). Sidecars are always data kinds.
+
+## 2. Writers (mark first, after every other check of the door)
+
+Each writer first reads its own record and answers with the door's duplicate response if it is present. The rail does this read only in the home bucket (createleftovers.go:136), so the mark step does it itself. Then it marks, then it persists.
+
+| Writer | Mark |
+|---|---|
+| lifetimes on: `createRecordWithLifetimeLocked` for the instance door (apiinstances.go:1702) and `createSeedRecord` (apiinstanceseed.go:84; seeds and imports, apiinstanceimport.go:179) | before `BeginAllocation` (lifetimes_create.go:107) |
+| lifetime recovery: every replay branch publishes through `allocRecordLocked` (lifetimes_recovery.go:201, :207) | inside `allocRecordLocked`: after activation it publishes only if the mark exists. An absent mark invalidates the history (§4) and leaves the allocation pending. Before activation it marks create-only and ignores a conflict |
+| lifetimes off: `CreateRecord` (apiinstances.go:1706), `createSeedRecord` (apiinstanceseed.go:87) | immediately before the write |
+| sidecars, always the direct writer even with lifetimes on (`CreateSidecarRecord`, apisidecars.go:391) | immediately before the write |
+| attach (domainattach.go:250, :675), deploy's first create (deploy.go:1023), temporary static sites | exempt: **no mark** |
+| `carlos accounts migrate` (accounts_record_sequence.go:17-40) | **cut:** after activation it refuses to create a data-kind record at an absent destination (S6). An identical present destination and unrelated objects still migrate. It retains its sources (accounts.go:69), so a re-run would resurrect a record |
+| `internal/hostops` writers | claims-on only, unreachable with claims off (#404). A witness asserts that |
+
+A successful mark followed by a failed write or a crash leaves the hostname refused for ever. That is accepted.
+
+## 3. Inventory: hazard-complete, once
+
+**Roster**, fixed when the operator opens the window: every region and pool from `control/edges/*.json`, every fleet in the console's fleet table, and every box in those edges files and fleet bindings. **Sources**, each one a union of marks:
+1. **Current records:** raw keys under `apps/`, whatever the body, including Trash, orphans, soft-deleted or missing accounts and malformed bodies (the strict listings skip these: reconcile.go:2509, provision.go:2980, sidecar.go:353). Only a body that decodes to an exempt kind is skipped.
+2. **Current objects** in every roster region's data bucket, under the box's **configured** replica prefix (`activator.Config.Prefix`, activator.go:147, read from each box's configuration, not assumed) and under `moves/`, `moves/@offline/` and `seeds/` (`seeds/<host>/<id>/snapshot.db`, read by boxes at seedwiring.go:25). An orphan snapshot whose seed record is gone still marks its host.
+3. **Local data on every box** (platform, pool, fleet) under its configured data directory: flat `<host>.db*` and `<host>` entries, nested `instances/<InstanceID>` and `.instances/<InstanceID>`, and `.offline-moves/<host>`. A hashed `InstanceID` (`_` + prefix + hash, provision.go:3127-3145) maps to its hostname by the full host in the file names inside (provision.go:3147-3158).
+4. **Console tables:** `complete` refuses while **any** `host_allocations` or `record_retirements` row is not terminal, whatever console version wrote it (§3a).
+
+Deleted history and noncurrent versions are not sources, because they are harmless (§1).
+
+**`complete` refuses** on any failed, partial or unmappable source (an object key or directory it cannot map to a hostname), a roster change since `begin`, a pending row from source 4, an unfinished move, or claims or Phase 1 on. Provider discovery (S3 listing, an SSM read-only listing) lives in the adapter in infra. The core imports lists per target, each with its result.
+
+**An uninventoried fleet can be closed instead.** Its old data is reachable only by a record placed on that fleet. Platform boxes never mint fleet records, and fleet boxes mint only their own fleet's (`inScope`, reconcile.go:443-455). Moves refuse fleet routes (apiinstancemove.go:65), and placement changes are cut (§5). A closed fleet refuses data-kind creates placed on it and app creation with `--place` on it (apicli.go:411-445), with S4. Regions and pools cannot be closed. Their inventories must succeed.
+
+**After completion, unexamined targets are refused.** A region, pool or fleet that was not in the roster gets S4 for data-kind creates, and the nearest-region picker skips it, until its own inventory is imported.
+
+## 3a. The activation window (accepted 2026-10-26)
+
+A one-time maintenance window wraps the inventory. It closes round 3's P1: a marked allocation started before activation and still pending could otherwise publish over old data after `complete` (recovery's "our slot, absent record" branch, lifetimes_recovery.go:204).
+
+1. **`carlos system hosts-used begin`** puts the console in **activating**. It stops admitting data-kind creates (S8), offline move admissions and their cleanup (S7), and `apps place` (S7). Exempt kinds and every other door keep working.
+2. **Drain.** Work admitted before `begin` finishes on its own. In-flight create and place requests are counted in process and leave when their handler returns. Offline moves already admitted keep running on boxes from record state, since the worker dispatches them itself (movespass.go:1149, movesoffline.go:416). Lifetime recovery keeps settling allocations and retirements. `carlos system hosts-used status` reports what is left: in-flight requests, pending `host_allocations` and `record_retirements` rows of any writer version, and records whose `Move` is not terminal. **The scans may start only when every count is zero.** `status` reads every record body each time it runs: one `apps/` listing (a page per 1,000 keys) plus one GET per record. That is an operator action, not a poll.
+3. **Scan and import** (§3), with admissions still stopped.
+4. **`complete`** re-checks the drain and every source result, writes `control/hosts-used/@mode` = `active`, and switches the console to **active** in the same step. Admissions resume with the rule enforced.
+5. **`cancel`** at any point returns to **initial incomplete**.
+
+**How consoles observe the mode.** The doors live on the console, and a deployment runs one console process (the same assumption self-serve moves plan 1 makes for `console.db`). The roll stops the old process before starting the new one. A console reads `@mode` (`incomplete`, `activating`, `active` or `invalidated`) once at start, before serving, and the doors change it in process and in the store together. Cost: one GET per console start and nothing per request. A second console process is out of scope. The README says so, and it would need its own mode read per create.
+
+## 4. Modes and the floor
+
+| Mode | Behaviour |
+|---|---|
+| **initial incomplete** (from the release until `complete`) | today's behaviour: the rail in the home region only, and creates honour an already stored non-home app region as today (apiinstances.go:1232). `CONSOLE_APP_REGIONS=on` has no effect: no new non-home app regions are assigned, and the console logs that once |
+| **active** | §1-§3 enforced; nearest-region works |
+| **activating** (from `begin`) | §3a: data-kind creates, move admissions and `apps place` refused; drain, scan, `complete` or `cancel` |
+| **invalidated** (after activation: tripwire, absent mark in recovery, or operator) | every data-kind create refused (S5), nearest-region off, page. Leaving it needs a fresh full inventory and `complete` |
+
+A re-inventory restores the invariant. A create-and-delete during a breach either left current data, which the scan finds, or did not, which is harmless. Live breach records are current records. What a breach already exposed cannot be undone. That is why the floor exists.
+
+**The floor covers every record-writing binary:** the console and the `carlos` CLI's `accounts migrate`. The console's floor is enforced by `roll-console.sh` (carloku-infrastructure). Today it builds the checkout's HEAD after a cleanliness check (roll-console.sh:39). Plan task 12 makes it refuse a version below the floor once `@complete` exists, with a refusal test, landed **before activation**. The CLI's floor is the README and the operator recipe. From this release the CLI also reads `control/hosts-used/@floor` and refuses below it.
+
+**Tripwire** at each console start: list `apps/` keys and `control/hosts-used/`, then GET the body of every record key with no mark, to tell exempt kinds from breach records. Cost per start: two listings (one page per 1,000 keys) plus one GET per unmarked record, which is every current static and service record. There is no per-request cost.
+
+**Restores:** restoring console SQLite alone is safe. A control-store restore must keep the union of marks. Any restore that may have dropped keys enters **invalidated**.
+
+## 5. Placement and moves
+
+- **`apps place` is cut after activation:** refused (S3) at the top of `placeAppTarget` (fleets.go:578), its only implementation, called by the API (:747) and both page entry points (:810, :859). The refusal comes before its temporary-app check, before the registry is opened and before any write (`SetPlacement` :679, `SetRecordRegion` :702). The create-versus-place race and route-only rows therefore never arise. Placement at app creation (`carlos apps create --place fleet/<f>`, apicli.go:411) stays, and its instances go through the gated door.
+- **Offline moves:** a host created after activation is never recreated, so a move destination can hold only that host's own older data. Promotion mirrors staging exactly (mirror.go:185-216, deletes at :332). On versioned buckets the deletes leave noncurrent versions for `data_noncurrent_days`, the same time-limited recovery as today. Landing parks local warm files (movesoffline_land.go:550-596). Hosts reused before activation are scoped out: the operator runbook's destination check stays their guard.
+- **Remedy:** choose another hostname. No string points at moves.
+
+## 6. Strings (drafts for Paul's copy review)
+
+- S1: "<host> is in use or has held an app's data before, so it can't be created. Choose another address."
+- S2: "Could not check whether <host> is free. Try again."
+- S3: "An app's placement can't be changed once it exists."
+- S4: "New instances can't be created on <target> yet. Choose another region."
+- S5: "New instances can't be created right now. Try again later."
+- S6 (CLI): "<host>: not migrated. Its destination record is gone, and recreating it would reuse a hostname that held data."
+- S7: "Moves and placement are paused for maintenance. Try again later."
+- S8: "New instances can't be created during maintenance. Try again in a few minutes."
+- Operator log: "app regions are off until the hostname history is complete"
+
+## 7. Findings
+
+| Round, # | Disposition |
+|---|---|
+| r1-1 home reuse | fixed: no reuse anywhere; §1 says why gone data is harmless |
+| r1-2, r2-5 writers | fixed: §2, mark before `BeginAllocation`, recovery inside `allocRecordLocked`, sidecars always direct, exempt cases unmarked |
+| r1-3 concurrency | fixed: a conflict is S1, with one string |
+| r1-4, r2-2 inventory | reframed to current data (§1). Sources with configured prefixes and hashed directories, a fixed roster, a window that freezes moves, refusal on any gap. Fleets close; regions and pools cannot |
+| r1-5, r2-4 rollback | three modes, a floor over console and CLI, the roll-script refusal as a task before activation, a tripwire with its real cost, and a stated breach cost |
+| r1-6, r2-3 placement | cut: `apps place` refused after activation, before any write |
+| r1-7 moves | fresh hosts: own data only, time-limited version recovery. Pre-activation reuse scoped out |
+| r1-8 move remedy | fixed: another hostname |
+| r1-9, r2-5 plan | §8 applies Astra's task table |
+| r1-10 table | this table separates fixes, cuts and scope-outs |
+| r2-1 migrate | cut: refused at an absent destination after activation |
+| r3-1 pre-activation allocation | cut: the activation window (§3a) refuses `complete` while any allocation or retirement is pending, whatever wrote it. Plan witness: Astra's sequence |
+| r3-2 freeze boundary | §3a: `begin` stops admissions, admitted moves and placements drain, scans wait for zero |
+| r3-3 version reads | §1: bound to claims and Phase 1 off; `SealedClient` attributed |
+| r3-4 seed snapshots | §3 source 2 includes `seeds/`; orphan-snapshot witness |
+| lifetime design (rev 1) | its mechanisms are gone. Its local and process reuse findings are fixed by §1's invariant |
+
+## 8. Plan
+
+docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md: one plan, with the witnesses from rounds 1-3.
+
+## 9. Switch-on, dev first
+
+1. Roll the marking console and CLI (boxes unchanged), dev then flagship. Land the `roll-console.sh` floor.
+2. Announce the window, then `begin`, drain to zero, scan every roster target, import and `complete`. Dev first.
+3. Dev check: create a data-kind instance and a sidecar, delete them, then recreate each host in every region (all S1). A new host through nearest-region lands in the nearest region.
+4. README "Turning app regions on", steps 1-6, with **new probe hostnames on every run**, and `scripts/region-service-gate.sh` per eligible region, dev then flagship.
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index ae0f0cb51..ab11b4593 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -1856,7 +1856,9 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
rec = *created
}
default:
- recordWriteErr = provision.CreateRecord(ctx, s.cfg.Releases, rec)
+ // The hostname history's mark for a data kind, then the
+ // create-only write (hostsused.go).
+ recordWriteErr = s.createRecordMarked(ctx, rec)
}
if err := recordWriteErr; err != nil {
if ref, ok := lifetimeCreateRefusal(host, err, msgLifetimeCreatePending); ok {
diff --git a/internal/console/apiinstances_test.go b/internal/console/apiinstances_test.go
index ca2c63c93..0ab0d5e14 100644
--- a/internal/console/apiinstances_test.go
+++ b/internal/console/apiinstances_test.go
@@ -2024,10 +2024,13 @@ func TestAPIInstanceStoreFailure(t *testing.T) {
enableInstances(t, fx, "titogo", titoManifest())
u := instancesURL(fx, "bab", "titogo")
+ // An unwritable bucket now fails at the hostname history's mark, the
+ // create's first write: 503 with S2 (nearest-region never-reuse, plan
+ // Task 3), still with no store text in it.
fx.srv.cfg.Releases = brokenStore{fx.rel}
status, _, out := rawReq(t, http.MethodPost, u, token, `{"host":"acme.go.tito.io","region":"ie"}`)
- if status != http.StatusBadGateway {
- t.Fatalf("create against an unwritable bucket = %d %s, want 502", status, out)
+ if status != http.StatusServiceUnavailable || ltErr(out) != msgHostUnchecked("acme.go.tito.io") {
+ t.Fatalf("create against an unwritable bucket = %d %s, want 503 %q", status, out, msgHostUnchecked("acme.go.tito.io"))
}
if strings.Contains(out, "carlos-prod-secret-bucket") || strings.Contains(out, "ABC123") {
t.Fatalf("refusal leaks the store's error text: %s", out)
diff --git a/internal/console/apiinstanceseed.go b/internal/console/apiinstanceseed.go
index eec696fbb..1126eed88 100644
--- a/internal/console/apiinstanceseed.go
+++ b/internal/console/apiinstanceseed.go
@@ -79,13 +79,14 @@ type seedCreate struct {
// createSeedRecord writes a seed door's first record: the lifetime create
// when the request was admitted with lifetimes on (dispatch by the unit),
-// today's create-only write otherwise.
+// today's create-only write otherwise. Both mark the hostname first
+// (hostsused.go).
func (s *Server) createSeedRecord(ctx context.Context, c seedCreate, rec provision.Record) error {
if lifetimesUnit(ctx) {
_, err := s.createRecordWithLifetime(ctx, rec, c.lifetime)
return err
}
- return provision.CreateRecord(ctx, s.cfg.Releases, rec)
+ return s.createRecordMarked(ctx, rec)
}
// seedCommonRefusal is both seed doors' shape rule: an ordinary instance.
diff --git a/internal/console/apisidecars.go b/internal/console/apisidecars.go
index 034f91f81..9916a4a65 100644
--- a/internal/console/apisidecars.go
+++ b/internal/console/apisidecars.go
@@ -393,9 +393,16 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request)
return
}
} else {
- recordWriteErr = provision.CreateSidecarRecord(ctx, s.cfg.Releases, rec)
+ // Always the direct writer, lifetimes on or off: the hostname
+ // history's mark, then the create-only write (hostsused.go).
+ recordWriteErr = s.createSidecarMarked(ctx, rec)
}
if err := recordWriteErr; err != nil {
+ var used *hostsUsedError
+ if errors.As(err, &used) {
+ writeDoorRefusalJSON(w, r, &used.ref)
+ return
+ }
if errors.Is(err, release.ErrCASConflict) {
// A lost race against a second create for the same name, or a
// plain duplicate. Either way the winner's record stands.
diff --git a/internal/console/apisidecars_test.go b/internal/console/apisidecars_test.go
index 62ff24636..5669ed431 100644
--- a/internal/console/apisidecars_test.go
+++ b/internal/console/apisidecars_test.go
@@ -808,10 +808,13 @@ func TestAPISidecarStoreFailure(t *testing.T) {
enableSidecars(t, fx, "titogo", titoSidecarManifest())
u := sidecarsURL(fx, "bab", "titogo")
+ // An unwritable bucket now fails at the hostname history's mark, the
+ // create's first write: 503 with S2 (nearest-region never-reuse, plan
+ // Task 3), still with no store text in it.
fx.srv.cfg.Releases = brokenStore{fx.rel}
status, _, out := rawReq(t, http.MethodPost, u, token, `{"name":"bot","region":"ie"}`)
- if status != http.StatusBadGateway {
- t.Fatalf("create against an unwritable bucket = %d %s, want 502", status, out)
+ if status != http.StatusServiceUnavailable || ltErr(out) != msgHostUnchecked(botHost) {
+ t.Fatalf("create against an unwritable bucket = %d %s, want 503 %q", status, out, msgHostUnchecked(botHost))
}
if strings.Contains(out, "carlos-prod-secret-bucket") || strings.Contains(out, "ABC123") {
t.Fatalf("refusal leaks the store's error text: %s", out)
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 0d1fc183a..da8dde151 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -1071,6 +1071,9 @@ func (s *Server) registerCLIRoutes() {
// Pointer digests (#253, spec §4.6): each account's emission marker and
// the channels still without digests. apiSystemRoller, like the update
// doors.
+ // The hostname history's status (nearest-region never-reuse, plan Task
+ // 4, hostsused.go): apiSystemRoller, read-only.
+ s.cliRoute("GET /api/cli/system/hosts-used/status", svcrole.Set{}, s.handleAPIHostsUsedStatus)
s.cliRoute("GET /api/cli/system/pointer-digests", svcrole.Set{}, s.handleAPISystemPointerDigests)
s.cliRoute("POST /api/cli/system/pointer-digests", svcrole.Set{}, s.handleAPISystemPointerDigests)
}
diff --git a/internal/console/browserupdates_test.go b/internal/console/browserupdates_test.go
index 336da6022..35781904a 100644
--- a/internal/console/browserupdates_test.go
+++ b/internal/console/browserupdates_test.go
@@ -153,6 +153,26 @@ func (fx *pageFx) setRecordSettings(host string, edit func(*provision.Record)) {
}
}
+// recreateRecord replaces host's record with an edited copy created afresh,
+// for a fixture whose record must be born another kind: an in-place write
+// cannot change a record's kind (provision.ErrKindChange).
+func (fx *pageFx) recreateRecord(host string, edit func(*provision.Record)) {
+ fx.t.Helper()
+ ctx := context.Background()
+ rec, _, err := provision.GetRecordETag(ctx, fx.rel, fx.sqid, "kass", host)
+ if err != nil {
+ fx.t.Fatal(err)
+ }
+ edit(rec)
+ rec.RecordSeq = 0
+ if err := fx.rel.Delete(ctx, provision.RecordKey(fx.sqid, "kass", host)); err != nil {
+ fx.t.Fatal(err)
+ }
+ if err := provision.CreateRecord(ctx, fx.rel, *rec); err != nil {
+ fx.t.Fatal(err)
+ }
+}
+
func (fx *pageFx) setRecordUpdates(host, updates string) {
fx.setRecordSettings(host, func(r *provision.Record) { r.Updates = updates })
}
@@ -296,7 +316,7 @@ func TestUpdatesSectionForANamedUnit(t *testing.T) {
func TestUpdatesSectionForANamedUnitService(t *testing.T) {
fx := updatesPageFixture(t)
fx.grant("updates", "major", "pin")
- fx.setRecordSettings(heldHost, func(r *provision.Record) { r.Kind, r.Unit, r.Addr = "service", "console.service", "127.0.0.1:8080" })
+ fx.recreateRecord(heldHost, func(r *provision.Record) { r.Kind, r.Unit, r.Addr = "service", "console.service", "127.0.0.1:8080" })
c := signInPaul(t, fx.consoleFixture)
code, body := fx.getPage(c, fx.u("/apps/kass/instances/"+heldHost))
sec := updatesSection(body)
@@ -309,7 +329,7 @@ func TestUpdatesSectionForANamedUnitService(t *testing.T) {
// R12: a record of another kind shows no Updates section at all.
func TestUpdatesSectionIsAbsentForOtherKinds(t *testing.T) {
fx := updatesPageFixture(t)
- fx.setRecordSettings(heldHost, func(r *provision.Record) { r.Kind, r.Addr = "service", "127.0.0.1:8080" })
+ fx.recreateRecord(heldHost, func(r *provision.Record) { r.Kind, r.Addr = "service", "127.0.0.1:8080" })
c := signInPaul(t, fx.consoleFixture)
code, body := fx.getPage(c, fx.u("/apps/kass/instances/"+heldHost))
if code != http.StatusOK || updatesSection(body) != "" {
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 9ce4e7565..01acb8f1a 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -874,6 +874,7 @@ var claimFixtures = map[string]claimFixture{
"route GET /api/cli/billing/problems": claimRead("operator view of billing problems; names no app"),
"route GET /api/cli/system/antivirus": claimRead("reads the deployment scanning setting"),
"route GET /api/cli/system/geoip": claimRead("operator view of the GeoIP pointer, box heartbeats and feed status (control/geoip/, status/, edge files); writes nothing"),
+ "route GET /api/cli/system/hosts-used/status": claimRead("operator view of the hostname history: its mode, a count of control/hosts-used/ marks and the console's pending lifetime rows; writes nothing"),
"route GET /api/cli/system/jobs/{id}": claimRead("reads a system update job"),
"route GET /api/cli/system/layout": claimRead("reads the deployment layout intent"),
"route GET /api/cli/system/pointer-digests": claimRead("operator report of each account's pointer digest marker and the channels whose head has no digest; writes nothing"),
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index 5b56260af..99e76a929 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -279,7 +279,8 @@ var claimReadProbes = map[string]claimProbe{
do: claimGetAPI("/api/cli/system/jobs/<job>"),
body: []string{`"steps"`, `"done":true`},
},
- "route GET /api/cli/system/layout": claimAPIRead(nil, "/api/cli/system/layout", `"mode":"none"`),
+ "route GET /api/cli/system/hosts-used/status": claimAPIRead(nil, "/api/cli/system/hosts-used/status", `"mode":"incomplete"`),
+ "route GET /api/cli/system/layout": claimAPIRead(nil, "/api/cli/system/layout", `"mode":"none"`),
"route GET /api/cli/system/pointer-digests": claimAPIRead(nil, "/api/cli/system/pointer-digests",
`"account":"bab"`, `"app":"kass","channel":"stable"`),
"route GET /api/cli/system/status": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.systemRelease(t, "canary", "66587fa") },
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go
new file mode 100644
index 000000000..b3fd81990
--- /dev/null
+++ b/internal/console/hostsused.go
@@ -0,0 +1,244 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "log"
+ "net/http"
+ "os"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The hostname history at the create doors (nearest-region never-reuse,
+// spec docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md
+// §2, plan Task 3). Every data-kind create writer marks its hostname
+// (provision.MarkHostUsed) after every other check of its door and
+// immediately before the call that persists the record: the create-only
+// record write with lifetimes off and for sidecars, BeginAllocation with
+// lifetimes on. Exempt kinds (static, service) never mark.
+//
+// Until the history is active (Task 6's complete) a mark that is already
+// there passes: today's behaviour, with the history filling in. Once active
+// it refuses the create (S1). A store that cannot be read or written
+// refuses in every mode (S2): a create is never persisted unmarked.
+
+// The approved strings (docs/superpowers/notes/copy/nearest-region-never-reuse.md).
+func msgHostUsed(host string) string {
+ return host + " is in use or has held an app's data before, so it can't be created. Choose another address."
+}
+
+func msgHostUnchecked(host string) string {
+ return "Could not check whether " + host + " is free. Try again."
+}
+
+const (
+ msgHostsInvalidated = "New instances can't be created right now. Try again later."
+ msgHostsActivating = "New instances can't be created during maintenance. Try again in a few minutes."
+)
+
+// hostsHistory is the process's copy of control/hosts-used/@mode. One
+// console process serves a deployment (spec §3a), so the mode is read once
+// per process and changed only by this process's own doors (Task 5).
+type hostsHistory struct {
+ mu sync.Mutex
+ mode string // "" until read
+}
+
+// hostsMode is the history mode: read from the control store the first time
+// it is needed, then held. A failed read is not held, so the next caller
+// reads again, and it is an error, never a default: the caller refuses.
+// A console with no control store has no records to write, and reads
+// incomplete.
+func (s *Server) hostsMode(ctx context.Context) (string, error) {
+ s.hosts.mu.Lock()
+ defer s.hosts.mu.Unlock()
+ if s.hosts.mode != "" {
+ return s.hosts.mode, nil
+ }
+ if s.cfg.Releases == nil {
+ return provision.HostsModeIncomplete, nil
+ }
+ mode, _, err := provision.ReadHostsMode(ctx, s.cfg.Releases)
+ if err != nil {
+ return "", err
+ }
+ s.hosts.mode = mode
+ return mode, nil
+}
+
+// hostsUsedError carries a mark refusal out of a create core that answers
+// errors (createRecordWithLifetimeLocked, createRecordMarked);
+// lifetimeCreateRefusal turns it back into its door refusal.
+type hostsUsedError struct{ ref doorRefusal }
+
+func (e *hostsUsedError) Error() string { return "console: hosts used: " + e.ref.Msg }
+
+// markResult is what one mark found.
+type markResult int
+
+const (
+ markPass markResult = iota + 1 // marked: fresh, or already there before the history is active
+ markConflict // a mark was there already, and the history is active
+)
+
+// markHost is the mark step: the mode, then the create-only mark. A refusal
+// is the door's answer; otherwise it reports whether the create may go on.
+// A conflict once active is the caller's to judge (markForCreate,
+// markBeforeCreate).
+func (s *Server) markHost(ctx context.Context, u provision.HostUse) (markResult, *doorRefusal) {
+ mode, err := s.hostsMode(ctx)
+ if err != nil {
+ log.Printf("console: hosts used: read the mode for %s: %v", u.Host, err)
+ return 0, &doorRefusal{http.StatusServiceUnavailable, msgHostUnchecked(u.Host)}
+ }
+ switch mode {
+ case provision.HostsModeActivating:
+ return 0, &doorRefusal{http.StatusServiceUnavailable, msgHostsActivating}
+ case provision.HostsModeInvalidated:
+ return 0, &doorRefusal{http.StatusServiceUnavailable, msgHostsInvalidated}
+ }
+ if u.At.IsZero() {
+ u.At = time.Now().UTC()
+ }
+ fresh, err := provision.MarkHostUsed(ctx, s.cfg.Releases, u)
+ if err != nil {
+ log.Printf("console: hosts used: mark %s: %v", u.Host, err)
+ return 0, &doorRefusal{http.StatusServiceUnavailable, msgHostUnchecked(u.Host)}
+ }
+ if fresh || mode != provision.HostsModeActive {
+ return markPass, nil
+ }
+ return markConflict, nil
+}
+
+// markForCreate marks u.Host for a create whose door has already settled
+// that no record of its own stands under the key (the lifetime create's
+// step 2). A mark already there refuses once the history is active (S1),
+// whoever wrote it: an earlier record's, or a concurrent create's.
+func (s *Server) markForCreate(ctx context.Context, u provision.HostUse) *doorRefusal {
+ res, ref := s.markHost(ctx, u)
+ if ref != nil {
+ return ref
+ }
+ if res == markConflict {
+ return &doorRefusal{http.StatusConflict, msgHostUsed(u.Host)}
+ }
+ return nil
+}
+
+// markBeforeCreate is the mark for a create-only writer that has not read
+// its own key (lifetimes off, sidecars). On a conflict once active it reads
+// the key: a record there is this create's own duplicate, answered as the
+// write would (release.ErrCASConflict), so a create retried after its record
+// landed gets the door's ordinary answer and not S1. Anything else is S1. A
+// failed read refuses (S2). The read costs nothing until a mark conflicts.
+func (s *Server) markBeforeCreate(ctx context.Context, u provision.HostUse, key string) error {
+ res, ref := s.markHost(ctx, u)
+ if ref != nil {
+ return &hostsUsedError{*ref}
+ }
+ if res != markConflict {
+ return nil
+ }
+ _, _, err := s.cfg.Releases.Get(ctx, key)
+ switch {
+ case err == nil:
+ return release.ErrCASConflict
+ case errors.Is(err, os.ErrNotExist):
+ return &hostsUsedError{doorRefusal{http.StatusConflict, msgHostUsed(u.Host)}}
+ }
+ log.Printf("console: hosts used: read %s after a conflicting mark: %v", key, err)
+ return &hostsUsedError{doorRefusal{http.StatusServiceUnavailable, msgHostUnchecked(u.Host)}}
+}
+
+// recordUse is the mark a data-kind instance record's create writes.
+func recordUse(rec provision.Record) provision.HostUse {
+ return provision.HostUse{Host: rec.Host, Account: rec.Account, App: rec.App, Kind: rec.KindOrDefault(), Source: "create"}
+}
+
+// createRecordMarked is the lifetimes-off create of an instance record
+// (the instance, seed and import doors): the mark for a data kind, then
+// provision.CreateRecord. Exempt kinds write as before.
+func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) error {
+ if rec.DataKind() {
+ if err := s.markBeforeCreate(ctx, recordUse(rec), provision.RecordKey(rec.Account, rec.App, rec.Host)); err != nil {
+ return err
+ }
+ }
+ return provision.CreateRecord(ctx, s.cfg.Releases, rec)
+}
+
+// createSidecarMarked is the sidecar door's create: a sidecar is always a
+// data kind, marked at its host, then provision.CreateSidecarRecord.
+func (s *Server) createSidecarMarked(ctx context.Context, rec provision.SidecarRecord) error {
+ u := provision.HostUse{Host: rec.Host, Account: rec.Account, App: rec.App, Kind: "sidecar", Source: "create"}
+ if err := s.markBeforeCreate(ctx, u, provision.SidecarRecordKey(rec.Account, rec.App, rec.Name)); err != nil {
+ return err
+ }
+ return provision.CreateSidecarRecord(ctx, s.cfg.Releases, rec)
+}
+
+// hostsUsedStatus is GET /api/cli/system/hosts-used/status (plan Task 4).
+// InflightCreates and UnfinishedMoves are null until the activation window
+// (Task 5) counts them: a zero there would claim a drain this console
+// cannot see yet.
+type hostsUsedStatus struct {
+ Mode string `json:"mode"`
+ Marks int `json:"marks"`
+ InflightCreates *int `json:"inflight_creates"`
+ PendingAllocations int `json:"pending_allocations"`
+ PendingRetirements int `json:"pending_retirements"`
+ UnfinishedMoves *int `json:"unfinished_moves"`
+}
+
+// handleAPIHostsUsedStatus answers the history's mode and how many
+// hostnames it holds, counted by listing the prefix (a page per 1,000
+// keys; an operator action, never polled), with the console's pending
+// lifetime rows. apiSystemRoller, like the other system doors. It writes
+// nothing.
+func (s *Server) handleAPIHostsUsedStatus(w http.ResponseWriter, r *http.Request) {
+ if _, _, ok := s.apiSystemRoller(w, r); !ok {
+ return
+ }
+ if !s.systemBucket(w) {
+ return
+ }
+ ctx := r.Context()
+ mode, err := s.hostsMode(ctx)
+ if err != nil {
+ log.Printf("console: hosts used status: read the mode: %v", err)
+ jsonError(w, http.StatusBadGateway, "could not read the hostname history's mode. Try again.")
+ return
+ }
+ keys, err := s.cfg.Releases.List(ctx, provision.HostsUsedPrefix)
+ if err != nil {
+ log.Printf("console: hosts used status: list the marks: %v", err)
+ jsonError(w, http.StatusBadGateway, "could not list the hostname history. Try again.")
+ return
+ }
+ out := hostsUsedStatus{Mode: mode}
+ for _, k := range keys {
+ if host, ok := strings.CutSuffix(strings.TrimPrefix(k, provision.HostsUsedPrefix), ".json"); ok && provision.HostsUsedKey(host) == k {
+ out.Marks++
+ }
+ }
+ allocs, err := s.store.PendingAllocations()
+ if err != nil {
+ log.Printf("console: hosts used status: pending allocations: %v", err)
+ jsonError(w, http.StatusBadGateway, "could not read the console's pending creates. Try again.")
+ return
+ }
+ rets, err := s.store.PendingRetirements()
+ if err != nil {
+ log.Printf("console: hosts used status: pending retirements: %v", err)
+ jsonError(w, http.StatusBadGateway, "could not read the console's pending deletes. Try again.")
+ return
+ }
+ out.PendingAllocations, out.PendingRetirements = len(allocs), len(rets)
+ writeJSON(w, http.StatusOK, out)
+}
diff --git a/internal/console/hostsused_writers_test.go b/internal/console/hostsused_writers_test.go
new file mode 100644
index 000000000..2996de63e
--- /dev/null
+++ b/internal/console/hostsused_writers_test.go
@@ -0,0 +1,591 @@
+package console
+
+// The hostname history at every create writer (nearest-region never-reuse
+// plan, Task 3; spec 2026-10-26-nearest-region-without-claims-design.md §2).
+// Every witness goes through the real door, with lifetimes off and on, over
+// the fixture's bucket behind an ltStore that records and can fail calls.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "net/http"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// markCase is one create through one door, ready to run.
+type markCase struct {
+ fx *consoleFixture
+ bucket *ltStore
+ host string
+ recordKey string
+ kind string // the mark's kind
+ created int // the door's success status
+ duplicate string // the door's ordinary duplicate answer
+ create func(t *testing.T) (int, string)
+}
+
+// markDoor builds a markCase for one door with lifetimes off or on.
+type markDoor struct {
+ name string
+ build func(t *testing.T) markCase
+}
+
+// lifetimesFor runs body once with lifetimes off and once on. useClock is
+// set before any fixture exists, as newLtOn does.
+func lifetimesFor(t *testing.T, body func(t *testing.T, on func(*testing.T, markCase))) {
+ t.Run("lifetimes off", func(t *testing.T) { body(t, func(*testing.T, markCase) {}) })
+ t.Run("lifetimes on", func(t *testing.T) {
+ clock := useLifetimesClock(t)
+ body(t, func(t *testing.T, c markCase) {
+ t.Helper()
+ turnLifetimesOn(t, c.fx.srv, clock)
+ })
+ })
+}
+
+// wrapBucket puts the fixture's bucket behind an ltStore.
+func wrapBucket(fx *consoleFixture) *ltStore {
+ b := &ltStore{Store: fx.srv.cfg.Releases}
+ fx.srv.cfg.Releases = b
+ return b
+}
+
+func postCase(fx *consoleFixture, url, token, body string) func(t *testing.T) (int, string) {
+ return func(t *testing.T) (int, string) {
+ t.Helper()
+ code, _, out := rawReq(t, http.MethodPost, url, token, body)
+ fx.srv.seedCopies.Wait()
+ return code, out
+ }
+}
+
+// markDoors is every data-kind create door, in each placement shape.
+var markDoors = []markDoor{
+ {"instance", func(t *testing.T) markCase {
+ fx, member, domain := canaryDoorFixture(t, "code-mark-instance")
+ host := "plain." + domain
+ return markCase{fx: fx, bucket: wrapBucket(fx), host: host,
+ recordKey: provision.RecordKey("bab", "titogo", host), kind: "instance", created: http.StatusCreated,
+ duplicate: "instance " + host + " already exists",
+ create: postCase(fx, instancesURL(fx, "bab", "titogo"), member, `{"host":"`+host+`"}`)}
+ }},
+ {"addr-backed instance", func(t *testing.T) markCase {
+ fx, member, domain := canaryDoorFixture(t, "code-mark-addr")
+ letStateUpstreams(t, fx, "alice@keymail.dev")
+ host := "addr." + domain
+ return markCase{fx: fx, bucket: wrapBucket(fx), host: host,
+ recordKey: provision.RecordKey("bab", "titogo", host), kind: "instance", created: http.StatusCreated,
+ duplicate: "instance " + host + " already exists",
+ create: postCase(fx, instancesURL(fx, "bab", "titogo"), member,
+ `{"host":"`+host+`","addrs":["10.0.0.4:8080"],"hibernate":false}`)}
+ }},
+ {"canary", func(t *testing.T) markCase {
+ fx, member, domain := canaryDoorFixture(t, "code-mark-canary")
+ host := "new-queue-titogo." + domain
+ return markCase{fx: fx, bucket: wrapBucket(fx), host: host,
+ recordKey: provision.RecordKey("bab", "titogo", host), kind: "instance", created: http.StatusCreated,
+ duplicate: "instance " + host + " already exists",
+ create: postCase(fx, instancesURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","channel":"canary/new-queue"}`)}
+ }},
+ {"region", func(t *testing.T) markCase {
+ fx := leftoverFixture(t, "code-mark-region")
+ return markCase{fx: fx.consoleFixture, bucket: wrapBucket(fx.consoleFixture), host: "acme.go.tito.io",
+ recordKey: provision.RecordKey("bab", "titogo", "acme.go.tito.io"), kind: "instance", created: http.StatusCreated,
+ duplicate: "instance acme.go.tito.io already exists",
+ create: postCase(fx.consoleFixture, instancesURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"host":"acme.go.tito.io","region":"ie"}`)}
+ }},
+ {"app region", func(t *testing.T) markCase {
+ fx, token, u := fillFixture(t, "uk")
+ return markCase{fx: fx, bucket: wrapBucket(fx), host: "a.go.tito.io",
+ recordKey: provision.RecordKey("bab", "titogo", "a.go.tito.io"), kind: "instance", created: http.StatusCreated,
+ duplicate: "instance a.go.tito.io already exists",
+ create: postCase(fx, u, token, `{"host":"a.go.tito.io"}`)}
+ }},
+ {"seed", func(t *testing.T) markCase {
+ f := newFromFixture(t, 3)
+ return markCase{fx: f.fx, bucket: wrapBucket(f.fx), host: fromHost,
+ recordKey: provision.RecordKey("bab", fromApp, fromHost), kind: "instance", created: http.StatusAccepted,
+ duplicate: "instance " + fromHost + " already exists",
+ create: postCase(f.fx, f.url, f.token, fromBody)}
+ }},
+ {"import", func(t *testing.T) markCase {
+ f := newImportFixture(t)
+ return markCase{fx: f.fx, bucket: wrapBucket(f.fx), host: importHost,
+ recordKey: provision.RecordKey("bab", fromApp, importHost), kind: "instance", created: http.StatusCreated,
+ duplicate: "instance " + importHost + " already exists",
+ create: postCase(f.fx, f.url, f.token, importBody(importHost, importSHA, 4096, importAddr))}
+ }},
+ {"sidecar", func(t *testing.T) markCase {
+ fx := leftoverFixture(t, "code-mark-sidecar")
+ return markCase{fx: fx.consoleFixture, bucket: wrapBucket(fx.consoleFixture), host: botHost,
+ recordKey: provision.SidecarRecordKey("bab", "titogo", "bot"), kind: "sidecar", created: http.StatusCreated,
+ duplicate: "sidecar bot already exists",
+ create: postCase(fx.consoleFixture, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot","region":"ie"}`)}
+ }},
+}
+
+// recordPresent reports whether key holds a body in the bucket under the
+// wrapper.
+func recordPresent(t *testing.T, c markCase, key string) bool {
+ t.Helper()
+ _, _, err := c.bucket.Store.Get(context.Background(), key)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ return err == nil
+}
+
+// markOf reads host's mark; nil when absent.
+func markOf(t *testing.T, c markCase) *provision.HostUse {
+ t.Helper()
+ raw, _, err := c.bucket.Store.Get(context.Background(), provision.HostsUsedKey(c.host))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ var u provision.HostUse
+ if err := json.Unmarshal(raw, &u); err != nil {
+ t.Fatal(err)
+ }
+ return &u
+}
+
+// forceHostsMode writes mode to the control store and has srv read it again,
+// as a console start would.
+func forceHostsMode(t *testing.T, srv *Server, mode string) {
+ t.Helper()
+ ctx := context.Background()
+ _, etag, err := provision.ReadHostsMode(ctx, srv.cfg.Releases)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provision.WriteHostsMode(ctx, srv.cfg.Releases, mode, etag); err != nil {
+ t.Fatal(err)
+ }
+ srv.hosts.mu.Lock()
+ srv.hosts.mode = ""
+ srv.hosts.mu.Unlock()
+ if got, err := srv.hostsMode(ctx); err != nil || got != mode {
+ t.Fatalf("hostsMode = %q %v, want %q", got, err, mode)
+ }
+}
+
+func eachMarkDoor(t *testing.T, body func(t *testing.T, c markCase)) {
+ for _, d := range markDoors {
+ t.Run(d.name, func(t *testing.T) {
+ lifetimesFor(t, func(t *testing.T, on func(*testing.T, markCase)) {
+ c := d.build(t)
+ on(t, c)
+ body(t, c)
+ })
+ })
+ }
+}
+
+// TestCreateDoorsMarkBeforePersisting: the mark's Put lands while nothing of
+// the create is persisted (no record body, no allocation row), and the
+// create then persists its record.
+func TestCreateDoorsMarkBeforePersisting(t *testing.T) {
+ eachMarkDoor(t, func(t *testing.T, c markCase) {
+ markKey := provision.HostsUsedKey(c.host)
+ var mu sync.Mutex
+ var problems []string
+ marked := false
+ c.bucket.setHook(func(op, key string) error {
+ if op != "put" {
+ return nil
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ switch key {
+ case markKey:
+ marked = true
+ if _, _, err := c.bucket.Store.Get(context.Background(), c.recordKey); !errors.Is(err, os.ErrNotExist) {
+ problems = append(problems, "the record was present when the mark was written")
+ }
+ if rows, err := c.fx.st.allocations(`host = ?`, c.host); err != nil || len(rows) != 0 {
+ problems = append(problems, "an allocation row existed when the mark was written")
+ }
+ case c.recordKey:
+ if !marked {
+ problems = append(problems, "the record was written before the mark")
+ }
+ }
+ return nil
+ })
+ code, out := c.create(t)
+ c.bucket.setHook(nil)
+ if code != c.created {
+ t.Fatalf("create = %d %s, want %d", code, out, c.created)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if len(problems) > 0 {
+ t.Fatal(strings.Join(problems, "; "))
+ }
+ u := markOf(t, c)
+ if u == nil || u.Host != c.host || u.Account != "bab" || u.Kind != c.kind || u.At.IsZero() {
+ t.Fatalf("mark = %+v, want %s's, kind %s", u, c.host, c.kind)
+ }
+ if !recordPresent(t, c, c.recordKey) {
+ t.Fatal("no record after the create")
+ }
+ })
+}
+
+// TestRetryAfterLandedCreateIsDuplicate: the same create again gets the
+// door's ordinary duplicate answer, never S1, before and after activation.
+func TestRetryAfterLandedCreateIsDuplicate(t *testing.T) {
+ for _, mode := range []string{provision.HostsModeIncomplete, provision.HostsModeActive} {
+ t.Run(mode, func(t *testing.T) {
+ eachMarkDoor(t, func(t *testing.T, c markCase) {
+ if code, out := c.create(t); code != c.created {
+ t.Fatalf("first create = %d %s", code, out)
+ }
+ forceHostsMode(t, c.fx.srv, mode)
+ before, _, err := c.bucket.Store.Get(context.Background(), c.recordKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ code, out := c.create(t)
+ if code != http.StatusConflict || !strings.Contains(out, c.duplicate) {
+ t.Fatalf("retry = %d %s, want the door's 409 %q", code, out, c.duplicate)
+ }
+ after, _, err := c.bucket.Store.Get(context.Background(), c.recordKey)
+ if err != nil || string(after) != string(before) {
+ t.Fatalf("the retry changed the record (%v)", err)
+ }
+ })
+ })
+ }
+}
+
+// TestMarkErrorRefusesInIncomplete: a mark that cannot be written refuses
+// the create with S2 before anything is persisted.
+func TestMarkErrorRefusesInIncomplete(t *testing.T) {
+ eachMarkDoor(t, func(t *testing.T, c markCase) {
+ c.bucket.setHook(failNth("put", provision.HostsUsedKey(c.host), 1, true))
+ code, out := c.create(t)
+ c.bucket.setHook(nil)
+ if code != http.StatusServiceUnavailable || ltErr(out) != msgHostUnchecked(c.host) {
+ t.Fatalf("create with the mark failing = %d %s, want 503 %q", code, out, msgHostUnchecked(c.host))
+ }
+ if recordPresent(t, c, c.recordKey) {
+ t.Fatal("a record was written unmarked")
+ }
+ if rows, err := c.fx.st.allocations(`host = ?`, c.host); err != nil || len(rows) != 0 {
+ t.Fatalf("allocation rows = %+v %v, want none", rows, err)
+ }
+ })
+}
+
+// TestModeReadErrorRefuses: a mode that cannot be read is never a default.
+func TestModeReadErrorRefuses(t *testing.T) {
+ eachMarkDoor(t, func(t *testing.T, c markCase) {
+ c.fx.srv.hosts.mu.Lock()
+ c.fx.srv.hosts.mode = ""
+ c.fx.srv.hosts.mu.Unlock()
+ c.bucket.setHook(failNth("get", provision.HostsModeKey, 1, true))
+ code, out := c.create(t)
+ c.bucket.setHook(nil)
+ if code != http.StatusServiceUnavailable || ltErr(out) != msgHostUnchecked(c.host) {
+ t.Fatalf("create with the mode unreadable = %d %s, want 503 %q", code, out, msgHostUnchecked(c.host))
+ }
+ if recordPresent(t, c, c.recordKey) || markOf(t, c) != nil {
+ t.Fatal("the create wrote something with its mode unread")
+ }
+ // The next create reads it again and goes ahead.
+ if code, out := c.create(t); code != c.created {
+ t.Fatalf("create once the mode reads = %d %s", code, out)
+ }
+ })
+}
+
+// TestUsedHostRefusedEverywhereWhenActive: once active, a hostname with a
+// mark is refused with S1 at every door and placement, and nothing is
+// written.
+func TestUsedHostRefusedEverywhereWhenActive(t *testing.T) {
+ eachMarkDoor(t, func(t *testing.T, c markCase) {
+ if _, err := provision.MarkHostUsed(context.Background(), c.bucket.Store, provision.HostUse{Host: c.host, Account: "zzz", App: "gone", Kind: "instance", Source: "test"}); err != nil {
+ t.Fatal(err)
+ }
+ forceHostsMode(t, c.fx.srv, provision.HostsModeActive)
+ code, out := c.create(t)
+ if code != http.StatusConflict || ltErr(out) != msgHostUsed(c.host) {
+ t.Fatalf("create of a used host = %d %s, want 409 %q", code, out, msgHostUsed(c.host))
+ }
+ if recordPresent(t, c, c.recordKey) {
+ t.Fatal("a record was written over a used host")
+ }
+ if rows, err := c.fx.st.allocations(`host = ?`, c.host); err != nil || len(rows) != 0 {
+ t.Fatalf("allocation rows = %+v %v, want none", rows, err)
+ }
+ })
+}
+
+// TestIncompleteModePassesAUsedHost: before activation a mark already there
+// changes nothing a user sees.
+func TestIncompleteModePassesAUsedHost(t *testing.T) {
+ eachMarkDoor(t, func(t *testing.T, c markCase) {
+ if _, err := provision.MarkHostUsed(context.Background(), c.bucket.Store, provision.HostUse{Host: c.host, Account: "zzz", App: "gone", Kind: "instance", Source: "test"}); err != nil {
+ t.Fatal(err)
+ }
+ if code, out := c.create(t); code != c.created {
+ t.Fatalf("create of a marked host before activation = %d %s, want %d", code, out, c.created)
+ }
+ if u := markOf(t, c); u == nil || u.Account != "zzz" {
+ t.Fatalf("mark = %+v, want the first writer's, unchanged", u)
+ }
+ })
+}
+
+// TestExemptCreatesDoNotMark: static and service records, the attach
+// doors' first routes and temporary apps write no mark.
+func TestExemptCreatesDoNotMark(t *testing.T) {
+ noMarks := func(t *testing.T, st release.Store) {
+ t.Helper()
+ keys, err := st.List(context.Background(), provision.HostsUsedPrefix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(keys) != 0 {
+ t.Fatalf("marks written: %v", keys)
+ }
+ }
+ lifetimesFor(t, func(t *testing.T, on func(*testing.T, markCase)) {
+ t.Run("static and service", func(t *testing.T) {
+ fx, member, domain := canaryDoorFixture(t, "code-exempt-kinds")
+ letStateUpstreams(t, fx, "alice@keymail.dev")
+ c := markCase{fx: fx, bucket: wrapBucket(fx)}
+ on(t, c)
+ for _, body := range []string{
+ `{"host":"site.` + domain + `","kind":"static"}`,
+ `{"host":"svc.` + domain + `","kind":"service","addrs":["10.0.0.4:8080"],"hibernate":false}`,
+ } {
+ if code, _, out := rawReq(t, http.MethodPost, instancesURL(fx, "bab", "titogo"), member, body); code != http.StatusCreated {
+ t.Fatalf("%s = %d %s", body, code, out)
+ }
+ }
+ noMarks(t, c.bucket.Store)
+ })
+ t.Run("attach first route", func(t *testing.T) {
+ fx, member := instanceFixture(t, "code-exempt-attach")
+ c := markCase{fx: fx, bucket: wrapBucket(fx)}
+ on(t, c)
+ shipVersion(t, fx, "titogo", "v1")
+ seedChannel(t, fx, "titogo", "canary/live", "v1")
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"fresh.example.com","kind":"static"}`)
+ if code != http.StatusOK {
+ t.Fatalf("attach = %d %s", code, out)
+ }
+ if _, err := provision.GetRecord(context.Background(), c.bucket.Store, "bab", "titogo", "fresh.example.com"); err != nil {
+ t.Fatalf("the first route's record: %v", err)
+ }
+ noMarks(t, c.bucket.Store)
+ })
+ t.Run("temporary app", func(t *testing.T) {
+ fx, token := temporaryFixture(t)
+ c := markCase{fx: fx, bucket: wrapBucket(fx)}
+ on(t, c)
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ if code, out := createTemporary(t, fx, token, "tmp-docs", 0); code != http.StatusOK {
+ t.Fatalf("temporary create = %d %v", code, out)
+ }
+ // Its site's first record, as carlos deploy mints it
+ // (mintPlatformHost): instances enabled, then a static create
+ // of the app's platform host through the instance door.
+ code, _, out := rawReq(t, http.MethodPut, enableURL(fx, fx.sqid, "tmp-docs"), token, `{}`)
+ if code != http.StatusOK {
+ t.Fatalf("enable = %d %s", code, out)
+ }
+ var m provision.Manifest
+ if err := json.Unmarshal([]byte(out), &m); err != nil || m.Domain == "" {
+ t.Fatalf("enable answer %s: %v", out, err)
+ }
+ host := "tmp-docs." + m.Domain
+ if code, _, out := rawReq(t, http.MethodPost, instancesURL(fx, fx.sqid, "tmp-docs"), token, `{"host":"`+host+`","kind":"static"}`); code != http.StatusCreated {
+ t.Fatalf("the temporary site's static create = %d %s", code, out)
+ }
+ if _, err := provision.GetRecord(context.Background(), c.bucket.Store, fx.sqid, "tmp-docs", host); err != nil {
+ t.Fatalf("the temporary site's record: %v", err)
+ }
+ noMarks(t, c.bucket.Store)
+ })
+ })
+}
+
+// createWriterSites is every call in internal/console that persists a new
+// record or begins one, by file and enclosing function, with whether it
+// must mark first (and through which call) or why it is exempt. A new
+// writer fails TestEveryCreateWriterMarksFirst until it is listed here.
+var createWriterSites = map[string]string{
+ // Marked: the mark call must come first in the same function.
+ "hostsused.go Server.createRecordMarked provision.CreateRecord": "mark:markBeforeCreate",
+ "hostsused.go Server.createSidecarMarked provision.CreateSidecarRecord": "mark:markBeforeCreate",
+ "lifetimes_create.go Server.createRecordWithLifetimeLocked s.store.BeginAllocation": "mark:markForCreate",
+ "domainattach.go Server.attachDomainAs provision.CreateRecord": "exempt: a first route is a static record",
+ "lifetimes_create.go Server.allocRecordLocked provision.WriteRecord": "exempt: publishes an allocation its door marked before BeginAllocation (recovery is Task 7)",
+ "lifetimes_create.go Server.fenceRecord provision.WriteRecord": "exempt: the fence rewrites a present body's exact bytes",
+ "lifetimes_migrate.go Server.migrationMarkLocked provision.WriteRecord": "exempt: an in-place rewrite of a present body",
+ "lifetimes_migrate.go Server.migrationFinishLocked provision.WriteRecord": "exempt: an in-place rewrite of a present body",
+ "lifetimes_retire.go Server.retirementStepsLocked provision.WriteRecord": "exempt: a tombstone of a present body",
+ "apiinstances.go Server.handleAPIInstanceCreate Server.createRecordMarked": "marks",
+ "apiinstanceseed.go Server.createSeedRecord Server.createRecordMarked": "marks",
+ "apisidecars.go Server.handleAPISidecarCreate Server.createSidecarMarked": "marks",
+}
+
+// TestEveryCreateWriterMarksFirst is a source scan of internal/console: every
+// call of a record-creating primitive is listed in createWriterSites, and a
+// marked one is preceded in its function by its mark call.
+func TestEveryCreateWriterMarksFirst(t *testing.T) {
+ primitives := map[string]bool{
+ "provision.CreateRecord": true, "provision.CreateSidecarRecord": true, "provision.CreateRecordReplica": true,
+ "provision.WriteRecord": true, "s.store.BeginAllocation": true,
+ }
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ seen := map[string]bool{}
+ var problems []string
+ for _, file := range files {
+ if strings.HasSuffix(file, "_test.go") {
+ continue
+ }
+ f, err := parser.ParseFile(fset, file, nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, decl := range f.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if !ok || fn.Body == nil {
+ continue
+ }
+ name := fn.Name.Name
+ if fn.Recv != nil && len(fn.Recv.List) == 1 {
+ if star, ok := fn.Recv.List[0].Type.(*ast.StarExpr); ok {
+ if id, ok := star.X.(*ast.Ident); ok {
+ name = id.Name + "." + name
+ }
+ }
+ }
+ calls := map[string]token.Pos{}
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ callee := exprName(call.Fun)
+ if _, dup := calls[callee]; !dup {
+ calls[callee] = call.Pos()
+ }
+ if primitives[callee] || callee == "s.createRecordMarked" || callee == "s.createSidecarMarked" {
+ site := file + " " + name + " " + strings.Replace(callee, "s.create", "Server.create", 1)
+ seen[site] = true
+ if _, listed := createWriterSites[site]; !listed {
+ problems = append(problems, "unlisted create writer: "+site+" ("+fset.Position(call.Pos()).String()+")")
+ }
+ }
+ return true
+ })
+ for site, rule := range createWriterSites {
+ parts := strings.SplitN(site, " ", 3)
+ if parts[0] != file || parts[1] != name || !strings.HasPrefix(rule, "mark:") {
+ continue
+ }
+ prim := strings.Replace(parts[2], "Server.", "s.", 1)
+ mark, ok := calls["s."+strings.TrimPrefix(rule, "mark:")]
+ if !ok || mark > calls[prim] {
+ problems = append(problems, site+": its mark call does not come before it")
+ }
+ }
+ }
+ }
+ for site := range createWriterSites {
+ if !seen[site] {
+ problems = append(problems, "listed but not found (moved or renamed?): "+site)
+ }
+ }
+ sort.Strings(problems)
+ if len(problems) > 0 {
+ t.Fatal(strings.Join(problems, "\n"))
+ }
+}
+
+// exprName is a call's callee as written: s.store.BeginAllocation,
+// provision.CreateRecord, s.createRecordMarked.
+func exprName(e ast.Expr) string {
+ switch x := e.(type) {
+ case *ast.Ident:
+ return x.Name
+ case *ast.SelectorExpr:
+ if inner := exprName(x.X); inner != "" {
+ return inner + "." + x.Sel.Name
+ }
+ }
+ return ""
+}
+
+// ---- Task 4: the status door ----------------------------------------------
+
+const hostsUsedStatusURL = "/api/cli/system/hosts-used/status"
+
+// TestHostsUsedStatusDoor: operators only (a member gets the family's 404),
+// the mode, and the marks counted by listing; the mode and floor objects are
+// not marks. The drain counts it cannot know before Task 5 are null.
+func TestHostsUsedStatusDoor(t *testing.T) {
+ l := newLifetimesFx(t)
+ get := func(token string) (int, map[string]any) {
+ t.Helper()
+ code, _, out := rawReq(t, http.MethodGet, l.fx.ts.URL+hostsUsedStatusURL, token, "")
+ var m map[string]any
+ _ = json.Unmarshal([]byte(out), &m)
+ return code, m
+ }
+ if code, _ := get(l.member); code != http.StatusNotFound {
+ t.Fatalf("a member's status = %d, want 404", code)
+ }
+ code, st := get(l.operator)
+ if code != http.StatusOK || st["mode"] != provision.HostsModeIncomplete || st["marks"] != float64(0) {
+ t.Fatalf("empty status = %d %v", code, st)
+ }
+ for _, k := range []string{"pending_allocations", "pending_retirements"} {
+ if st[k] != float64(0) {
+ t.Fatalf("%s = %v, want 0", k, st[k])
+ }
+ }
+ for _, k := range []string{"inflight_creates", "unfinished_moves"} {
+ if v, ok := st[k]; !ok || v != nil {
+ t.Fatalf("%s = %v (present %v), want null until the activation window exists", k, v, ok)
+ }
+ }
+ for _, host := range []string{"a.shop.example.com", "b.shop.example.com"} {
+ if code, out := (ltOn{lifetimesFx: l}).create(t, host); code != http.StatusCreated {
+ t.Fatalf("create %s = %d %s", host, code, out)
+ }
+ }
+ if _, err := provision.WriteHostsFloor(context.Background(), l.fx.rel, provision.HostsFloor{Version: "v0", Commit: "c"}, ""); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provision.WriteHostsMode(context.Background(), l.fx.rel, provision.HostsModeIncomplete, ""); err != nil {
+ t.Fatal(err)
+ }
+ if code, st = get(l.operator); code != http.StatusOK || st["marks"] != float64(2) {
+ t.Fatalf("status after two creates = %d %v, want two marks", code, st)
+ }
+}
diff --git a/internal/console/lifetimes.go b/internal/console/lifetimes.go
index 51d209097..0eb8b4f04 100644
--- a/internal/console/lifetimes.go
+++ b/internal/console/lifetimes.go
@@ -101,7 +101,11 @@ func (e *lifetimeAppError) Unwrap() error { return e.Err }
func lifetimeCreateRefusal(host string, err error, pendingMsg string) (*doorRefusal, bool) {
var held *hostHeldError
var app *lifetimeAppError
+ var used *hostsUsedError
switch {
+ case errors.As(err, &used):
+ // The hostname history's refusal (hostsused.go), lifetimes on or off.
+ return &used.ref, true
case errors.As(err, &held):
return &doorRefusal{http.StatusConflict, hostHeldSentence(host, held.Hold)}, true
case errors.Is(err, errLifetimeSettling):
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go
index a5550cec6..b7921bb0b 100644
--- a/internal/console/lifetimes_create.go
+++ b/internal/console/lifetimes_create.go
@@ -105,6 +105,15 @@ func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provisi
if plan.ownerStaleETag != "" {
a.PrevOwnerKey = provision.RecordKey(plan.ownerAccount, plan.ownerApp, host)
}
+ // The hostname history (hostsused.go): a data kind marks its hostname
+ // after every check above, step 2's record read among them, and before
+ // anything is persisted. Nothing is durable yet, so a refusal leaves
+ // nothing behind.
+ if rec.DataKind() {
+ if ref := s.markForCreate(ctx, recordUse(rec)); ref != nil {
+ return nil, &hostsUsedError{*ref}
+ }
+ }
if err := s.store.BeginAllocation(a); err != nil {
return nil, fmt.Errorf("console: lifetimes: begin allocation of %s: %w", host, err)
}
diff --git a/internal/console/server.go b/internal/console/server.go
index 1847972ea..93ce5ce98 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -902,6 +902,9 @@ type Server struct {
// billing is nil when billing is off (Config.Billing, plans 6a).
billing *billingRuntime
+ // hosts is the hostname history's mode, read once (hostsused.go).
+ hosts hostsHistory
+
// lapseBeforeConverge, when set (tests only), runs inside the account's
// grace pass just before the lapse converges (plans 4d, Astra finding 1).
lapseBeforeConverge func()
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 56f023174..d3ed03c36 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -291,6 +291,9 @@ var closedDoors = []string{
// root-signed, the same cut as the update doors.
"GET /api/cli/system/pointer-digests",
"POST /api/cli/system/pointer-digests",
+ // The hostname history's status (nearest-region never-reuse): an
+ // operator's deployment-wide view, the same cut.
+ "GET /api/cli/system/hosts-used/status",
// `carlos channels resign`: the console signs digests a person has
// confirmed. A credential never confirms on a person's behalf.
"POST /api/cli/apps/{account}/{app}/channels/resign",
@@ -1100,8 +1103,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
}
seen++
}
- if seen != len(closedDoors) || seen != 66 {
- t.Errorf("walked %d closed doors, want all %d (and 66 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, and two billing problem doors)",
+ if seen != len(closedDoors) || seen != 67 {
+ t.Errorf("walked %d closed doors, want all %d (and 67 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, and two billing problem doors)",
seen, len(closedDoors))
}
}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index bf3fbd477..908a5fda2 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -96,6 +96,7 @@ route GET /api/cli/status/layout
route GET /api/cli/store/approvals
route GET /api/cli/system/antivirus
route GET /api/cli/system/geoip
+route GET /api/cli/system/hosts-used/status
route GET /api/cli/system/jobs/{id}
route GET /api/cli/system/layout
route GET /api/cli/system/pointer-digests
diff --git a/internal/provision/hostsused.go b/internal/provision/hostsused.go
new file mode 100644
index 000000000..14469660f
--- /dev/null
+++ b/internal/provision/hostsused.go
@@ -0,0 +1,241 @@
+package provision
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The hostname history (nearest-region never-reuse; spec
+// docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md
+// §1, §4). A mark at control/hosts-used/<host>.json means "this hostname may
+// hold data". Every data-kind create writer puts one, create-only, before it
+// persists anything; no code path ever deletes one. Beside the marks live two
+// objects whose names cannot be hostnames: @mode (the console's history
+// mode) and @floor (the oldest record-writing build allowed once active).
+
+// HostsUsedPrefix is where the marks, the mode and the floor live, in the
+// console's control store.
+const HostsUsedPrefix = "control/hosts-used/"
+
+// HostsModeKey and HostsFloorKey start with "@", which no valid hostname
+// does, so a listing of HostsUsedPrefix tells them from marks.
+const (
+ HostsModeKey = HostsUsedPrefix + "@mode"
+ HostsFloorKey = HostsUsedPrefix + "@floor"
+)
+
+// The history modes (spec §4). Absent in the store means incomplete.
+const (
+ HostsModeIncomplete = "incomplete"
+ HostsModeActivating = "activating"
+ HostsModeActive = "active"
+ HostsModeInvalidated = "invalidated"
+)
+
+// ErrKindChange refuses an in-place write that changes a record's kind: an
+// exempt record (static, service) must never become a data kind without the
+// mark its create would have written.
+var ErrKindChange = errors.New("provision: a record's kind cannot change")
+
+// HostUse is a mark's body. It records who first marked the hostname and
+// why; nothing reads it back as authority, since the mark's presence alone
+// is the fact.
+type HostUse struct {
+ Host string `json:"host"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Kind string `json:"kind"`
+ Source string `json:"source"`
+ At time.Time `json:"at"`
+}
+
+// HostsUsedKey is host's mark key, or "" for a host that fails
+// ValidHostShape (uppercase, a trailing dot, a slash, "@mode").
+func HostsUsedKey(host string) string {
+ if !ValidHostShape(host) {
+ return ""
+ }
+ return HostsUsedPrefix + host + ".json"
+}
+
+// MarkHostUsed writes u's mark create-only. fresh reports that this call
+// wrote it; a mark already present is (false, nil) and its body is left as
+// it was. Any other store error passes through: the caller does not know
+// whether the hostname is marked.
+func MarkHostUsed(ctx context.Context, s release.Store, u HostUse) (fresh bool, err error) {
+ key := HostsUsedKey(u.Host)
+ if key == "" {
+ return false, fmt.Errorf("provision: hosts used: %q is not a hostname", u.Host)
+ }
+ body, err := json.Marshal(u)
+ if err != nil {
+ return false, err
+ }
+ if _, err := s.Put(ctx, key, body, ""); err != nil {
+ if errors.Is(err, release.ErrCASConflict) {
+ return false, nil
+ }
+ return false, err
+ }
+ return true, nil
+}
+
+// HostIsUsed reports whether host's mark exists. An unreadable store is an
+// error, never "unused".
+func HostIsUsed(ctx context.Context, s release.Store, host string) (bool, error) {
+ key := HostsUsedKey(host)
+ if key == "" {
+ return false, fmt.Errorf("provision: hosts used: %q is not a hostname", host)
+ }
+ _, _, err := s.Get(ctx, key)
+ switch {
+ case err == nil:
+ return true, nil
+ case errors.Is(err, os.ErrNotExist):
+ return false, nil
+ }
+ return false, err
+}
+
+// DataKind reports whether a record of r's kind can hold data: every kind
+// but static and service (spec §1). An addr-backed instance is a data kind,
+// because its Addrs can change. Sidecars are always data kinds and are
+// marked by their own writer.
+func (r Record) DataKind() bool {
+ switch r.KindOrDefault() {
+ case "static", "service":
+ return false
+ }
+ return true
+}
+
+func validHostsMode(m string) bool {
+ switch m {
+ case HostsModeIncomplete, HostsModeActivating, HostsModeActive, HostsModeInvalidated:
+ return true
+ }
+ return false
+}
+
+type hostsModeBody struct {
+ Mode string `json:"mode"`
+}
+
+// ReadHostsMode reads @mode. Absent is (incomplete, "", nil). A body that
+// does not name a known mode is an error, never a default.
+func ReadHostsMode(ctx context.Context, s release.Store) (mode, etag string, err error) {
+ raw, etag, err := s.Get(ctx, HostsModeKey)
+ if errors.Is(err, os.ErrNotExist) {
+ return HostsModeIncomplete, "", nil
+ }
+ if err != nil {
+ return "", "", err
+ }
+ var b hostsModeBody
+ if err := json.Unmarshal(raw, &b); err != nil {
+ return "", "", fmt.Errorf("provision: hosts used: %s: %w", HostsModeKey, err)
+ }
+ if !validHostsMode(b.Mode) {
+ return "", "", fmt.Errorf("provision: hosts used: %s names no known mode (%q)", HostsModeKey, b.Mode)
+ }
+ return b.Mode, etag, nil
+}
+
+// WriteHostsMode writes @mode on ifMatch ("" is create-only, as Store.Put)
+// and returns the new ETag. A lost race is release.ErrCASConflict.
+func WriteHostsMode(ctx context.Context, s release.Store, mode, ifMatch string) (string, error) {
+ if !validHostsMode(mode) {
+ return "", fmt.Errorf("provision: hosts used: unknown mode %q", mode)
+ }
+ body, err := json.Marshal(hostsModeBody{Mode: mode})
+ if err != nil {
+ return "", err
+ }
+ return s.Put(ctx, HostsModeKey, body, ifMatch)
+}
+
+// HostsFloor is the oldest console and CLI build allowed to write records
+// once the history is active (spec §4).
+type HostsFloor struct {
+ Version string `json:"version"`
+ Commit string `json:"commit"`
+}
+
+// ReadHostsFloor reads @floor; absent is (nil, "", nil).
+func ReadHostsFloor(ctx context.Context, s release.Store) (*HostsFloor, string, error) {
+ raw, etag, err := s.Get(ctx, HostsFloorKey)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, "", nil
+ }
+ if err != nil {
+ return nil, "", err
+ }
+ var f HostsFloor
+ if err := json.Unmarshal(raw, &f); err != nil {
+ return nil, "", fmt.Errorf("provision: hosts used: %s: %w", HostsFloorKey, err)
+ }
+ return &f, etag, nil
+}
+
+// WriteHostsFloor writes @floor on ifMatch, as WriteHostsMode.
+func WriteHostsFloor(ctx context.Context, s release.Store, f HostsFloor, ifMatch string) (string, error) {
+ body, err := json.Marshal(f)
+ if err != nil {
+ return "", err
+ }
+ return s.Put(ctx, HostsFloorKey, body, ifMatch)
+}
+
+// checkKindUnchanged is WriteRecord's kind immutability for an in-place
+// write (a create from {} never reaches it). before is the If-Match read and
+// body the exact bytes about to be written. Both are decoded as
+// DecodeRecord decodes a record (json.Unmarshal into the field: names match
+// case-insensitively and a later match wins), so the check sees the kind
+// every reader will see, whatever spellings or order the bytes carry. A
+// tombstone body keeps no kind (TombstoneBody) and is no live record, so
+// retiring a record of any kind still lands. Absent and "" read as
+// instance. A body that does not decode is refused, except an exact rewrite
+// of before's own bytes (exact), which changes nothing.
+func checkKindUnchanged(before, body []byte, exact bool) error {
+ a, errA := decodeKindFields(body)
+ if errA == nil && a.Retired {
+ return nil
+ }
+ b, errB := decodeKindFields(before)
+ if errA != nil || errB != nil {
+ if exact {
+ return nil
+ }
+ return ErrKindChange
+ }
+ if kindOrInstance(a.Kind) != kindOrInstance(b.Kind) {
+ return ErrKindChange
+ }
+ return nil
+}
+
+// kindFields is the part of a record body the kind check reads, with the
+// same tags Record and the tombstone use.
+type kindFields struct {
+ Kind string `json:"kind"`
+ Retired bool `json:"retired"`
+}
+
+func decodeKindFields(raw []byte) (kindFields, error) {
+ var f kindFields
+ err := json.Unmarshal(raw, &f)
+ return f, err
+}
+
+func kindOrInstance(k string) string {
+ if k == "" {
+ return "instance"
+ }
+ return k
+}
diff --git a/internal/provision/hostsused_test.go b/internal/provision/hostsused_test.go
new file mode 100644
index 000000000..0a67f51ca
--- /dev/null
+++ b/internal/provision/hostsused_test.go
@@ -0,0 +1,278 @@
+package provision
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The hostname history (nearest-region never-reuse plan, Task 2; spec
+// 2026-10-26-nearest-region-without-claims-design.md §1): a create-only mark
+// per hostname that may hold data, the data-kind predicate that decides who
+// marks, and the mode and floor objects beside the marks.
+
+func TestMarkHostUsedCreateOnly(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ at := time.Date(2026, 10, 26, 9, 0, 0, 0, time.UTC)
+ first := HostUse{Host: "shop.example.com", Account: "bab", App: "shop", Kind: "instance", Source: "create", At: at}
+ fresh, err := MarkHostUsed(ctx, s, first)
+ if err != nil || !fresh {
+ t.Fatalf("first mark = (%v, %v), want (true, nil)", fresh, err)
+ }
+ key := HostsUsedKey("shop.example.com")
+ if key != "control/hosts-used/shop.example.com.json" {
+ t.Fatalf("HostsUsedKey = %q", key)
+ }
+ before, _, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second := first
+ second.Account, second.App, second.At = "other", "other", at.Add(time.Hour)
+ fresh, err = MarkHostUsed(ctx, s, second)
+ if err != nil || fresh {
+ t.Fatalf("second mark = (%v, %v), want (false, nil)", fresh, err)
+ }
+ after, _, err := s.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(before, after) {
+ t.Fatalf("the second mark changed the body:\n%s\n%s", before, after)
+ }
+ used, err := HostIsUsed(ctx, s, "shop.example.com")
+ if err != nil || !used {
+ t.Fatalf("HostIsUsed = (%v, %v), want (true, nil)", used, err)
+ }
+ used, err = HostIsUsed(ctx, s, "other.example.com")
+ if err != nil || used {
+ t.Fatalf("HostIsUsed of an unmarked host = (%v, %v), want (false, nil)", used, err)
+ }
+}
+
+func TestMarkHostUsedRefusesABadHost(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ for _, host := range []string{"", "Shop.example.com", "shop.example.com.", "../x", "a/b"} {
+ if HostsUsedKey(host) != "" {
+ t.Errorf("HostsUsedKey(%q) = %q, want empty", host, HostsUsedKey(host))
+ }
+ if fresh, err := MarkHostUsed(context.Background(), s, HostUse{Host: host}); err == nil || fresh {
+ t.Errorf("MarkHostUsed(%q) = (%v, %v), want an error", host, fresh, err)
+ }
+ }
+}
+
+// failingStore fails every call with err.
+type failingStore struct {
+ release.Store
+ err error
+}
+
+func (f failingStore) Get(context.Context, string) ([]byte, string, error) { return nil, "", f.err }
+func (f failingStore) Put(context.Context, string, []byte, string) (string, error) {
+ return "", f.err
+}
+
+func TestMarkHostUsedStoreError(t *testing.T) {
+ down := errors.New("the bucket did not answer")
+ s := failingStore{Store: release.NewDirStore(t.TempDir()), err: down}
+ fresh, err := MarkHostUsed(context.Background(), s, HostUse{Host: "shop.example.com"})
+ if !errors.Is(err, down) || fresh {
+ t.Fatalf("MarkHostUsed = (%v, %v), want the store's error", fresh, err)
+ }
+ if used, err := HostIsUsed(context.Background(), s, "shop.example.com"); !errors.Is(err, down) || used {
+ t.Fatalf("HostIsUsed = (%v, %v), want the store's error", used, err)
+ }
+}
+
+func TestDataKindExemptsStaticAndService(t *testing.T) {
+ for _, c := range []struct {
+ rec Record
+ want bool
+ }{
+ {Record{}, true},
+ {Record{Kind: "instance"}, true},
+ {Record{Kind: "instance", Addrs: []string{"10.0.0.1:8080"}}, true},
+ {Record{Kind: "instance", Addr: "10.0.0.1:8080"}, true},
+ {Record{Kind: "static"}, false},
+ {Record{Kind: "service", Addrs: []string{"10.0.0.1:8080"}}, false},
+ } {
+ if got := c.rec.DataKind(); got != c.want {
+ t.Errorf("Record{Kind: %q, Addrs: %v, Addr: %q}.DataKind() = %v, want %v", c.rec.Kind, c.rec.Addrs, c.rec.Addr, got, c.want)
+ }
+ }
+}
+
+func TestHostsModeDefaultsIncomplete(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ mode, etag, err := ReadHostsMode(ctx, s)
+ if err != nil || mode != HostsModeIncomplete || etag != "" {
+ t.Fatalf("ReadHostsMode of an empty store = (%q, %q, %v), want (incomplete, \"\", nil)", mode, etag, err)
+ }
+ tag, err := WriteHostsMode(ctx, s, HostsModeActivating, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := WriteHostsMode(ctx, s, HostsModeActive, ""); !errors.Is(err, release.ErrCASConflict) {
+ t.Fatalf("a create-only mode write over a present one = %v, want a conflict", err)
+ }
+ if _, err := WriteHostsMode(ctx, s, HostsModeActive, tag); err != nil {
+ t.Fatal(err)
+ }
+ mode, _, err = ReadHostsMode(ctx, s)
+ if err != nil || mode != HostsModeActive {
+ t.Fatalf("ReadHostsMode = (%q, %v), want active", mode, err)
+ }
+ if _, err := WriteHostsMode(ctx, s, "sideways", ""); err == nil {
+ t.Fatal("WriteHostsMode accepted an unknown mode")
+ }
+ // An unknown mode in the store is an error, never a default.
+ if _, err := s.Put(ctx, HostsModeKey, []byte(`{"mode":"sideways"}`), ""); err == nil {
+ t.Fatal("the mode key was writable create-only while present")
+ }
+ _, etag, _ = ReadHostsMode(ctx, s)
+ if _, err := s.Put(ctx, HostsModeKey, []byte(`{"mode":"sideways"}`), etag); err != nil {
+ t.Fatal(err)
+ }
+ if mode, _, err := ReadHostsMode(ctx, s); err == nil {
+ t.Fatalf("ReadHostsMode of an unknown mode = %q, want an error", mode)
+ }
+ // The mode and floor keys never parse as marks.
+ if HostsUsedKey("@mode") != "" || HostsUsedKey("@floor") != "" {
+ t.Fatal("a mode or floor name passes as a host")
+ }
+}
+
+func TestHostsFloorRoundTrips(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ f, etag, err := ReadHostsFloor(ctx, s)
+ if err != nil || f != nil || etag != "" {
+ t.Fatalf("ReadHostsFloor of an empty store = (%v, %q, %v), want nothing", f, etag, err)
+ }
+ if _, err := WriteHostsFloor(ctx, s, HostsFloor{Version: "v0.29.0", Commit: "0123456789abcdef0123456789abcdef01234567"}, ""); err != nil {
+ t.Fatal(err)
+ }
+ f, _, err = ReadHostsFloor(ctx, s)
+ if err != nil || f == nil || f.Version != "v0.29.0" || f.Commit != "0123456789abcdef0123456789abcdef01234567" {
+ t.Fatalf("ReadHostsFloor = (%+v, %v)", f, err)
+ }
+}
+
+// TestWriteRecordRefusesKindChange: a record's kind is fixed at create, so
+// an exempt record (static, service) can never become a data kind in place
+// and skip the mark its create would have written.
+func TestWriteRecordRefusesKindChange(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ ctx := context.Background()
+ key := RecordKey("bab", "shop", "shop.example.com")
+ body := func(kind string) []byte {
+ if kind == "-" {
+ return []byte(`{"schema":1,"host":"shop.example.com","slug":"shop","app":"shop","account":"bab","channel":"stable","created_at":"2026-10-26T09:00:00Z"}`)
+ }
+ return []byte(`{"schema":1,"host":"shop.example.com","slug":"shop","app":"shop","account":"bab","channel":"stable","created_at":"2026-10-26T09:00:00Z","kind":"` + kind + `"}`)
+ }
+ tag, _, err := WriteRecord(ctx, s, key, []byte(`{}`), body("static"), "")
+ if err != nil {
+ t.Fatalf("a create from {} of any kind: %v", err)
+ }
+ if _, _, err := WriteRecord(ctx, s, key, body("static"), body("instance"), tag); !errors.Is(err, ErrKindChange) {
+ t.Fatalf("static to instance = %v, want ErrKindChange", err)
+ }
+ if _, _, err := WriteRecord(ctx, s, key, body("static"), body("-"), tag); !errors.Is(err, ErrKindChange) {
+ t.Fatalf("static to an absent kind = %v, want ErrKindChange", err)
+ }
+ if _, _, err := WriteRecord(ctx, s, key, body("static"), body("service"), tag); !errors.Is(err, ErrKindChange) {
+ t.Fatalf("static to service = %v, want ErrKindChange", err)
+ }
+ if raw, _, _ := s.Get(ctx, key); !bytes.Equal(raw, body("static")) {
+ t.Fatalf("a refused kind change wrote %s", raw)
+ }
+ if tag, _, err = WriteRecord(ctx, s, key, body("static"), body("static"), tag); err != nil {
+ t.Fatalf("same kind: %v", err)
+ }
+ // "" and "instance" are one kind.
+ key2 := RecordKey("bab", "shop", "two.example.com")
+ tag2, _, err := WriteRecord(ctx, s, key2, []byte(`{}`), body("-"), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := WriteRecord(ctx, s, key2, body("-"), body("instance"), tag2); err != nil {
+ t.Fatalf("absent kind to instance: %v", err)
+ }
+ // A tombstone keeps no kind (TombstoneBody), and retiring a static
+ // record must still land.
+ tomb, err := TombstoneBody(body("static"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := WriteRecord(ctx, s, key, body("static"), tomb, tag); err != nil {
+ t.Fatalf("tombstoning a static record: %v", err)
+ }
+}
+
+// TestWriteRecordKindReadsAsReadersDo (Astra Task 2 round 1, P1): the kind
+// check decodes as DecodeRecord does (case-insensitive names, the later
+// match wins) and checks the bytes actually written, after the sequence
+// re-encoding, so alias spellings cannot carry a kind change past it.
+func TestWriteRecordKindReadsAsReadersDo(t *testing.T) {
+ ctx := context.Background()
+ const ident = `"schema":1,"host":"shop.example.com","slug":"shop","app":"shop","account":"bab","channel":"stable","created_at":"2026-10-26T09:00:00Z"`
+ key := RecordKey("bab", "shop", "shop.example.com")
+ put := func(t *testing.T, s release.Store, raw string) string {
+ t.Helper()
+ tag, err := s.Put(ctx, key, []byte(raw), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return tag
+ }
+ t.Run("aliases reordered by hand", func(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ before := `{` + ident + `,"kind":"instance","Kind":"static"}` // reads static
+ after := `{` + ident + `,"Kind":"static","kind":"instance"}` // reads instance
+ if got := mustDecodeKind(t, before); got != "static" {
+ t.Fatalf("fixture: before reads %q", got)
+ }
+ tag := put(t, s, before)
+ if _, _, err := WriteRecord(ctx, s, key, []byte(before), []byte(after), tag); !errors.Is(err, ErrKindChange) {
+ t.Fatalf("static to instance by alias order = %v, want ErrKindChange", err)
+ }
+ })
+ t.Run("aliases reordered by the sequence advance", func(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ raw := `{` + ident + `,"record_seq":1,"kind":"instance","Kind":"static"}` // reads static
+ tag := put(t, s, raw)
+ // The same bytes, re-encoded by AdvanceRecordSequence in sorted key
+ // order ("Kind" before "kind"), would read as instance.
+ if _, _, err := WriteRecord(WithRecordSequence(ctx), s, key, []byte(raw), []byte(raw), tag); !errors.Is(err, ErrKindChange) {
+ t.Fatalf("a sequence advance that flips the read kind = %v, want ErrKindChange", err)
+ }
+ if got, _, _ := s.Get(ctx, key); string(got) != raw {
+ t.Fatalf("the refused write landed: %s", got)
+ }
+ })
+ t.Run("a same-kind typed update over another spelling", func(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ before := `{` + ident + `,"Kind":"static"}`
+ tag := put(t, s, before)
+ if _, _, err := WriteRecord(ctx, s, key, []byte(before), []byte(`{`+ident+`,"kind":"static"}`), tag); err != nil {
+ t.Fatalf("static to static, respelled: %v", err)
+ }
+ })
+}
+
+func mustDecodeKind(t *testing.T, raw string) string {
+ t.Helper()
+ rec, err := DecodeRecord([]byte(raw))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return rec.Kind
+}
diff --git a/internal/provision/nearest_region_a_census_test.go b/internal/provision/nearest_region_a_census_test.go
new file mode 100644
index 000000000..6748b15f9
--- /dev/null
+++ b/internal/provision/nearest_region_a_census_test.go
@@ -0,0 +1,73 @@
+package provision
+
+// Record-write census entries for nearest-region never-reuse merge A (branch
+// nearest-region-a, plan docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md
+// Tasks 2-4), layered on appRegionSetWriteCensusInventory (main's newest at
+// 25bfb7a5). Reviewed by the branch author; the census approval is recorded
+// on #280 with the root-read card
+// (docs/superpowers/notes/census-proposal-nearest-region-a.md).
+// - WriteRecord, re-pinned: it now refuses an in-place write that changes
+// the record's kind (checkKindUnchanged), except a create from {} or a
+// tombstone. Its one Put is unchanged: still the record-primitive.
+// - MarkHostUsed, WriteHostsMode, WriteHostsFloor, new: each Puts one
+// object under control/hosts-used/ (a hostname's mark, @mode, @floor).
+// No record key, no record body: nonrecord.
+// - Server.createRecordMarked, Server.createSidecarMarked (console), new:
+// the hostname history's mark (markBeforeCreate, a create-only Put under
+// control/hosts-used/ through provision.MarkHostUsed), then the same
+// create-only CreateRecord / CreateSidecarRecord the doors called
+// before. On a conflicting mark once active they read the door's own
+// record key (RecordKey / SidecarRecordKey) to answer a duplicate as the
+// write would. record-writer.
+// - Server.handleAPIInstanceCreate, Server.createSeedRecord,
+// Server.handleAPISidecarCreate: their CreateRecord and
+// CreateSidecarRecord calls moved into the two units above, so they no
+// longer name a write site and leave the inventory.
+// - Server.createRecordWithLifetimeLocked, re-pinned: it marks a data
+// kind's hostname (markForCreate) before BeginAllocation. Same
+// RecordKey site: still key-site.
+// - Server.registerCLIRoutes, re-pinned: it registers GET
+// /api/cli/system/hosts-used/status (plan Task 4), a read-only operator
+// door. Same "instances" and "sidecars" literals: still key-site.
+func nearestRegionAWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), appRegionSetWriteCensusInventory()...)
+ for _, r := range []struct{ file, unit string }{
+ {"internal/console/apiinstances.go", "Server.handleAPIInstanceCreate"},
+ {"internal/console/apiinstanceseed.go", "Server.createSeedRecord"},
+ {"internal/console/apisidecars.go", "Server.handleAPISidecarCreate"},
+ } {
+ found := false
+ for i, e := range entries {
+ if e.File == r.file && e.Unit == r.unit {
+ entries = append(entries[:i], entries[i+1:]...)
+ found = true
+ break
+ }
+ }
+ if !found {
+ panic("nearest-region-a removal of an unlisted unit " + r.file + ":" + r.unit)
+ }
+ }
+ replacements := []censusEntry{
+ {"internal/console/hostsused.go", "Server.createRecordMarked", "record-writer", "key:CreateRecord,key:RecordKey", "a6f3c61d177171b3b1100ac178e0f84dd195eb9294aee117b64264c2a09be12d"},
+ {"internal/console/hostsused.go", "Server.createSidecarMarked", "record-writer", "key:CreateSidecarRecord,key:SidecarRecordKey", "3df0c9053fcd071af9a371cf70413ab9ed99dedc9d3bc0bd69b1821cb2ab2b3a"},
+ {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "25cb2b7d4f7d264d8a45e5b9306f8f7f95fe886237fd88b9e4a492d7e66e90e3"},
+ {"internal/console/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "c3b601f16c8ceeb03f7a9512d9c079ad2eadb5414036beeeb032fd622b587a92"},
+ {"internal/provision/hostsused.go", "MarkHostUsed", "nonrecord", "sel:Put", "439f9ca1443f2c815f2ddb18b4732285d236d745fb660de66dc3a175b4532fd3"},
+ {"internal/provision/hostsused.go", "WriteHostsFloor", "nonrecord", "sel:Put", "c10e2e2fd57470c81785df3dddd9bb33013b416ce5381e74a9657811ec6b5c79"},
+ {"internal/provision/hostsused.go", "WriteHostsMode", "nonrecord", "sel:Put", "21147fa65d21d7a074589ca4ea6cf2ec9852a7ab42ca3acaac429562d8f22146"},
+ {"internal/provision/record_sequence.go", "WriteRecord", "record-primitive", "key:IsRecordKey,key:WriteRecord,key:preparedRecordKey,sel:Put", "d58d11066b4e4445e4295170de0f4aec1d9c8c046f1a9fc4cd79fc6e6353d527"},
+ }
+ for _, r := range replacements {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ entries = append(entries, r)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index e166f61ba..e3496027a 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := appRegionSetWriteCensusInventory()
+ inventory := nearestRegionAWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/record_sequence.go b/internal/provision/record_sequence.go
index f8c307f18..43c099ab5 100644
--- a/internal/provision/record_sequence.go
+++ b/internal/provision/record_sequence.go
@@ -116,7 +116,9 @@ type preparedRecord struct {
// Legacy absent counters and no claim context retain the exact body bytes.
// A before marked by a migration (incarnation_migrating) is refused with
// ErrRecordMigrating unless ctx carries WithMigration of that marker; a
-// create-only write reads no before and is unaffected.
+// create-only write reads no before and is unaffected. A body whose kind
+// differs from before's is refused with ErrKindChange, except a create or a
+// tombstone (checkKindUnchanged).
func WriteRecord(ctx context.Context, s release.Store, key string, before, body []byte, etag string) (string, uint64, error) {
if !IsRecordKey(key) {
return "", 0, ErrRecordSequence
@@ -132,6 +134,7 @@ func WriteRecord(ctx context.Context, s release.Store, key string, before, body
if err != nil {
return "", 0, err
}
+ exact := bytes.Equal(before, body)
enabled, _ := ctx.Value(recordSequenceKey{}).(bool)
_, present := fields["record_seq"]
p, nested := ctx.Value(preparedRecordKey{}).(*preparedRecord)
@@ -153,6 +156,15 @@ func WriteRecord(ctx context.Context, s release.Store, key string, before, body
}
p.body, p.seq, p.sequenced = append([]byte(nil), body...), base+1, true
}
+ // A record's kind is fixed at create (nearest-region never-reuse,
+ // hostsused.go): only a create ({} before) or a tombstone may differ.
+ // Checked on the exact bytes about to be written, after any sequence
+ // re-encoding, as the record's readers will decode them.
+ if len(fields) != 0 {
+ if err := checkKindUnchanged(before, body, exact); err != nil {
+ return "", 0, err
+ }
+ }
tag, err := s.Put(ctx, key, body, etag)
return tag, p.seq, err
}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index a70137945..83161f11f 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -58,3 +58,4 @@ plan14-root-reads-instance-egress-sizes-328-329.tsv c1ab16d1d7eaccb3928a4fd5f74f
plan14-root-reads-region-labels-decisions.tsv b265c2ae74edbaca766d33e085d31a8e7c6f86883d12d0ed4472bd99a7c3278d
plan14-root-reads-region-labels.tsv d1e00cfb29d88b7a8e4998b641164e539067a6e1e9e4f52524255343c0c5f9f7
plan14-root-reads-app-region-set.tsv 798a1ee3d8c8b775f963b9ae1dbc45e18628fa0c1e63404f46606601766ad66c
+plan14-root-reads-nearest-region-a.tsv 798a1ee3d8c8b775f963b9ae1dbc45e18628fa0c1e63404f46606601766ad66c
diff --git a/internal/provision/testdata/plan14-root-reads-nearest-region-a.tsv b/internal/provision/testdata/plan14-root-reads-nearest-region-a.tsv
new file mode 100644
index 000000000..37e8608b3
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-nearest-region-a.tsv
@@ -0,0 +1,7 @@
+# Census overlay nearest-region-a, written by census-propose (#369). census-ruling-nearest-region-a, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-nearest-region-a.md.
+# 2 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+system.go runSystem authority B,C,D,F,G,J4 rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops the claims case (host.RunSystemClaims, deleted); every other branch unchanged; no read added;rev3=census-ruling-nearest-region-a;basis=adds the hosts-used family to the system dispatch (carlos system hosts-used status, one GET of a console door as the operator); every existing command branch unchanged; no read added 1dd5600c0af83094659c370416afcfa86ba31aa533f2f64e7f61e0384907dc5f
+system.go systemVerb authority B,C,D,F,G,J4 rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops "claims" from the verb list, so it now falls to the unknown-verb message; no read added;rev3=census-ruling-nearest-region-a;basis=adds "hosts-used" to the verb list, routed to runSystemHostsUsedVerb; no read added cc990ab40e7157fbc365e6dfccba81eec46a8df45d95df9b7ba41330dcdf8cca
+@coverage . fb557ea8582c1a1e5badc6e9102997fa052d81e31f903031da39669c23e60fc1
+@coverage internal/console ac528271760e68a2a9b5287418a374bdb02ccef0acd87efc9ed4887c14366495
+@coverage internal/provision 9f7572e1933c2dcb9d3faa27480a624c1d6581a6b76af72b2c356eb89b83a375
diff --git a/system.go b/system.go
index 8e9a6c9db..c00ce01a6 100644
--- a/system.go
+++ b/system.go
@@ -51,7 +51,7 @@ func systemVerb(args []string) (verb string, rest []string, component string) {
// untouched in rest for runSystemAntivirusVerb to read.
// layout is a family too: migrate|revert|status stay in rest for
// runSystemLayout.
- case "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "box", "group", "install-channel", "join", "host-env", "db-worker", "help", "-h", "--help":
+ case "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "join", "host-env", "db-worker", "help", "-h", "--help":
return args[0], args[1:], component
}
return "", args, component
@@ -94,6 +94,8 @@ func runSystem(args []string) {
runSystemLegacyRoutesVerb(rest)
case "lifetimes":
runSystemLifetimesVerb(rest)
+ case "hosts-used":
+ runSystemHostsUsedVerb(rest)
case "box":
runSystemBoxVerb(rest)
case "group":
@@ -146,6 +148,7 @@ func systemUsage() {
carlos system seeds-floor publish --min-release <release>
carlos system legacy-routes assign --name <name> --to <account>/<app>
carlos system lifetimes cutover [--no-wait]
+ carlos system hosts-used status
carlos system box role <box> <default|legacy|platform>
carlos system box publish-record
carlos system group role <region> <default|legacy>
@@ -169,6 +172,9 @@ The platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):
lifetimes cutover [--no-wait]
switch a console without host claims onto instance lifetimes,
once, after the old console has stopped. Waits until they are on
+ hosts-used status
+ the hostname history: its mode, how many hostnames it has
+ recorded, and the instance creates and deletes still settling
box role <box> <default|legacy|platform>
whether new instances may be placed on a box. A legacy or
platform box keeps the instances it has and takes no new ones
diff --git a/system_hostsused.go b/system_hostsused.go
new file mode 100644
index 000000000..776862681
--- /dev/null
+++ b/system_hostsused.go
@@ -0,0 +1,98 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+)
+
+// carlos system hosts-used status (nearest-region never-reuse, plan Task 4):
+// the console's hostname history, its mode and how many hostnames it has
+// recorded, with the work still settling. Ops account owners and
+// CARLOS_SYSTEM_OPERATORS. It reads and never writes.
+
+const hostsUsedStatusDoor = "/api/cli/system/hosts-used/status"
+
+// hostsUsedStatusView is what the door answers. A nil count is one the
+// console does not report yet.
+type hostsUsedStatusView struct {
+ Mode string `json:"mode"`
+ Marks int `json:"marks"`
+ InflightCreates *int `json:"inflight_creates"`
+ PendingAllocations int `json:"pending_allocations"`
+ PendingRetirements int `json:"pending_retirements"`
+ UnfinishedMoves *int `json:"unfinished_moves"`
+}
+
+type roleGet func(ctx context.Context, path string) (int, []byte, error)
+
+func systemHostsUsedStatus(ctx context.Context, get roleGet) (hostsUsedStatusView, error) {
+ status, body, err := get(ctx, hostsUsedStatusDoor)
+ if err != nil {
+ return hostsUsedStatusView{}, err
+ }
+ if status != http.StatusOK {
+ return hostsUsedStatusView{}, apiErrorFromBody(status, body)
+ }
+ var st hostsUsedStatusView
+ if err := json.Unmarshal(body, &st); err != nil {
+ return hostsUsedStatusView{}, fmt.Errorf("unreadable response: %w", err)
+ }
+ return st, nil
+}
+
+// hostsUsedModeLine says what each mode means for a create. Drafts: the
+// copy review of these lines comes with merge B.
+func hostsUsedModeLine(mode string) string {
+ switch mode {
+ case "incomplete":
+ return "mode: incomplete. new hostnames are recorded, and a hostname that held data is not refused yet"
+ case "activating":
+ return "mode: activating. new instances, moves and placement changes are paused"
+ case "active":
+ return "mode: active. a hostname that has held data is never created again"
+ case "invalidated":
+ return "mode: invalidated. new instances are refused until a fresh inventory completes"
+ }
+ return "mode: " + mode
+}
+
+func printHostsUsedStatus(w io.Writer, st hostsUsedStatusView) {
+ fmt.Fprintln(w, hostsUsedModeLine(st.Mode))
+ fmt.Fprintf(w, "hostnames recorded: %d\n", st.Marks)
+ if st.InflightCreates != nil {
+ fmt.Fprintf(w, "create requests in progress: %d\n", *st.InflightCreates)
+ }
+ fmt.Fprintf(w, "instance creates still settling: %d\n", st.PendingAllocations)
+ fmt.Fprintf(w, "instance deletes still settling: %d\n", st.PendingRetirements)
+ if st.UnfinishedMoves != nil {
+ fmt.Fprintf(w, "moves not finished: %d\n", *st.UnfinishedMoves)
+ }
+}
+
+// runSystemHostsUsedVerb is `carlos system hosts-used status`.
+func runSystemHostsUsedVerb(rest []string) {
+ if len(rest) == 0 || rest[0] != "status" {
+ systemUsage()
+ os.Exit(2)
+ }
+ fs := flag.NewFlagSet("system hosts-used status", flag.ExitOnError)
+ consoleFlag := consoleOption(fs, "console origin (default: the only logged-in one)")
+ fs.Parse(rest[1:])
+ if fs.NArg() != 0 {
+ fs.Usage()
+ os.Exit(2)
+ }
+ sess := requireDeployAPISession(*consoleFlag)
+ printUsing(stdout, sess)
+ st, err := systemHostsUsedStatus(context.Background(), sess.getJSON)
+ if err != nil {
+ log.Fatalf("carlos system hosts-used status: %v", err)
+ }
+ printHostsUsedStatus(stdout, st)
+}
diff --git a/system_hostsused_test.go b/system_hostsused_test.go
new file mode 100644
index 000000000..1a3610138
--- /dev/null
+++ b/system_hostsused_test.go
@@ -0,0 +1,138 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+)
+
+// TestSystemHostsUsedStatusCLI: `carlos system hosts-used status` asks the
+// status door and prints one line per field the console knows.
+func TestSystemHostsUsedStatusCLI(t *testing.T) {
+ if verb, rest, _ := systemVerb([]string{"hosts-used", "status"}); verb != "hosts-used" || len(rest) != 1 || rest[0] != "status" {
+ t.Fatalf("systemVerb = %q %q", verb, rest)
+ }
+ var asked []string
+ get := func(body string, status int) func(context.Context, string) (int, []byte, error) {
+ return func(_ context.Context, path string) (int, []byte, error) {
+ asked = append(asked, path)
+ return status, []byte(body), nil
+ }
+ }
+ st, err := systemHostsUsedStatus(context.Background(), get(`{"mode":"incomplete","marks":12,"inflight_creates":null,"pending_allocations":1,"pending_retirements":0,"unfinished_moves":null}`, http.StatusOK))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(asked) != 1 || asked[0] != "/api/cli/system/hosts-used/status" {
+ t.Fatalf("asked %v", asked)
+ }
+ var out bytes.Buffer
+ printHostsUsedStatus(&out, st)
+ want := "mode: incomplete. new hostnames are recorded, and a hostname that held data is not refused yet\n" +
+ "hostnames recorded: 12\n" +
+ "instance creates still settling: 1\n" +
+ "instance deletes still settling: 0\n"
+ if out.String() != want {
+ t.Fatalf("output:\n%s\nwant:\n%s", out.String(), want)
+ }
+ st, err = systemHostsUsedStatus(context.Background(), get(`{"mode":"activating","marks":3,"inflight_creates":2,"pending_allocations":0,"pending_retirements":0,"unfinished_moves":1}`, http.StatusOK))
+ if err != nil {
+ t.Fatal(err)
+ }
+ out.Reset()
+ printHostsUsedStatus(&out, st)
+ want = "mode: activating. new instances, moves and placement changes are paused\n" +
+ "hostnames recorded: 3\n" +
+ "create requests in progress: 2\n" +
+ "instance creates still settling: 0\n" +
+ "instance deletes still settling: 0\n" +
+ "moves not finished: 1\n"
+ if out.String() != want {
+ t.Fatalf("output:\n%s\nwant:\n%s", out.String(), want)
+ }
+ if _, err := systemHostsUsedStatus(context.Background(), get(`{"error":"not found"}`, http.StatusNotFound)); err == nil {
+ t.Fatal("a refusal was not an error")
+ }
+}
+
+// TestSystemHostsUsedStatusThroughTheBinary (Astra branch review r1, P2):
+// the built command, through runSystem's dispatch and the operator's own
+// session, against a fake console. It asks the one door with the saved
+// token, prints the door's answer, and exits non-zero on a refusal.
+func TestSystemHostsUsedStatusThroughTheBinary(t *testing.T) {
+ bin := buildCarlos(t)
+ var mu sync.Mutex
+ var asked []string
+ refuse := false
+ mux := http.NewServeMux()
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ asked = append(asked, r.Method+" "+r.URL.Path+" "+r.Header.Get("Authorization"))
+ no := refuse
+ mu.Unlock()
+ if r.Method != http.MethodGet || r.URL.Path != "/api/cli/system/hosts-used/status" {
+ http.NotFound(w, r)
+ return
+ }
+ if no {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusNotFound)
+ w.Write([]byte(`{"error":"404 page not found"}`))
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte(`{"mode":"incomplete","marks":7,"inflight_creates":null,"pending_allocations":0,"pending_retirements":2,"unfinished_moves":null}`))
+ })
+ ts := httptest.NewServer(mux)
+ t.Cleanup(ts.Close)
+ credPath := filepath.Join(t.TempDir(), "credentials")
+ creds := `{"version":1,"credentials":[{"console":"` + ts.URL + `","address":"paul@keymail.dev","token":"tok-operator"}]}`
+ if err := os.WriteFile(credPath, []byte(creds), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ run := func() (string, error) {
+ cmd := exec.Command(bin, "system", "hosts-used", "status")
+ cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+credPath)
+ cmd.Dir = t.TempDir()
+ out, err := cmd.CombinedOutput()
+ return string(out), err
+ }
+ out, err := run()
+ if err != nil {
+ t.Fatalf("status: %v\n%s", err, out)
+ }
+ for _, line := range []string{
+ "mode: incomplete. new hostnames are recorded, and a hostname that held data is not refused yet\n",
+ "hostnames recorded: 7\n",
+ "instance deletes still settling: 2\n",
+ } {
+ if !strings.Contains(out, line) {
+ t.Fatalf("output lacks %q:\n%s", line, out)
+ }
+ }
+ mu.Lock()
+ door := 0
+ for _, a := range asked {
+ if strings.HasPrefix(a, "GET /api/cli/system/hosts-used/status ") {
+ door++
+ if a != "GET /api/cli/system/hosts-used/status Bearer tok-operator" {
+ t.Errorf("the door was asked as %q, want the saved token", a)
+ }
+ }
+ }
+ refuse = true
+ mu.Unlock()
+ if door != 1 {
+ t.Fatalf("the door was asked %d times (%v), want once", door, asked)
+ }
+ if out, err := run(); err == nil || !strings.Contains(out, "carlos system hosts-used status:") {
+ t.Fatalf("a refused status exited %v:\n%s", err, out)
+ }
+}