carlos / platform Public

Merge remote-tracking branch 'origin/main' into fix-423-test-substring

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 363464f589b508d46021f5e9e44b42f39ca1327d parent 4e75908parent 25bfb7a
29 files changed, +2,252 −10
  • apps.go +7 −0
  • apps_region_cmd.go +161 −0
  • apps_region_cmd_e2e_test.go +176 −0
  • docs/site/cli.md +14 −2
  • docs/superpowers/notes/census-proposal-app-region-set.md +27 −0
  • docs/superpowers/notes/copy-app-region-set.md +45 −0
  • docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R2.md +65 −0
  • docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R3.md +37 −0
  • docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md +60 −0
  • docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md +186 −0
  • docs/superpowers/specs/LUNA-COPY-BRIEF-APP-REGION-SET.md +86 −0
  • docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md +71 −0
  • internal/console/appregionset.go +477 −0
  • internal/console/appregionset_test.go +676 −0
  • internal/console/authcli.go +5 −0
  • internal/console/claim_invariant_fixtures_test.go +15 −0
  • internal/console/claim_invariant_probes_read_test.go +1 −0
  • internal/console/claim_invariant_test.go +2 −0
  • internal/console/regionfacts.go +2 −0
  • internal/console/server.go +9 −0
  • internal/console/store.go +47 −5
  • internal/console/svcroutes_test.go +6 −2
  • internal/console/templates/app_settings.html +11 −0
  • internal/console/testdata/claim-routes.txt +3 −0
  • internal/provision/app_region_set_census_test.go +33 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/testdata/plan14-root-reads-app-region-set.tsv +16 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/regionlabel/regionlabel.go +12 −0

CI passed — run details

diff --git a/apps.go b/apps.go
index ed37ba017..9e4831726 100644
--- a/apps.go
+++ b/apps.go
@@ -73,6 +73,11 @@ const appsUsage = `usage: carlos apps <create|place|build-probe|set|show|delete|
silent clear (a fleet box retires an app's routes on its
next reconcile the moment placement reads empty).
+ region --app <name> [--set <region>] show the region where the app's new
+ instances start, or change it with --set. existing
+ instances stay where they are. changing it is for account
+ owners and deployment operators.
+
build-probe --app <name> </path|-> set (or clear, with "-") the path whose
response body names the RUNNING build, on an app that
already exists. "carlos deploy" polls it instead of the
@@ -151,6 +156,8 @@ func RunApps(args []string) {
runAppsCreate(args[1:])
case "place":
runAppsPlace(args[1:])
+ case "region":
+ runAppsRegion(args[1:])
case "build-probe":
runAppsBuildProbe(args[1:])
case "set":
diff --git a/apps_region_cmd.go b/apps_region_cmd.go
new file mode 100644
index 000000000..1b3cb82e0
--- /dev/null
+++ b/apps_region_cmd.go
@@ -0,0 +1,161 @@
+package main
+
+// `carlos apps region` (Paul, 2026-10-26): show an app's region, or change
+// it with --set. The region is only where the app's NEW instances start;
+// existing instances never move. Console only, through GET and PUT
+// /api/cli/apps/{account}/{app}/region (internal/console/appregionset.go).
+// Any member may read it; an account owner or a deployment operator may
+// change it.
+
+import (
+ "context"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "log"
+ "net/http"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/updatewords"
+)
+
+// The verb's strings (deck docs/superpowers/notes/copy-app-region-set.md;
+// approved by delegation, Luna pass 2026-10-26).
+const (
+ // AR-30, AR-31
+ appsRegionUsage = "usage: carlos apps region --app <name> [--set <region>] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>]"
+ appsRegionFlagSet = "the region where this app's new instances start. existing instances stay where they are. only account owners and deployment operators can change it"
+ // AR-32: app, label
+ appsRegionShow = "%s's region is %s. for apps not using a pool, new instances start there; pooled apps start new instances in the home region"
+ // AR-33: app, fleet name
+ appsRegionShowFleet = "%s runs on your fleet %s, which decides where its instances run."
+ // AR-34: app, old label, new label, new label
+ appsRegionChanged = "%s's region changed from %s to %s. new instances start in %s. existing instances stay where they are."
+ // AR-35: app, label
+ appsRegionSame = "%s's region is already %s. nothing changed."
+ // AR-36
+ appsRegionDirectMode = "apps region works through a console, and this shell is in direct bucket mode (CARLOS_DEPLOYMENT_BUCKET or CARLOS_DEPLOYMENT_DIR is set). log in instead: carlos auth login --console <url>"
+ // AR-37: app
+ appsRegionOldConsole = "not found: either %s is not an app in this account, or this console is too old for carlos apps region (deploy a console built from current main)"
+)
+
+// apiAppRegion is the door's answer (the console's appRegionView).
+type apiAppRegion struct {
+ App string `json:"app"`
+ Region string `json:"region"`
+ Label string `json:"label"`
+ Source string `json:"source"`
+ Fleet string `json:"fleet"`
+ Previous string `json:"previous"`
+ PreviousLabel string `json:"previous_label"`
+ Changed bool `json:"changed"`
+}
+
+// runAppsRegion is `carlos apps region`.
+func runAppsRegion(args []string) {
+ fs := flag.NewFlagSet("apps region", flag.ExitOnError)
+ app := appFlag(fs, "app whose region to show or change")
+ set := fs.String("set", "", appsRegionFlagSet)
+ acctRaw := fs.String("account", "", "account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one)")
+ acctIDRaw := fs.String("account-id", "", updatewords.Text("settings.cli.flag-account-id"))
+ consoleFlag := consoleOption(fs, "console to act through (default: the only logged-in one)")
+ fs.Usage = flagUsage(fs, appsRegionUsage)
+ fs.Parse(args)
+ name := strings.TrimSpace(*app)
+ if name == "" || fs.NArg() != 0 {
+ log.Fatal(appsRegionUsage)
+ }
+ if err := validAppName(name); err != nil {
+ log.Fatal(err)
+ }
+ setGiven := false
+ fs.Visit(func(f *flag.Flag) {
+ if f.Name == "set" {
+ setGiven = true
+ }
+ })
+ sess, err := resolveMode(*consoleFlag)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if sess == nil {
+ log.Fatal(appsRegionDirectMode)
+ }
+ acct := resolvedAccount(sess, acctRaw, acctIDRaw)
+ ctx := context.Background()
+ if !setGiven {
+ got, err := sess.appRegion(ctx, acct, name)
+ if err != nil {
+ log.Fatalf("apps region: %v", err)
+ }
+ printAppRegionShow(got)
+ return
+ }
+ got, err := sess.setAppRegion(ctx, acct, name, strings.TrimSpace(*set))
+ if err != nil {
+ log.Fatalf("apps region: %v", err)
+ }
+ printAppRegionSet(got)
+}
+
+func printAppRegionShow(got apiAppRegion) {
+ if got.Fleet != "" {
+ fmt.Fprintf(stdout, appsRegionShowFleet+"\n", got.App, got.Fleet)
+ return
+ }
+ fmt.Fprintf(stdout, appsRegionShow+"\n", got.App, got.Label)
+}
+
+func printAppRegionSet(got apiAppRegion) {
+ if !got.Changed {
+ fmt.Fprintf(stdout, appsRegionSame+"\n", got.App, got.Label)
+ return
+ }
+ fmt.Fprintf(stdout, appsRegionChanged+"\n", got.App, got.PreviousLabel, got.Label, got.Label)
+}
+
+// appRegion is the door's GET.
+func (s *apiSession) appRegion(ctx context.Context, a apiAcct, app string) (apiAppRegion, error) {
+ a, err := s.policyAccount(ctx, a)
+ if err != nil {
+ return apiAppRegion{}, err
+ }
+ status, body, err := s.getJSON(ctx, apiPath(a, app, "/region"))
+ if err != nil {
+ return apiAppRegion{}, err
+ }
+ return appRegionReply(app, status, body)
+}
+
+// setAppRegion is the door's PUT.
+func (s *apiSession) setAppRegion(ctx context.Context, a apiAcct, app, region string) (apiAppRegion, error) {
+ a, err := s.policyAccount(ctx, a)
+ if err != nil {
+ return apiAppRegion{}, err
+ }
+ status, body, err := s.sendJSON(ctx, http.MethodPut, apiPath(a, app, "/region"), map[string]string{"region": region})
+ if err != nil {
+ return apiAppRegion{}, err
+ }
+ return appRegionReply(app, status, body)
+}
+
+// appRegionReply reads the door's answer. A 404 with no JSON error is an
+// unknown app, an account the caller cannot reach, or a console from
+// before the door, and the message names them.
+func appRegionReply(app string, status int, body []byte) (apiAppRegion, error) {
+ switch {
+ case status == http.StatusNotFound && !hasJSONError(body):
+ return apiAppRegion{}, fmt.Errorf(appsRegionOldConsole, app)
+ case status != http.StatusOK:
+ return apiAppRegion{}, apiErrorFromBody(status, body)
+ }
+ var out apiAppRegion
+ if err := json.Unmarshal(body, &out); err != nil {
+ return apiAppRegion{}, fmt.Errorf("unreadable region reply: %w", err)
+ }
+ if out.App == "" {
+ out.App = app
+ }
+ return out, nil
+}
diff --git a/apps_region_cmd_e2e_test.go b/apps_region_cmd_e2e_test.go
new file mode 100644
index 000000000..454c00410
--- /dev/null
+++ b/apps_region_cmd_e2e_test.go
@@ -0,0 +1,176 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdh"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// newAppRegionE2E is a real console as newLabelsE2E builds it (HomeRegion
+// ie, the ops account bab owning shop, a signed-in CLI), with the secrets
+// key configured and both boxes publishing every eligibility fact and a
+// fresh status snapshot: the create door can place an instance in uk with
+// no region named, as on a production deployment.
+func newAppRegionE2E(t *testing.T) *labelsE2E {
+ t.Helper()
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ tmp := t.TempDir()
+ rel := release.NewDirStore(filepath.Join(tmp, "store"))
+ seed, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, err := release.ParseSigningKey(seed, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := release.ParsePublicKey(pubB64, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ secrets, err := ecdh.P256().NewPrivateKey(bytes.Repeat([]byte{1}, 32))
+ if err != nil {
+ t.Fatal(err)
+ }
+ fp := appconfig.KeyFingerprint(secrets.PublicKey())
+ cst, err := console.Open(filepath.Join(tmp, "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cst.Close() })
+ var srv *console.Server
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv.ServeHTTP(w, r) }))
+ t.Cleanup(ts.Close)
+ regPath := filepath.Join(tmp, "registry.db")
+ srv, err = console.NewServer(console.Config{
+ Origin: ts.URL, Keymail: "http://keymail.invalid", Registry: regPath,
+ Releases: rel, ReleasePub: pub, Key: priv, AppScheme: "http",
+ AppsDomain: "oncarlos.test", HomeRegion: "ie",
+ SecretsPub: base64.StdEncoding.EncodeToString(secrets.PublicKey().Bytes()),
+ }, cst)
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if err := cst.AddMember(console.OpsAccountID, labelsAddr, console.RoleOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := cst.CreateAppIn(console.OpsAccountID, "shop", labelsAddr, now); err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ for _, b := range []struct{ machine, placement, aws string }{{"ie-machine", "", "eu-west-1"}, {"uk-machine", "uk", "eu-west-2"}} {
+ box := status.Label(b.machine)
+ body, err := json.Marshal(map[string]any{
+ "v": 1, "box": box, "box_id": box, "eip": "192.0.2.10", "region": b.aws, "placement": b.placement,
+ "hibernation_configured": true, "serves_shared_pool": true, "accepts_inbound": true,
+ "secrets_key_fp": fp, "hosts": map[string]any{},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := rel.Put(ctx, edgesfile.Key(box), body, ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := status.WriteBox(ctx, rel, status.Box{Label: box, GeneratedAt: now}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if !srv.LoadRegionNames(ctx) {
+ t.Fatal("the console did not read its region names")
+ }
+ token, expiresAt := e2eDeviceLogin(t, ts.URL, cst, labelsAddr, "e2e@laptop")
+ credFile, err := loadCredentials()
+ if err != nil {
+ t.Fatal(err)
+ }
+ credFile.put(credential{Console: ts.URL, Address: labelsAddr, Token: token, ExpiresAt: expiresAt})
+ if err := credFile.save(); err != nil {
+ t.Fatal(err)
+ }
+ return &labelsE2E{rel: rel, cst: cst, srv: srv, regPath: regPath, buf: captureStdout(t)}
+}
+
+// carlos apps region through a real console: it shows the region, a change
+// leaves the instance that already exists where it is, and the next
+// instance created with no region starts in the new one.
+func TestAppsRegionThroughTheConsole(t *testing.T) {
+ e := newAppRegionE2E(t)
+ ctx := context.Background()
+ e.out(t, runInstancesEnable, "-app", "shop", "-account", "ops", "-channel", "beta")
+ before := "home1." + labelsDomain
+ e.out(t, runInstancesCreate, "-app", "shop", "-account", "ops", "-host", before)
+
+ if got := e.out(t, runAppsRegion, "--app", "shop", "--account", "ops"); got != "shop's region is Dublin (ie). for apps not using a pool, new instances start there; pooled apps start new instances in the home region\n" {
+ t.Fatalf("apps region:\n%q", got)
+ }
+ got := e.out(t, runAppsRegion, "--app", "shop", "--account", "ops", "--set", "uk")
+ if !strings.HasSuffix(got, "shop's region changed from Dublin (ie) to London (uk). new instances start in London (uk). existing instances stay where they are.\n") {
+ t.Fatalf("apps region --set:\n%q", got)
+ }
+ if got := e.out(t, runAppsRegion, "--app", "shop", "--account", "ops", "--set", "uk"); !strings.HasSuffix(got, "shop's region is already London (uk). nothing changed.\n") {
+ t.Fatalf("apps region --set again:\n%q", got)
+ }
+
+ rec, err := provision.GetRecord(ctx, e.rel, release.OpsAccount, "shop", before)
+ if err != nil || rec.Region != "" {
+ t.Fatalf("the instance created before the change has region %q (%v), want the home still", rec.Region, err)
+ }
+ after := "new1." + labelsDomain
+ if got := e.out(t, runInstancesCreate, "-app", "shop", "-account", "ops", "-host", after); !strings.Contains(got,
+ "created instance "+after+" (channel beta, London (uk))") {
+ t.Fatalf("instances create after the change:\n%s", got)
+ }
+ rec, err = provision.GetRecord(ctx, e.rel, release.OpsAccount, "shop", after)
+ if err != nil || rec.Region != "uk" {
+ t.Fatalf("the new instance has region %q (%v), want uk", rec.Region, err)
+ }
+ if apps := e.out(t, runAppsList, "--account", "ops"); !strings.Contains(apps, "London (uk)") {
+ t.Fatalf("apps list after the change:\n%s", apps)
+ }
+}
+
+// deploy --region after a change: naming the new region ships, naming the
+// old one is refused before anything ships, as for any app. The app starts
+// in uk and moves to the home, which needs no box evidence.
+func TestDeployRegionAfterAppsRegionSet(t *testing.T) {
+ for _, c := range []struct {
+ asked string
+ ships bool
+ }{{"ie", true}, {"uk", false}} {
+ t.Run(c.asked, func(t *testing.T) {
+ e := regionE2EConsole(t, "uk")
+ if out, err := e.run(t, "apps", "region", "--app", "titogo", "--account", "ops", "--console", e.url, "--set", "ie"); err != nil ||
+ !strings.Contains(out, "titogo's region changed from uk to ie.") {
+ t.Fatalf("apps region --set: %v\n%s", err, out)
+ }
+ e.writes.Store(0)
+ out, err := e.deployAsking(t, c.asked)
+ if c.ships {
+ if strings.Contains(out, "already runs in") || e.releases(t) == 0 {
+ t.Fatalf("deploy --region %s did not ship: %v\n%s", c.asked, err, out)
+ }
+ return
+ }
+ if err == nil || !strings.Contains(out, deployRegionMismatch("titogo", "ie")) || e.writes.Load() != 0 || e.releases(t) != 0 {
+ t.Fatalf("deploy --region %s: err=%v writes=%d\n%s", c.asked, err, e.writes.Load(), out)
+ }
+ })
+ }
+}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index a1ad9363e..08d959a04 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -184,7 +184,16 @@ carlos apps ttl --app tmp-docs 5d
carlos apps keep --app tmp-docs
```
-carlos apps list shows each app's own region, the one it was given when it was created, or the fleet it runs on. Where new instances start can differ. For a pooled app, the app's Running page in the console shows where they start.
+`carlos apps list` shows each app's own region, the region where its new instances start. For an app with a region, it shows the region set when the app was created or changed later. For an app on a fleet, it shows the fleet instead. Where new instances start can differ from where existing instances run. For a pooled app, the app's Running page in the console shows where its instances start.
+
+`carlos apps region` shows where an app's new instances start, and `--set` changes that default:
+
+```sh
+carlos apps region --app hello
+carlos apps region --app hello --set uk
+```
+
+An app's region sets where its new instances start, except for apps whose instances start in a pool. Those instances start in the home region instead. Changing the region moves nothing: existing instances stay where they are, and only instances created afterwards start in the new region when the app uses its region. Use `carlos move` to move one that exists. The new region must be one the platform offers, able to start instances now, and allowed for this app's instances. An app on a fleet is refused because the fleet decides where its instances run. Use `carlos apps place` instead. The command also refuses an app whose instances start in a pool because the app's region does not decide where its new instances start. It also refuses an app in the Trash. Account owners and deployment operators can change the region with this command. In the console, the Region control is on the app's settings page, which only account members can open. Owners and deployment operators who are members can use the control. A deployment operator who is not a member must use the command. The console records who changed it, from what and to what, in the app's activity. After a change, `carlos deploy --region` must name the app's current region.
`carlos apps set` changes how the app's running instances take a new build:
@@ -342,7 +351,10 @@ nothing.
When `carlos deploy` creates your first app, it sends your timezone so the
console can pick the region nearest you, and prints the choice. `--region
<code>` chooses instead. On an app that already exists, `--region` must
-match the app's region, or deploy stops before shipping anything.
+match the app's region, or deploy stops before shipping anything. That is
+the app's current region after any `carlos apps region --set`. If `carlos
+deploy --region` names another region, deploy stops before shipping
+anything. Deploy never moves an instance to match the app's region.
`carlos deploy` takes the same repeatable `--assets` flag and passes it to the ship. Save the list as `"assets": ["/assets/"]` in `.carlos/config` and a bare `carlos deploy` declares it on every release. A flag on the command line replaces the saved list for that run, and `--no-assets` ships with none. A release that declares no folders gets no copies, so deploying a build without them turns copying off for that build. `--assets` and `--no-assets` cannot be given together.
diff --git a/docs/superpowers/notes/census-proposal-app-region-set.md b/docs/superpowers/notes/census-proposal-app-region-set.md
new file mode 100644
index 000000000..9202dee9b
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-app-region-set.md
@@ -0,0 +1,27 @@
+# Census approval: app-region-set
+
+Ruling `census-ruling-app-region-set`. Every change below keeps the disposition it already has, so it needs an approval, not a decision.
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/console/server.go` `NewServer` | body | unchanged (1) | registers POST /a/{sqid}/apps/{app}/region (handleAppRegionSet, appregionset.go) beside the rename route; route registration only; no read added, read site unchanged |
+| `internal/console/store.go` `Store.NonHomeAppRegions` | body | unchanged (1) | selects max(created_at, region_set_at) instead of created_at, so a record from before an app region change is not a discrepancy candidate; the same one console-owned SQLite query; no read added |
+| `internal/console/store.go` `Store.migrate` | body | unchanged (2) | adds the additive apps.region_set_at column (INTEGER NOT NULL DEFAULT 0) to the ALTER list; the same two Exec sites; no read added |
+| `internal/console/store.go` `Store.migrateAppsKey` | body | unchanged (2) | carries region_set_at across the apps rebuild (column list and INSERT ... SELECT); console-owned table only; no read added |
+| `internal/console/templates/app_settings.html` `external` | body | unchanged (1) | the General Region section gains, for an owner or a deployment operator, a select of region codes and a Change region button posting to /a/{sqid}/apps/{app}/region with the CSRF token, and a note; markup only; no read added |
+
+Envelopes re-pinned: `.`, `internal/console`, `internal/console/templates`, `internal/regionlabel`.
+
+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:
+
+- `internal/console/server.go` `NewServer`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console construction adds the lifetime judge, the cutover admission gate and its first marker read; claims-off app materialisation moves to the cutover watch; the existing logs/data route literal moves and is not a filesystem read;rev3=census-ruling-plans-4d-lapse;basis=registers GET and POST /a/{sqid}/plan/keep (the owner-only keep page, plans 4d) beside the account settings routes; no goroutine; read sites unchanged, offsets moved;rev3=census-ruling-plans-6-checkout;basis=refuses Config.Billing without a plan catalog, sets the billing runtime from Config.Billing, and registers POST /billing/webhook beside /api/ses/events; no goroutine and no store call; the one data-literal is still the logs/data route pattern, moved; no read added;rev3=census-ruling-console-perf-1;basis=takes cfg.Perf (or makes its own perf.Recorder), builds the instance fetcher after it so app-host calls are counted, and wraps the mux in perf.Middleware with /healthz skipped; no read added, read site unchanged;rev3=census-ruling-console-ux-nav;basis=GET /deployments now registers handleAppDeploymentsRedirect and GET /pipeline handleAppPipelineRedirect (named handlers in appredirect.go that call appRedirect for /releases and /settings/pipeline, after accountApp's gates) instead of their handlers; route registration only; no root read added, read site unchanged
+- `internal/console/store.go` `Store.NonHomeAppRegions`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+- `internal/console/store.go` `Store.migrate`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console.service user carlos-console, J4 root-input: adds the three account/app-scoped lifetime intent tables and apps.lifetime at unarmed store boot, then backfills missing lifetimes;rev3=census-ruling-plans-4d-lapse;basis=adds the additive account_plans.lapse_since and account_plans.disabled columns and calls migratePlanLapse last, which creates the console's own plan_lapse_items table (plans 4d). No read added; the new store units are the plans-4d-units decision.;rev3=census-ruling-plans-6-checkout;basis=calls migrateBilling last, after main's migratePlanLapse, which creates the console's own billing tables (plans 6a, its own decision row); no read added here;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328/#329 plan 1 Task 9: calls migrateAppPolicy (a new unit: CREATE TABLE IF NOT EXISTS app_policy_revisions, the console's own table) before migratePlanLapse. The same two Exec sites; no read added here.
+- `internal/console/store.go` `Store.migrateAppsKey`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console.service user carlos-console, J4 root-input: copies apps into the composite-key schema while preserving existing lifetimes and minting only missing ids
+- `internal/console/templates/app_settings.html` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-design-edge-rate-limit-358;basis=the Settings page gains a Rate limit section: per instance host, a form of four numbers (busy at, per address while busy, backstop rate, backstop burst) and a reset form, both posting to /a/{sqid}/apps/{app}/ratelimit with the CSRF token, and the record's path rules listed read-only; embedded and rendered by the console (carlos-console), as before; no read added;rev3=census-ruling-console-ux-nav;basis=adds the Placement section (the existing POST /place form, moved from app_instances) and the Errors and analytics section; Advanced folds into General; link texts reworded; markup only; no read added;rev3=census-ruling-region-labels;basis=General gains a Region section (RC-18a, RC-18d, RC-19, RL-S1, or the unread sentence); the placement form's button reads Change fleet (RC-14); markup only; no read added
+
+Seal: `d1e00cfb29d88b7a8e4998b641164e539067a6e1e9e4f52524255343c0c5f9f7` → `798a1ee3d8c8b775f963b9ae1dbc45e18628fa0c1e63404f46606601766ad66c`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-app-region-set.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/copy-app-region-set.md b/docs/superpowers/notes/copy-app-region-set.md
new file mode 100644
index 000000000..7cf3da359
--- /dev/null
+++ b/docs/superpowers/notes/copy-app-region-set.md
@@ -0,0 +1,45 @@
+# Copy deck: carlos apps region (app-region-set)
+
+Every new human string of branch `app-region-set`: changing an existing app's region, the default for its NEW instances (Paul, 2026-10-26). Placeholders in order. `|` inside a cell is escaped.
+
+| id | kind | placeholders | text |
+|---|---|---|---|
+| AR-1 | door refusal, printed by the CLI as "apps region: <text>" | | only an account owner or a deployment operator can change an app's region |
+| AR-2 | door refusal, printed by the CLI as "apps region: <text>" | app | %s is in the Trash. Restore it before you change its region. |
+| AR-3 | door refusal, printed by the CLI as "apps region: <text>" | app, fleet name | %s runs on your fleet %s, which decides where its instances run. Use carlos apps place to change that. |
+| AR-4 | door refusal, printed by the CLI as "apps region: <text>" | app | %s starts its instances in a pool, so an app region would not be used. Nothing was changed. |
+| AR-5 | door refusal, printed by the CLI as "apps region: <text>" | | name the region to set, for example --set uk |
+| AR-6 | door refusal, printed by the CLI as "apps region: <text>" | code, list | region %s is not one this platform offers. Choose from: %s. |
+| AR-6b | door refusal, printed by the CLI as "apps region: <text>" | code | region %s is not one this platform offers right now. |
+| AR-7 | door refusal, printed by the CLI as "apps region: <text>" | code, list | region %s is not one this app's instances may use. Allowed: %s. |
+| AR-7b | door refusal, printed by the CLI as "apps region: <text>" | code | region %s is not one this app's instances may use, and none of the regions they may use is offered right now. |
+| AR-8 | door refusal, printed by the CLI as "apps region: <text>" | | this app's region changed while this ran. Run it again. |
+| AR-9 | door refusal, printed by the CLI as "apps region: <text>" | | could not read this app's instance policy, so its region was not changed. Try again. |
+| AR-9b | door refusal, printed by the CLI as "apps region: <text>" | | could not read the regions this platform offers, so the app's region was not changed. Try again. |
+| AR-10 | door refusal, printed by the CLI as "apps region: <text>" | | could not change this app's region. Nothing was changed. Try again. |
+| AR-11 | activity row (lower case, like "made shop permanent") | app, old label, new label | changed %s's region from %s to %s |
+| AR-12 | browser sentence | | Changed after the app was created. |
+| AR-13 | flash | new label | New instances now start in %s. Existing instances stay where they are. |
+| AR-14 | flash | label | This app's region is already %s. |
+| AR-15 | form label | | Region for new instances |
+| AR-16 | button | | Change region |
+| AR-17 | help paragraph | | Changing the region moves nothing. Only instances created after the change start in the new region. |
+| AR-19 | door refusal, printed by the CLI as "apps region: <text>" | code, reason text (R-*) | region %s can't take new instances right now (%s), so the app's region was not changed. |
+| AR-20 | door refusal, printed by the CLI as "apps region: <text>" | code | could not confirm that region %s can take new instances, so the app's region was not changed. Try again. |
+| AR-21 | door refusal, printed by the CLI as "apps region: <text>" | | changing an app's region is not supported on a console with host claims on |
+| AR-22 | door refusal, printed by the CLI as "apps region: <text>" | | this console names no home region (CONSOLE_HOME_REGION is unset), so an app's region cannot be changed |
+| AR-30 | usage line | | usage: carlos apps region --app <name> [--set <region>] [--account <sqid\|name>] [--account-id <sqid>] [--console <origin>] |
+| AR-31 | flag help for --set | | the region this app's new instances start in. existing instances stay where they are. account owners and deployment operators only |
+| AR-32 | CLI line | app, region label | %s's region is %s. new instances start there. |
+| AR-33 | CLI line | app, fleet name | %s runs on your fleet %s, which decides where its instances run. |
+| AR-34 | CLI line | app, old label, new label, new label | %s's region changed from %s to %s. new instances start in %s. existing instances stay where they are. |
+| AR-35 | CLI line | app, label | %s's region is already %s. nothing changed. |
+| AR-36 | CLI refusal | | apps region works through a console, and this shell is in direct bucket mode (CARLOS_DEPLOYMENT_BUCKET or CARLOS_DEPLOYMENT_DIR is set). log in instead: carlos auth login --console <url> |
+| AR-37 | CLI refusal | app | not found: either %s is not an app in this account, or this console predates carlos apps region (deploy a console built from current main) |
+| AR-38 | help paragraph in carlos apps usage (keep the indentation) | | region --app <name> [--set <region>] show the region the app's new<br> instances start in, or change it with --set. existing<br> instances stay where they are. changing it is for account<br> owners and deployment operators. |
+| AR-40 | docs (docs/site/cli.md) | | carlos apps list shows each app's own region, the one it was given when it was created or changed to since, or the fleet it runs on. Where new instances start can differ. For a pooled app, the app's Running page in the console shows where they start. |
+| AR-41 | docs (docs/site/cli.md) | | `carlos apps region` shows an app's region, and `--set` changes it: |
+| AR-42 | docs (docs/site/cli.md) | | An app's region is only where its new instances start. Changing it moves nothing: instances that already exist stay where they are, and only instances created afterwards start in the new region. Use carlos move to move one that exists. The new region must be one the platform offers and can start instances in now, and one the app's instances may use. An app on a fleet is refused, because the fleet decides where its instances run; use `carlos apps place` instead. So is an app whose instances start in a pool, and an app in the Trash. Account owners and deployment operators can change the region, here or in the Region section of the app's settings in the console. The console records who changed it, from what and to what, in the app's activity. After a change, `carlos deploy --region` has to name the new region. |
+| AR-43 | docs (docs/site/cli.md) | | That is the region the app has now, after any `carlos apps region --set`, and deploy never moves an instance to match it. |
+
+Drafts as first sent to Luna; the applied text is in docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md (pass 3 revises AR-32 and AR-42 and adds AR-22).
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R2.md b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R2.md
new file mode 100644
index 000000000..855017976
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R2.md
@@ -0,0 +1,65 @@
+- **Round 1 P1, closed-door count — resolved.** The inventory and assertion both require 66.
+- **Round 1 P1, write identity — partly resolved; P1 remains.** API and store checks are fixed, but the browser still captures identity after its initial app lookup.
+- **Round 1 P2, operator paths — resolved under the Round 2 ruling.** Member operators retain authority; non-member operators use the CLI.
+- **Round 1 P2, pooled display — resolved.** CLI output now distinguishes the stored region from pooled placement.
+- **Round 1 P2, unnamed home — resolved.** Writes are refused before region validation when the home is unnamed.
+
+Reviewed `6f8d3b5c114bcb376d9e84d49855feb150ff83ec` against `origin/main` at `b1d00ca7d84dd2c158151469f9fd40283707e33b`. No files changed.
+
+1. **P1 — Write identity: the browser can still change a replacement app.**
+
+ [handleAppRegionSet:405](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:405) first calls `accountApp`, whose [existence check:3701](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:3701) captures no incarnation. It then calls `FormValue("csrf")`, parsing the request body, before capturing identity at [appregionset.go:427](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:427).
+
+ **Failure scenario:** the handler finds `shop`; form-body reading pauses; another request renames `shop` away and creates a replacement; form reading resumes. The handler captures the replacement’s incarnation. Both later comparisons succeed, and it changes and audits the replacement.
+
+ The [replacement test:488](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset_test.go:488) supplies an already-captured incarnation directly to `setAppRegion`. It cannot catch this handler-level window.
+
+ **Fix:** establish one app-resolution boundary that returns the incarnation with the existence result, and preserve that identity through the mutation. Add a browser-handler test that pauses body reading while the name is replaced.
+
+ **Fault family:** a mutation must affect the app incarnation the request originally resolved. This is the unresolved Round 1 invariant.
+
+2. **P1 — Account resolution: an operator’s name-based API request can mutate another account.**
+
+ [appRegionCaller:124](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:124) tries a global `AccountBySqid` lookup and immediately returns its result. It does this even without `?exact=sqid`, before considering the caller’s account-name matches.
+
+ **Failure scenario:** an operator belongs to account A, named `cdef`, while account B has sqid `cdef`. Both contain `shop`. A direct `PUT /api/cli/apps/cdef/shop/region` intended to address A by name changes B instead. Creating B can therefore change what an existing name-based request targets.
+
+ The shared resolver explicitly rejects this precedence because it silently changes the target account: [apicli.go:172](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/apicli.go:172). The new [operator-name test:465](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset_test.go:465) uses a non-colliding name. The CLI canonicalizes its reference, so this finding concerns direct API requests.
+
+ **Fix:** preserve collision detection for non-exact requests. Refuse a membership-name/global-sqid collision and require `?exact=sqid`; retain operators’ approved access to non-member accounts by explicit sqid.
+
+ **Fault family:** account references must not silently select a different tenant when another matching identifier exists.
+
+3. **P2 — Concurrent placement: the fleet refusal can become stale before the write.**
+
+ Fleet placement is checked at [appregionset.go:298](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:298), before `lockApp`. The placement writer at [fleets.go:657](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/fleets.go:657) does not share that lock. Neither incarnation comparison includes placement, and the [UPDATE predicate:1716](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1716) checks only identity, live state and the previous region.
+
+ **Failure scenario:** region validation observes an unplaced app; a concurrent placement commits `fleet/racks`; the region write then succeeds and reports that new instances start in the selected region, although the fleet now governs them. I executed the exact UPDATE against in-memory SQLite after that placement transition: it affected one row.
+
+ **Fix:** make the validated placement part of the atomic write condition, or serialize placement validation and mutation with the placement writer. Add a controlled concurrent-placement test.
+
+ **Fault family:** the placement prerequisite for changing the default must remain valid when the write commits.
+
+No P3 findings.
+
+Stopping rule 2 applies to the repeated write-identity finding. Before another patch, choose between refusing the case up front, removing the browser write, or enforcing the incarnation invariant at one shared boundary with a controlled race test. I recommend the shared boundary.
+
+The remaining reader paths do not move or rewrite existing instances. Seeded creates pass through the same defaulting checks; deploy and canary compare the stored region; `changed` is accepted as display metadata. The migration adds and preserves `region_set_at`, and main’s already-rebuilt schema path remains structurally compatible. GET and the added page control introduce no bucket reads or polling.
+
+The targeted Go tests could not start because the read-only sandbox prevented creation of Go’s work directory. This is a validation limitation, not a failing test result. The inspected new Go files are formatted. `git diff --check` reports trailing spaces in the committed Round 1 findings Markdown.
+
+Census verdicts for this tip:
+
+| Unit or envelope | Verdict and evidence |
+|---|---|
+| `NewServer` | **Approve.** [server.go:1738](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:1738): route registration only; existing read basis unchanged. |
+| `Store.NonHomeAppRegions` | **Approve.** [store.go:1735](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1735): same console-owned query, with the later discrepancy cutoff. |
+| `Store.migrate` | **Approve.** [store.go:574](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:574): additive column through existing execution sites. |
+| `Store.migrateAppsKey` | **Approve.** [store.go:715](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:715), [store.go:734](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:734): preserves the column in the existing transactional rebuild. |
+| Template `external` unit | **Approve.** [app_settings.html:25](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/templates/app_settings.html:25): embedded form and CSRF field; no new read authority. |
+| `.` envelope | **Approve.** [apps.go:159](/home/paulca/amadan.net/carlos/platform-app-region/apps.go:159), [apps_region_cmd.go:55](/home/paulca/amadan.net/carlos/platform-app-region/apps_region_cmd.go:55): dispatch, authenticated API calls and formatting; no new root execution or filesystem authority. |
+| `internal/console` envelope | **Approve.** [appregionset.go:118](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:118), [appregionset.go:251](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:251), [store.go:1710](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1710), [server.go:4440](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:4440): configured stores and console-owned SQLite; host-claim writes remain refused. The findings above do not expand root-read targets or weaken the recorded root-read basis. |
+| `internal/console/templates` envelope | **Approve.** [app_settings.html:25](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/templates/app_settings.html:25): unchanged embedded-template boundary. |
+| `internal/regionlabel` envelope | **Approve.** [regionlabel.go:81](/home/paulca/amadan.net/carlos/platform-app-region/internal/regionlabel/regionlabel.go:81): sorts existing in-memory keys; no I/O. |
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R3.md b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R3.md
new file mode 100644
index 000000000..3eff79cb3
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R3.md
@@ -0,0 +1,37 @@
+- **Round 2 P1, browser write identity — resolved.** [appregionset.go:415](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:415) captures the incarnation before form parsing; both mutation checks preserve it.
+- **Round 2 P1, account collision — resolved.** [appregionset.go:128](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:128) requires `?exact=sqid` for the operator’s global lookup; other references use membership-based resolution.
+- **Round 2 P2, concurrent placement — resolved.** [store.go:1721](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1721) atomically requires `placement = ''`.
+
+Reviewed `551018757b6377b7ce3547befc23ccf550a8d396` against `origin/main` at `b1d00ca7d84dd2c158151469f9fd40283707e33b`. No files changed.
+
+1. **P2 — Tests: synchronize the browser replacement test with the handler.**
+
+ [appregionset_test.go:561](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset_test.go:561) writes into the client-side pipe, then sleeps 200 milliseconds before replacing the app. That confirms the HTTP transport consumed bytes; it does not establish that the server captured the incarnation.
+
+ **Failure scenario:** a slow handler reaches account/app resolution after the replacement. It correctly resolves and changes the replacement, but the test fails at [appregionset_test.go:587](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset_test.go:587). The intended interleaving therefore depends on scheduling.
+
+ **Fix:** wrap the server-side request body with a notification on its first `Read`. Wait for that notification, replace the app, then release the remaining body. Include bounded waits and cleanup.
+
+ **Fault family:** a concurrency regression test must establish the ordering it claims to exercise. This is a test defect; no production write-identity P1 remains.
+
+No P1 or P3 findings. Fix the P2 without another review round.
+
+The authorization paths preserve the person-only gate, owner/operator authority and non-member 404s. The readers do not relocate existing instances. Deploy compares the current stored region; canary checks its existing instance’s region. GET and the added Settings control introduce no bucket reads or polling.
+
+Targeted Go tests could not start because the read-only sandbox blocked Go’s work directory. Independent in-memory SQLite checks passed for the update predicates, timestamp preservation through the legacy rebuild, and compatibility with main’s app-schema reads and inserts. Changed Go files are formatted; `git diff --check` is clean.
+
+Census verdicts for this tip:
+
+| Unit or envelope | Verdict and evidence |
+|---|---|
+| `NewServer` | **Approve.** [server.go:1738](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:1738): route registration; existing read basis unchanged. |
+| `Store.NonHomeAppRegions` | **Approve.** [store.go:1739](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1739): same console-owned query, with the later discrepancy cutoff. |
+| `Store.migrate` | **Approve.** [store.go:574](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:574): additive column through existing execution sites. |
+| `Store.migrateAppsKey` | **Approve.** [store.go:715](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:715), [store.go:734](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:734): preserves the column through the existing transactional rebuild. |
+| Template `external` unit | **Approve.** [app_settings.html:25](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/templates/app_settings.html:25): embedded form; no new read authority. |
+| `.` envelope | **Approve.** [apps.go:159](/home/paulca/amadan.net/carlos/platform-app-region/apps.go:159), [apps_region_cmd.go:55](/home/paulca/amadan.net/carlos/platform-app-region/apps_region_cmd.go:55): dispatch, authenticated API calls and formatting; no new root execution or filesystem authority. |
+| `internal/console` envelope | **Approve, including the Round 3 changes.** [appregionset.go:122](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:122), [appregionset.go:261](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:261), [appregionset.go:453](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:453), [store.go:1711](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1711): configured stores and console-owned SQLite; host-claim writes remain refused. `url.ParseQuery` parses the URL and adds no database read. No recorded root-read basis is weakened. |
+| `internal/console/templates` envelope | **Approve.** [app_settings.html:25](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/templates/app_settings.html:25): unchanged embedded-template boundary. |
+| `internal/regionlabel` envelope | **Approve.** [regionlabel.go:81](/home/paulca/amadan.net/carlos/platform-app-region/internal/regionlabel/regionlabel.go:81): sorts existing in-memory keys; no I/O. |
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md
new file mode 100644
index 000000000..b8336c461
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md
@@ -0,0 +1,60 @@
+Reviewed round 1 of 3 at `f686d3d5e26efd000f144e10a94318f96a7f65e5` against `origin/main` (`b1d00ca7d84dd2c158151469f9fd40283707e33b`). No files changed.
+
+1. **P1 — Tests: the closed-route test necessarily fails.**
+ The two additions at [svcroutes_test.go:260](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/svcroutes_test.go:260) increase `closedDoors` from 64 to 66. [Line 1103](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/svcroutes_test.go:1103) still requires `seen == 64`. Even when every authorization refusal succeeds, the test fails its final assertion. I verified both list counts directly from the Git revisions.
+ **Fix:** update the expected count and its explanatory message to include both region routes, then run this targeted test.
+ **Fault family:** the security-route inventory and its executable assertion must agree.
+
+2. **P1 — Write identity: an in-flight request can change a replacement app.**
+ [appRegionApp](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:148) checks existence without capturing an incarnation. The first incarnation read occurs at [appregionset.go:311](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:311), after request parsing, remote reads and policy validation.
+
+ If `shop` is renamed away or purged and recreated during that interval, the handler captures the replacement’s incarnation and writes its region. The SQL comparison succeeds because it compares against the replacement it just read. Earlier policy checks can also belong to the previous app.
+
+ Furthermore, [SetAppRegion](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1705) ignores `AppIncarnation.freed`, comparing only second-resolution `created_at`. An in-memory check using the exact SQL confirmed that replacing a row with the same timestamp permits the stale update.
+
+ **Fix:** capture the incarnation when resolving the app, then compare the complete identity under the existing app/name locking discipline before validation and commit. Preserve identity through the write. Add controlled rename/recreate and same-second replacement tests.
+ **Fault family:** a mutation must affect the app incarnation the request originally resolved.
+
+3. **P2 — Authorization: operator permission is lost on two supported paths.**
+ The browser handler calls `accountApp` at [appregionset.go:394](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:394). Its underlying [account gate](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:2696) searches memberships only. An ops owner or listed system operator who is not a member receives 404 before CSRF or operator authorization is checked. They also cannot reach the Settings control.
+
+ Separately, an operator who is an ordinary member and addresses the API by account name falls through to [appregionset.go:139](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:139), which requires ownership and forgets their operator status. The equivalent sqid request succeeds.
+
+ **Fix:** retain operator authority through account resolution; implement the browser’s session → CSRF → owner/operator gate and provide access to the advertised control. Add browser tests for both operator kinds without membership, and API tests for the name fallback.
+ **Fault family:** equivalent authorized requests must retain the same owner-or-operator permission.
+
+4. **P2 — CLI output: stored region is presented as effective placement for pooled apps.**
+ [apps_region_cmd.go:106](/home/paulca/amadan.net/carlos/platform-app-region/apps_region_cmd.go:106) always prints “new instances start there” for a non-fleet app. GET returns the stored region without reading pool policy. An app storing `uk` with a pooled manifest therefore reports London, although [regiondefault.go:70](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/regiondefault.go:70) explicitly makes its no-region pooled creates use the home.
+
+ **Fix:** describe GET’s result as the stored app region and qualify its applicability. Preserve the zero-bucket-read GET budget. Add a pooled-app output case and correct the equivalent documentation claim.
+ **Fault family:** stored defaults must not be presented as effective placement when another policy overrides them.
+
+5. **P2 — Configuration: an unnamed home makes the change one-way.**
+ [appregionset.go:253](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:253) rejects an empty value but permits an eligible non-home code without requiring `HomeRegion`. With no named home, [explicitChoices](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/regionclaim.go:83) omits the home, and [homeRegionIn](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/apiinstancemove.go:312) cannot map any nonempty input to it.
+
+ Consequently, a console with eligible `uk` boxes and no `CONSOLE_HOME_REGION` can change an app to `uk`, but neither this command nor an explicit instance-region value can select the home afterward.
+
+ **Fix:** require a named home before accepting a non-home default, while retaining the approved switch-off behavior when the home is named. Test this configuration explicitly.
+ **Fault family:** every stored non-home default must leave the home explicitly selectable.
+
+No P3 findings.
+
+The shared authentication code refuses expired/revoked tokens and every service role before account resolution. Ordinary non-members retain the standard 404, and API Trash details follow account authorization. Existing-instance readers do not move or rewrite records; seeded creates use the same defaulting path. The migration preserves `region_set_at` through the rebuild, and rollback to main remains structurally compatible. GET and the added page controls introduce no bucket reads or polling.
+
+The new tests cover ordinary owner/member behavior, several refusals, unchanged existing instances and deploy-region behavior. They do not cover the replacement races or operator paths above. Go tests could not start because the read-only sandbox prevented creation of Go’s work directory; this is a validation limitation, not a test result. `git diff --check` passed.
+
+Census verdicts for the reviewed tip:
+
+| Unit or envelope | Verdict and evidence |
+|---|---|
+| `Server.NewServer` | **Approve.** [server.go:1738](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:1738): route registration only; existing read basis unchanged. |
+| `Store.NonHomeAppRegions` | **Approve.** [store.go:1725](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1725): same console-owned query, with a later discrepancy cutoff. |
+| `Store.migrate` | **Approve.** [store.go:574](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:574): additive column through existing execution sites. |
+| `Store.migrateAppsKey` | **Approve.** [store.go:715](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:715), [store.go:734](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:734): preserves the new column in the existing transactional rebuild. |
+| Template `external` unit | **Approve.** [app_settings.html:25](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/templates/app_settings.html:25): embedded form markup and CSRF field; no new read. |
+| `.` envelope | **Approve.** [apps.go:156](/home/paulca/amadan.net/carlos/platform-app-region/apps.go:156), [apps_region_cmd.go:55](/home/paulca/amadan.net/carlos/platform-app-region/apps_region_cmd.go:55): CLI dispatch, authenticated API calls and formatting; no new root execution or filesystem authority. |
+| `internal/console` envelope | **Approve.** [appregionset.go:116](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:116), [appregionset.go:246](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:246), [server.go:4440](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:4440): existing configured stores and validated region vocabulary; host-claim writes refused. The correctness findings above do not introduce a new root-read target or weaken the recorded root-read basis. |
+| `internal/console/templates` envelope | **Approve.** [app_settings.html:25](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/templates/app_settings.html:25): same embedded-template boundary. |
+| `internal/regionlabel` envelope | **Approve.** [regionlabel.go:81](/home/paulca/amadan.net/carlos/platform-app-region/internal/regionlabel/regionlabel.go:81): sorts keys from an existing in-memory map; no I/O. |
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md
new file mode 100644
index 000000000..65de99101
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md
@@ -0,0 +1,186 @@
+# Review brief: branch app-region-set (carlos apps region), round 3 of 3
+
+Repo carlos/platform, branch `app-region-set`, commit named in the prompt
+(the commit that adds this brief).
+Under review: the diff `origin/main..app-region-set`
+(`git diff origin/main...HEAD`).
+Authorities: AGENTS.md (the security gate order, the Stopping rules, the
+census section); `docs/superpowers/specs/2026-10-01-nearest-region-default-design.md`
+(the app region and its readers); `docs/superpowers/specs/2026-10-25-region-labels-design.md`
+(labels). All MERGED on main. The member-moves design is on an unmerged
+branch: do not review against it; its §18 Q5 ruling is quoted below as a
+ruling, nothing more.
+
+You are an independent reviewer. Read the diff, then the code it names, and
+check every claim against that code.
+
+## What the branch does
+
+An app's stored region (`apps.region` in the console's SQLite) is the
+default region for the app's NEW instances. Until now only create set it.
+The branch adds:
+
+- `GET` and `PUT /api/cli/apps/{account}/{app}/region`
+ (`internal/console/appregionset.go`), registered with `svcrole.Set{}`
+ (closed to every service credential).
+- `POST /a/{sqid}/apps/{app}/region`, the browser form on Settings >
+ General's Region section (`app_settings.html`).
+- `carlos apps region --app <x> [--set <code>]` (`apps_region_cmd.go`).
+- `apps.region_set_at`, read by the placement discrepancy log
+ (`regiondrift.go` via `Store.NonHomeAppRegions`).
+
+## Fixed: do not re-argue
+
+Paul's design (2026-10-26, relayed in the task):
+
+- Only the default for new instances changes. Existing instances never
+ move. Deploy `--region` keeps comparing against the stored region.
+- Who may change it: the account's owner and deployment operators.
+ Members and service credentials are refused, using the existing
+ owner-only gate pattern.
+- Refusals checked up front: unknown or not-offered region; an app on a
+ fleet (use `carlos apps place`); an app in the Trash; temporary apps if
+ pinned; the `CONSOLE_APP_REGIONS` switch per the create-time behaviour.
+- An audit line with the old and the new region. No new polling.
+
+The builder's rulings (record a P1 only if one is unsafe or breaks
+something, with evidence):
+
+1. "Deployment operator" is `platformOperator`: an owner of the ops
+ account or an address on `CARLOS_SYSTEM_OPERATORS`, as the app policy
+ door and the platform-domain door use. An operator reaches any account
+ by sqid without being a member; anyone else goes through
+ `apiPrincipalAccount` (byte-identical 404 for a non-member). A member
+ gets a 403 with the owner sentence, as `apiOwnerAccountFor` does. Any
+ member may READ the region.
+2. The switch: the write is allowed with `CONSOLE_APP_REGIONS` off. The
+ instance create door reads the stored region with the switch off
+ (`apiinstances.go`, the app-derived region branch has no switch check),
+ and member moves §18 Q5 (Paul) accepted writing it with the switch off.
+3. Temporary apps are not pinned (create takes a region for them), so they
+ are allowed.
+4. Extra refusals the code shows are needed: a pooled app (the create door
+ ignores the app region for a pooled manifest), a region the app's
+ manifest allow-list excludes, a region that cannot start an instance
+ now by the create door's own positive test (so a no-region create after
+ the change is not refused), and a host-claim console (no claim operation
+ gates the row write; host claims are shelved).
+5. The write is SQLite only: no bucket object and no serial bump, because
+ no box reads `apps.region`.
+6. The Settings control's options come from the in-memory region name map,
+ so a page view reads no store; the door validates the choice on submit.
+
+## What to check
+
+1. **Authorization, the security gate (focus here).** For both the API and
+ the browser door: can anyone other than an account owner or a
+ deployment operator change an app's region? Walk every principal kind
+ (person member, person owner, person non-member, ops owner, listed
+ system operator, service credential of every role, an app-bound
+ service credential, a revoked or expired token), every account
+ reference form (sqid, name, `?exact=sqid`, a name that collides with
+ another account's sqid), and the operator branch's fall-through to the
+ member path. Is the non-member answer byte-identical to the family's
+ 404 in every case, so the door is no membership or existence oracle?
+ Does the trashed-app 409 leak anything to a caller who could not
+ otherwise see the app? Is the browser gate order session, CSRF, then
+ owner/operator (404), as AGENTS.md requires?
+2. **The write.** `setAppRegion` holds `lockApp`, re-reads the
+ incarnation, and `Store.SetAppRegion` pins `created_at` and the region
+ it read. Can a rename, a purge and re-create, a trash, a placement or
+ another change in between make it write the wrong row or a stale value?
+ Is anything written or audited on any refusal path?
+3. **Every reader of `apps.region`** (grep `AppRegion(`, `appRegion(`,
+ `region_source`, `NonHomeAppRegions`): the instance create door, the
+ `/regions` app_default that `carlos deploy --region` and `carlos canary
+ --region` compare against, seeded instance creates, region labels, the
+ app create echo, the discrepancy log. Does any of them move, retire or
+ rewrite an existing instance or route when the value changes, or break
+ on the new `region_source` value `changed`?
+4. **Migration.** `region_set_at` in the ALTER list and in
+ `migrateAppsKey`'s rebuild. A console rolled back to main must still
+ start and work on the migrated database.
+5. **Refusals and request budget.** Each refusal fires before the write,
+ in an order that never reveals more than the caller may see. Requests
+ per change: one manifest GET (appPolicy), the edges reads of
+ `readExplicitGate` and `liveEdges`; per GET and per page view: none of
+ the bucket. Is any new polling or per-view store read added?
+6. **Tests.** `internal/console/appregionset_test.go` and
+ `apps_region_cmd_e2e_test.go` run a real console. Do they prove the
+ authorization matrix, each refusal, that existing instances do not move,
+ and deploy `--region` after a change? Name any gap that would hide a
+ defect.
+7. **The census approval** (AGENTS.md, "The census"). The card is
+ `docs/superpowers/notes/census-proposal-app-region-set.md`. Give a
+ verdict per unit and per re-pinned envelope (`.`, `internal/console`,
+ `internal/console/templates`, `internal/regionlabel`), citing the lines
+ you read: approve, or escalate if root can now open, run, query or
+ follow anything from a tenant-, app- or box-writable path or input, or
+ a check the basis relies on is weakened.
+
+## Round 3
+
+Earlier rounds: round 1 `docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md`
+(f686d3d5: 2 P1, 3 P2), round 2 `docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET-R2.md`
+(6f8d3b5c: 2 P1, 1 P2; round 1's five dispositions recorded there). This is
+the last round the stopping rules allow. Stopping rule 2 has triggered for
+the write-identity family; this round's fix is the shared boundary you
+recommended. If a P1 remains in that family, say so and say whether
+refusing up front or cutting the browser write removes it.
+
+First give one line per round 2 P1 and P2: resolved, partly, or not. The
+builder's dispositions:
+
+1. P1 browser write identity: the browser door now resolves the app
+ through `accountAppIncarnation`, whose existence check IS the
+ incarnation read, before it reads the form body (CSRF included);
+ `setAppRegion` and `Store.SetAppRegion` compare that incarnation as
+ before. Test: `TestAppRegionBrowserRefusesAnAppReplacedMidRequest`
+ pauses the body on a pipe, purges and re-creates the app, then
+ finishes the body; it was watched to fail with the incarnation read
+ moved after the CSRF check.
+2. P1 account collision: the operator branch (any account by sqid) is
+ taken only with `?exact=sqid`, which the CLI always sends after
+ resolving names against the caller's memberships; any other reference
+ goes through `apiPrincipalAccount`'s symmetric member resolution.
+ `exactSqidAsked` parses the raw query with `url.ParseQuery` (the
+ census scanner reads a `.Query()` selector as a database read; this is
+ URL parsing, named here so you can judge it). Test:
+ `TestAppRegionSetNameNeverLosesToASqid`, watched to fail without the
+ exact condition.
+3. P2 concurrent placement: `Store.SetAppRegion`'s UPDATE also requires
+ `placement = ''`, the state the door validated (the placement writer
+ writes that column). Test: `TestAppRegionSetRefusesAPlacementMadeMeanwhile`.
+
+CI passed at 6f8d3b5c. The census overlay was re-proposed under the same
+name (the console envelope re-pinned); give the envelope verdict again.
+
+## 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 area, the problem, the evidence
+(file:line, verified), the failure scenario, a concrete fix and the
+invariant or trust boundary it breaks (that is its fault family). Then the
+census verdicts. End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites; a targeted `go test -run` on a
+package is fine (leave GOCACHE unset).
diff --git a/docs/superpowers/specs/LUNA-COPY-BRIEF-APP-REGION-SET.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-APP-REGION-SET.md
new file mode 100644
index 000000000..86d27e723
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-APP-REGION-SET.md
@@ -0,0 +1,86 @@
+# Copy pass brief: carlos apps region (branch app-region-set)
+
+You are reviewing user-facing strings for a hosting platform's CLI, console
+and docs. Paul, the owner, delegated this review to you. Apply his house
+rules and return improved strings.
+
+The feature: an app has a stored **region**, the place its NEW instances
+start when a create names no region. Until now it could only be set when the
+app was created. `carlos apps region --app <x>` now shows it, and `--set
+<code>` changes it; the console's app Settings > General page has a small
+Region control that does the same. The deck with every string, its id, kind
+and placeholders is `docs/superpowers/notes/copy-app-region-set.md`.
+
+## House rules
+
+- Plain words, short sentences, no jargon, no marketing tone, no
+ exclamation marks.
+- No em dashes or en dashes used as dashes. Where you would use one, end the
+ sentence with a full stop and start a separate sentence that **continues
+ in lower case**, the way Go error strings and this CLI write. Paul's own
+ example: "could not provision the store — re-run `carlos store create` to
+ resume" becomes "could not provision the store. re-run `carlos store
+ create` to resume". If the second half is a bare command with no verb,
+ give it a verb. Semicolons are fine; the rule is about em dashes.
+- Casing by kind:
+ - **door refusals, CLI lines, CLI refusals, the usage line, the flag help
+ and the activity row**: lower case at the start (a placeholder that
+ starts the string is fine) and after every full stop, and no full stop
+ at the very end. The newest approved CLI strings read this way, for
+ example "default size for %s set to %s. instances with their own size
+ are unchanged". Command names, flag names, `Trash` (a page name) and
+ environment variable names keep their own spelling.
+ - **flash, browser sentence, form label, button, help paragraph** and
+ **docs**: ordinary sentence case with full stops, as the surrounding
+ console and docs text has. Still no em dashes.
+ - AR-38 is a help paragraph inside the CLI's usage text: keep its
+ indentation and line breaks (`<br>`), and the lower-case style of the
+ usage text around it.
+- Keep every placeholder (`%s`) and their order. Go cannot reorder them. If
+ a placeholder must move, say so in Flags instead.
+- Leave flag names (`--set`, `--app`, `--account`, `--account-id`,
+ `--console`, `--region`), command names (`carlos apps region`, `carlos
+ apps place`, `carlos apps list`, `carlos deploy`, `carlos move`, `carlos
+ auth login --console <url>`) and environment variable names exactly as
+ they are.
+- Do not name the product. Use neutral examples only (`shop`, `hello`,
+ `uk`, `ie`); never a real customer.
+- Human text only. Log lines and JSON keys are out of scope and not listed.
+
+## Facts that must stay true
+
+- The region is ONLY the default for the app's new instances. Changing it
+ moves nothing: every instance that exists stays where it is. Only
+ instances created after the change, with no region named, start in the
+ new region. Every string that reports a change must leave no doubt about
+ that.
+- Placeholders that print a region print its label, for example
+ "London (uk)" or "Dublin (ie)"; AR-6, AR-7, AR-19 and AR-20 print the code
+ the person typed, and their lists are codes ("ie, uk").
+- Who may change it: an owner of the account, or a deployment operator.
+ Members and service credentials may not. Any member may read it.
+- Refusals: a region the platform does not offer (AR-6), one that cannot
+ start instances right now (AR-19, its bracket is one of "no box runs
+ there now", "boxes there can't start instances", "boxes there can't open
+ this deployment's secrets", "boxes there don't take ordinary instances"),
+ one the app's instances may not use (AR-7), an app on a fleet (AR-3: the
+ fleet decides; `carlos apps place` changes that), an app whose instances
+ start in a pool (AR-4: the region would not be used), an app in the Trash
+ (AR-2), a console with host claims on (AR-21). Nothing is written when
+ any of these is refused.
+- AR-8 is a race: someone else changed the app (its region, or deleted or
+ replaced it) while the command ran. Running it again is the fix.
+- AR-11 is a row on the app's Activity page, for example
+ "changed shop's region from Dublin (ie) to London (uk)".
+- AR-12 follows "This app's region is London (uk)." on the settings page,
+ in place of "Chosen when the app was created."
+- `carlos deploy --region` on an existing app must name the app's current
+ region, or deploy stops before shipping anything (AR-42, AR-43).
+
+## Output
+
+Do not edit any file. Answer with one markdown table, `| key | new | why |`,
+one row per deck id, every id included, `unchanged` in why when you keep a
+string as it is. Then a short **Flags** list for anything you could not fix
+within these rules (a fact you think is wrong, a placeholder that must
+move, a string that should be split). Nothing else.
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md b/docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md
new file mode 100644
index 000000000..9aab9ea44
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md
@@ -0,0 +1,71 @@
+# Luna copy result: carlos apps region (app-region-set)
+
+Approved by delegation (Luna). Model gpt-5.6-luna via codex, reasoning high, read-only, run 2026-10-26 against docs/superpowers/specs/LUNA-COPY-BRIEF-APP-REGION-SET.md and the deck docs/superpowers/notes/copy-app-region-set.md (commit 1f11e665). Applied verbatim. Luna flagged nothing.
+
+The brief asked for full stops on form labels and buttons by mistake, so Luna's AR-15 and AR-16 ended in one. A follow-up pass with that rule corrected (label and button take no final full stop, like the neighbouring Change fleet button) answered the second table below, and that is what is applied.
+
+## Pass 1
+
+| key | new | why |
+|---|---|---|
+| AR-1 | only an account owner or a deployment operator can change an app's region | unchanged |
+| AR-2 | %s is in the Trash. restore it before you change its region | lower-case continuation; no final stop |
+| AR-3 | %s runs on your fleet %s, which decides where its instances run. use carlos apps place to change that | lower-case continuation; no final stop |
+| AR-4 | %s starts its instances in a pool, so an app region would not be used. nothing was changed | lower-case continuation; no final stop |
+| AR-5 | name the region to set, for example --set uk | unchanged |
+| AR-6 | region %s is not offered by this platform. choose from: %s | plainer wording; required casing |
+| AR-6b | region %s is not offered by this platform right now | plainer wording |
+| AR-7 | region %s cannot be used by this app's instances. allowed: %s | plainer wording; required casing |
+| AR-7b | region %s cannot be used by this app's instances, and none of the regions this app can use is offered right now | plainer wording |
+| AR-8 | this app's region changed while this ran. run it again | lower-case continuation; no final stop |
+| AR-9 | could not read this app's instance policy, so its region was not changed. try again | lower-case continuation; no final stop |
+| AR-9b | could not read the regions this platform offers, so the app's region was not changed. try again | lower-case continuation; no final stop |
+| AR-10 | could not change this app's region. nothing was changed. try again | lower-case continuation; no final stop |
+| AR-11 | changed %s's region from %s to %s | unchanged |
+| AR-12 | Changed after the app was created. | unchanged |
+| AR-13 | New instances now start in %s. Existing instances stay where they are. | unchanged |
+| AR-14 | This app's region is already %s. | unchanged |
+| AR-15 | Region for new instances. | added required full stop |
+| AR-16 | Change region. | added required full stop |
+| AR-17 | Changing the region moves nothing. Only instances created after the change start in the new region. | unchanged |
+| AR-19 | region %s can't start new instances right now (%s), so the app's region was not changed | aligned wording with the stated fact; no final stop |
+| AR-20 | could not confirm that region %s can start new instances, so the app's region was not changed. try again | lower-case continuation; no final stop |
+| AR-21 | changing an app's region is not supported on a console with host claims on | unchanged |
+| AR-30 | usage: carlos apps region --app <name> [--set <region>] [--account <sqid\|name>] [--account-id <sqid>] [--console <origin>] | unchanged |
+| AR-31 | the region where this app's new instances start. existing instances stay where they are. only account owners and deployment operators can change it | clearer flag help |
+| AR-32 | %s's region is %s. new instances start there. | unchanged |
+| AR-33 | %s runs on your fleet %s, which decides where its instances run. | unchanged |
+| AR-34 | %s's region changed from %s to %s. new instances start in %s. existing instances stay where they are. | unchanged |
+| AR-35 | %s's region is already %s. nothing changed. | unchanged |
+| AR-36 | apps region works through a console, and this shell is in direct bucket mode (CARLOS_DEPLOYMENT_BUCKET or CARLOS_DEPLOYMENT_DIR is set). log in instead: carlos auth login --console <url> | unchanged |
+| AR-37 | not found: either %s is not an app in this account, or this console is too old for carlos apps region (deploy a console built from current main) | plainer wording |
+| AR-38 | region --app <name> [--set <region>] show the region where the app's new<br> instances start, or change it with --set. existing<br> instances stay where they are. changing it is for account<br> owners and deployment operators. | clearer wording; preserved indentation and line breaks |
+| AR-40 | `carlos apps list` shows each app's own region, the region where its new instances start. For an app with a region, it shows the region set when the app was created or changed later. For an app on a fleet, it shows the fleet instead. Where new instances start can differ from where existing instances run. For a pooled app, the app's Running page in the console shows where its instances start. | clarified region, fleet, pooled, and existing-instance behavior |
+| AR-41 | `carlos apps region` shows where an app's new instances start, and `--set` changes that default: | clarified that the region is the default for new instances |
+| AR-42 | An app's region is only where its new instances start. Changing it moves nothing: instances that already exist stay where they are, and only instances created afterwards start in the new region. Use `carlos move` to move one that exists. The new region must be one the platform offers, able to start instances now, and allowed for this app's instances. An app on a fleet is refused because the fleet decides where its instances run. Use `carlos apps place` instead. The command also refuses an app whose instances start in a pool or an app in the Trash. Account owners and deployment operators can change the region with this command or in the Region section of the app's settings in the console. The console records who changed it, from what and to what, in the app's activity. After a change, `carlos deploy --region` must name the app's current region. | clarified restrictions and deploy behavior |
+| AR-43 | That is the app's current region after any `carlos apps region --set`. If `carlos deploy --region` names another region, deploy stops before shipping anything. Deploy never moves an instance to match the app's region. | made the deploy constraint explicit |
+
+**Flags**
+
+- None.
+## Pass 2 (AR-15, AR-16)
+
+| key | new | why |
+|---|---|---|
+| AR-15 | Region for new instances | Form label; no final full stop. |
+| AR-16 | Change region | Button label; no final full stop, matching “Change fleet”. |
+
+**Flags**
+
+- None.
+## Pass 3 (after Astra round 1: AR-22 new, AR-32 and AR-42 revised)
+
+| key | new | why |
+|---|---|---|
+| AR-22 | this console names no home region (CONSOLE_HOME_REGION is unset), so an app's region cannot be changed | added the missing refusal reason |
+| AR-32 | %s's region is %s. for apps not using a pool, new instances start there; pooled apps start new instances in the home region | avoids claiming the region always controls new instances |
+| AR-42 | An app's region sets where its new instances start, except for apps whose instances start in a pool. Those instances start in the home region instead. Changing the region moves nothing: existing instances stay where they are, and only instances created afterwards start in the new region when the app uses its region. Use `carlos move` to move one that exists. The new region must be one the platform offers, able to start instances now, and allowed for this app's instances. An app on a fleet is refused because the fleet decides where its instances run. Use `carlos apps place` instead. The command also refuses an app whose instances start in a pool because the app's region does not decide where its new instances start. It also refuses an app in the Trash. Account owners and deployment operators can change the region with this command. In the console, the Region control is on the app's settings page, which only account members can open. Owners and deployment operators who are members can use the control. A deployment operator who is not a member must use the command. The console records who changed it, from what and to what, in the app's activity. After a change, `carlos deploy --region` must name the app's current region. | corrected pooled-app behavior and console access rules |
+
+**Flags**
+
+- The overlap check could not reach its service because network/DNS access was blocked. No files were edited.
\ No newline at end of file
diff --git a/internal/console/appregionset.go b/internal/console/appregionset.go
new file mode 100644
index 000000000..7a82647a5
--- /dev/null
+++ b/internal/console/appregionset.go
@@ -0,0 +1,477 @@
+package console
+
+// Changing an existing app's region (Paul, 2026-10-26): `carlos apps region`
+// and the Region control on the app's Settings > General page. The stored
+// region (apps.region) is ONLY the default for the app's new instances:
+// nothing reads it to place an instance that exists, so a change moves
+// nothing. Its readers: the instance create door (apiinstances.go, a create
+// naming no region), the app_default answer on /regions that deploy
+// --region and canary --region compare against (regiondefault.go), the
+// region labels (regionfacts.go) and the placement discrepancy log
+// (regiondrift.go, which reads region_set_at).
+//
+// Who may: an owner of the account, or a deployment operator (an owner of
+// the ops account, or an address on CARLOS_SYSTEM_OPERATORS:
+// platformOperator), who need not be a member. A member is refused, and a
+// service credential never reaches the door (svcrole.Set{}). Every refusal
+// comes before the write, and the write is SQLite only: no bucket object
+// and no serial bump, because no box reads apps.region.
+//
+// The switch: the write is allowed with CONSOLE_APP_REGIONS off. The create
+// door honours the stored region with the switch off (apiinstances.go), and
+// Paul accepted writing it with the switch off for member moves (member
+// moves design §18, Q5), so the value is used either way.
+
+import (
+ "context"
+ "crypto/subtle"
+ "fmt"
+ "log"
+ "net/http"
+ "net/url"
+ "slices"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/regionlabel"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// appRegionSetCopy is every string this file adds (deck
+// docs/superpowers/notes/copy-app-region-set.md; approved by delegation,
+// Luna pass 2026-10-26, docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md).
+type appRegionSetCopyStrings struct {
+ NotOwner string // AR-1
+ InTrash string // AR-2: app
+ OnFleet string // AR-3: app, fleet name
+ Pooled string // AR-4: app
+ NoRegion string // AR-5
+ NotOffered string // AR-6: code, list
+ NotOfferedNone string // AR-6b: code
+ NotAllowed string // AR-7: code, list
+ NotAllowedNone string // AR-7b: code
+ ClaimOff string // AR-21
+ NoHome string // AR-22
+ Unavailable string // AR-19: code, reason text (R-*)
+ Unconfirmed string // AR-20: code
+ Changed string // AR-8
+ PolicyUnread string // AR-9
+ OptionsUnread string // AR-9b
+ WriteFailed string // AR-10
+ AuditChanged string // AR-11: app, old label, new label
+ SourceChanged string // AR-12
+ FlashChanged string // AR-13: new label
+ FlashSame string // AR-14: label
+ ControlLabel string // AR-15
+ ControlButton string // AR-16
+ ControlNote string // AR-17
+}
+
+var appRegionSetCopy = appRegionSetCopyStrings{
+ NotOwner: "only an account owner or a deployment operator can change an app's region",
+ InTrash: "%s is in the Trash. restore it before you change its region",
+ OnFleet: "%s runs on your fleet %s, which decides where its instances run. use carlos apps place to change that",
+ Pooled: "%s starts its instances in a pool, so an app region would not be used. nothing was changed",
+ NoRegion: "name the region to set, for example --set uk",
+ NotOffered: "region %s is not offered by this platform. choose from: %s",
+ NotOfferedNone: "region %s is not offered by this platform right now",
+ NotAllowed: "region %s cannot be used by this app's instances. allowed: %s",
+ NotAllowedNone: "region %s cannot be used by this app's instances, and none of the regions this app can use is offered right now",
+ ClaimOff: "changing an app's region is not supported on a console with host claims on",
+ NoHome: "this console names no home region (CONSOLE_HOME_REGION is unset), so an app's region cannot be changed",
+ Unavailable: "region %s can't start new instances right now (%s), so the app's region was not changed",
+ Unconfirmed: "could not confirm that region %s can start new instances, so the app's region was not changed. try again",
+ Changed: "this app's region changed while this ran. run it again",
+ PolicyUnread: "could not read this app's instance policy, so its region was not changed. try again",
+ OptionsUnread: "could not read the regions this platform offers, so the app's region was not changed. try again",
+ WriteFailed: "could not change this app's region. nothing was changed. try again",
+ AuditChanged: "changed %s's region from %s to %s",
+ SourceChanged: "Changed after the app was created.",
+ FlashChanged: "New instances now start in %s. Existing instances stay where they are.",
+ FlashSame: "This app's region is already %s.",
+ ControlLabel: "Region for new instances",
+ ControlButton: "Change region",
+ ControlNote: "Changing the region moves nothing. Only instances created after the change start in the new region.",
+}
+
+// appRegionView is the door's answer. region is the display code (the
+// home's name for the home), label its region label.
+type appRegionView struct {
+ App string `json:"app"`
+ Region string `json:"region"`
+ Label string `json:"label"`
+ Source string `json:"source,omitempty"`
+ Fleet string `json:"fleet,omitempty"`
+ Previous string `json:"previous,omitempty"`
+ PreviousLabel string `json:"previous_label,omitempty"`
+ Changed bool `json:"changed"`
+}
+
+// appRegionCaller resolves the account a person may read or change an app's
+// region in. A deployment operator reaches any account by an exact sqid
+// (?exact=sqid, which the CLI always sends); anyone else, and any other
+// reference, goes through apiPrincipalAccount, so a name is only ever
+// matched against the caller's own memberships and a sqid can never take
+// over a name (apicli.go's symmetric resolution), so an unknown account and someone
+// else's are the family's byte-identical 404. write adds the owner rule
+// (apiOwnerAccountFor's: a member gets a 403, since membership is already
+// proved). A service principal never gets here (the route allows no role);
+// it is refused again here all the same.
+func (s *Server) appRegionCaller(w http.ResponseWriter, r *http.Request, write bool) (addr string, acct *Account, ok bool) {
+ p, pok := principalFrom(r.Context())
+ if !pok || p.Kind != PrincipalUser {
+ http.NotFound(w, r)
+ return "", nil, false
+ }
+ if s.principalPlatformOperator(p) && exactSqidAsked(r) {
+ a, err := s.store.AccountBySqid(r.PathValue("account"))
+ if err != nil {
+ log.Printf("console: app region: account: %v", err)
+ jsonError(w, http.StatusInternalServerError, "could not load accounts")
+ return "", nil, false
+ }
+ if a != nil {
+ return p.Address, a, true
+ }
+ // No such account: the member path answers the family's 404.
+ }
+ p, acct, ok = s.apiPrincipalAccount(w, r)
+ if !ok {
+ return "", nil, false
+ }
+ if write && acct.Role != RoleOwner && !s.principalPlatformOperator(p) {
+ jsonError(w, http.StatusForbidden, appRegionSetCopy.NotOwner)
+ return "", nil, false
+ }
+ return p.Address, acct, true
+}
+
+// exactSqidAsked is the ?exact=sqid switch (--account-id, and every
+// reference the CLI has resolved), read as apiPrincipalAccount reads it.
+func exactSqidAsked(r *http.Request) bool {
+ v, _ := url.ParseQuery(r.URL.RawQuery)
+ return v.Get("exact") == "sqid"
+}
+
+// appRegionApp is the {app} half: a live app and the incarnation the
+// request found, or the Trash refusal for a trashed one (the caller may
+// already see the Trash), else the bare 404.
+func (s *Server) appRegionApp(w http.ResponseWriter, r *http.Request, acct *Account) (string, AppIncarnation, bool) {
+ app := r.PathValue("app")
+ inc, live, err := s.store.AppIncarnationContext(r.Context(), acct.ID, app)
+ if err != nil {
+ log.Printf("console: app region %s/%s: has app: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusInternalServerError, msgAppRegionUnreadable)
+ return "", AppIncarnation{}, false
+ }
+ if live {
+ return app, inc, true
+ }
+ trashed, err := s.store.HasTrashedAppIn(acct.ID, app)
+ if err != nil {
+ log.Printf("console: app region %s/%s: has trashed app: %v", acct.Sqid, app, err)
+ }
+ if err == nil && trashed {
+ jsonError(w, http.StatusConflict, fmt.Sprintf(appRegionSetCopy.InTrash, app))
+ return "", AppIncarnation{}, false
+ }
+ http.NotFound(w, r)
+ return "", AppIncarnation{}, false
+}
+
+// handleAPIAppRegionGet is GET /api/cli/apps/{account}/{app}/region: the
+// stored region and its label, or the fleet that governs. SQLite and the
+// registry only.
+func (s *Server) handleAPIAppRegionGet(w http.ResponseWriter, r *http.Request) {
+ _, acct, ok := s.appRegionCaller(w, r, false)
+ if !ok {
+ return
+ }
+ app, _, ok := s.appRegionApp(w, r, acct)
+ if !ok {
+ return
+ }
+ // The same placement the change door refuses on (appPolicy's
+ // appPlacement: the stored column, else the registry's legacy rows).
+ placed := ""
+ reg, err := openRegistry(s.cfg.Registry)
+ if err == nil {
+ placed, err = s.appPlacement(reg, acct, app)
+ }
+ if err != nil {
+ log.Printf("console: app region %s/%s: placement: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, msgAppRegionUnreadable)
+ return
+ }
+ if name, ok := registry.FleetPlacement(placed); ok {
+ l := regionlabel.ForCode(placed, s.regionHome(), s.regionNames())
+ writeJSON(w, http.StatusOK, appRegionView{App: app, Region: l.Code, Label: l.Text, Fleet: name})
+ return
+ }
+ region, source, err := s.appRegion(acct.ID, app)
+ if err != nil {
+ log.Printf("console: app region %s/%s: read: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, msgAppRegionUnreadable)
+ return
+ }
+ l := regionlabel.ForCode(region, s.regionHome(), s.regionNames())
+ writeJSON(w, http.StatusOK, appRegionView{App: app, Region: l.Code, Label: l.Text, Source: source})
+}
+
+// handleAPIAppRegionSet is PUT /api/cli/apps/{account}/{app}/region with
+// {"region": "<code>"}.
+func (s *Server) handleAPIAppRegionSet(w http.ResponseWriter, r *http.Request) {
+ addr, acct, ok := s.appRegionCaller(w, r, true)
+ if !ok {
+ return
+ }
+ app, inc, ok := s.appRegionApp(w, r, acct)
+ if !ok {
+ return
+ }
+ p, _ := principalFrom(r.Context())
+ if !s.allowWrite(p, time.Now()) {
+ jsonError(w, http.StatusTooManyRequests, "too many requests. Wait a minute and try again")
+ return
+ }
+ var req struct {
+ Region string `json:"region"`
+ }
+ if !readJSONStrictLimit(w, r, &req, 8<<10) {
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
+ defer cancel()
+ v, ref := s.setAppRegion(ctx, acct, app, inc, req.Region, addr, "cli")
+ if ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ writeJSON(w, http.StatusOK, v)
+}
+
+// setAppRegion is both doors' mechanism. Every refusal is checked before
+// the write. found is the incarnation the request resolved: the write holds
+// the app lock (which a rename, purge, trash or create also takes), checks
+// that the name still names that incarnation, and lands on it and the
+// region it read, or not at all. via is appended to the audit line ("cli"
+// or "" for the browser).
+func (s *Server) setAppRegion(ctx context.Context, acct *Account, app string, found AppIncarnation, raw, addr, via string) (appRegionView, *doorRefusal) {
+ // A host-claim console gates every app-row write through a claim
+ // operation, and this one has none: refused before anything is read
+ // (host claims are shelved; claimRenameUnsupportedMsg is the precedent).
+ if s.cfg.HostClaim {
+ return appRegionView{}, &doorRefusal{http.StatusConflict, appRegionSetCopy.ClaimOff}
+ }
+ // With no home named, the home has no code to choose, so a change away
+ // from it could never be undone here.
+ if s.regionHome() == "" {
+ return appRegionView{}, &doorRefusal{http.StatusConflict, appRegionSetCopy.NoHome}
+ }
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return appRegionView{}, &doorRefusal{http.StatusBadRequest, appRegionSetCopy.NoRegion}
+ }
+ code := s.homeRegionIn(raw)
+ choices, ref := s.appRegionChoices(ctx)
+ if ref != nil {
+ return appRegionView{}, ref
+ }
+ if (code != "" && !provision.ValidRegion(code)) || !slices.Contains(choices, s.homeRegionOut(code)) {
+ if len(choices) == 0 {
+ return appRegionView{}, &doorRefusal{http.StatusBadRequest, fmt.Sprintf(appRegionSetCopy.NotOfferedNone, raw)}
+ }
+ return appRegionView{}, &doorRefusal{http.StatusBadRequest, fmt.Sprintf(appRegionSetCopy.NotOffered, raw, strings.Join(choices, ", "))}
+ }
+ // The region must also be able to take an instance now, by the same
+ // positive test the create door puts an app-derived region to
+ // (apiinstances.go): otherwise every create naming no region would be
+ // refused after the change. The home needs no evidence.
+ if code != "" {
+ snap, err := s.liveEdges(ctx)
+ if err != nil || !snap.EvidenceComplete() {
+ if err != nil {
+ log.Printf("console: app region %s/%s: read edges: %v", acct.Sqid, app, err)
+ }
+ return appRegionView{}, &doorRefusal{http.StatusServiceUnavailable, fmt.Sprintf(appRegionSetCopy.Unconfirmed, raw)}
+ }
+ reason := "absent"
+ if c, ok := findCandidate(s.regionCands(snap), code); ok {
+ reason = c.unavailableReason()
+ }
+ if reason != "" {
+ return appRegionView{}, &doorRefusal{http.StatusConflict, fmt.Sprintf(appRegionSetCopy.Unavailable, raw, reasonText(reason))}
+ }
+ }
+ pol := s.appPolicy(ctx, acct, app)
+ switch {
+ case pol.State == policyUnreadable:
+ return appRegionView{}, &doorRefusal{http.StatusBadGateway, appRegionSetCopy.PolicyUnread}
+ case pol.Placed != "":
+ name, _ := strings.CutPrefix(pol.Placed, "fleet/")
+ return appRegionView{}, &doorRefusal{http.StatusConflict, fmt.Sprintf(appRegionSetCopy.OnFleet, app, name)}
+ case pol.pooled():
+ return appRegionView{}, &doorRefusal{http.StatusConflict, fmt.Sprintf(appRegionSetCopy.Pooled, app)}
+ case !pol.allows(code):
+ var allowed []string
+ for _, c := range choices {
+ if pol.allows(s.homeRegionIn(c)) {
+ allowed = append(allowed, c)
+ }
+ }
+ if len(allowed) == 0 {
+ return appRegionView{}, &doorRefusal{http.StatusConflict, fmt.Sprintf(appRegionSetCopy.NotAllowedNone, raw)}
+ }
+ return appRegionView{}, &doorRefusal{http.StatusConflict, fmt.Sprintf(appRegionSetCopy.NotAllowed, raw, strings.Join(allowed, ", "))}
+ }
+
+ defer s.lockApp(acct.Sqid, app)()
+ inc, live, err := s.store.AppIncarnationContext(ctx, acct.ID, app)
+ if err != nil {
+ log.Printf("console: app region %s/%s: incarnation: %v", acct.Sqid, app, err)
+ return appRegionView{}, &doorRefusal{http.StatusInternalServerError, appRegionSetCopy.WriteFailed}
+ }
+ if !live || inc != found {
+ return appRegionView{}, &doorRefusal{http.StatusConflict, appRegionSetCopy.Changed}
+ }
+ from, fromSource, err := s.store.AppRegion(acct.ID, app)
+ if err != nil {
+ log.Printf("console: app region %s/%s: read: %v", acct.Sqid, app, err)
+ return appRegionView{}, &doorRefusal{http.StatusBadGateway, msgAppRegionUnreadable}
+ }
+ home, names := s.regionHome(), s.regionNames()
+ newLabel := regionlabel.ForCode(code, home, names)
+ v := appRegionView{App: app, Region: s.homeRegionOut(code), Label: newLabel.Text, Source: "changed"}
+ if from == code {
+ v.Source = fromSource
+ return v, nil
+ }
+ oldLabel := regionlabel.ForCode(from, home, names)
+ ok, err := s.store.SetAppRegion(ctx, acct.ID, app, inc, from, code, time.Now())
+ if err != nil {
+ log.Printf("console: app region %s/%s: write: %v", acct.Sqid, app, err)
+ return appRegionView{}, &doorRefusal{http.StatusInternalServerError, appRegionSetCopy.WriteFailed}
+ }
+ if !ok {
+ return appRegionView{}, &doorRefusal{http.StatusConflict, appRegionSetCopy.Changed}
+ }
+ detail := fmt.Sprintf(appRegionSetCopy.AuditChanged, app, oldLabel.Text, newLabel.Text)
+ if via != "" {
+ detail += " (" + via + ")"
+ }
+ s.audit(acct, app, addr, "region", detail)
+ v.Previous, v.PreviousLabel, v.Changed = s.homeRegionOut(from), oldLabel.Text, true
+ return v, nil
+}
+
+// appRegionChoices is the regions an app's region may be set to, as display
+// codes, sorted: exactly the list the create door's explicit --region
+// accepts (explicitChoices: the home, and every published region that is
+// armed, hosting and not without the secrets key). One read of the edges
+// files, per change; never on a page view.
+func (s *Server) appRegionChoices(ctx context.Context) ([]string, *doorRefusal) {
+ if s.cfg.Releases == nil {
+ return nil, &doorRefusal{http.StatusServiceUnavailable, appRegionSetCopy.OptionsUnread}
+ }
+ return s.explicitChoices(s.readExplicitGate(ctx)), nil
+}
+
+// appRegionPageChoices is the Region control's options: the home and every
+// code the console's region name map knows (regionnames.go), held in memory,
+// so a page view reads no store. The door checks the choice when it is sent.
+func (s *Server) appRegionPageChoices() []regionOption {
+ home, names := s.regionHome(), s.regionNames()
+ set := map[string]bool{}
+ if home != "" {
+ set[home] = true
+ }
+ for _, c := range names.Codes() {
+ set[c] = true
+ }
+ out := make([]regionOption, 0, len(set))
+ for c := range set {
+ out = append(out, regionOption{Value: c, Label: regionlabel.ForCode(s.homeRegionIn(c), home, names).Text})
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].Value < out[j].Value })
+ return out
+}
+
+// AppRegionSetCopy hands the Region control its strings.
+func (p page) AppRegionSetCopy() appRegionSetCopyStrings { return appRegionSetCopy }
+
+// canSetAppRegion is the browser's form of the rule: an owner, or a
+// deployment operator. The browser reaches only accounts the person is a
+// member of (accountApp), so an operator who is no member uses the CLI.
+func (s *Server) canSetAppRegion(addr, role string) bool {
+ return role == RoleOwner || s.platformOperator(addr)
+}
+
+// handleAppRegionSet is POST /a/{sqid}/apps/{app}/region, the Settings >
+// General control: session, CSRF, then the owner-or-operator rule, whose
+// refusal is the same 404 a non-member gets.
+func (s *Server) handleAppRegionSet(w http.ResponseWriter, r *http.Request) {
+ addr, raw, acct, role, app, found, ok := s.accountAppIncarnation(w, r)
+ if !ok {
+ return
+ }
+ if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
+ return
+ }
+ if !s.canSetAppRegion(addr, role) {
+ http.NotFound(w, r)
+ return
+ }
+ if s.cfg.HostClaim {
+ s.renderMessage(w, r, http.StatusConflict, "Not available", appRegionSetCopy.ClaimOff)
+ return
+ }
+ back := func(kind, msg string) {
+ s.setFlash(w, kind, msg)
+ http.Redirect(w, r, appSettingsURL(acct.Sqid, app, "general"), http.StatusSeeOther)
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
+ defer cancel()
+ v, ref := s.setAppRegion(ctx, acct, app, found, r.FormValue("region"), addr, "")
+ if ref != nil {
+ back("err", sentenceCase(ref.Msg))
+ return
+ }
+ if !v.Changed {
+ back("ok", fmt.Sprintf(appRegionSetCopy.FlashSame, v.Label))
+ return
+ }
+ back("ok", fmt.Sprintf(appRegionSetCopy.FlashChanged, v.Label))
+}
+
+// accountAppIncarnation is accountApp whose existence check IS the
+// incarnation read: the app the browser door resolves, before it reads the
+// form body, is the one setAppRegion must find again under its locks.
+// Every answer is accountApp's, byte for byte.
+func (s *Server) accountAppIncarnation(w http.ResponseWriter, r *http.Request) (addr, raw string, acct *Account, role, app string, inc AppIncarnation, ok bool) {
+ addr, raw, acct, role, ok = s.account(w, r)
+ if !ok {
+ return "", "", nil, "", "", AppIncarnation{}, false
+ }
+ app = r.PathValue("app")
+ inc, live, err := s.store.AppIncarnationContext(r.Context(), acct.ID, app)
+ if err != nil {
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read your apps. Please try again.")
+ return "", "", nil, "", "", AppIncarnation{}, false
+ }
+ if !live {
+ s.renderMessage(w, r, http.StatusNotFound, "Not found", "No such app here.")
+ return "", "", nil, "", "", AppIncarnation{}, false
+ }
+ return addr, raw, acct, role, app, inc, true
+}
+
+// sentenceCase capitalizes a door message's first letter for a flash.
+func sentenceCase(msg string) string {
+ if msg == "" || msg[0] < 'a' || msg[0] > 'z' {
+ return msg
+ }
+ return strings.ToUpper(msg[:1]) + msg[1:]
+}
diff --git a/internal/console/appregionset_test.go b/internal/console/appregionset_test.go
new file mode 100644
index 000000000..9cb5f56dc
--- /dev/null
+++ b/internal/console/appregionset_test.go
@@ -0,0 +1,676 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// appRegionFx is the console fixture with HomeRegion ie, two boxes
+// publishing themselves (the home box in eu-west-1 and a uk box in
+// eu-west-2, both armed), a region name map read from them, and a tenant
+// account cdef holding the app shop, owned by owner@example.test with
+// member@example.test as a member. paul@keymail.dev owns the ops account,
+// so he is a deployment operator and no member of cdef.
+type appRegionFx struct {
+ *consoleFixture
+ acct *Account
+}
+
+const (
+ arSqid = "cdef"
+ arOwner = "owner@example.test"
+ arMember = "member@example.test"
+)
+
+func newAppRegionFx(t *testing.T) *appRegionFx {
+ t.Helper()
+ return newAppRegionFxWith(t, nil)
+}
+
+// newAppRegionFxWith is newAppRegionFx with the console's handler wrapped.
+func newAppRegionFxWith(t *testing.T, wrap func(http.Handler) http.Handler) *appRegionFx {
+ t.Helper()
+ fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, Wrap: wrap})
+ fx.srv.cfg.HomeRegion = "ie"
+ pub, _, _ := sealedFor(t, "irrelevant")
+ fx.srv.cfg.SecretsPub = pub
+ ctx := context.Background()
+ for _, b := range []struct{ box, placement, aws, eip string }{
+ {"ie-machine", "", "eu-west-1", "192.0.2.10"},
+ {"uk-machine", "uk", "eu-west-2", "192.0.2.11"},
+ // Published, but with no dial address: known and not armed.
+ {"us-machine", "us", "us-east-1", ""},
+ // Armed, but serving named pools only: offered by the explicit
+ // gate, and no box there can take an ordinary instance.
+ {"fr-machine", "fr", "eu-west-3", "192.0.2.13"},
+ } {
+ publishAppRegionBox(t, fx, b.box, b.placement, b.aws, b.eip, b.box == "fr-machine")
+ }
+ if !fx.srv.LoadRegionNames(ctx) {
+ t.Fatal("the console did not read its region names")
+ }
+ now := time.Now()
+ if err := fx.st.CreateAccount(42, arSqid, "Shop Co", arOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.AddMember(42, arMember, RoleMember, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(42, "shop", arOwner, now.Add(-time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ acct, err := fx.st.AccountBySqid(arSqid)
+ if err != nil || acct == nil {
+ t.Fatalf("account: %v %v", acct, err)
+ }
+ return &appRegionFx{consoleFixture: fx, acct: acct}
+}
+
+// publishAppRegionBox writes a box's edges file, every eligibility field
+// positively true, and a fresh status snapshot for it.
+func publishAppRegionBox(t *testing.T, fx *consoleFixture, box, placement, aws, eip string, poolsOnly bool) {
+ t.Helper()
+ ctx := context.Background()
+ body, err := json.Marshal(map[string]any{
+ "v": 1, "box": box, "box_id": box, "eip": eip, "region": aws, "placement": placement,
+ "hibernation_configured": true, "serves_shared_pool": !poolsOnly, "accepts_inbound": true,
+ "secrets_key_fp": fx.srv.expectedSecretsFP(), "hosts": map[string]any{},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.rel.Put(ctx, edgesfile.Key(box), body, ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := status.WriteBox(ctx, fx.rel, status.Box{Label: box, GeneratedAt: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func (fx *appRegionFx) put(t *testing.T, token, app, region string) (int, string) {
+ t.Helper()
+ st, _, out := rawReq(t, http.MethodPut, fx.ts.URL+"/api/cli/apps/"+arSqid+"/"+app+"/region?exact=sqid", token,
+ fmt.Sprintf(`{"region":%q}`, region))
+ return st, out
+}
+
+func (fx *appRegionFx) get(t *testing.T, token, app string) (int, string) {
+ t.Helper()
+ st, _, out := rawReq(t, http.MethodGet, fx.ts.URL+"/api/cli/apps/"+arSqid+"/"+app+"/region?exact=sqid", token, "")
+ return st, out
+}
+
+func (fx *appRegionFx) stored(t *testing.T, app string) (string, string) {
+ t.Helper()
+ r, src, err := fx.st.AppRegion(42, app)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return r, src
+}
+
+func (fx *appRegionFx) regionEvents(t *testing.T, app string) []Event {
+ t.Helper()
+ evs, err := fx.st.Events(42, app, 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []Event
+ for _, e := range evs {
+ if e.Action == "region" {
+ out = append(out, e)
+ }
+ }
+ return out
+}
+
+func decodeRegionView(t *testing.T, out string) appRegionView {
+ t.Helper()
+ var v appRegionView
+ if err := json.Unmarshal([]byte(out), &v); err != nil {
+ t.Fatalf("reply %q: %v", out, err)
+ }
+ return v
+}
+
+// Authorization: an owner may, a deployment operator may (an ops owner and
+// an address on CARLOS_SYSTEM_OPERATORS, neither a member), a member is
+// refused with the owner sentence, a service credential is refused by the
+// role gate, and an owner of another account gets the bare 404. Nothing a
+// refused caller sends is written or audited.
+func TestAppRegionSetAuthorization(t *testing.T) {
+ fx := newAppRegionFx(t)
+ fx.srv.cfg.SystemOperators = []string{"sysop@example.test"}
+ now := time.Now()
+ if err := fx.st.CreateAccount(43, "efgh", "Other Co", "other@example.test", now); err != nil {
+ t.Fatal(err)
+ }
+ owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner")
+ member := cliToken(t, fx.consoleFixture, arMember, "code-ar-member")
+ other := cliToken(t, fx.consoleFixture, "other@example.test", "code-ar-other")
+ sysop := cliToken(t, fx.consoleFixture, "sysop@example.test", "code-ar-sysop")
+ opsOwner := cliToken(t, fx.consoleFixture, "paul@keymail.dev", "code-ar-ops")
+ _, bare := getRaw(t, fx.ts.URL+"/api/cli/apps/zzzz/nosuch/region", other)
+
+ if st, out := fx.put(t, member, "shop", "uk"); st != http.StatusForbidden || !strings.Contains(out, appRegionSetCopy.NotOwner) {
+ t.Fatalf("member = %d %s, want 403 with the owner sentence", st, out)
+ }
+ if st, out := fx.put(t, other, "shop", "uk"); st != http.StatusNotFound || out != bare {
+ t.Fatalf("another account's owner = %d %q, want the bare 404 %q", st, out, bare)
+ }
+ for _, role := range []svcrole.Role{svcrole.Admin, svcrole.Publish, svcrole.Instance, svcrole.Operate} {
+ svc := serviceToken(t, fx.st, 42, "svc-"+string(role), "shop", role)
+ if st, out := fx.put(t, svc, "shop", "uk"); st != http.StatusForbidden {
+ t.Fatalf("service %s = %d %s, want 403", role, st, out)
+ }
+ if st, out := fx.get(t, svc, "shop"); st != http.StatusForbidden {
+ t.Fatalf("service %s GET = %d %s, want 403", role, st, out)
+ }
+ }
+ if r, _ := fx.stored(t, "shop"); r != "" {
+ t.Fatalf("a refused caller changed the region to %q", r)
+ }
+ if evs := fx.regionEvents(t, "shop"); len(evs) != 0 {
+ t.Fatalf("refused callers audited %d rows", len(evs))
+ }
+ // A member may read the region; another account may not.
+ if st, out := fx.get(t, member, "shop"); st != http.StatusOK || decodeRegionView(t, out).Label != "Dublin (ie)" {
+ t.Fatalf("member GET = %d %s", st, out)
+ }
+ if st, out := fx.get(t, other, "shop"); st != http.StatusNotFound || out != bare {
+ t.Fatalf("another account's GET = %d %q", st, out)
+ }
+
+ for i, c := range []struct {
+ who, token, to string
+ }{
+ {arOwner, owner, "uk"},
+ {"paul@keymail.dev", opsOwner, "ie"},
+ {"sysop@example.test", sysop, "uk"},
+ } {
+ st, out := fx.put(t, c.token, "shop", c.to)
+ if st != http.StatusOK {
+ t.Fatalf("%s = %d %s, want 200", c.who, st, out)
+ }
+ v := decodeRegionView(t, out)
+ if !v.Changed || v.Region != c.to {
+ t.Fatalf("%s reply = %+v", c.who, v)
+ }
+ evs := fx.regionEvents(t, "shop")
+ if len(evs) != i+1 || evs[0].Address != c.who {
+ t.Fatalf("%s: audit rows %+v", c.who, evs)
+ }
+ }
+ if r, src := fx.stored(t, "shop"); r != "uk" || src != "changed" {
+ t.Fatalf("stored = %q %q, want uk changed", r, src)
+ }
+}
+
+// The change is a SQLite write: no bucket object is written, changed or
+// removed, so no box sees anything and no instance record moves. The audit
+// row carries the old and the new region.
+func TestAppRegionSetWritesOnlyTheRowAndAudits(t *testing.T) {
+ fx := newAppRegionFx(t)
+ owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner")
+ ctx := context.Background()
+ if err := provision.CreateRecord(ctx, fx.rel, provision.Record{Schema: 1, Host: "one.shop.example", Slug: "one", App: "shop",
+ Account: arSqid, Channel: "edge", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ before := bucketSnapshot(t, fx.rel)
+ st, out := fx.put(t, owner, "shop", "uk")
+ if st != http.StatusOK {
+ t.Fatalf("set = %d %s", st, out)
+ }
+ v := decodeRegionView(t, out)
+ if v.Previous != "ie" || v.PreviousLabel != "Dublin (ie)" || v.Label != "London (uk)" {
+ t.Fatalf("reply = %+v", v)
+ }
+ if after := bucketSnapshot(t, fx.rel); !equalSnapshots(before, after) {
+ t.Fatalf("the change touched the bucket:\nbefore %v\nafter %v", before, after)
+ }
+ rec, err := provision.GetRecord(ctx, fx.rel, arSqid, "shop", "one.shop.example")
+ if err != nil || rec.Region != "" {
+ t.Fatalf("the existing instance's region is %q (%v), want it unchanged", rec.Region, err)
+ }
+ evs := fx.regionEvents(t, "shop")
+ if len(evs) != 1 || evs[0].Detail != "changed shop's region from Dublin (ie) to London (uk) (cli)" {
+ t.Fatalf("audit = %+v", evs)
+ }
+ // The same region again changes nothing and audits nothing.
+ st, out = fx.put(t, owner, "shop", "uk")
+ if v := decodeRegionView(t, out); st != http.StatusOK || v.Changed || v.Label != "London (uk)" {
+ t.Fatalf("same region = %d %s", st, out)
+ }
+ if evs := fx.regionEvents(t, "shop"); len(evs) != 1 {
+ t.Fatalf("a no-op change audited: %+v", evs)
+ }
+ // The home by name stores the record's "" again.
+ if st, out := fx.put(t, owner, "shop", "ie"); st != http.StatusOK {
+ t.Fatalf("back home = %d %s", st, out)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "" {
+ t.Fatalf("home stored as %q, want \"\"", r)
+ }
+}
+
+// Each refusal, checked before any write.
+func TestAppRegionSetRefusals(t *testing.T) {
+ fx := newAppRegionFx(t)
+ owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner")
+ ctx := context.Background()
+ now := time.Now()
+ for _, app := range []string{"fleeted", "pooled", "narrow", "binned"} {
+ if _, err := fx.st.CreateAppIn(42, app, arOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := fx.st.SetAppPlacement(42, "fleeted", "fleet/racks"); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(ctx, fx.rel, arSqid, "pooled", provision.Manifest{Schema: 1, App: "pooled", Domain: "cdef.example", Pool: "web"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(ctx, fx.rel, arSqid, "narrow", provision.Manifest{Schema: 1, App: "narrow", Domain: "cdef.example", Regions: []string{"uk"}}); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.TrashAppRow(42, "binned", now); err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range []struct {
+ name, app, region string
+ status int
+ want string
+ }{
+ {"unknown region", "shop", "zz", http.StatusBadRequest, "region zz is not offered by this platform. choose from: fr, ie, uk"},
+ {"not armed", "shop", "us", http.StatusBadRequest, "region us is not offered by this platform. choose from: fr, ie, uk"},
+ {"not a region", "shop", "UK!", http.StatusBadRequest, "region UK! is not offered by this platform. choose from: fr, ie, uk"},
+ {"cannot start instances", "shop", "fr", http.StatusConflict, "region fr can't start new instances right now (boxes there don't take ordinary instances), so the app's region was not changed"},
+ {"no region", "shop", " ", http.StatusBadRequest, appRegionSetCopy.NoRegion},
+ {"fleet", "fleeted", "uk", http.StatusConflict, fmt.Sprintf(appRegionSetCopy.OnFleet, "fleeted", "racks")},
+ {"pooled", "pooled", "uk", http.StatusConflict, fmt.Sprintf(appRegionSetCopy.Pooled, "pooled")},
+ {"allow-list", "narrow", "ie", http.StatusConflict, "region ie cannot be used by this app's instances. allowed: uk"},
+ {"trash", "binned", "uk", http.StatusConflict, fmt.Sprintf(appRegionSetCopy.InTrash, "binned")},
+ } {
+ st, out := fx.put(t, owner, c.app, c.region)
+ var e struct{ Error string }
+ json.Unmarshal([]byte(out), &e)
+ if st != c.status || e.Error != c.want {
+ t.Errorf("%s = %d %q, want %d %q", c.name, st, out, c.status, c.want)
+ }
+ if r, _, _ := fx.st.AppRegion(42, c.app); r != "" {
+ t.Errorf("%s: stored %q", c.name, r)
+ }
+ }
+ if evs, _ := fx.st.Events(42, "", 100); len(evs) != 0 {
+ for _, e := range evs {
+ if e.Action == "region" {
+ t.Fatalf("a refusal audited: %+v", e)
+ }
+ }
+ }
+ // A temporary app is not pinned: its region changes like any other.
+ if _, err := insertAppRow(fx.st.db, newAppRow{AccountID: 42, App: "tmp-docs", CreatedBy: arOwner, CreatedAt: now.Unix(),
+ ExpiresAt: now.Add(time.Hour).Unix()}); err != nil {
+ t.Fatal(err)
+ }
+ if st, out := fx.put(t, owner, "tmp-docs", "uk"); st != http.StatusOK {
+ t.Fatalf("temporary app = %d %s", st, out)
+ }
+}
+
+// With CONSOLE_APP_REGIONS off (the fixture's default) the change is still
+// written, because the instance create door reads the stored region with
+// the switch off too (member moves Q5).
+func TestAppRegionSetWithTheSwitchOff(t *testing.T) {
+ fx := newAppRegionFx(t)
+ if fx.srv.appRegionsOn() {
+ t.Fatal("fixture has app regions on")
+ }
+ owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner")
+ if st, out := fx.put(t, owner, "shop", "uk"); st != http.StatusOK {
+ t.Fatalf("switch off = %d %s", st, out)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "uk" {
+ t.Fatalf("stored %q", r)
+ }
+}
+
+// The GET names a fleet that governs instead of a region.
+func TestAppRegionGetOnAFleet(t *testing.T) {
+ fx := newAppRegionFx(t)
+ owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner")
+ if err := fx.st.SetAppPlacement(42, "shop", "fleet/racks"); err != nil {
+ t.Fatal(err)
+ }
+ st, out := fx.get(t, owner, "shop")
+ if v := decodeRegionView(t, out); st != http.StatusOK || v.Fleet != "racks" {
+ t.Fatalf("GET = %d %s", st, out)
+ }
+}
+
+// The placement discrepancy log reads a record from before the change as
+// made under the old region.
+func TestAppRegionSetMovesTheDiscrepancyCut(t *testing.T) {
+ fx := newAppRegionFx(t)
+ created := time.Unix(1_700_000_000, 0)
+ if _, err := fx.st.CreateAppInRegion(42, "cart", arOwner, "uk", "chosen", created); err != nil {
+ t.Fatal(err)
+ }
+ inc, ok, err := fx.st.AppIncarnationContext(context.Background(), 42, "cart")
+ if err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+ changed := created.Add(48 * time.Hour)
+ if ok, err := fx.st.SetAppRegion(context.Background(), 42, "cart", inc, "uk", "us", changed); err != nil || !ok {
+ t.Fatalf("set = %v %v", ok, err)
+ }
+ // A second write pinned to the old region lands nowhere.
+ if ok, err := fx.st.SetAppRegion(context.Background(), 42, "cart", inc, "uk", "ie", changed); err != nil || ok {
+ t.Fatalf("stale set = %v %v, want false", ok, err)
+ }
+ rows, err := fx.st.NonHomeAppRegions()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, r := range rows {
+ if r.App == "cart" {
+ if r.Region != "us" || !r.CreatedAt.Equal(changed) {
+ t.Fatalf("row = %+v, want us from %v", r, changed)
+ }
+ return
+ }
+ }
+ t.Fatalf("cart missing from %+v", rows)
+}
+
+// The browser control: shown to an owner on Settings > General, absent for
+// a member; the form changes the region for an owner, and a member's post
+// is the same 404 a non-member gets.
+func TestAppRegionSettingsControl(t *testing.T) {
+ fx := newAppRegionFx(t)
+ ownerC, ownerCSRF := signInAs(t, fx.consoleFixture, arOwner, "code-ar-owner-web")
+ memberC, memberCSRF := signInAs(t, fx.consoleFixture, arMember, "code-ar-member-web")
+ page := fx.ts.URL + "/a/" + arSqid + "/apps/shop/settings"
+ _, _, body := get(t, ownerC, page)
+ if !strings.Contains(body, appRegionSetCopy.ControlButton) || !strings.Contains(body, `<option value="uk">London (uk)</option>`) ||
+ !strings.Contains(body, `<option value="ie" selected>Dublin (ie)</option>`) {
+ t.Fatalf("owner's settings page has no region control:\n%s", body)
+ }
+ if _, _, body := get(t, memberC, page); strings.Contains(body, appRegionSetCopy.ControlButton) {
+ t.Fatal("a member sees the region control")
+ }
+ action := fx.ts.URL + "/a/" + arSqid + "/apps/shop/region"
+ if st, _, _ := postForm(t, memberC, action, url.Values{"csrf": {memberCSRF}, "region": {"uk"}}); st != http.StatusNotFound {
+ t.Fatalf("member post = %d, want 404", st)
+ }
+ if st, _, _ := postForm(t, ownerC, action, url.Values{"csrf": {"wrong"}, "region": {"uk"}}); st != http.StatusForbidden {
+ t.Fatalf("bad csrf = %d, want 403", st)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "" {
+ t.Fatalf("a refused post stored %q", r)
+ }
+ st, loc, _ := postForm(t, ownerC, action, url.Values{"csrf": {ownerCSRF}, "region": {"uk"}})
+ if st != http.StatusSeeOther || !strings.HasSuffix(loc, "/apps/shop/settings") {
+ t.Fatalf("owner post = %d %q", st, loc)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "uk" {
+ t.Fatalf("stored %q after the owner's post", r)
+ }
+ _, _, body = get(t, ownerC, page)
+ if !strings.Contains(body, fmt.Sprintf(appRegionSetCopy.FlashChanged, "London (uk)")) || !strings.Contains(body, appRegionSetCopy.SourceChanged) {
+ t.Fatalf("no flash or source sentence after the change:\n%s", body)
+ }
+}
+
+// bucketSnapshot is every key in the store with its bytes.
+func bucketSnapshot(t *testing.T, s release.Store) map[string]string {
+ t.Helper()
+ keys, err := s.List(context.Background(), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := map[string]string{}
+ for _, k := range keys {
+ b, _, err := s.Get(context.Background(), k)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out[k] = string(b)
+ }
+ return out
+}
+
+func equalSnapshots(a, b map[string]string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for k, v := range a {
+ if b[k] != v {
+ return false
+ }
+ }
+ return true
+}
+
+// A deployment operator who is an ordinary member keeps operator authority
+// when naming the account by name (the member path), in the API and in the
+// browser.
+func TestAppRegionSetMemberOperator(t *testing.T) {
+ fx := newAppRegionFx(t)
+ fx.srv.cfg.SystemOperators = []string{arMember}
+ member := cliToken(t, fx.consoleFixture, arMember, "code-ar-member")
+ st, _, out := rawReq(t, http.MethodPut, fx.ts.URL+"/api/cli/apps/"+url.PathEscape("Shop Co")+"/shop/region", member, `{"region":"uk"}`)
+ if st != http.StatusOK {
+ t.Fatalf("member operator by name = %d %s", st, out)
+ }
+ c, csrf := signInAs(t, fx.consoleFixture, arMember, "code-ar-member-web")
+ if _, _, body := get(t, c, fx.ts.URL+"/a/"+arSqid+"/apps/shop/settings"); !strings.Contains(body, appRegionSetCopy.ControlButton) {
+ t.Fatal("a member operator does not see the region control")
+ }
+ if st, _, _ := postForm(t, c, fx.ts.URL+"/a/"+arSqid+"/apps/shop/region", url.Values{"csrf": {csrf}, "region": {"ie"}}); st != http.StatusSeeOther {
+ t.Fatalf("member operator post = %d", st)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "" {
+ t.Fatalf("stored %q after the member operator's post, want the home", r)
+ }
+}
+
+// A request that resolved one incarnation never writes another: the app is
+// purged and created again under the same name in the same second between
+// the request's resolution and its write.
+func TestAppRegionSetRefusesAReplacedApp(t *testing.T) {
+ fx := newAppRegionFx(t)
+ ctx := context.Background()
+ created := time.Unix(1_700_000_000, 0)
+ if _, err := fx.st.CreateAppIn(42, "cart", arOwner, created); err != nil {
+ t.Fatal(err)
+ }
+ found, ok, err := fx.st.AppIncarnationContext(ctx, 42, "cart")
+ if err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+ if err := fx.st.TrashAppRow(42, "cart", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.PurgeAppRow(42, "cart"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(42, "cart", arOwner, created); err != nil {
+ t.Fatal(err)
+ }
+ _, ref := fx.srv.setAppRegion(ctx, fx.acct, "cart", found, "uk", arOwner, "cli")
+ if ref == nil || ref.Status != http.StatusConflict || ref.Msg != appRegionSetCopy.Changed {
+ t.Fatalf("refusal = %+v, want the 409 changed sentence", ref)
+ }
+ // The store's own check, under the name lock, refuses it too.
+ if ok, err := fx.st.SetAppRegion(ctx, 42, "cart", found, "", "uk", time.Now()); err != nil || ok {
+ t.Fatalf("store write with the replaced incarnation = %v %v, want false", ok, err)
+ }
+ if r, _ := fx.stored(t, "cart"); r != "" {
+ t.Fatalf("the replacement's region became %q", r)
+ }
+}
+
+// With no home region named, the change is refused: the home could not be
+// chosen again afterwards.
+func TestAppRegionSetNeedsANamedHome(t *testing.T) {
+ fx := newAppRegionFx(t)
+ fx.srv.cfg.HomeRegion = ""
+ owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner")
+ st, out := fx.put(t, owner, "shop", "uk")
+ var e struct{ Error string }
+ json.Unmarshal([]byte(out), &e)
+ if st != http.StatusConflict || e.Error != appRegionSetCopy.NoHome {
+ t.Fatalf("no home = %d %s", st, out)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "" {
+ t.Fatalf("stored %q", r)
+ }
+}
+
+// The browser door resolves the app's incarnation before it reads the form
+// body: a rename-and-replace while the body is still arriving changes
+// nothing, and the replacement keeps its region.
+func TestAppRegionBrowserRefusesAnAppReplacedMidRequest(t *testing.T) {
+ // The server side of the form post signals its first body read: by
+ // then the handler has resolved the app (accountAppIncarnation runs
+ // before the CSRF check reads the form).
+ reading := make(chan struct{})
+ var once sync.Once
+ fx := newAppRegionFxWith(t, func(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/apps/shop/region") {
+ r.Body = &firstReadSignal{ReadCloser: r.Body, fire: func() { once.Do(func() { close(reading) }) }}
+ }
+ h.ServeHTTP(w, r)
+ })
+ })
+ c, csrf := signInAs(t, fx.consoleFixture, arOwner, "code-ar-owner-web")
+ pr, pw := io.Pipe()
+ req, err := http.NewRequest(http.MethodPost, fx.ts.URL+"/a/"+arSqid+"/apps/shop/region", pr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ done := make(chan *http.Response, 1)
+ go func() {
+ res, err := c.Do(req)
+ if err != nil {
+ t.Error(err)
+ }
+ done <- res
+ }()
+ go pw.Write([]byte("csrf="))
+ select {
+ case <-reading:
+ case <-time.After(10 * time.Second):
+ pw.CloseWithError(fmt.Errorf("timed out"))
+ t.Fatal("the handler never read the form body")
+ }
+ now := time.Now()
+ if err := fx.st.TrashAppRow(42, "shop", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.PurgeAppRow(42, "shop"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(42, "shop", arOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pw.Write([]byte(url.QueryEscape(csrf) + "&region=uk")); err != nil {
+ t.Fatal(err)
+ }
+ pw.Close()
+ res := <-done
+ if res == nil {
+ t.Fatal("no response")
+ }
+ res.Body.Close()
+ if res.StatusCode != http.StatusSeeOther {
+ t.Fatalf("status = %d, want the flash redirect", res.StatusCode)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "" {
+ t.Fatalf("the replacement's region became %q", r)
+ }
+ if evs := fx.regionEvents(t, "shop"); len(evs) != 0 {
+ t.Fatalf("audited %+v", evs)
+ }
+}
+
+// A name never loses to a sqid: an operator who is a member of an account
+// NAMED like another account's sqid, addressing it by name without
+// ?exact=sqid, changes the app in the account it is a member of.
+func TestAppRegionSetNameNeverLosesToASqid(t *testing.T) {
+ fx := newAppRegionFx(t)
+ fx.srv.cfg.SystemOperators = []string{"sysop@example.test"}
+ now := time.Now()
+ if err := fx.st.CreateAccount(44, "wxyz", arSqid, "sysop@example.test", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(44, "shop", "sysop@example.test", now); err != nil {
+ t.Fatal(err)
+ }
+ sysop := cliToken(t, fx.consoleFixture, "sysop@example.test", "code-ar-sysop")
+ st, _, out := rawReq(t, http.MethodPut, fx.ts.URL+"/api/cli/apps/"+arSqid+"/shop/region", sysop, `{"region":"uk"}`)
+ if st != http.StatusOK {
+ t.Fatalf("by name = %d %s", st, out)
+ }
+ if r, _, _ := fx.st.AppRegion(44, "shop"); r != "uk" {
+ t.Fatalf("the named account's shop is %q, want uk", r)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "" {
+ t.Fatalf("the sqid's account's shop became %q", r)
+ }
+ // With ?exact=sqid the operator reaches the sqid's account.
+ if st, out := fx.put(t, sysop, "shop", "uk"); st != http.StatusOK {
+ t.Fatalf("by exact sqid = %d %s", st, out)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "uk" {
+ t.Fatalf("exact sqid left %q", r)
+ }
+}
+
+// A fleet placement committed after the door's check stops the write.
+func TestAppRegionSetRefusesAPlacementMadeMeanwhile(t *testing.T) {
+ fx := newAppRegionFx(t)
+ ctx := context.Background()
+ inc, ok, err := fx.st.AppIncarnationContext(ctx, 42, "shop")
+ if err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+ if err := fx.st.SetAppPlacement(42, "shop", "fleet/racks"); err != nil {
+ t.Fatal(err)
+ }
+ if ok, err := fx.st.SetAppRegion(ctx, 42, "shop", inc, "", "uk", time.Now()); err != nil || ok {
+ t.Fatalf("write after a placement = %v %v, want false", ok, err)
+ }
+ if r, _ := fx.stored(t, "shop"); r != "" {
+ t.Fatalf("stored %q", r)
+ }
+}
+
+// firstReadSignal calls fire on the first Read of the body it wraps.
+type firstReadSignal struct {
+ io.ReadCloser
+ fire func()
+}
+
+func (f *firstReadSignal) Read(p []byte) (int, error) {
+ f.fire()
+ return f.ReadCloser.Read(p)
+}
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index c0a6ba816..0d1fc183a 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -536,6 +536,11 @@ func (s *Server) registerCLIRoutes() {
s.cliRoute("GET /api/cli/apps/{account}/list", svcrole.Allow(svcrole.Publish), s.handleAPIAppList)
s.cliRoute("POST /api/cli/apps/{account}/{app}/ttl", svcrole.Allow(svcrole.Publish), s.handleAPIAppTTL)
s.cliRoute("POST /api/cli/apps/{account}/{app}/keep", svcrole.Allow(svcrole.Publish), s.handleAPIAppKeep)
+ // The app's region, the default for its NEW instances (appregionset.go).
+ // A person only: an account owner or a deployment operator may change
+ // it, so no service role reaches either door.
+ s.cliRoute("GET /api/cli/apps/{account}/{app}/region", svcrole.Set{}, s.handleAPIAppRegionGet)
+ s.cliRoute("PUT /api/cli/apps/{account}/{app}/region", svcrole.Set{}, s.handleAPIAppRegionSet)
s.cliRoute("GET /api/cli/apps/{account}/{app}/channels", svcrole.Allow(svcrole.Publish, svcrole.Deploy), s.handleAPIChannels)
s.cliRoute("POST /api/cli/apps/{account}/{app}/promote", svcrole.Allow(svcrole.Publish, svcrole.Deploy), s.handleAPIPromote)
s.cliRoute("POST /api/cli/apps/{account}/{app}/rollback", svcrole.Allow(svcrole.Publish, svcrole.Deploy), s.handleAPIRollback)
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 41b56db35..9ce4e7565 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -848,6 +848,7 @@ var claimFixtures = map[string]claimFixture{
"route GET /api/cli/apps/{account}/{app}/pending": claimRead("lists pending proposals"),
"route GET /api/cli/apps/{account}/{app}/pipeline": claimRead("reads the pipeline"),
"route GET /api/cli/apps/{account}/{app}/regions": claimRead("reads armed regions"),
+ "route GET /api/cli/apps/{account}/{app}/region": claimRead("reads the app's stored region and placement from SQLite and the registry; writes nothing"),
"route GET /api/cli/apps/{account}/{app}/relay": claimRead("reads relay status and heartbeats"),
"route GET /api/cli/apps/{account}/{app}/releases": claimRead("lists releases"),
"route GET /api/cli/apps/{account}/{app}/releases/{version}/authorize": claimRead(
@@ -1253,6 +1254,20 @@ var claimFixtures = map[string]claimFixture{
},
do: claimForm("/a/bab/apps/titogo/ratelimit", "host", "acme.go.tito.io", "action", "set", "rate", "500"),
}},
+ // Changing an app's region (appregionset.go) has no claim operation:
+ // a host-claim console refuses it before reading anything.
+ "route POST /a/{sqid}/apps/{app}/region": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"),
+ do: claimRefusedForm("/a/bab/apps/titogo/region", "region", "ie"),
+ status: http.StatusConflict,
+ msg: appRegionSetCopy.ClaimOff,
+ }},
+ "route PUT /api/cli/apps/{account}/{app}/region": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"),
+ do: claimRefusedAPI(http.MethodPut, "/api/cli/apps/bab/titogo/region", `{"region":"ie"}`),
+ status: http.StatusConflict,
+ msg: appRegionSetCopy.ClaimOff,
+ }},
"route POST /a/{sqid}/apps/{app}/rename": {refused: &claimRefusalFixture{
apps: claimRefs("bab/titogo", "+bab/titogo-renamed"),
do: claimRefusedForm("/a/bab/apps/titogo/rename", "to", "titogo-renamed", "confirmed", "1"),
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index 0b5be7c63..5b56260af 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -234,6 +234,7 @@ var claimReadProbes = map[string]claimProbe{
"/api/cli/apps/bab/titogo/pending", "<pending>"),
"route GET /api/cli/apps/{account}/{app}/pipeline": claimAPIRead(nil, "/api/cli/apps/bab/titogo/pipeline", `"pipeline"`),
"route GET /api/cli/apps/{account}/{app}/regions": claimAPIRead(nil, "/api/cli/apps/bab/titogo/regions", `"regions"`),
+ "route GET /api/cli/apps/{account}/{app}/region": claimAPIRead(nil, "/api/cli/apps/bab/titogo/region", `"app":"titogo"`),
"route GET /api/cli/apps/{account}/{app}/relay": claimSerialProbe("relayEnabled stages the region's relay master through t.Setenv: process environment",
claimAPIRead(func(t *testing.T, cx *claimCase) { cx.relayEnabled(t) },
"/api/cli/apps/bab/titogo/relay", `"app":"titogo"`, `"enabled":true`)),
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go
index 8ae62d251..f4921d5e1 100644
--- a/internal/console/claim_invariant_test.go
+++ b/internal/console/claim_invariant_test.go
@@ -119,6 +119,8 @@ var claimUnsupported = map[string]string{
"the cutover door refuses after its operator check and before it reads or writes anything",
claimDBReadResidencyMsg: "a forwarded db read needs the root signer, which a host-claim console never uses for it " +
"(db region forward spec §6): the reads route reads the record and answers main's residency sentence, writing nothing",
+ appRegionSetCopy.ClaimOff: "changing an app's stored region writes its SQL row, and no claim operation gates that write; " +
+ "both doors refuse after their caller gates and before they read or write anything",
seedClaimConsoleRefusal().Msg: "seeded instances need nested boxes, and the claim-armed path waits for #250 (seeded-instances spec §3.4); " +
"every import door refuses before it reads the record, and the legacy route assignment before it reads anything",
}
diff --git a/internal/console/regionfacts.go b/internal/console/regionfacts.go
index b1eeb4580..c93c769b8 100644
--- a/internal/console/regionfacts.go
+++ b/internal/console/regionfacts.go
@@ -101,6 +101,8 @@ func (f appRegionFacts) SourceSentence() string {
return regionLabelCopy.SourceIP
case "default":
return regionLabelCopy.SourceDefault
+ case "changed":
+ return appRegionSetCopy.SourceChanged
}
return ""
}
diff --git a/internal/console/server.go b/internal/console/server.go
index 72027db93..1847972ea 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1735,6 +1735,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// The Deploys card's form (appswap.go): member-gated, like the gate.
s.registerRoute("POST /a/{sqid}/apps/{app}/swap", s.handleAppSwap)
s.registerRoute("POST /a/{sqid}/apps/{app}/rename", s.handleAppRename)
+ s.registerRoute("POST /a/{sqid}/apps/{app}/region", s.handleAppRegionSet)
s.registerRoute("POST /a/{sqid}/apps/{app}/keep", s.handleAppKeep)
s.registerRoute("POST /a/{sqid}/apps/{app}/delete", s.handleAppDelete)
s.registerRoute("POST /a/{sqid}/apps/{app}/move", s.handleAppMoveAccount)
@@ -2021,6 +2022,11 @@ type page struct {
// counts from the rows the page holds.
StoredRegion appRegionFacts
StoredElsewhere []regionCount
+ // CanSetRegion shows Settings > General's Region control (an owner or a
+ // deployment operator, appregionset.go); RegionOptions are its choices,
+ // from the region name map in memory.
+ CanSetRegion bool
+ RegionOptions []regionOption
InstanceDetail *instanceDetail
InstanceGroups []instanceGroup
@@ -4431,6 +4437,9 @@ func (s *Server) populateAppSettings(r *http.Request, p *page, acct *Account, se
if reads.swap {
s.loadSwapPolicy(r.Context(), p, acct)
}
+ if section == "general" && p.StoredRegion.Known && p.StoredRegion.Fleet == "" && s.canSetAppRegion(p.Address, p.Role) {
+ p.CanSetRegion, p.RegionOptions = true, s.appRegionPageChoices()
+ }
if !reads.telemetry {
return
}
diff --git a/internal/console/store.go b/internal/console/store.go
index b953f5be1..229e79aa2 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -566,6 +566,12 @@ func (s *Store) migrate() error {
// predates the feature). No timezone, IP or coordinate is stored.
`ALTER TABLE apps ADD COLUMN region TEXT NOT NULL DEFAULT '';`,
`ALTER TABLE apps ADD COLUMN region_source TEXT NOT NULL DEFAULT '';`,
+ // When the app's region was last changed after its create (carlos
+ // apps region --set), Unix seconds; 0 = never. The placement
+ // discrepancy log reads a record created before it as made under the
+ // old region (regiondrift.go). Member moves' region write uses the
+ // same column (member-moves design §6.6).
+ `ALTER TABLE apps ADD COLUMN region_set_at INTEGER NOT NULL DEFAULT 0;`,
// How a session was proved (email sign-in spec §5.4). Every session
// that predates the column was made through Keymail, so the default
// is the backfill.
@@ -706,6 +712,7 @@ func (s *Store) migrateAppsKey() error {
build_probe TEXT NOT NULL DEFAULT '',
region TEXT NOT NULL DEFAULT '',
region_source TEXT NOT NULL DEFAULT '',
+ region_set_at INTEGER NOT NULL DEFAULT 0,
expires_at INTEGER NOT NULL DEFAULT 0,
restoring INTEGER NOT NULL DEFAULT 0,
purge_after INTEGER NOT NULL DEFAULT 0,
@@ -715,7 +722,7 @@ func (s *Store) migrateAppsKey() error {
);`,
// The ALTERs above run before migrateAppsKey in migrate(), so
// deleted_at, placement, control_plane, build_probe, region,
- // region_source and the temporary columns already exist on the old
+ // region_source, region_set_at and the temporary columns already exist on the old
// table by the time this rebuild copies them — a row already
// trashed, already placed, already the control plane, already
// carrying a build probe or an app region, or already temporary,
@@ -724,8 +731,8 @@ func (s *Store) migrateAppsKey() error {
// lifetime is carried across, and minted for a row that has none (the
// ALTER above adds it empty); randomblob(8) is 16 hex digits, the
// same form insertAppRow mints.
- `INSERT INTO apps_new (app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, expires_at, restoring, purge_after, purge_for, lifetime)
- SELECT app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, expires_at, restoring, purge_after, purge_for,
+ `INSERT INTO apps_new (app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, expires_at, restoring, purge_after, purge_for, lifetime)
+ SELECT app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, expires_at, restoring, purge_after, purge_for,
CASE WHEN lifetime = '' THEN lower(hex(randomblob(8))) ELSE lifetime END FROM apps;`,
`DROP TABLE apps;`,
`ALTER TABLE apps_new RENAME TO apps;`,
@@ -1687,15 +1694,50 @@ func (s *Store) AppRegion(accountID int64, app string) (region, source string, e
return region, source, err
}
+// SetAppRegion changes a live app's stored region, the default for its NEW
+// instances (carlos apps region --set). The update is pinned to the
+// incarnation and the region the caller read (inc, from), so a delete, a
+// rename that freed the name, a create that took it again, or another
+// change in between writes nothing: ok is false. So does a fleet placement
+// committed since the caller checked: the write is for an unplaced app. region is in the record
+// vocabulary ("" is the home). The source becomes "changed" and
+// region_set_at the time of the change. Nothing else reads the row's region
+// to place an existing instance, so no instance moves.
+//
+// It holds the name's lock (apppolicy_names.go), which a purge and a
+// rename hold while they free the name, and compares the whole incarnation
+// under it, so a same-second replacement cannot pass for the app it
+// replaced.
+func (s *Store) SetAppRegion(ctx context.Context, accountID int64, app string, inc AppIncarnation, from, to string, now time.Time) (ok bool, err error) {
+ defer s.lockAppNames(appNameKey{accountID, app})()
+ cur, live, err := s.AppIncarnationContext(ctx, accountID, app)
+ if err != nil || !live || cur != inc {
+ return false, err
+ }
+ // placement = '': the door refused a fleet-placed app, and a placement
+ // committed since must not let the write through (fleets.go writes the
+ // column without the app lock).
+ res, err := s.db.ExecContext(ctx, `UPDATE apps SET region = ?, region_source = 'changed', region_set_at = ?
+WHERE account_id = ? AND app = ? AND deleted_at = 0 AND created_at = ? AND region = ? AND placement = ''`,
+ to, now.Unix(), accountID, app, inc.createdAt, from)
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ return n == 1, err
+}
+
// nonHomeAppRegion is one live app holding a non-home region, for the
-// roll-forward discrepancy log (spec §5.7).
+// roll-forward discrepancy log (spec §5.7). CreatedAt is the later of the
+// app's create and its last region change: a record from before either was
+// made under another default.
type nonHomeAppRegion struct {
Sqid, App, Region string
CreatedAt time.Time
}
func (s *Store) NonHomeAppRegions() ([]nonHomeAppRegion, error) {
- rows, err := s.db.Query(`SELECT a.sqid, p.app, p.region, p.created_at FROM apps p
+ rows, err := s.db.Query(`SELECT a.sqid, p.app, p.region, max(p.created_at, p.region_set_at) FROM apps p
JOIN accounts a ON a.id = p.account_id
WHERE p.region != '' AND p.deleted_at = 0 ORDER BY a.sqid, p.app`)
if err != nil {
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 614416b39..56f023174 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -255,6 +255,10 @@ var closedDoors = []string{
// no service role is the right holder of an operator's decision.
"GET /api/cli/apps/{account}/{app}/policy",
"PUT /api/cli/apps/{account}/{app}/policy",
+ // An app's region (appregionset.go): an account owner or a deployment
+ // operator changes it, a person in either case.
+ "GET /api/cli/apps/{account}/{app}/region",
+ "PUT /api/cli/apps/{account}/{app}/region",
// The sidecar manifest, shut for the instances manifest's reason and one
// of its own. It is standing policy — which domain, pool, regions and
// channel a sidecar may ever come up on — and it also carries `args`,
@@ -1096,8 +1100,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
}
seen++
}
- if seen != len(closedDoors) || seen != 64 {
- t.Errorf("walked %d closed doors, want all %d (and 64 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, 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 != 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)",
seen, len(closedDoors))
}
}
diff --git a/internal/console/templates/app_settings.html b/internal/console/templates/app_settings.html
index 452912542..6ec60d656 100644
--- a/internal/console/templates/app_settings.html
+++ b/internal/console/templates/app_settings.html
@@ -22,6 +22,17 @@ release moves through, and what each one takes to promote onto.</p>
{{if .StoredRegion.Known}}
<p>{{.StoredRegion.Sentence}}{{with .StoredRegion.SourceSentence}} {{.}}{{end}}</p>
<p class="small"><a href="{{.Nav}}/apps/{{.Detail.App}}/instances#app-region-line">{{.RegionLabelCopy.SeeRunning}}</a></p>
+{{if and .CanSetRegion .RegionOptions}}
+<form method="post" action="{{.Base}}/apps/{{.Detail.App}}/region" class="settings-row">
+ <input type="hidden" name="csrf" value="{{.CSRF}}">
+ <label for="app-region">{{.AppRegionSetCopy.ControlLabel}}</label>
+ <select id="app-region" name="region">
+ {{range .RegionOptions}}<option value="{{.Value}}"{{if eq .Value $.StoredRegion.Code}} selected{{end}}>{{.Label}}</option>{{end}}
+ </select>
+ <button type="submit" class="btn-sm">{{.AppRegionSetCopy.ControlButton}}</button>
+</form>
+<p class="small">{{.AppRegionSetCopy.ControlNote}}</p>
+{{end}}
{{else}}
<p class="small">Could not read where this app runs.</p>
{{end}}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 416a0401e..bf3fbd477 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -73,6 +73,7 @@ route GET /api/cli/apps/{account}/{app}/logs
route GET /api/cli/apps/{account}/{app}/pending
route GET /api/cli/apps/{account}/{app}/pipeline
route GET /api/cli/apps/{account}/{app}/policy
+route GET /api/cli/apps/{account}/{app}/region
route GET /api/cli/apps/{account}/{app}/regions
route GET /api/cli/apps/{account}/{app}/relay
route GET /api/cli/apps/{account}/{app}/releases
@@ -146,6 +147,7 @@ route POST /a/{sqid}/apps/{app}/place
route POST /a/{sqid}/apps/{app}/production
route POST /a/{sqid}/apps/{app}/promote
route POST /a/{sqid}/apps/{app}/ratelimit
+route POST /a/{sqid}/apps/{app}/region
route POST /a/{sqid}/apps/{app}/rename
route POST /a/{sqid}/apps/{app}/restart
route POST /a/{sqid}/apps/{app}/rollback
@@ -294,6 +296,7 @@ route PUT /api/cli/apps/{account}/{app}/instances/{host}/import
route PUT /api/cli/apps/{account}/{app}/instances/{host}/updates
route PUT /api/cli/apps/{account}/{app}/pipeline
route PUT /api/cli/apps/{account}/{app}/policy
+route PUT /api/cli/apps/{account}/{app}/region
route PUT /api/cli/apps/{account}/{app}/sidecars-manifest
route PUT /api/cli/apps/{account}/{app}/swap
route PUT /api/cli/apps/{account}/{app}/telemetry
diff --git a/internal/provision/app_region_set_census_test.go b/internal/provision/app_region_set_census_test.go
new file mode 100644
index 000000000..25b8a91c8
--- /dev/null
+++ b/internal/provision/app_region_set_census_test.go
@@ -0,0 +1,33 @@
+package provision
+
+// Record-write census entries for branch app-region-set (carlos apps
+// region: changing an app's stored region, the default for its new
+// instances), layered on regionLabelsWriteCensusInventory (main's newest at
+// the branch point b1d00ca7). Reviewed by the branch author; the root-read
+// card is docs/superpowers/notes/census-proposal-app-region-set.md. No
+// record write is added anywhere and no class or site kind changes: the
+// change writes the console's own apps row in SQLite, never a record.
+// - Server.registerCLIRoutes: registers GET and PUT
+// /api/cli/apps/{account}/{app}/region (appregionset.go). Same
+// "instances" and "sidecars" literals: still key-site.
+// - NewServer: registers POST /a/{sqid}/apps/{app}/region. Same
+// "instances" literal: still key-site.
+func appRegionSetWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), regionLabelsWriteCensusInventory()...)
+ replacements := []censusEntry{
+ {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "390e86260d25e9bf4968d5268a3d4842656c6594cbd497397302ece8b61e3a26"},
+ {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "b9b22ee5933f80618afa83e46c228632af67a7d2e5a15d3dae4a11dddff4bf77"},
+ }
+ 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 9ba7acb51..e166f61ba 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 := regionLabelsWriteCensusInventory()
+ inventory := appRegionSetWriteCensusInventory()
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/testdata/plan14-root-reads-app-region-set.tsv b/internal/provision/testdata/plan14-root-reads-app-region-set.tsv
new file mode 100644
index 000000000..2b17940d4
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-app-region-set.tsv
@@ -0,0 +1,16 @@
+# Census overlay app-region-set, written by census-propose (#369). census-ruling-app-region-set, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-app-region-set.md.
+# 5 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy c7b572706c114574ad45b597b62ee98ac688149f026c24baa72f59fae4f4ddf6 internal/console/server.go NewServer legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console construction adds the lifetime judge, the cutover admission gate and its first marker read; claims-off app materialisation moves to the cutover watch; the existing logs/data route literal moves and is not a filesystem read;rev3=census-ruling-plans-4d-lapse;basis=registers GET and POST /a/{sqid}/plan/keep (the owner-only keep page, plans 4d) beside the account settings routes; no goroutine; read sites unchanged, offsets moved;rev3=census-ruling-plans-6-checkout;basis=refuses Config.Billing without a plan catalog, sets the billing runtime from Config.Billing, and registers POST /billing/webhook beside /api/ses/events; no goroutine and no store call; the one data-literal is still the logs/data route pattern, moved; no read added;rev3=census-ruling-console-perf-1;basis=takes cfg.Perf (or makes its own perf.Recorder), builds the instance fetcher after it so app-host calls are counted, and wraps the mux in perf.Middleware with /healthz skipped; no read added, read site unchanged;rev3=census-ruling-console-ux-nav;basis=GET /deployments now registers handleAppDeploymentsRedirect and GET /pipeline handleAppPipelineRedirect (named handlers in appredirect.go that call appRedirect for /releases and /settings/pipeline, after accountApp's gates) instead of their handlers; route registration only; no root read added, read site unchanged;rev3=census-ruling-app-region-set;basis=registers POST /a/{sqid}/apps/{app}/region (handleAppRegionSet, appregionset.go) beside the rename route; route registration only; no read added, read site unchanged data-literal@10574 b9b22ee5933f80618afa83e46c228632af67a7d2e5a15d3dae4a11dddff4bf77
+@legacy 6287d4aa7901529278b845fc7bd8d108231a91baeb23e37ee749aa1b0b2b4078 internal/console/store.go Store.NonHomeAppRegions legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-app-region-set;basis=selects max(created_at, region_set_at) instead of created_at, so a record from before an app region change is not a discrepancy candidate; the same one console-owned SQLite query; no read added file:Query@80 6ca73e6f90e7b0a8f373bc8b9c6bb8011f3471ecb54519a0d604ef6854ca9388
+@legacy 6be36fa21f2645e0a9b13c846b9dd63907300a3f6329647dfd2ed01b49731f72 internal/console/store.go Store.migrate legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console.service user carlos-console, J4 root-input: adds the three account/app-scoped lifetime intent tables and apps.lifetime at unarmed store boot, then backfills missing lifetimes;rev3=census-ruling-plans-4d-lapse;basis=adds the additive account_plans.lapse_since and account_plans.disabled columns and calls migratePlanLapse last, which creates the console's own plan_lapse_items table (plans 4d). No read added; the new store units are the plans-4d-units decision.;rev3=census-ruling-plans-6-checkout;basis=calls migrateBilling last, after main's migratePlanLapse, which creates the console's own billing tables (plans 6a, its own decision row); no read added here;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328/#329 plan 1 Task 9: calls migrateAppPolicy (a new unit: CREATE TABLE IF NOT EXISTS app_policy_revisions, the console's own table) before migratePlanLapse. The same two Exec sites; no read added here.;rev3=census-ruling-app-region-set;basis=adds the additive apps.region_set_at column (INTEGER NOT NULL DEFAULT 0) to the ALTER list; the same two Exec sites; no read added file:Exec@13226,file:Exec@20688 9cce47c664c920211c5f9ef290164c1b34962a2106f6a9bc7b797fcc4d71092a
+@legacy d94d8d07152e015dc1f629f8c9293701d556428ea2be291694957d1469cc31ed internal/console/store.go Store.migrateAppsKey legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console.service user carlos-console, J4 root-input: copies apps into the composite-key schema while preserving existing lifetimes and minting only missing ids;rev3=census-ruling-app-region-set;basis=carries region_set_at across the apps rebuild (column list and INSERT ... SELECT); console-owned table only; no read added file:Exec@2425,file:QueryRow@65 a6d4f9c819c32c9d311e793e3de0cbd9aa4f387fbaf3ca85b0e03d732a93182f
+@legacy bdd627c48bd58792268d2891089790829fad8ce6ef50ab0ac29352ecc9539524 internal/console/templates/app_settings.html external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-design-edge-rate-limit-358;basis=the Settings page gains a Rate limit section: per instance host, a form of four numbers (busy at, per address while busy, backstop rate, backstop burst) and a reset form, both posting to /a/{sqid}/apps/{app}/ratelimit with the CSRF token, and the record's path rules listed read-only; embedded and rendered by the console (carlos-console), as before; no read added;rev3=census-ruling-console-ux-nav;basis=adds the Placement section (the existing POST /place form, moved from app_instances) and the Errors and analytics section; Advanced folds into General; link texts reworded; markup only; no read added;rev3=census-ruling-region-labels;basis=General gains a Region section (RC-18a, RC-18d, RC-19, RL-S1, or the unread sentence); the placement form's button reads Change fleet (RC-14); markup only; no read added;rev3=census-ruling-app-region-set;basis=the General Region section gains, for an owner or a deployment operator, a select of region codes and a Change region button posting to /a/{sqid}/apps/{app}/region with the CSRF token, and a note; markup only; no read added file:external@0 9a9cd510dbd50d7362db8355ecca9226eaf2c05dc89fe46ac33aa22abb33fca9
+internal/console/server.go NewServer legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console construction adds the lifetime judge, the cutover admission gate and its first marker read; claims-off app materialisation moves to the cutover watch; the existing logs/data route literal moves and is not a filesystem read;rev3=census-ruling-plans-4d-lapse;basis=registers GET and POST /a/{sqid}/plan/keep (the owner-only keep page, plans 4d) beside the account settings routes; no goroutine; read sites unchanged, offsets moved;rev3=census-ruling-plans-6-checkout;basis=refuses Config.Billing without a plan catalog, sets the billing runtime from Config.Billing, and registers POST /billing/webhook beside /api/ses/events; no goroutine and no store call; the one data-literal is still the logs/data route pattern, moved; no read added;rev3=census-ruling-console-perf-1;basis=takes cfg.Perf (or makes its own perf.Recorder), builds the instance fetcher after it so app-host calls are counted, and wraps the mux in perf.Middleware with /healthz skipped; no read added, read site unchanged;rev3=census-ruling-console-ux-nav;basis=GET /deployments now registers handleAppDeploymentsRedirect and GET /pipeline handleAppPipelineRedirect (named handlers in appredirect.go that call appRedirect for /releases and /settings/pipeline, after accountApp's gates) instead of their handlers; route registration only; no root read added, read site unchanged;rev3=census-ruling-app-region-set;basis=registers POST /a/{sqid}/apps/{app}/region (handleAppRegionSet, appregionset.go) beside the rename route; route registration only; no read added, read site unchanged data-literal@10574 b9b22ee5933f80618afa83e46c228632af67a7d2e5a15d3dae4a11dddff4bf77
+internal/console/store.go Store.NonHomeAppRegions legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-app-region-set;basis=selects max(created_at, region_set_at) instead of created_at, so a record from before an app region change is not a discrepancy candidate; the same one console-owned SQLite query; no read added file:Query@80 6ca73e6f90e7b0a8f373bc8b9c6bb8011f3471ecb54519a0d604ef6854ca9388
+internal/console/store.go Store.migrate legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console.service user carlos-console, J4 root-input: adds the three account/app-scoped lifetime intent tables and apps.lifetime at unarmed store boot, then backfills missing lifetimes;rev3=census-ruling-plans-4d-lapse;basis=adds the additive account_plans.lapse_since and account_plans.disabled columns and calls migratePlanLapse last, which creates the console's own plan_lapse_items table (plans 4d). No read added; the new store units are the plans-4d-units decision.;rev3=census-ruling-plans-6-checkout;basis=calls migrateBilling last, after main's migratePlanLapse, which creates the console's own billing tables (plans 6a, its own decision row); no read added here;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328/#329 plan 1 Task 9: calls migrateAppPolicy (a new unit: CREATE TABLE IF NOT EXISTS app_policy_revisions, the console's own table) before migratePlanLapse. The same two Exec sites; no read added here.;rev3=census-ruling-app-region-set;basis=adds the additive apps.region_set_at column (INTEGER NOT NULL DEFAULT 0) to the ALTER list; the same two Exec sites; no read added file:Exec@13226,file:Exec@20688 9cce47c664c920211c5f9ef290164c1b34962a2106f6a9bc7b797fcc4d71092a
+internal/console/store.go Store.migrateAppsKey legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console.service user carlos-console, J4 root-input: copies apps into the composite-key schema while preserving existing lifetimes and minting only missing ids;rev3=census-ruling-app-region-set;basis=carries region_set_at across the apps rebuild (column list and INSERT ... SELECT); console-owned table only; no read added file:Exec@2425,file:QueryRow@65 a6d4f9c819c32c9d311e793e3de0cbd9aa4f387fbaf3ca85b0e03d732a93182f
+internal/console/templates/app_settings.html external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-design-edge-rate-limit-358;basis=the Settings page gains a Rate limit section: per instance host, a form of four numbers (busy at, per address while busy, backstop rate, backstop burst) and a reset form, both posting to /a/{sqid}/apps/{app}/ratelimit with the CSRF token, and the record's path rules listed read-only; embedded and rendered by the console (carlos-console), as before; no read added;rev3=census-ruling-console-ux-nav;basis=adds the Placement section (the existing POST /place form, moved from app_instances) and the Errors and analytics section; Advanced folds into General; link texts reworded; markup only; no read added;rev3=census-ruling-region-labels;basis=General gains a Region section (RC-18a, RC-18d, RC-19, RL-S1, or the unread sentence); the placement form's button reads Change fleet (RC-14); markup only; no read added;rev3=census-ruling-app-region-set;basis=the General Region section gains, for an owner or a deployment operator, a select of region codes and a Change region button posting to /a/{sqid}/apps/{app}/region with the CSRF token, and a note; markup only; no read added file:external@0 9a9cd510dbd50d7362db8355ecca9226eaf2c05dc89fe46ac33aa22abb33fca9
+@coverage . fc29f7b37d6a5b150c9d5955b40300da7a8e7b830e41ff8dc7e0f4633d94f00f
+@coverage internal/console 9dd6b5fe9d183f6e9a4e399583439cc05a63b42b28f3ea75a276cea0298657be
+@coverage internal/console/templates 31b5a71a123d232e2f36cd8032b5ff8d9f43c1474f203c81b2dd1852aeedc6e7
+@coverage internal/regionlabel a4cc5a2ff624a1aa3215c711302c7dc68d2bdca9853eadc372f31a8c99113872
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index f814feea2..a70137945 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -57,3 +57,4 @@ plan14-root-reads-instance-egress-sizes-328-329-new.tsv aa6c6832fe50f05ab771ebe2
plan14-root-reads-instance-egress-sizes-328-329.tsv c1ab16d1d7eaccb3928a4fd5f74f8fc931221cbd67d5d751a63354984c7b249f
plan14-root-reads-region-labels-decisions.tsv b265c2ae74edbaca766d33e085d31a8e7c6f86883d12d0ed4472bd99a7c3278d
plan14-root-reads-region-labels.tsv d1e00cfb29d88b7a8e4998b641164e539067a6e1e9e4f52524255343c0c5f9f7
+plan14-root-reads-app-region-set.tsv 798a1ee3d8c8b775f963b9ae1dbc45e18628fa0c1e63404f46606601766ad66c
diff --git a/internal/regionlabel/regionlabel.go b/internal/regionlabel/regionlabel.go
index d10388363..fd56d3dac 100644
--- a/internal/regionlabel/regionlabel.go
+++ b/internal/regionlabel/regionlabel.go
@@ -6,6 +6,7 @@
package regionlabel
import (
+ "sort"
"strings"
"github.com/carlosframework/platform/internal/edgesfile"
@@ -75,6 +76,17 @@ func NamesFrom(snap edgesfile.Snapshot, home string) Names {
return n
}
+// Codes is every display code an edges file names with an AWS region,
+// sorted: the places the map can label.
+func (n Names) Codes() []string {
+ out := make([]string, 0, len(n.aws))
+ for c := range n.aws {
+ out = append(out, c)
+ }
+ sort.Strings(out)
+ return out
+}
+
// BoxPlacement is a box's placement code in the record vocabulary. known
// is false for a box no edges file names; ("", true) is the home.
func (n Names) BoxPlacement(label string) (code string, known bool) {