plans: G6 pool path rev 2, Astra round 1 fixes
1 file changed,
+116
−76
docs/superpowers/plans/2026-11-12-g6-pool-path.md+116 −76
Intent
Human
<task-notification> <task-id>bo7pi2cgj</task-id> <tool-use-id>toolu_01ErxN5YuPpd4ZYfcZKavLYt</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/1be65f1d-61c8-4308-afb1-2c756edd9c6e/tasks/bo7pi2cgj.output</output-file> <status>completed</status> <summary>Background command "Wait for the fence plan review" completed (exit code 0)</summary> </task-notification>
diff --git a/docs/superpowers/plans/2026-11-12-g6-pool-path.md b/docs/superpowers/plans/2026-11-12-g6-pool-path.md| index 8a2d80c26..5c47e3750 100644 |
| --- a/docs/superpowers/plans/2026-11-12-g6-pool-path.md |
| +++ b/docs/superpowers/plans/2026-11-12-g6-pool-path.md |
| @@ -2,15 +2,19 @@ |
| > **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:** An account on `CONSOLE_HA_POOL_ACCOUNTS` can create an app with high availability in a region that has a scoped HA pool (CLI `carlos apps create --ha`, or the web form's checkbox), its first instance is born HA, and nobody else can put a record into a scoped HA pool by any door. |
| +**Goal:** An account on `CONSOLE_HA_POOL_ACCOUNTS` can create an app with high availability in a region that has a scoped HA pool (CLI `carlos apps create --ha`, or the web form's checkbox), its first instance is born HA, and nobody else can put a record into a restricted pool (any pool named in any region's `ha_pools`) by any door. |
| -**Architecture:** The HA choice is stored once, on the app row (`apps.ha_pool`, written in the same insert as the row). The existing person-only enable door is the only writer of the manifest's `Pool`, and it copies `Pool` and `Regions` from the live row on the manifest's first create only. One gate, `haPoolAllowed`, guards every door that can write a record into a scoped HA pool; the row binds the region, so the region doors, the place door and the swap door refuse changes for a born-HA app. |
| +**Architecture:** The HA choice is stored once, on the app row (`apps.ha_pool`, written in the same insert as the row). The existing person-only enable door is the only writer of the manifest's `Pool`, and it copies `Pool` and `Regions` from the live row on the manifest's first create only. One gate, `haPoolAllowed(acct, pool)`, keyed on the POOL NAME alone (never the region or HA activation), guards every door that can write a record with a pool; the row binds the region, so the region doors, the place door and the swap door refuse changes for a born-HA app. |
| **Tech Stack:** Go, SQLite (console store), `html/template` console pages, the `carlos` CLI (root package). |
| **Spec:** `docs/superpowers/specs/2026-11-11-g6-pool-path-design.md` (rev 3). Also read `docs/superpowers/reviews/CODEX-FINDINGS-G6-R1.md` (G6-1.8, 1.9, 1.12) and `R2.md` (G6-2.5, 2.8), and `docs/superpowers/specs/2026-11-11-g6-us-capacity-design.md` §3 (swap concurrency held to 1 for born-HA apps). Region HA parent: `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md` §23 (B10). |
| -## Spec corrections (verified against this tree, 3d332f24) |
| +## Review history |
| + |
| +- Plan round 1 (Astra, `docs/superpowers/reviews/CODEX-FINDINGS-G6-POOL-PLAN-R1.md`, at ba96f50b): NOT READY, 4 P1 + 2 P2, all fixed in this revision. Families: P1-1 "pool authorization fails closed across configuration changes" and P1-2 "authorization covers every serving destination" share one cause and one fix (the gate keys on the pool name, Task 1); P1-3 G6-2.5 "born-HA placement stays bound to the incarnation" (Task 4); P1-4 "test prerequisites reach the behaviour under test" (every fixture now has a positive control and named prerequisites); P2-5 "concurrency tests prove the interleaving happened" (Task 4 barrier test); P2-6 "compatibility checks are enforced by the command users run" (Task 5 end-to-end). Round 2 is the last planned round (stopping rules). |
| + |
| +## Spec corrections (verified at 3d332f24; rechecked at 39ecad21, the cited files unchanged by the main merge) |
| The spec cites `origin/main` at 01d6ca78. Lines have moved; some claims were wrong. |
| @@ -24,9 +28,10 @@ The spec cites `origin/main` at 01d6ca78. Lines have moved; some claims were wro |
| 8. The swap door has a SECOND, browser form: `appswap.go:20` (`handleAppSwap`). Both go through `setCopiesSwapPolicy` (`copiespublication.go:256`), which is where the refusal belongs. |
| 9. `cmd/console/main.go:1157-1191` is now `sidecarAccounts` at `:1178-1212`; it is called at `:358-363` (before the database opens) and wired into `Config` at `:637`. The header comment block for env vars is `:58-64`. |
| 10. `approved_region_ha_copy_test.go` does not exist. The approved-copy pattern is `approved_burst_copy_test.go` / `approved_protection_copy_test.go`. |
| -11. The domain-attach first route (`domainattach.go:308-313` and `:737-742`) always writes `Kind: "static"` with `Pool: ""`, and demo claims (`demo_claim_seed.go:176-188`) and demo publish (`demo_publish.go:179-193`) never set a pool. None of them can write into a scoped pool, so they get a guard test, not a gate call. The doors that can are the instance create door (plain, `--from`, import, restore, host-claim and lifetime arms all pass one point) and the standalone sidecar create door. |
| +11. The domain-attach first route (`domainattach.go:308-313` and `:737-742`) always writes `Kind: "static"` with `Pool: ""`, and demo claims (`demo_claim_seed.go:176-188`) and demo publish (`demo_publish.go:179-193`) never set a pool. None of them can write a record with any pool, so they get a guard test, not a gate call. The doors that write a pool are the instance create door (plain, `--from`, import, restore, host-claim and lifetime arms all pass one point) and the standalone sidecar create door. |
| 12. A third door changes a born-HA app's effective region: `carlos apps place` (`placeAppTarget`, `fleets.go:809`, also the Settings > Placement form). A placed app's instances take the fleet as their region and skip the manifest's allow-list (`apiinstances.go:2048`). It is refused for an `ha_pool` row like the region doors (G6-2.5's invariant), and `apps create --ha --place` is refused. |
| -13. Spec §2 says dev IE carries `ha_pools: ["hapair"]`; RHA §23 says dev IE carries none. That is live configuration, checked under "After merge", not code. |
| +13. **Authorization is by pool name, not region** (plan round 1, P1-1/P1-2). The spec's `haPoolAllowed(acct, region, pool)` keyed on the region missed two cases: a region dropped from `CONSOLE_HA_REGIONS` keeps its `ha_pools` in the capacity config (parse only checks that every listed region HAS coordinates, `hacapacity.go:175-179`, not the reverse), and a static record is served by every platform box whose pools include its pool, whatever its stored region (`internal/provision/reconcile.go:412` `everywhere`, `:524-536` `inScope`: pool first, region widened for everywhere classes). The gate is therefore `haPoolAllowed(acct, pool)`: a pool named in ANY region's `ha_pools` is restricted, whatever the record's region, kind or the HA switch. B10's region-based `haCreate` and `poolInHAPools` stay as they are: they decide whether a create is BORN HA (stamp, capacity, proof, leftovers, app-default region: `seedmove.go:40-54`, `nocapacity.go:49-56`, `createleftovers.go:168-171`, `apiinstances.go:1944`, `regiondefault.go:70`), not who may use a pool. Nothing on the box side changes: boxes admit by pool and region (`inScope`), a record's `Pool` is fixed at create (the update door's body has no pool field, `apiinstances.go:2995-3025`, and the create door says so, `:1627`; moves and place rewrite `Region` only), and a record reaches the bucket only through the gated console doors or an operator's own store-mode bucket write, which is not a console door (the same scope `sidecarsgate.go:20-23` states). |
| +14. Spec §2 says dev IE carries `ha_pools: ["hapair"]`; RHA §23 says dev IE carries none. That is live configuration, checked under "After merge", not code. |
| ## Global Constraints |
| @@ -36,6 +41,7 @@ The spec cites `origin/main` at 01d6ca78. Lines have moved; some claims were wro |
| - The machine code `ha-pool-not-allowed` is not copy; it is fixed now. |
| - The branch does not merge while any `COPY-PENDING:` string remains (Task 8 adds the test that enforces it): the settings status line would show a placeholder to the flagship canary account. |
| - Tests: targeted only, `go test ./<pkg>/ -run 'TestX|TestY' -count=1`; never `go test ./...`, never the full suite (CI on amadan runs it). `internal/console`, `cmd/console` and the root package bind sockets: run them with the sandbox OFF and `d=$(mktemp -d /tmp/g/g6pool-tN.XXXX) && TMPDIR=$d go test ...; rm -rf "$d"` (remove that exact dir; never a glob in `/tmp/g`, `/tmp`, `$TMPDIR` or `~/.cache`). `GOCACHE` stays at its default. Add `GOFLAGS=-buildvcs=false` only if VCS stamping errors appear. |
| +- Every refusal test has a positive control in the same fixture: the same request, with the refused condition removed, succeeds with the stated status. A refusal whose control fails is testing an earlier refusal; fix the fixture (plan round 1, P1-4). |
| - Mutation checks only on refusal, security and lifecycle paths, at most ~10 per task, each a targeted `-run`; revert each mutation. |
| - Commit subjects under 80 characters. Implementers never create or remove worktrees, never `git worktree prune`, never `git stash`, never push, never touch amadan. |
| - Census: the root package (`apps.go`, `apimode.go`) is in the root binary, so Task 5 makes `TestPlan14RootReadCensus` fail until Task 7 proposes the overlay; Task 8 reruns it. `internal/console` and `cmd/console` are out of census scope. The reviewer (Astra) decides. |
| @@ -47,16 +53,16 @@ The spec cites `origin/main` at 01d6ca78. Lines have moved; some claims were wro |
| ## Review Focus |
| 1. **HA in the HOME region** (dev: IE is home and the HA region). The row stores `""`, the manifest gets `Regions: [""]`, and an instance create naming the home's code must pass while any other region is refused. Test: Task 3 `TestEnableHAHomeRegion`. |
| -2. **New CLI, older console.** An older console ignores `"ha"` and creates a plain app with a 200. The CLI must fail loudly, naming the app, not print success. Test: Task 5 `TestHAMismatchErr`. |
| +2. **New CLI, older console.** An older console ignores `"ha"` and creates a plain app with a 200. The CLI must fail loudly, naming the app, not print success. Test: Task 5 `TestAppsCreateHAAgainstOlderConsole` (the real binary). |
| 3. **Owner adoption with `--ha`.** An owner may adopt objects already under the name's prefix; with `ha` that would turn an existing app's history HA. Expect `409 that name is taken`, no row. Test: Task 2 case (g). |
| 4. **Placement.** `carlos apps create --ha --place fleet/x` and `carlos apps place` on a born-HA app must refuse, before and after enable. Test: Task 2 case (e), Task 4 `TestPlaceRefusesHAApp`. |
| -5. **Broken HA config** (`CONSOLE_HA_CAPACITY_CONFIG` invalid while `CONSOLE_HA_REGIONS` is set, `haScopeInvalid`). The pool's scope is unknown, so the gate fails closed for every named pool in an HA region, and an HA app create is refused (400). Plain (pool `""`) creates are untouched. Test: Task 1 `TestHAPoolScopedPredicate` invalid rows, Task 2 case (h). |
| +5. **Broken HA config** (`CONSOLE_HA_CAPACITY_CONFIG` set but unparseable, or missing/invalid while `CONSOLE_HA_REGIONS` is set). The restricted set is unknown, so the gate fails closed for EVERY non-empty pool, in every region, and an HA app create is refused (400). Plain (pool `""`) creates are untouched; a deployment with neither variable set restricts nothing. Test: Task 1 `TestHAPoolRestrictedPredicate`, Task 2 case (h). |
| --- |
| ## Decisions this plan makes (the spec leaves them open; none needs Paul) |
| -- `haPoolScoped(region, pool)` is: pool non-empty, region in `CONSOLE_HA_REGIONS`, and (scope invalid OR pool in the region's `ha_pools`). Fail-closed on an invalid config matches B10's "an invalid document is not unscoped". |
| +- `haPoolRestricted(pool)` is: pool non-empty, and (the HA config is broken OR pool appears in any region's `ha_pools`). "Broken" is: `parseHACapacityConfig` failed AND (`CONSOLE_HA_CAPACITY_CONFIG` is non-blank OR `CONSOLE_HA_REGIONS` is set). Neither set means no HA anywhere and nothing restricted, so deployments without HA keep every named pool as today. Note: the parser also fails with no `HomeRegion` (`hacapacity.go:118`), which then fails closed for named pools; that is intended. |
| - The enable door re-checks the allowlist and the region only on the manifest's FIRST create. An update writes no pool, so a removed account can still change its HA app's channel; its new instances are refused at the instance door. |
| - A 409 for "existing manifest has another pool" has no sentence in the deck: new id `console.refusal.ha_pool_mismatch` (only an operator's store-mode write can cause it). |
| - The CLI's "the console did not confirm HA" failure has no sentence in the deck: new id `cli.apps_create.ha_unconfirmed`. The CLI's success line reuses the console's status sentence (`console.app_settings.ha.status`), echoed by the console as `ha_status`, so the CLI adds no other copy. |
| @@ -70,31 +76,34 @@ The spec cites `origin/main` at 01d6ca78. Lines have moved; some claims were wro |
| ### Task 1: The allowlist and the gate at the record doors |
| **Read first (traps):** |
| -- Empty means NOBODY. Every existing test that creates into a scoped pool for account `bab` breaks unless its fixture lists `bab`. Set `c.HAPoolAccounts = []string{"bab"}` in `haPoolWorldNew` (`ha_pool_scope_test.go:107`, set just before `tweak(c)` at `:139`), and in any fixture in `apiinstances_test.go`, `hacreate_test.go`, `regiondefault_test.go`, `demo_claim_ha_gate_test.go` whose test creates into a scoped pool. Run every test in those files (list below) before committing. |
| -- The instance door's gate goes AFTER the region is final (`region = placed` or validated, `:2048-2055`) and after `ValidateShape` + `haCreateShapeRefusal` (`:2332-2339`), and BEFORE `environmentBindingRefusal` (`:2344`). Everything after that point (store ceiling, leftover LISTs, capacity, the seed doors, every write) is behind it. The restore, `--from`, import, host-claim and lifetime arms all pass this point. |
| -- The sidecar gate goes immediately after `refuseSidecarsPaused` (`apisidecars.go:381-383`), before `planLock`. |
| -- Do not gate the domain-attach first route, demo claims or demo publish (Spec correction 11). Pin that with the guard test instead. |
| +- The gate keys on the POOL NAME only (Spec correction 13). Do not pass or consult the region, the record's kind, `CONSOLE_HA_REGIONS`, `haCreate` or `poolInHAPools` in the gate. Those stay B10's "is this create born HA" machinery, unchanged. |
| +- Restricted set: computed once in `NewServer` beside `s.haPools` (`server.go:1982-1990`) as the union of `HAPools` over EVERY region of the parsed config (`capacity.Regions`, not only `cfg.HARegions`). Broken: parse failed AND (`strings.TrimSpace(cfg.HACapacityConfig) != ""` OR `len(cfg.HARegions) > 0`). Broken fails closed for every non-empty pool. |
| +- Empty list means NOBODY. Every existing test that creates a record whose pool is restricted (or any named pool while the config is broken) for account `bab` breaks unless its fixture lists `bab`. Set `c.HAPoolAccounts = []string{"bab"}` in `haPoolWorldNew` (`ha_pool_scope_test.go:107`, just before `tweak(c)` at `:139`), and in any fixture in `apiinstances_test.go`, `hacreate_test.go`, `regiondefault_test.go`, `demo_claim_ha_gate_test.go`, `ha_pool_scope_test.go` (`TestHAPoolInvalidConfig` sets HA regions with no config: broken) that creates such a record. Run every test in those files before committing. |
| +- The instance door's gate goes AFTER `ValidateShape` + `haCreateShapeRefusal` (`apiinstances.go:2332-2339`) and BEFORE `environmentBindingRefusal` (`:2344`). Everything after that point (store ceiling, leftover LISTs, capacity, the seed doors, every write) is behind it, and the plain, `--from`, import, restore, host-claim and lifetime arms all pass it. The pool there is `rec.Pool` (= `m.Pool`, `:2218`). |
| +- The sidecar gate goes immediately after `refuseSidecarsPaused` (`apisidecars.go:381-383`), before `planLock`, on `rec.Pool`. |
| +- Do not gate the domain-attach first route, demo claims or demo publish (Spec correction 11): they write pool `""`. Pin that with the guard test. |
| +- Fixture prerequisites (plan round 1, P1-4): every refusal test below has a POSITIVE CONTROL in the same fixture (the same request with `bab` listed must succeed with the stated status). A refusal test whose control fails is testing an earlier refusal, not the gate; fix the fixture, not the assertion. `haPoolWorldNew`'s instance hosts are under its manifest domain `go.tito.io` (`acme.go.tito.io`); it needs no `AppsDomain` because it never calls the enable door. |
| **Files:** |
| - Modify: `cmd/console/main.go` (header comment `:58-64`, parse beside `sidecarAccounts` `:358-363`, `Config` literal `:637`, new func after `:1212`) |
| - Create: `cmd/console/hapoolaccounts_test.go`, `cmd/console/hapoolaccounts_serve_test.go` |
| -- Modify: `internal/console/server.go` (`Config`: add `HAPoolAccounts` after `SidecarAccounts` `:1009`) |
| +- Modify: `internal/console/server.go` (`Config`: `HAPoolAccounts` after `SidecarAccounts` `:1009`; `Server`: `haRestrictedPools map[string]bool`, `haPoolsBroken bool` beside `haPools` `:1019-1020`; computed at `:1982-1990`) |
| - Create: `internal/console/hapool.go`, `internal/console/hapoolcopy.go`, `internal/console/hapool_test.go` |
| - Modify: `internal/console/apiinstances.go:~2339`, `internal/console/apisidecars.go:~383` |
| -- Modify (fixtures only): `internal/console/ha_pool_scope_test.go` and the other scoped-pool test files above; the existing domain-attach first-route test (find with `grep -n 'func TestAttach.*First\|first route' internal/console/domainattach*_test.go`) |
| +- Modify (fixtures only): the scoped-pool test files above; the existing domain-attach first-route test (`grep -n 'func TestAttach.*First\|first route' internal/console/domainattach*_test.go`) |
| **Interfaces:** |
| - Produces (cmd/console): `func haPoolAccounts(getenv func(string) string) ([]string, error)` |
| - Produces (console `Config`): `HAPoolAccounts []string` (nil = nobody) |
| - Produces (`hapool.go`): |
| - - `func (s *Server) haPoolScoped(region, pool string) bool` |
| - - `func (s *Server) haPoolFor(region string) string` — the region's first `ha_pools` entry when `s.haRegion(region)` and the scope is valid, else `""`; region is record vocabulary (`""` = home; look up `s.haPools[s.homeRegionOut(region)]`) |
| + - `func (s *Server) haPoolRestricted(pool string) bool` — `pool != "" && (s.haPoolsBroken || s.haRestrictedPools[pool])` |
| - `func (s *Server) haPoolListed(acct *Account) bool` — `slices.Contains(s.cfg.HAPoolAccounts, acct.Sqid)` |
| - - `func (s *Server) haPoolAllowed(acct *Account, region, pool string) bool` — `!s.haPoolScoped(region, pool) || s.haPoolListed(acct)` |
| + - `func (s *Server) haPoolAllowed(acct *Account, pool string) bool` — `!s.haPoolRestricted(pool) || s.haPoolListed(acct)` |
| + - `func (s *Server) haPoolFor(region string) string` — for the CREATE OPTION's region checks only (Task 2): the region's first `ha_pools` entry when `s.haRegion(region)` and the config parsed, else `""`; region is record vocabulary (`""` = home; look up `s.haPools[s.homeRegionOut(region)]`) |
| - `type haDoorRefusal struct { Status int; Msg, Code string }` |
| - `func writeHARefusal(w http.ResponseWriter, ref *haDoorRefusal)` — JSON `{"error": Msg}` plus `"code": Code` when non-empty |
| - - `func (s *Server) haPoolRefusal(acct *Account, app, door string) *haDoorRefusal` — logs `console: <door> <sqid>/<app>: refused, account not in CONSOLE_HA_POOL_ACCOUNTS`, returns `{403, haCopyNotAllowed, haPoolNotAllowedCode}` |
| - - `func (s *Server) refuseHAPool(w http.ResponseWriter, acct *Account, app, region, pool, door string) bool` — false when allowed; otherwise writes `haPoolRefusal` and returns true |
| + - `func (s *Server) haPoolRefusal(acct *Account, app, pool, door string) *haDoorRefusal` — logs `console: <door> <sqid>/<app>: pool <pool> refused, account not in CONSOLE_HA_POOL_ACCOUNTS`, returns `{403, haCopyNotAllowed, haPoolNotAllowedCode}` |
| + - `func (s *Server) refuseHAPool(w http.ResponseWriter, acct *Account, app, pool, door string) bool` — false when allowed; otherwise writes `haPoolRefusal` and returns true |
| - Produces (`hapoolcopy.go`, all used by later tasks): |
| `haCopyLabel`, `haCopyExplainer`, `haCopyDocsLink`, `haCopyStatus` (`%s` = region label), `haCopyNotAllowed`, `haCopyRegion` (`%s`), `haCopyNeedsRegion`, `haCopyRegionLocked`, `haCopySwapConcurrency`, `haCopyPoolMismatch`, each `"COPY-PENDING:<copy id>"` (`"COPY-PENDING:console.app_settings.ha.status:%s"` and `"...ha_region:%s"` keep the verb); `haPoolNotAllowedCode = "ha-pool-not-allowed"`; `haDocsURL = "https://carlosframework.com/docs/high-availability"`. |
| @@ -108,65 +117,74 @@ The spec cites `origin/main` at 01d6ca78. Lines have moved; some claims were wro |
| Run (sandbox off): `d=$(mktemp -d /tmp/g/g6pool-t1.XXXX) && TMPDIR=$d go test ./cmd/console/ -run 'TestHAPoolAccountsParsesTheList|TestServeStopsOnABadHAPoolAccount' -count=1; rm -rf "$d"` |
| -- [ ] **Step 3: Implement `haPoolAccounts`** mirroring `sidecarAccounts`, error prefix `CONSOLE_HA_POOL_ACCOUNTS:`; the "names no sqid" error says "unset it for nobody, or list at least one sqid". Call it beside `sidecarAccounts` before `openServeDB`, `log.Fatalf` on error, set `Config.HAPoolAccounts`. Header comment: what the list gates, that unset/empty is nobody, that operators are not exempt, that changing it is a console restart. |
| +- [ ] **Step 3: Implement `haPoolAccounts`** mirroring `sidecarAccounts`, error prefix `CONSOLE_HA_POOL_ACCOUNTS:`; the "names no sqid" error says "unset it for nobody, or list at least one sqid". Call it beside `sidecarAccounts` before `openServeDB`, `log.Fatalf` on error, set `Config.HAPoolAccounts`. Header comment: what the list gates (any record whose pool is named in any region's `ha_pools`), that unset/empty is nobody, that operators are not exempt, that changing it is a console restart. |
| - [ ] **Step 4: Run, expect PASS** (same command). |
| - [ ] **Step 5: Write the failing gate tests** (`internal/console/hapool_test.go`) |
| ```go |
| -// TestHAPoolScopedPredicate: HARegions {ie, us}, us scoped ["ha"], ie unscoped. |
| -// valid config rows: (us,ha)=true (us,"")=false (us,other)=false (ie,ha)=false (uk,ha)=false ("",ha)=false |
| -// invalid config (HACapacityConfig ""): (us,ha)=true (us,other)=true (ie,ha)=true (us,"")=false (uk,ha)=false |
| -// haPoolFor: valid → us:"ha", ie:"", "":"" ; invalid → "" everywhere |
| -// haPoolAllowed(bab,"us","ha"): list nil → false; list ["bab"] → true; list ["cdef"] → false |
| -// haPoolAllowed(bab,"us",""): true with list nil |
| +// TestHAPoolRestrictedPredicate, one NewServer per row (newConsoleFixtureWith + Tweak), HomeRegion "ie": |
| +// config haPoolRaw("us", true), HARegions {us}: ha=true other=false ""=false |
| +// same config, HARegions nil (US dropped from the switch): ha=true other=false |
| +// same config, HARegions {ie}: ha=true |
| +// config `{`, HARegions nil (set, unparseable): ha=true other=true ""=false |
| +// config "", HARegions {us} (missing): other=true ""=false |
| +// config "", HARegions nil (no HA anywhere): ha=false other=false |
| +// haPoolAllowed(bab, "ha") with config haPoolRaw("us", true): list nil → false; {"bab"} → true; {"cdef"} → false |
| +// haPoolAllowed(bab, "") → true with list nil |
| +// haPoolFor (valid config, HARegions {us}): "us"→"ha", "ie"→"", ""→"" ; HARegions nil: "us"→"" ; broken: "" |
| ``` |
| -`TestHAPoolGateInstanceCreate` — `haPoolWorldNew(t, "us", "ha", func(c *Config){ c.HAPoolAccounts = nil })`, keys := `sidecarAppKeys`-style listing of `apps/bab/titogo/` before: |
| -- plain `w.post(t, false, w.body(false))` → 403; body decodes to `{Error: haCopyNotAllowed, Code: "ha-pool-not-allowed"}`; app keys unchanged; `w.data.counts()` is `(0, nil)` (no proof LIST ran); no record at `acme.go.tito.io`. |
| -- the same body plus `"from":{"host":"<an existing sibling host>"}` → 403 with the same body (the seed arm is behind the gate). |
| -- a non-member's token (a fresh `cliToken` for an address with no membership) → 404, body byte-identical to the door's existing non-member 404. |
| -- with `HAPoolAccounts = []string{"bab"}` → 201 and the record has `HA: true, Pool: "ha", Region: "us"` (as `TestHAPoolScopedBirth`). |
| +Every test below records the bucket keys under `apps/bab/titogo/` and `w.data.counts()` before the request, and on a refusal asserts both are unchanged (no write, no proof LIST) and no record exists at the requested host. Each has the positive control named in "Read first". |
| + |
| +`TestHAPoolGateInstanceCreate` — `haPoolWorldNew(t, "us", "ha", func(c *Config){ c.HAPoolAccounts = nil })`: |
| +- plain `w.post(t, false, w.body(false))` → 403, body decodes to `{Error: haCopyNotAllowed, Code: "ha-pool-not-allowed"}`. |
| +- the same body plus `"from":{"host":"<an existing sibling host>"}` → 403, same body (the seed arm is behind the gate). |
| +- a non-member's token (a fresh `cliToken` for an address with no membership) → 404, byte-identical to the door's existing non-member 404. |
| +- control: `HAPoolAccounts = {"bab"}` → 201, record `HA: true, Pool: "ha", Region: "us"` (as `TestHAPoolScopedBirth`). |
| + |
| +`TestHAPoolGateSidecarCreate` — the same four through `w.post(t, true, w.body(true))` and `provision.GetSidecarRecord`. |
| -`TestHAPoolGateSidecarCreate` — the same four assertions through `w.post(t, true, w.body(true))` and `provision.GetSidecarRecord`. |
| +`TestHAPoolGateRegionDroppedFromSwitch` (round 1, P1-1) — `haPoolWorldNew(t, "us", "ha", tweak)` with `c.HARegions = nil` (US keeps `ha_pools: ["ha"]` in the config) and list nil: an instance create naming `"region":"us"` → 403 with the code, nothing written; the sidecar create → 403, nothing written. Control: with `{"bab"}`, the instance create → 201 and the record is LEGACY (`HA: false, Pool: "ha"`), proving the request reached the gate on the legacy path. (If the control answers a placement refusal instead, publish the `us` placement the legacy `checkPlacement` needs, `apiinstances.go:2088-2131`, before asserting.) |
| -`TestHAPoolGateLeavesLegacyAlone` — list nil, account bab: |
| -- `haPoolWorldNew(t, "us", "", ...)` (manifest pool `""`): instance create → 201 legacy (`HA: false`); |
| -- `haPoolWorldNew(t, "ie", "ha", ...)` with ie's entry made unscoped (pass a tweak that sets `HACapacityConfig = haPoolRaw("ie", false)`): create → not 403 (answer equals what it was before this task: run it once on the base commit and pin the status). |
| +`TestHAPoolGateStaticRecordAnyRegion` (round 1, P1-2) — config `haPoolRaw("us", true)`, `HARegions {"us"}`, home `ie` unscoped, manifest pool `ha`, list nil: an instance create with `"kind":"static"` at the home (no region, and again with `"region":"ie"`) → 403 with the code, nothing written. Control: with `{"bab"}` → 201, record `Kind: "static", Pool: "ha", Region: "", HA: false`. Comment in the test: a US box serving pool `ha` would serve this record (`provision.ReconcileConfig.inScope` widens region for everywhere classes, `reconcile.go:524-536`), which is why the gate ignores the region. |
| -Guard: in the existing domain-attach first-route test, make the app's manifest `Pool: "ha"` in a scoped region and assert the written record's `Pool == ""` and `HA == false`, with a comment: the first route never carries a pool, so it needs no HA gate (Spec correction 11). |
| +`TestHAPoolGateLeavesUnrestrictedAlone` — list nil, account bab: |
| +- manifest pool `""` in scoped US → 201 legacy (`HA: false`). |
| +- manifest pool `tito` (in no region's `ha_pools`), config valid → the answer it gave before this task (run once on the base commit and pin the status; it must not be 403 `ha-pool-not-allowed`). |
| +- no HA config at all (`HACapacityConfig ""`, `HARegions nil`), manifest pool `tito` → 201. |
| -- [ ] **Step 6: Run, expect FAIL** (`undefined: haPoolScoped` etc.) |
| +Guard: in the existing domain-attach first-route test, make the app's manifest `Pool: "ha"` with `ha` restricted and the account unlisted, and assert the written record's `Pool == ""` and `HA == false`, with a comment: the first route never carries a pool, so it needs no gate (Spec correction 11). |
| -Run (sandbox off): `... go test ./internal/console/ -run 'TestHAPoolScopedPredicate|TestHAPoolGate' -count=1 ...` |
| +- [ ] **Step 6: Run, expect FAIL** (`undefined: haPoolRestricted` etc.) |
| -- [ ] **Step 7: Implement** `hapool.go`, `hapoolcopy.go`, `Config.HAPoolAccounts` (comment: "nil is nobody, the opposite of SidecarAccounts on purpose"), and the two gate calls: |
| +Run (sandbox off): `... go test ./internal/console/ -run 'TestHAPoolRestrictedPredicate|TestHAPoolGate' -count=1 ...` |
| + |
| +- [ ] **Step 7: Implement** `hapool.go` (package comment: the rule is by pool name, why the region is not consulted (Spec correction 13), which doors call it and why only these, the way `sidecarsgate.go`'s header does), `hapoolcopy.go`, the two `Server` fields, `Config.HAPoolAccounts` (comment: "nil is nobody, the opposite of SidecarAccounts on purpose"), and the two calls: |
| ```go |
| // apiinstances.go, after haCreateShapeRefusal |
| -if s.refuseHAPool(w, acct, app, region, rec.Pool, "api instances create") { |
| +if s.refuseHAPool(w, acct, app, rec.Pool, "api instances create") { |
| return |
| } |
| // apisidecars.go, after refuseSidecarsPaused |
| -if s.refuseHAPool(w, acct, app, rec.Region, rec.Pool, "api sidecars create") { |
| +if s.refuseHAPool(w, acct, app, rec.Pool, "api sidecars create") { |
| return |
| } |
| ``` |
| -`hapool.go`'s package comment lists the doors and why only these two (Spec correction 11), the way `sidecarsgate.go`'s header does. |
| - |
| - [ ] **Step 8: Run the new tests and every scoped-pool test, expect PASS** |
| `... go test ./internal/console/ -run 'TestHAPool|TestSidecarsPaused|TestHACreate|TestRegionDefault|TestDemoClaimHA|TestAPIInstances.*HA|TestAttach' -count=1 ...` (widen `-run` to the exact test names in the files listed under "Read first" if a pattern misses one; `grep -n '^func Test' <file>`). |
| -- [ ] **Step 9: Mutation checks** (each one targeted `-run`, then revert): delete the instance gate call → `TestHAPoolGateInstanceCreate` fails; delete the sidecar call → `TestHAPoolGateSidecarCreate` fails; make `haPoolScoped` ignore `haScopeInvalid` → `TestHAPoolScopedPredicate` fails; make `haPoolAccounts("")` return a non-nil empty slice treated as "no gate" (`len==0 → allowed`) → predicate test fails. |
| +- [ ] **Step 9: Mutation checks** (each one targeted `-run`, then revert): delete the instance gate call → `TestHAPoolGateInstanceCreate` fails; delete the sidecar call → `TestHAPoolGateSidecarCreate` fails; build the restricted set from `cfg.HARegions` only → `TestHAPoolGateRegionDroppedFromSwitch` fails; make the gate also require `s.haRegion(region)` → `TestHAPoolGateStaticRecordAnyRegion` fails; drop the broken-config branch → `TestHAPoolRestrictedPredicate` fails; treat an empty list as "no gate" → the predicate test fails. |
| - [ ] **Step 10: Commit** |
| ```bash |
| git add cmd/console/main.go cmd/console/hapoolaccounts_test.go cmd/console/hapoolaccounts_serve_test.go internal/console/server.go internal/console/hapool.go internal/console/hapoolcopy.go internal/console/hapool_test.go internal/console/apiinstances.go internal/console/apisidecars.go <fixture test files touched> |
| -git commit -m "console: CONSOLE_HA_POOL_ACCOUNTS gates creates into scoped HA pools" |
| +git commit -m "console: CONSOLE_HA_POOL_ACCOUNTS gates records in restricted pools" |
| ``` |
| --- |
| @@ -179,6 +197,8 @@ git commit -m "console: CONSOLE_HA_POOL_ACCOUNTS gates creates into scoped HA po |
| - The HA checks run AFTER `apiPrincipalAccount` (auth, membership, the app-scoped-service 404), the rate limit, `readJSON`, and the `place` validation (its foreign-fleet 404 must still come first), and BEFORE `newAppRegionReq` (otherwise `"@auto"` meets the region-unknown refusal instead of `ha_needs_region`). |
| - Adoption: in `claimAppWith`, `rq.haPool != "" && adoptingExistingApp` returns `claimTaken` before any write. |
| - An older CLI never sends `ha`; the answer gains `ha_pool` and `ha_status` ONLY when the row has a pool, so a plain create's body is byte-identical to today. |
| +- The option's REGION checks stay region-based (spec §3.1.1): the region must be in `CONSOLE_HA_REGIONS` with a non-empty `ha_pools` (`haPoolFor`). The ALLOWLIST check is Task 1's pool-only `haPoolAllowed(acct, pool)`. |
| +- Fixture prerequisites (P1-4 class): an explicit `"region":"us"` create reaches the HA code only when the region switch is on, which needs `cfg.AppRegions`, a `HomeRegion` and an ACTIVE, verified hostname history (`appRegionsOn`, `regionconfig.go:12`; `hostsActive`, `hostsused.go:180`), plus a published armed+hosting `us` edges entry and `SecretsPub` for `validateExplicitRegion` (`regionclaim.go:31`). The HA config is parsed ONCE in `NewServer` (`server.go:1982`), so `HomeRegion`, `HARegions`, `HACapacityConfig` and `HAPoolAccounts` go in the fixture's `Tweak`; setting them on `fx.srv.cfg` afterwards does nothing. Write `haRegionFixture(t *testing.T, accounts []string) (*consoleFixture, string)` in `apicli_ha_test.go`: `newConsoleFixtureWith(Tweak: HomeRegion "ie", HARegions {"us"}, HACapacityConfig haPoolRaw("us", true), HAPoolAccounts accounts, AppsDomain "apps.example.test")` (`AppsDomain` because Tasks 4 and 6 call the enable door, which answers 503 without it), then `regionFixture`'s lines (`regionclaim_test.go:19-26`: `AppRegions`, `SecretsPub`, `historyActive`, `setEdges`) with a `us` box added beside `ie-box`/`uk-box` (a copy of `ukEligible` placed in `us`). Tasks 4 and 6 reuse it. Its first assertion is the control: a PLAIN create with `"region":"us"` answers 200 with `region == "us"`. |
| **Files:** |
| - Create: `internal/console/store_hapool.go` (migration, `CreateHAAppInRegion`, `AppHAPool`) |
| @@ -188,12 +208,13 @@ git commit -m "console: CONSOLE_HA_POOL_ACCOUNTS gates creates into scoped HA po |
| - Create: `internal/console/store_hapool_test.go`, `internal/console/apicli_ha_test.go` |
| **Interfaces:** |
| -- Consumes: Task 1's `haPoolFor`, `haPoolAllowed`, `haDoorRefusal`, `writeHARefusal`, copy constants. |
| +- Consumes: Task 1's `haPoolFor`, `haPoolAllowed(acct, pool)`, `haPoolRefusal`, `haDoorRefusal`, `writeHARefusal`, copy constants. |
| - Produces: |
| - `func (s *Store) CreateHAAppInRegion(accountID int64, app, createdBy, region, source, haPool string, now time.Time) (created bool, err error)` |
| - `func (s *Store) AppHAPool(ctx context.Context, accountID int64, app string) (pool, region string, err error)` — the LIVE row (`deleted_at = 0`); no live row is `"", "", nil` |
| - `regionReq.haPool string` — set only by an HA create |
| - `func (s *Server) haCreateChoice(p Principal, acct *Account, raw, place string) (pool string, ref *haDoorRefusal)` |
| + - test helper `haRegionFixture(t *testing.T, accounts []string) (*consoleFixture, string)` (fixture, person token) |
| - [ ] **Step 1: Write the failing store test** (`store_hapool_test.go`) |
| @@ -212,7 +233,7 @@ git commit -m "console: CONSOLE_HA_POOL_ACCOUNTS gates creates into scoped HA po |
| - [ ] **Step 5: Write the failing API tests** (`apicli_ha_test.go`) |
| -Fixture: the one the existing region-create API tests use (`grep -n 'region' internal/console/regionclaim_test.go internal/console/apicli_test.go` for a create that sends `"region"` and passes `validateExplicitRegion`), with `Tweak`: `HomeRegion "ie"`, `HARegions {"us"}`, `HACapacityConfig = haPoolRaw("us", true)`, `HAPoolAccounts {"bab"}`, region switch on, and a published armed+hosting `us` box. POST `/api/cli/apps/bab/new`. `TestAPICreateAppHA` subtests: |
| +Fixture: `haRegionFixture(t, []string{"bab"})` (see "Read first"; its plain-create control must pass first). POST `/api/cli/apps/bab/new`. Every refusal subtest asserts `HasAppIn` false and no new key under `apps/bab/<name>/`. `TestAPICreateAppHA` subtests: |
| - (a) person, `{"name":"shop","region":"us","ha":true}` → 200; `AppHAPool` = `("ha","us")`; body `ha_pool == "ha"`, `ha_status == fmt.Sprintf(haCopyStatus, srv.offlinePlace("us"))`, `region == "us"`. |
| - (b) a Publish service credential of bab (`grep -n 'svcrole.Publish' internal/console/*_test.go` for its helper) with `ha` → 403 `{haCopyNotAllowed, "ha-pool-not-allowed"}`, `HasAppIn` false; the same credential without `ha` → 200 and no `ha_pool` key in the body. |
| - (c) `ha` with region absent, and with `"@auto"` → 400 `haCopyNeedsRegion`; nothing created. |
| @@ -220,13 +241,13 @@ Fixture: the one the existing region-create API tests use (`grep -n 'region' int |
| - (e) `ha` with `"place":"fleet/<own fleet>"` → 400 `fmt.Sprintf(haCopyRegion, "fleet/<own fleet>")`; a foreign fleet with `ha` → 404 (the existing answer, first). |
| - (f) unlisted person (`HAPoolAccounts {"cdef"}`) → 403 with the code; nothing created. |
| - (g) owner, objects already under `apps/bab/shop/` (put any object there), `ha` → 409 `"that name is taken"`, no row; the same without `ha` → 200 (adoption unchanged). |
| -- (h) `HACapacityConfig ""` (scope invalid) with `ha` → 400 `haCopyRegion`. |
| +- (h) `HACapacityConfig ""` with `HARegions {"us"}` (broken) with `ha` → 400 `haCopyRegion`. |
| - (i) a plain create by an unlisted person → 200, body has no `ha_pool` key. |
| - [ ] **Step 6: Run, expect FAIL.** `... -run 'TestAPICreateAppHA' ...` |
| - [ ] **Step 7: Implement.** |
| - - `haCreateChoice` checks, in this order: `p.Kind != PrincipalUser` → `{403, haCopyNotAllowed, code}`; trimmed `raw == ""` or `== autoRegion` → `{400, haCopyNeedsRegion}`; `place != ""` → `{400, fmt.Sprintf(haCopyRegion, place)}`; `code := s.homeRegionIn(raw)`; `(!s.appRegionsOn() && code != "") || s.haPoolFor(code) == ""` → `{400, fmt.Sprintf(haCopyRegion, s.offlinePlace(code))}`; `!s.haPoolAllowed(acct, code, pool)` → `s.haPoolRefusal(...)`. Returns the pool. |
| + - `haCreateChoice` checks, in this order: `p.Kind != PrincipalUser` → `{403, haCopyNotAllowed, code}`; trimmed `raw == ""` or `== autoRegion` → `{400, haCopyNeedsRegion}`; `place != ""` → `{400, fmt.Sprintf(haCopyRegion, place)}`; `code := s.homeRegionIn(raw)`; `(!s.appRegionsOn() && code != "") || s.haPoolFor(code) == ""` → `{400, fmt.Sprintf(haCopyRegion, s.offlinePlace(code))}`; `!s.haPoolAllowed(acct, pool)` → `s.haPoolRefusal(acct, "", pool, "api create")`. Returns the pool. |
| - `handleAPICreateApp`: `HA bool \`json:"ha"\`` in the request; after the place checks, `if req.HA { pool, ref := s.haCreateChoice(p, acct, req.Region, place); if ref != nil { writeHARefusal(w, ref); return } }`; after `newAppRegionReq`, `rq.haPool = pool`. On `claimOK`, read `AppHAPool` back and, when non-empty, add `"ha_pool"` and `"ha_status"` (`fmt.Sprintf(haCopyStatus, s.offlinePlace(region))`). |
| - `claimAppWith`: adoption refusal (above); insert through `CreateHAAppInRegion` when `rq.haPool != ""`; defensive: if `rq.haPool != ""` and the resolved region does not satisfy `s.poolInHAPools(region, rq.haPool)`, log and return `claimCreateFailed` before the insert (unreachable through both doors). |
| @@ -246,6 +267,7 @@ Fixture: the one the existing region-create API tests use (`grep -n 'region' int |
| - Mark the first create with an explicit `created := true` in the `os.ErrNotExist` case; do not infer it from `etag == ""`. |
| - The re-checks (allowlist, region still HA) run on first create only (see Decisions). Update with a matching pool is untouched; a different pool is 409 and writes nothing. |
| - `Regions` is `[]string{row region}` in record vocabulary: `[""]` for the home. `instanceRegionAllowed` treats it correctly; no box reads `Manifest.Regions`. |
| +- Fixture prerequisites (round 1, P1-4): the enable door answers 503 before reading anything when `AppsDomain` is empty (`apiinstances.go:3562`), and neither `haPoolWorldNew` nor the base fixture's `Config` (`server_test.go:131-135`) sets it. Every Task 3 world passes a tweak setting `c.AppsDomain = "apps.example.test"`, so the door writes `Domain: "bab.apps.example.test"` (valid for `ValidHostShape`). Instance hosts are the app's own platform apex, `<app>.bab.apps.example.test` (e.g. `haapp.bab.apps.example.test`), which passes `ValidHost`, the namespace check (`apiinstances.go:1784-1791`) and the sibling-apex check (`:1834-1855`). `titogo`'s manifest is on `go.tito.io`, so the tests use new apps, never `titogo`. Control, first in each world: a PLAIN app `plainapp` (`CreateAppIn`) enables with 200 and an instance create at `plainapp.bab.apps.example.test` answers 201. |
| **Files:** |
| - Modify: `internal/console/apiinstances.go:3544-3700` (`handleAPIInstanceEnable`; extract the `AppsDomain` + `ValidHostShape` checks `:3562-3616` into `instancesDomain`, keeping their exact messages and statuses) |
| @@ -253,15 +275,15 @@ Fixture: the one the existing region-create API tests use (`grep -n 'region' int |
| - Create: `internal/console/apiinstances_haenable_test.go` |
| **Interfaces:** |
| -- Consumes: Task 1 (`haPoolAllowed`, `haPoolRefusal`, `haPoolFor`, refusal type, copy), Task 2 (`AppHAPool`, `CreateHAAppInRegion`). |
| +- Consumes: Task 1 (`haPoolAllowed(acct, pool)`, `haPoolRefusal`, refusal type, copy), Task 2 (`AppHAPool`, `CreateHAAppInRegion`). |
| - Produces: |
| - `func (s *Server) instancesDomain(acct *Account) (string, *doorRefusal)` |
| - - `func (s *Server) haManifestBinding(ctx context.Context, acct *Account, app string, m *provision.Manifest, created bool) *haDoorRefusal` — row pool `""` → nil. Created: allowlist (`haPoolRefusal`), then `s.haRegion(region) && s.poolInHAPools(region, pool)` else `{409, fmt.Sprintf(haCopyRegion, s.offlinePlace(region))}`, then `m.Pool, m.Regions = pool, []string{region}`. Not created: `m.Pool != pool` → `{409, haCopyPoolMismatch}`, else nil. A row read error → `{502, "could not read instance settings"}` (the door's existing sentence). |
| + - `func (s *Server) haManifestBinding(ctx context.Context, acct *Account, app string, m *provision.Manifest, created bool) *haDoorRefusal` — row pool `""` → nil. Created: allowlist (`haPoolAllowed(acct, pool)`, else `haPoolRefusal`), then `s.haRegion(region) && s.poolInHAPools(region, pool)` else `{409, fmt.Sprintf(haCopyRegion, s.offlinePlace(region))}`, then `m.Pool, m.Regions = pool, []string{region}`. Not created: `m.Pool != pool` → `{409, haCopyPoolMismatch}`, else nil. A row read error → `{502, "could not read instance settings"}` (the door's existing sentence). |
| - `func (s *Server) enableHAManifest(ctx context.Context, acct *Account, app, addr string) *haDoorRefusal` — for the browser create (Task 6): `instancesDomain`, `beginCopiesMutation`, `GetManifestETag`; absent → `{Schema:1, App, Domain}` + `haManifestBinding(created=true)` + `copiesChannelRefusal` + `PutManifestIfMatch(etag "")` + audit (`"enabled instances under "+domain+" (console)"`) + `bumpSerial`; present with another domain → the door's existing 409 sentence; present otherwise → `haManifestBinding(created=false)` and no write. |
| -- [ ] **Step 1: Write the failing tests** (`apiinstances_haenable_test.go`). World: `haPoolWorldNew(t, "us", "ha", nil)` (bab listed) plus a new app row `CreateHAAppInRegion(OpsAccountID, "haapp", ..., "us", "chosen", "ha", now)`, enabled through `PUT /api/cli/apps/bab/haapp/instances-manifest` with a person's token. |
| -- `TestEnableHAFirstCreateBindsPoolAndRegion`: PUT `{}` → 200; body `pool == "ha"`, `regions == ["us"]`; the bucket's manifest has the same; then `POST` an instance naming no region → 201, record `HA: true, Pool: "ha", Region: "us"`. |
| -- `TestEnableHAHomeRegion`: `haPoolWorldNew(t, "ie", "ha", nil)`, row region `""` → manifest `Regions == [""]`; instance create with `"region":"ie"` → 201 (`Region ""`, `HA: true`); with `"region":"us"` → 400 and no record. |
| +- [ ] **Step 1: Write the failing tests** (`apiinstances_haenable_test.go`). World: `haPoolWorldNew(t, "us", "ha", func(c *Config){ c.AppsDomain = "apps.example.test" })` (bab listed), the control above, then a new app row `CreateHAAppInRegion(OpsAccountID, "haapp", ..., "us", "chosen", "ha", now)`, enabled through `PUT /api/cli/apps/bab/haapp/instances-manifest` with `w.token` (a person). Every refusal asserts the manifest key is absent (or byte-identical when one existed) and no record was written. |
| +- `TestEnableHAFirstCreateBindsPoolAndRegion`: PUT `{}` → 200; body `pool == "ha"`, `regions == ["us"]`; the bucket's manifest has the same; then `POST` an instance at `haapp.bab.apps.example.test` naming no region → 201, record `HA: true, Pool: "ha", Region: "us"`. |
| +- `TestEnableHAHomeRegion`: `haPoolWorldNew(t, "ie", "ha", <AppsDomain tweak>)`, row region `""` → manifest `Regions == [""]`; instance create with `"region":"ie"` → 201 (`Region ""`, `HA: true`); with `"region":"us"` → 400 and no record. |
| - `TestEnableHAInstanceOtherRegionRefused`: after the first test's enable, instance create with `"region":"ie"` → 400 naming the allow-list (`us`); no record. |
| - `TestEnableHALegacyPooledUnchanged`: for manifests (store-mode written) with `Pool "other", Regions ["de"]` and with `Pool "ha", Regions nil` on rows WITHOUT `ha_pool`, PUT `{"channel":"beta"}` → 200, pool and regions exactly as before, channel `beta`. And a legacy row with no manifest → PUT creates `{Pool: "", Regions: nil}` as today. |
| - `TestEnableHAExistingManifestOtherPool`: `ha_pool` row, store-mode manifest `Pool "other"` → PUT → 409 `haCopyPoolMismatch`; manifest bytes unchanged. Manifest `Pool "ha"` → PUT `{"channel":"beta"}` → 200, pool `ha` kept. |
| @@ -286,32 +308,46 @@ Fixture: the one the existing region-create API tests use (`grep -n 'region' int |
| **Read first (traps):** |
| - Refuse from the ROW (`AppHAPool`), never the manifest: before enable there is no manifest and `appPolicy` reads that as unrestricted (G6-2.5). |
| -- `setAppRegion`'s refusal goes first, right after `demoMutationRefusal` (`appregionset.go:265`), so it answers before any choices or edges read. The store's conditional update ALSO gains `AND ha_pool = ''` (spec §3.1.4); it returns `ok == false` for an HA row even if a caller skipped the door check. |
| -- `placeAppTarget`'s refusal goes after `linkedRefusalFor` (`fleets.go:816`), before the hostname-history mode read. It covers `carlos apps place` and the Settings > Placement form (all three callers, `fleets.go:1093,1157,1206`). |
| -- The swap refusal lives in `setCopiesSwapPolicy` (`copiespublication.go:256`), before `beginCopiesMutation`, only when `concurrency > 1`, returned as `&statelessSelectionError{&doorRefusal{Status: 400, Msg: haCopySwapConcurrency}}`; both swap doors already render that type (`apiswap.go:78`, `appswap.go:65`). `concurrency == 0` means "unchanged" at the API door and is not refused. |
| +- Every early check can go stale before the write (round 1, P1-3): a request admitted for a plain app can pause while that app is trashed, purged and its name recreated as HA. So each door has THREE layers, and the store layer is the one that decides: (1) an early refusal for a clear answer, (2) a re-read under the door's locks, (3) a store update conditional on the admitted incarnation AND `ha_pool = ''`. |
| +- Region doors: (1) `setAppRegion`'s refusal right after `demoMutationRefusal` (`appregionset.go:265`); (2) and (3) already exist in shape: under `lockApp` (`:336`) it compares `AppIncarnationContext` with the admitted one (`:337-344`), and `Store.SetAppRegion` (`store.go:1933-1950`) compares the incarnation under `lockAppNames`; add `AND ha_pool = ''` to its UPDATE (`:1942-1943`). |
| +- Place door: (1) after `linkedRefusalFor` (`fleets.go:816`), read the admitted incarnation (`AppIncarnationContext`; not live → 409 `appRegionSetCopy.Changed`) and `AppHAPool`; an HA row → 409 `haCopyRegionLocked`. (2) Right after `lockAccount`/`lockApp` (`fleets.go:894-895`), re-read: an HA row → 409 `haCopyRegionLocked`; another incarnation or none → 409 `appRegionSetCopy.Changed` (approved AR-8, reused). (3) Replace the write at `fleets.go:977` (`SetAppPlacementContext`) with `SetAppPlacementIfContext` (below); `ok == false` → 409 `appRegionSetCopy.Changed`. The other `SetAppPlacementContext` callers (create-with-place in `claimAppWith`, `backfillApp` at `sealkey.go:288`) are unchanged: an HA create refuses `place`, and backfill only fills an empty placement from legacy fleet routes an HA app cannot have. |
| +- Deterministic pauses use package-level test hooks that are nil in production, the precedent being `backfillPlacementLocked` (`sealkey.go:285-299`): `placeAdmitted func(sqid, app string)`, called just before `fleets.go:894`, and `appRegionAdmitted func(sqid, app string)`, called just before `appregionset.go:336`. Tests set them with `t.Cleanup` resetting to nil, and never run in parallel with each other. |
| +- `carlos apps place` is refused once the hostname history is active (`fleets.go:822-835`), so the place tests use a fixture with the history INACTIVE (not `haRegionFixture`); their control is the same place request for a plain, unpaused app answering 200 with the placement written. |
| +- The swap refusal lives in `setCopiesSwapPolicy` (`copiespublication.go:256`), before `beginCopiesMutation`, only when `concurrency > 1`, returned as `&statelessSelectionError{&doorRefusal{Status: 400, Msg: haCopySwapConcurrency}}`; both swap doors already render that type (`apiswap.go:78`, `appswap.go:65`). `concurrency == 0` means "unchanged" at the API door and is not refused. `ha_pool` never changes after insert, and a recreated row is caught by `beginCopiesMutation`'s incarnation pin (`copiespublication.go:90-100`), so no store condition is needed here. |
| **Files:** |
| -- Modify: `internal/console/appregionset.go:264-270`, `internal/console/store.go:1942-1943`, `internal/console/fleets.go:809-819`, `internal/console/copiespublication.go:256` |
| +- Modify: `internal/console/appregionset.go:264-336`, `internal/console/store.go:1942-1943` and beside `SetAppPlacementContext` (`:3354`), `internal/console/fleets.go:809-977`, `internal/console/copiespublication.go:256` |
| - Create: `internal/console/appregion_ha_test.go` |
| **Interfaces:** |
| -- Consumes: Task 2's `AppHAPool`, `CreateHAAppInRegion`; Task 1's copy; Task 3's enable flow (for the "after enable" cases). |
| -- Produces: nothing new for later tasks. |
| +- Consumes: Task 2's `AppHAPool`, `CreateHAAppInRegion`, `haRegionFixture`; Task 1's copy; Task 3's enable door. |
| +- Produces: |
| + - `func (s *Store) SetAppPlacementIfContext(ctx context.Context, accountID int64, app string, inc AppIncarnation, target string) (ok bool, err error)` — through the same `withAutoAppSQL` wrapper as `SetAppPlacementContext`; holds `lockAppNames`, compares `AppIncarnationContext` with `inc` as `SetAppRegion` does, then `UPDATE apps SET placement = ? WHERE account_id = ? AND app = ? AND deleted_at = 0 AND created_at = ? AND ha_pool = ''`; `ok` is one row affected |
| + - test hooks `placeAdmitted`, `appRegionAdmitted` (`func(sqid, app string)`, nil in production) |
| -- [ ] **Step 1: Write the failing tests** (`appregion_ha_test.go`, on `newAppRegionFx` (`appregionset_test.go:39`) plus HA config `haPoolRaw("us", true)` and an `ha_pool` row `haapp` in `us`): |
| -- `TestAppRegionSetRefusesHAApp`: `fx.put(t, owner, "haapp", "uk")` → 409 `haCopyRegionLocked`; `fx.stored` unchanged; the same after enabling (manifest pool `ha`); the browser door `POST /a/bab/apps/haapp/region` → redirect whose flash is `sentenceCase(haCopyRegionLocked)`; a plain app in the same fixture still changes (200). |
| -- `TestStoreSetAppRegionSkipsHARow`: `inc` from `AppIncarnationContext`, `SetAppRegion(ctx, id, "haapp", inc, "us", "uk", now)` → `ok == false`, region `us`. |
| -- `TestHABindingRaceSimulation`: 20 rounds; each round a fresh name; three goroutines released together: API create `{"ha":true,"region":"us"}`, region PUT to `uk`, enable PUT. After the round, if the row exists: `AppHAPool == ("ha","us")`, and if the manifest exists: `Pool == "ha"` and `Regions == ["us"]`. (Answers may be 404/409 in any order; only the end state is asserted.) |
| -- `TestPlaceRefusesHAApp`: `apps place` API (`grep -n 'handleAPIPlace' internal/console/routedecls.go` for the path) with `fleet/<own fleet>` → 409 `haCopyRegionLocked`; `AppPlacement` unchanged; same with target `""`. |
| -- `TestSwapConcurrencyRefusedForHAApp`: `PUT .../haapp/swap {"swap_concurrency":2}` → 400 `haCopySwapConcurrency`, swap policy unchanged (`appconfig.GetSwapPolicy`); `{"swap_concurrency":1}` → 200; `{"swap":"hold"}` → not refused by this rule; browser `POST .../swap` with `swap_concurrency=2` → flash `haCopySwapConcurrency`; a plain app with 3 → 200. |
| +- [ ] **Step 1: Write the failing tests** (`appregion_ha_test.go`): |
| +- `TestAppRegionSetRefusesHAApp` (`haRegionFixture(t, {"bab"})`, HA app `haapp` created through the API in `us`, owner token): `PUT .../haapp/region {"region":"uk"}` → 409 `haCopyRegionLocked`, row region `us`; the same after a 200 enable (manifest pool `ha`); the browser door `POST /a/bab/apps/haapp/region` → redirect whose flash is `sentenceCase(haCopyRegionLocked)`. Control: a plain app in the same fixture changes to `uk` (200). |
| +- `TestStoreSetAppRegionSkipsHARow`: `inc` from `AppIncarnationContext`, `SetAppRegion(ctx, id, "haapp", inc, "us", "uk", now)` → `ok == false`, region `us`; the same call on a plain row in `us` → `ok == true` (control). |
| +- `TestRegionChangeAcrossHARecreation` (round 1, P2-5; replaces the earlier random simulation). Barrier-forced, every step required to succeed: |
| + 1. API create of plain `shop` with `"region":"us"` → 200. |
| + 2. Set `appRegionAdmitted` to signal `arrived` and block on `release` for `shop`; start `PUT .../shop/region {"region":"uk"}` in a goroutine; wait on `arrived` (the request has passed every check against the plain row and holds no lock). |
| + 3. Read `shop`'s `created_at`, `TrashAppRow` + `PurgeAppRow` it, and recreate it with `CreateHAAppInRegion(OpsAccountID, "shop", ..., "us", "chosen", "ha", <that same time>)`, so the `created_at` guard cannot be what saves it. |
| + 4. `PUT .../shop/instances-manifest {}` → 200, body `pool "ha"`, `regions ["us"]`. |
| + 5. Close `release`; the region request answers 409 `appRegionSetCopy.Changed`. |
| + 6. End state: `AppHAPool == ("ha","us")`; the manifest has `Pool "ha"`, `Regions ["us"]`; a second enable PUT → 200 with the manifest unchanged. |
| + Mutation that makes it fail: delete the incarnation comparison in `setAppRegion` (`:337-344`) AND in `Store.SetAppRegion`, AND the `AND ha_pool = ''` condition → step 5 answers 200 and the row reads `uk`. With any one layer left it passes; `TestStoreSetAppRegionSkipsHARow` pins the `ha_pool` layer alone. |
| +- `TestPlaceRefusesHAApp`: HA row `haapp` (store), history inactive: `POST /api/cli/apps/bab/haapp/place` (`routedecls.go:940`, an owner) with `fleet/<own fleet>` and with `""` → 409 `haCopyRegionLocked`; `AppPlacement` unchanged. Control: a plain app placed on the same fleet → 200, placement written. |
| +- `TestPlacePausedAcrossRecreation` (round 1, P1-3), deterministic: plain `shop`, `placeAdmitted` signals and blocks; start the place to `fleet/<own fleet>`; on `arrived`, trash + purge `shop` and recreate it (a) as HA (`CreateHAAppInRegion`) → release → 409 `haCopyRegionLocked`, `AppPlacement("shop") == ""`; (b) as a plain app → 409 `appRegionSetCopy.Changed`, placement `""`. Mutation: remove the under-lock re-read → (a) is still refused by the store (`ok == false` → Changed) and fails on the sentence; remove the store conditions as well → the placement is written and it fails on state. |
| +- `TestStoreSetAppPlacementIf`: stale `inc` (after purge and recreate) → `ok == false`; HA row with its current `inc` → `ok == false`; plain row with its current `inc` → `ok == true` and placement written (control). |
| +- `TestSwapConcurrencyRefusedForHAApp` (`haRegionFixture`, HA app enabled): `PUT .../haapp/swap {"swap_concurrency":2}` → 400 `haCopySwapConcurrency`, swap policy unchanged (`appconfig.GetSwapPolicy`); `{"swap_concurrency":1}` → 200; `{"swap":"hold"}` → not refused by this rule; browser `POST .../swap` with `swap_concurrency=2` → flash `haCopySwapConcurrency`. Control: a plain app with 3 → 200. |
| -- [ ] **Step 2: Run, expect FAIL.** `... -run 'TestAppRegionSetRefusesHAApp|TestStoreSetAppRegionSkipsHARow|TestHABindingRaceSimulation|TestPlaceRefusesHAApp|TestSwapConcurrencyRefusedForHAApp' ...` |
| +- [ ] **Step 2: Run, expect FAIL.** `... -run 'TestAppRegionSetRefusesHAApp|TestStoreSetAppRegionSkipsHARow|TestRegionChangeAcrossHARecreation|TestPlaceRefusesHAApp|TestPlacePausedAcrossRecreation|TestStoreSetAppPlacementIf|TestSwapConcurrencyRefusedForHAApp' ...` |
| -- [ ] **Step 3: Implement** the four refusals (a row read error: `setAppRegion` → `{502, msgAppRegionUnreadable}`, `placeAppTarget` → 502 with its existing "could not check this app's placement" sentence, `setCopiesSwapPolicy` → return the error). |
| +- [ ] **Step 3: Implement** the refusals, the two hooks, `SetAppPlacementIfContext` and its use at `fleets.go:977` (a row read error: `setAppRegion` → `{502, msgAppRegionUnreadable}`; `placeAppTarget` → 502 with its existing "could not check this app's placement" sentence; `setCopiesSwapPolicy` → return the error). |
| -- [ ] **Step 4: Run, expect PASS**, plus `-run 'TestAppRegionSet|TestPlace|TestAPISwap|TestAppSwap|TestAppsPlace'`. |
| +- [ ] **Step 4: Run, expect PASS**, plus `-run 'TestAppRegionSet|TestPlace|TestAPISwap|TestAppSwap|TestAppsPlace|TestBackfill'`. |
| -- [ ] **Step 5: Mutation checks:** drop the `setAppRegion` refusal → the race simulation or `TestAppRegionSetRefusesHAApp` fails; drop `AND ha_pool = ''` → `TestStoreSetAppRegionSkipsHARow` fails; drop the place refusal → `TestPlaceRefusesHAApp` fails. |
| +- [ ] **Step 5: Mutation checks:** the two stated in the race and pause tests; plus drop `AND ha_pool = ''` → `TestStoreSetAppRegionSkipsHARow` fails. |
| - [ ] **Step 6: Commit** — `git commit -m "console: a born-HA app's region, placement and swap width stay fixed"` |
| @@ -341,14 +377,17 @@ Fixture: the one the existing region-create API tests use (`grep -n 'region' int |
| - [ ] **Step 1: Write the failing tests** (`apps_ha_test.go`, `httptest` server capturing the body, `newTestSession` as `apps_analytics_test.go:44` does): |
| - `TestCreateAppHASendsTheFlag`: `createAppHA(..., "us", "", "", true)` → captured body has `"ha":true` and `"region":"us"`; `createAppAnalytics(...)` → body has no `"ha"` key; the server's `{"ha_pool":"ha","ha_status":"S"}` decodes to `HAPool "ha"`, `HAStatus "S"`. |
| - `TestHAMismatchErr`: `(app, false, "")` → nil; `(app, true, "ha")` → nil; `(app, true, "")` → error whose text equals `fmt.Sprintf(appsCreateHAUnconfirmed, "shop")`. |
| +- `TestAppsCreateHAAgainstOlderConsole` (round 1, P2-6), end to end through the built binary, following `runBuyTestCommand` (`domains_buy_cli_test.go:107-119`): `buildCarlos(t)`, a scratch dir as `cmd.Dir`, `writeTestCredential(t, creds, ts.URL)`, `cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+creds, "CARLOS_DEPLOYMENT_BUCKET=", "CARLOS_DEPLOYMENT_DIR=", "CARLOS_CONFIG=")`, argv `apps create --app shop --region us --ha --account-id bab --console <ts.URL>`. The mock older console answers `POST /api/cli/apps/bab/new` with 200 and a plain create body (`account`, `app`, `url`, `region`, no `ha_pool`), records the request body, and fails the test on any path it does not serve (add the account lookup the CLI makes, if any, once you see it). Assert: the recorded body has `"ha":true`; the command exits non-zero; its output contains `fmt.Sprintf(appsCreateHAUnconfirmed, "shop")` (which names the app). Control: the same mock answering with `"ha_pool":"ha","ha_status":"S"` → exit 0 and the output contains `S`. |
| -- [ ] **Step 2: Run, expect FAIL** (sandbox off): `d=$(mktemp -d /tmp/g/g6pool-t5.XXXX) && TMPDIR=$d go test . -run 'TestCreateAppHASendsTheFlag|TestHAMismatchErr' -count=1; rm -rf "$d"` |
| +- [ ] **Step 2: Run, expect FAIL** (sandbox off): `d=$(mktemp -d /tmp/g/g6pool-t5.XXXX) && TMPDIR=$d go test . -run 'TestCreateAppHASendsTheFlag|TestHAMismatchErr|TestAppsCreateHAAgainstOlderConsole' -count=1; rm -rf "$d"` |
| - [ ] **Step 3: Implement:** `--ha` flag (`fs.Bool("ha", false, flagHAAppsCreate)`), `[--ha]` added to the usage line after `[--region <code>]`, call `createAppHA`, and after the analytics check: `if err := haMismatchErr(res.App, *ha, res.HAPool); err != nil { log.Fatalf("apps create: %v", err) }` then, when `*ha`, `fmt.Fprintf(stdout, " %s\n", res.HAStatus)`. |
| - [ ] **Step 4: Run, expect PASS**, plus `-run 'TestAppsCreate|TestCreateApp|TestRegionCopy'` in the root package, and `GOOS=darwin go build . && GOOS=windows go build .` |
| -- [ ] **Step 5: Commit** — `git commit -m "cli: apps create --ha asks for a born-HA app and checks the echo"` |
| +- [ ] **Step 5: Mutation check:** delete the `haMismatchErr` call in `runAppsCreate` → `TestAppsCreateHAAgainstOlderConsole` fails (exit 0). |
| + |
| +- [ ] **Step 6: Commit** — `git commit -m "cli: apps create --ha asks for a born-HA app and checks the echo"` |
| --- |
| @@ -377,7 +416,7 @@ Fixture: the one the existing region-create API tests use (`grep -n 'region' int |
| - [ ] **Step 1: UX pass in the kit.** `d=$(mktemp -d)`; copy `docs/console-mockup-kit/shell.html` twice; mock the create form (name, region picker, the checkbox with the explainer placeholder at its draft length from spec §5 string 2, docs link, analytics checkbox, Create app) and Settings > General's Region section with the status line in place of the region control. Screenshot at 390 and 1280, light and dark (README step 3). Fix wrapping and crowding using styleguide classes only. Note in the task report which classes were used. `rm -rf "$d"`. |
| -- [ ] **Step 2: Write the failing tests** (`newapp_ha_test.go`, on the fixtures in `regionpicker_test.go` (`newAppForm`, `:42`) and `appregionset_test.go` with HA config `haPoolRaw("us", true)`): |
| +- [ ] **Step 2: Write the failing tests** (`newapp_ha_test.go`, on `haRegionFixture` (Task 2) and `newAppForm` (`regionpicker_test.go:42`)). Prerequisites (P1-4 class): the picker renders only with the region switch on and at least two eligible regions (`newAppPicker`, `regionpicker.go:35-46`), and `haRegionFixture` gives ie, uk and us. Its control comes first: the form for a listed member renders the picker (`id="app-region"`) with a `us` option, and a plain `POST` with `region=us` creates the app. The "picker absent" case uses a separate fixture with one eligible region (ie home, `haPoolRaw("ie", true)`, `HARegions {"ie"}`) whose control is that the form has no `id="app-region"`. Each refusal asserts `HasAppIn` false. |
| - `TestNewAppHACheckboxOnlyForListedAccounts`: listed + picker with `us` → the form has `name="ha"`, `has(body, haCopyLabel)`, `has(body, haCopyExplainer)`, `haDocsURL`, and the `us` option carries `data-ha`; unlisted → no `name="ha"`; listed but no HA option in the picker and home not HA → no `name="ha"`; picker absent and home HA (`haPoolRaw("ie", true)`, home `ie`) → `name="ha"` and a hidden `region` input with value `ie`. |
| - `TestNewAppHAForgedByUnlistedRefused`: unlisted `POST /a/bab/apps/new` with `ha=1®ion=us` → 303 to the form, flash `sentenceCase(haCopyNotAllowed)`, `HasAppIn` false. |
| - `TestNewAppHANeedsRegion`: listed, `ha=1®ion=@auto` → flash `sentenceCase(haCopyNeedsRegion)`, nothing created. |
| @@ -455,6 +494,7 @@ Fixture: the one the existing region-create API tests use (`grep -n 'region' int |
| 1. **Release and roll, dev first** (memory: platform-release-recipe, platform-roll-recipe, roll-order-dev-first). Ask 8a3d302 before any #421 lock during a window. |
| 2. **Set `CONSOLE_HA_POOL_ACCOUNTS` in the SAME window as the console roll** (drop-in written before the console restart): unset means nobody, so a roll without it stops the canaries' new instance creates in pool `ha` (flagship) and `hapair` (dev, if scoped) with a 403. Dev: the dev canary account. Flagship: `bab` plus the first app's account (still undecided). Live change: needs 8a3d302's GO. |
| -3. **Check dev's `CONSOLE_HA_CAPACITY_CONFIG`**: spec §2 expects IE to carry `ha_pools: ["hapair"]`; RHA §23 recorded none. Without it, dev has no scoped pool and exit-test step 1 cannot run on dev. |
| -4. **Docs**: sync `carlosframework/website` at the release tag (README 11a) so the form's docs link resolves. |
| -5. **Exit test (dev, then flagship)**, spec §6: (1) an allowed account creates an HA app in US (dev: IE, pool `hapair`) from the web form, deploys, and its default instance record has `ha: true`, the pool, the region, and serves from a group member; (2) an unlisted account sees no checkbox, a forged API request gets 403, and a store-mode manifest with the pool for it still gets 403 at instance create; (3) a plain create in US by any account stays legacy and lands on adi-knitting. |
| +3. **Find every account already using a restricted pool** before the roll: the gate is by pool name in every region, so an account with a store-mode manifest naming `ha` (flagship) or `hapair` (dev) anywhere gets 403 on its next instance or sidecar create unless listed. List the `apps/*/*/instances.json` and `sidecars.json` manifests whose `pool` appears in any region's `ha_pools`, and put their accounts on the list (or confirm with 8a3d302 that they should be refused). |
| +4. **Check dev's `CONSOLE_HA_CAPACITY_CONFIG`**: spec §2 expects IE to carry `ha_pools: ["hapair"]`; RHA §23 recorded none. Without it, dev has no scoped pool and exit-test step 1 cannot run on dev. |
| +5. **Docs**: sync `carlosframework/website` at the release tag (README 11a) so the form's docs link resolves. |
| +6. **Exit test (dev, then flagship)**, spec §6: (1) an allowed account creates an HA app in US (dev: IE, pool `hapair`) from the web form, deploys, and its default instance record has `ha: true`, the pool, the region, and serves from a group member; (2) an unlisted account sees no checkbox, a forged API request gets 403, and a store-mode manifest with the pool for it still gets 403 at instance create; (3) a plain create in US by any account stays legacy and lands on adi-knitting. |