carlos / platform Public

plan: apply round 1 fixes for the demo API site route

Keeps the edge rate limit, delivers settings through hostenv, rides the roll.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 71d426f83cc7bef4f13bf63068f6e1d1eb542380 parent 4a27835
2 files changed, +164 −29
  • docs/superpowers/plans/2026-11-05-demo-api-site-route.md +32 −29
  • docs/superpowers/plans/REVIEW-DEMO-API-SITE-ROUTE-R1.md +132 −0

CI passed — run details

Intent

Human

<task-notification> <task-id>a5c83580e7324f732</task-id> <tool-use-id>toolu_012hFED3RxsfUNhvhtPQJn3J</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ada77e36-2f79-4efb-88a5-c350ac2ffa6a/tasks/a5c83580e7324f732.output</output-file> <status>completed</status> <summary>Agent "Opus review of plan round 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result># Review, round 1: demo API site route plan (commit 4a27835c) I read the code and made no edits. I ran no tests and no scratch files were created. I did not check live boxes, so two facts are unknown: - whether any group-launched box takes public traffic today - whether any deployment sets `CARLOS_RATE_LIMIT=enforce` ## P1 None. ## P2 ### 1. The alias silently drops the edge rate limit (Decisions, plan:60 and :86; Task 2) **Problem:** The bypass list never names `rateAdmit`, and the requirement is "body and rate limits unchanged". The plan cites `edge.go:2638` without saying that it is the rate limit (the comment starts at `:2638`). **Evidence:** - The console row is `Kind` instance, so today it is judged at `internal/edge/ratelimit.go:127-146`. - The defaults are ClientShare 16, Rate 300, Burst 1000 (`internal/ratelimit/settings.go:48`). - The hook returns at about `edge.go:2009`, long before that check. - The console-host arm returns there too, so direct console traffic loses the limit as well. **Failure scenario:** On a deployment with `CARLOS_RATE_LIMIT=enforce`, a client sends unlimited `POST /api/demo/apps` with a bogus bearer. - Each request reaches `LookupDemoToken` (`internal/console/apidemo.go:328-345`), and no console budget sits in front of that lookup. - After the create budget is spent, the anonymous path still does a database check per request (`:367-374`). - The abuser is better off than today on both hosts. In observe mode (the default, `ratelimit.go:68`) the observation is lost instead. **Fix:** - On local console delivery, including a verified hop, call `e.rateAdmit(w, r, consoleUpstream)` before the proxy and honour its release. - It already keys on the route host and on `clientIP(r)`, which uses the hop chain (`analytics.go:100`), so buckets match today's. - Add an enforce-mode case to `TestDemoAPIAliasIsolation`, covering both hosts. - Name the limiter in plan:86 as retained. **Fault family:** edge admission boundary, "rate limits unchanged". ### 2. Hand-installed drop-ins do not reach group-launched or replaced ingresses (plan:56, Switch-on 2) **Problem:** The plan requires "every public site ingress", but its only delivery route is a hand-written file. **Evidence:** - Group boxes get a fixed drop-in set at boot (`infra/modules/region-host/group-init.sh.tftpl:87`, `:296`). - Their `host.env` comes from `system host-env write --group` (`:332`), limited to the `hostenv` allowlist, which refuses any other name. - The plan explicitly keeps these settings out of `hostenv.Optional`. **Failure scenario:** - A group box (or a replaced fixed box) takes site traffic with the alias off. - `/api/demo/*` falls through to the static site, so the agent gets a non-retryable 404 instead of a 503 with `Retry-After`. - The failure is intermittent, per ingress, and passes page checks. **Plan's reasoning on `hostenv`:** Calling the exclusion "explicit" (plan:56) overstates it. `hostenv.go:53` onward lists identity, address, pool, directory, relay and credential keys. It allows an endpoint override because only operators can write the parameter paths. A deployment-wide origin is arguable under that rule. **Fix (pick one and state it):** - add the two names to `hostenv.Optional`, or - add the drop-in through provisioning, or - add a Switch-on stop: "no group or replacement box takes site traffic until this is settled", with a per-ingress check in the witness. **Fault family:** every public ingress carries the alias. ### 3. Switch-on and Rollback use bare edge restarts while claiming to ride the roll (plan:144, :149) **Problem:** - Step 2 rolls the binaries, then installs the edge drop-in, then does "daemon-reload/restart". That is a second, bare restart on each ingress. The next sentence says "Settings ride this roll". - Project memory `host-env-restart-downtime` records about 11 s of refused connections from such a restart (flagship console box, 2026-11-01). It also says such a line must ride the roll or be announced in a quiet window. - Bad settings fail startup (plan:54, via `newEdge`). With `Restart=always`, a typo in a hand-written file takes every tenant on that box down. **Fix:** - Install the edge drop-in just before the roll. The old binary ignores it, and the roll's restart picks it up. - Install the console drop-in just before the console's roll restart. - Add a stop-at-first-box check. - Mark Rollback's edge restart as announced downtime. **Roll order:** This reverses plan:58 ("console reservation before enabling edges"). That is safe if Switch-on first confirms the site host is already claimed by the intended account: - The hook never consults claims. - With the edge on first, the console keeps returning console-origin links, so nothing breaks. - The plan's order has the opposite gap: the console hands out site `statusUrl`s before the edges serve them. **Fault family:** operator activation must not cause tenant downtime. ### 4. The Plan 4 amendment misses the contract line that matters most (Task 1 Files, plan:94) **Problem:** Task 1 edits Plan 4 lines 81, 84 and 123. - Plan 4 line 83 still says "Explain one exact console hostname to allow". As written, it sends agents to the console host. The copy table at plan:140 mentions this only as a copy task. - `verifyStartOrigin` (Plan 4:188) checks only the page and starter, so a site with the alias off passes. **Fix:** - Add line 83 and its `blocked host` transcript fixture (Plan 4 Task 2 Step 2) to the amendment. - Add a non-mutating check to `verifyStartOrigin`: a well-formed unknown `GET /api/demo/jobs/&lt;id&gt;` must return the console's JSON 404 with no-store. **Fault family:** one host for the agent journey. ### 5. The real-budget cross-box witness cannot be written as split (Task 3, plan:124, :126-127) **Problem:** - `NewDemoAPITestIngress` lives in edge's export test, visible only to `edge_test`. The TLS and port seams are private to edge (`backhaul_e2e_test.go:578`). - Console-package tests have the private fixtures (`apidemo_test.go:26-45` injects a peer) but cannot reach those seams. - In `edge_test`, `SpendDemoCreate` (`apidemo.go:383`) sits behind `demoPublishReady` (`:378`, `:704`), which needs an eligible connected worker. Without one, the create returns 503 and spends nothing. - So "shared client budgets across ingresses", the 202 and 409 comparisons and the Journey publish have no stated way to run. The helper also returns one client, so distinct real IPs have no path either. **Fix (say which):** - connect a real worker over `/api/box/demo-builds` with a fleet box row in `edge_test`, and let the helper accept a source address, or - witness cross-box attribution through the real status limiter (no peer needed, `apidemo.go:517-523`), and prove in the console package that create and status share `clientIP`. **Fault family:** production-wired witness for client attribution. ## P3 - **`withForwardKey`:** It runs at `edge.go:2034`, after the hook. The hook must call it as `replicaconsole.go:38` does, or every local delivery is unsigned and gets 503. Tests would catch this, but the plan should say so. - **`hostPlatform` side effects:** It also closes `apiplacements.go:478` to operators, plus `domaincatchall.go:60`, `domainbuy.go:97` and the plan cap at `plancaps.go:246`. These are harmless for a static site, but plan:58 does not list them. - **Citations:** `carlos-edge.service:15` should be `:18`. The `Environment=` survival claim matters only for `console.service`, because `carlos-edge` is not a stamped route. - **Cuts:** - `StartConfig.demoAPIOrigin` must equal `siteOrigin`, so it carries no information. - The 1xx and trailer machinery guards against console behaviour these handlers do not have. - **Lost signal:** The hook also skips `observeRecords` and `emitEdgeError`, so abuse and 5xx on these paths leave no edge record. This is a loss worth stating, not a leak. - **Plan 4:85:** It verifies a saved row at the permanent URL, which conflicts with Switch-on 3's site-only egress allowlist. - **Flagship Switch-on 5:** It does not state an edge/console order. ## Checked and true 1. **IP chain.** - Hop and same-box delivery behave as described: `setForwarded` at `homemap.go:1537-1555`, the proof strip at `edge.go:4393`, `signForwarded` binding the Host at `forwardproof.go:51`, and `clientIP` taking the last element at `authcli.go:1223`. - Forged hops are stripped (`homemap.go:1412-1414`). I found no route for a client or tenant process to get a chain signed. - The proof gate breaks no legitimate path: edges always send a single-element chain and no health check uses these paths. 2. **Dispatch.** - The earlier branches are host-specific (`handleDemoRequest`, steering, tunnel host, burst notice). - `:80` never reaches `ServeHTTP`, so ACME and the redirect are unaffected. - The console-host arm covers only allowlisted requests, and those handlers read no cookies. 3. **Destination.** - The console row is published in edges files (`internal/host/edgesfile.go:620-640`), and `ExactHome` resolves it. - Multiple claims resolve to one owner or to held, which the plan already refuses. - `hopTo` has the hooks claimed (`edge.go:4196`). The local console test is real and matches `proofnamed.go:141`. 4. **Authority.** - Static ship goes through channels, not the domain doors, so deploys keep working. The site owner does lose attach, path and detach, as intended. - No tenant path makes a host the alias, because the hook reads only process environment. 5. **Delivery.** - `zz-carlos-env.conf` resets only `EnvironmentFile=` (`appconfig/dropin.go:41-47`). - The guard exec keeps `os.Environ()` (`guardexec.go:106`). - An extra drop-in only changes the proof definition hash. 6. **Tokens.** I found no path where a token or job ID reaches logs; Authorization is forwarded only over TLS to the verified console host. 7. **Generality.** It is general enough: an operator setting with a fixed allowlist and no tenant names. 8. **Agent contract.** Only `statusUrl` and `claimUrl` carry the console origin (`apidemo.go:455`, `:459`), and error copy names no host. 9. **Census.** The census claims and the `make` targets match `Makefile:49-53` and `AGENTS.md:296-322`. ## Verdict **READY AFTER FIXES.** No P1s. P2s 1 to 5 are fixed without another round. The census and the review of newly changed security behaviour (P2 1) still check the fixes.</result> <usage><subagent_tokens>230303</subagent_tokens><tool_uses>31</tool_uses><duration_ms>587585</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bbotelegr</task-id> <tool-use-id>toolu_0154LRWJjnWzUQJJ4cPrNdg3</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ada77e36-2f79-4efb-88a5-c350ac2ffa6a/tasks/bbotelegr.output</output-file> <status>completed</status> <summary>Background command "Wait for the plan-fix run to finish" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 5.54 g CO₂e (534,162 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on demo-api-site-route, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/superpowers/plans/2026-11-05-demo-api-site-route.md b/docs/superpowers/plans/2026-11-05-demo-api-site-route.md
index b0c6fbc4f..d484cff53 100644
--- a/docs/superpowers/plans/2026-11-05-demo-api-site-route.md
+++ b/docs/superpowers/plans/2026-11-05-demo-api-site-route.md
@@ -47,19 +47,19 @@ Exclude `GET/POST /demo/report`, `GET /demo/claim`, all `/demo/claim/{intent,pro
Add console setting `CONSOLE_DEMO_API_ORIGIN`, represented by `Config.DemoAPIOrigin string`. Empty falls back to `Config.Origin`; otherwise it is one canonical HTTPS DNS origin, no port except implicit 443, credentials, path, query, fragment, wildcard or IP literal. Use it for `statusUrl` and any future **agent API** URL; do not rewrite JSON at the edge. Today both status and browser claim URLs use `s.cfg.Origin` (`internal/console/apidemo.go:455`). Keep `claimUrl` on `Config.Origin`, including its secret fragment: the agent validates and hands it to the human without fetching it. Live/permanent app URLs also remain unchanged. They are destinations to show the human, not additional API hosts to contact.
-Plan 4 must gain `StartConfig.demoAPIOrigin` and required enabled-build setting `CARLOS_START_DEMO_API_ORIGIN`, equal to `siteOrigin`. Retain `consoleOrigin` for browser claim validation and the later optional authenticated CLI workflow. Publish/update/poll and the merged claim API use `demoAPIOrigin`; validate returned agent endpoints against that exact HTTPS origin and allowed path, never follow redirects with credentials. Validate browser claim links against `consoleOrigin` plus `/demo/claim`, preserving the fragment. This replaces Plan 4's console-origin publishing and combined link check (`docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md:81`, `:84`, `:123`). The one-host promise covers the anonymous/claim API journey; normal CLI onboarding remains an explicit later choice (`:86`).
+Amend Plan 4 (`docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md`) to use `siteOrigin` for publish/update/poll and the merged claim API. Cut the proposed duplicate `demoAPIOrigin`/`CARLOS_START_DEMO_API_ORIGIN`; retain a separate value only with a concrete justification. Keep `consoleOrigin` for browser claim validation and optional later CLI onboarding. Validate agent endpoints against the exact HTTPS site origin and allowed path; never follow redirects with credentials. Validate browser links against `consoleOrigin` plus `/demo/claim`, preserving the fragment. Amend lines 81, **83**, 84 and 123, and Task 2 Step 2's blocked-host transcript (`:129`), so the one hostname to allow is the site. Extend `verifyStartOrigin` (`:188`) with a non-mutating GET for a well-formed unknown job ID: require the console's JSON 404 and no-store, not a static 404 (`internal/demobuild/job.go:68`; `internal/console/apidemo.go:526`). Normal CLI onboarding remains an explicit later choice (`:86`).
### Operator authority and routing
Edge settings are `CARLOS_DEMO_API_ORIGIN` (site) and `CARLOS_DEMO_API_CONSOLE_ORIGIN` (canonical console). Both unset disables the alias; partial, equal or invalid origins fail startup. Use the same origin grammar as the console setting. No wildcard, path, arbitrary destination address or operator-editable path list. Parse at edge construction (`internal/edge/edge.go:575`), then use current routing snapshots. Changing settings requires an edge restart; ordinary route changes use the existing reload.
-Deliver these settings in a root-owned `/etc/systemd/system/carlos-edge.service.d/40-demo-api.conf` with `[Service] Environment=` assignments, not an app config bundle. Deliver the console setting in `/etc/systemd/system/console.service.d/40-demo-api.conf` the same way. The edge runs the agent and already reads host settings (`internal/host/units/carlos-edge.service:15`). Do not add authority settings to `hostenv.Optional`, whose exclusion rule is explicit (`internal/hostenv/hostenv.go:53`). `Environment=` survives named-unit config delivery, while that delivery resets `EnvironmentFile=` (`AGENTS.md:550`). No new root file reader or unit generator is needed.
+Add both edge names, sorted, to `hostenv.Optional` (`internal/hostenv/hostenv.go:53`, `:73`): operator-only endpoint parameters, never tenant config. `carlos-edge` reads root-owned `/etc/carlos/host.env` (`internal/host/units/carlos-edge.service:18`). Group/replacement boot runs `system host-env write --group --install` (`infra/modules/region-host/group-init.sh.tftpl:332`); `FetchGroup`/`AssembleGroup` accept `Optional` and write the whole file (`internal/hostenv/group.go:99`, `:141`; `internal/hostenv/cli.go:104`, `:114`). Fixed boxes keep their existing host.env workflow: even plain `host-env write` calls `Fetch`, which adds the group marker (`cli.go:106`; `hostenv.go:341`, `:367`), so do not use it to rewrite a fixed box. Ensure replacement bootstrap releases understand the names before setting parameters. Keep `CONSOLE_DEMO_API_ORIGIN` in root-owned `/etc/systemd/system/console.service.d/40-demo-api.conf`, using `[Service] Environment=`; group provisioning installs no console and forbids custom user data/console settings (`infra/modules/region-host/main.tf:144`; `group-init.sh.tftpl:330`). Console named-unit config resets only `EnvironmentFile=` (`internal/appconfig/dropin.go:39`); this survival rule is not needed for the unstamped edge unit. No new reader or unit generator.
-Treat the configured public-origin host as `hostPlatform` in `domainHostPolicy`, after existing reserved-host checks. This makes later attach/repoint/path/detach writes operator-only, including a member of the site's own account; service credentials cannot be operators (`internal/console/domainpolicy.go:66`, `:117`, `:134`; `internal/console/apidomains.go:379`, `:966`, `:1145`). Configure the console reservation before enabling edges. A tenant can neither set process environment nor enable this feature with a route/alias/path record. Unconfigured hosts retain their own `/api/demo` handlers.
+Treat the configured public-origin host as `hostPlatform` in `domainHostPolicy`, after existing reserved-host checks. This makes later attach/repoint/path/detach writes operator-only, including a member of the site's own account; service credentials cannot be operators (`internal/console/domainpolicy.go:66`, `:117`, `:134`; `internal/console/apidomains.go:379`, `:966`, `:1145`). First confirm the site host is already claimed by the intended account; enable all edges before the console reservation/link setting. `hostPlatform` also affects placement, catch-all, purchase and custom-domain cap checks (`internal/console/apiplacements.go:478`; `domaincatchall.go:60`; `domainbuy.go:97`; `plancaps.go:246`). A tenant can neither set process environment nor enable this feature with a route/alias/path record. Unconfigured hosts retain their own `/api/demo` handlers.
-Add the dispatch hook after `acceptHop` and inbound control-header scrubbing, before `lookupUpstreamPath` (`internal/edge/edge.go:1983`, `:1998`, `:2009`). It handles the configured source's reserved namespace and the configured console's allowlisted API requests. The latter gives remote deliveries the same cookie/cache policy. Do not invoke `ServeHTTP` recursively. Clone the request; set Host and URL authority to the configured console before signing or proxying. Client Host only selects an exact configured source; it never selects the destination or response links. Reject edge-local door callers rather than grant a tenant process a cross-app door exception.
+Add the dispatch hook after `acceptHop` and inbound control-header scrubbing, before `lookupUpstreamPath` (`internal/edge/edge.go:1983`, `:1998`, `:2009`). It handles the configured source's reserved namespace and the configured console's allowlisted API requests. The latter gives remote deliveries the same cookie/cache policy. Do not invoke `ServeHTTP` recursively. Clone the request; set Host and URL authority to the configured console before signing or proxying. Call `e.withForwardKey(r)` in this hook as `internal/edge/replicaconsole.go:38` does; ordinary dispatch calls it too late (`edge.go:2034`). Client Host only selects an exact configured source; it never selects the destination or response links. Reject edge-local door callers rather than grant a tenant process a cross-app door exception.
-On the console box, use only the **exact** configured console route, ready, raw account empty, app `console`, unit `console.service`, non-alias, non-regional, non-tunnel and non-activator-owned, with a Unix socket or exclusively loopback addresses. This is the existing console-route authority test (`internal/edge/replicaconsole.go:8`), narrowed to one configured hostname. Build a dedicated proxy from the same socket/TCP/probed transport constructors in Reload, in the same atomic upstream entry; do not mutate the ordinary console proxy. Preserve its selected endpoint and version header. Missing/ineligible local target never falls through to another app.
+On the console box, use only the **exact** configured console route, ready, raw account empty, app `console`, unit `console.service`, non-alias, non-regional, non-tunnel and non-activator-owned, with a Unix socket or exclusively loopback addresses. This is the existing console-route authority test (`internal/edge/replicaconsole.go:8`), narrowed to one configured hostname. Build a dedicated proxy from the same socket/TCP/probed transport constructors in Reload, in the same atomic upstream entry; do not mutate the ordinary console proxy. Preserve its selected endpoint and version header. Before local delivery, including a verified hop, call `e.rateAdmit(w, r, consoleUpstream)` and honor refusal, deferred release and `slotWriter` as ordinary dispatch does (`internal/edge/edge.go:2646`). Run admission before filtering authenticated XFF: buckets use the console route host and verified `clientIP` (`internal/edge/ratelimit.go:126`; `internal/edge/analytics.go:100`). Missing/ineligible local target never falls through to another app.
On another ingress, use `homes.ExactHome(consoleHost)` and existing `hopTo`/`backhaulTransport`, including TLS SNI/verification, hop concurrency and fair-share admission (`internal/edge/homemap.go:1067`; `internal/edge/edge.go:4196`, `:4252`, `:4303`). Reject an empty dial/box, absent key or an already-hopped request needing another hop with empty 503 and `Retry-After: 2`. A held home is not a usable destination. Do not resolve the console through public DNS, a tenant wildcard, forward row or tunnel. A wrong/stale destination refuses instead of trying a second box.
@@ -79,11 +79,11 @@ Require a cached signing key even for local delivery; an invalid purported hop t
| Authorization | Do not validate away or coalesce malformed credentials. Presence selects update, so dropping an invalid/empty header could create a second app (`internal/console/apidemo.go:328`). The console gives its existing refusal. |
| Request framing | Preserve method, body stream and ContentLength; let net/http manage framing and 100-continue. No archive decode, buffering, source-size check, `GetBody` replay or POST retry. Preserve cancellation. |
| Response | Preserve upstream status, body bytes, Retry-After values, content metadata and ordinary end-to-end headers. Strip hop-by-hop/internal headers, every Set-Cookie (including 1xx, declared and late trailers), and cache validators/Age. Do not follow or rewrite Location. Force `Cache-Control: no-store, private`, `CDN-Cache-Control: no-store`, `Surrogate-Control: no-store`; strip conflicting cache policy trailers. |
-| Local failure | Empty 503, `Retry-After: 2`, the same no-store headers. Override proxy transport-error handlers, not received console 5xx responses. After response commitment, terminate the broken stream; do not append a page or replace its status. Existing hop admission may still return its own 429/503 (`internal/edge/edge.go:4252`). |
+| Local failure | Empty 503, `Retry-After: 2`, the same no-store headers. Override proxy transport-error handlers, not received console 5xx responses. After response commitment, terminate the broken stream; do not append a page or replace its status. Existing rate/hop admission retains its 429/503 (`internal/edge/ratelimit.go:149`; `internal/edge/edge.go:4252`). |
-Use a private-header streaming writer with `Unwrap()` and flush support to enforce policy on initial, informational and trailer headers; ModifyResponse alone misses 1xx (`internal/edge/cookiescope.go:49`, `:57`, `:63`). Never log bodies, Authorization, source archives or response tokens.
+Keep one small private-header streaming writer with `Unwrap()` and flush support, sanitizing headers at writes and trailers at proxy completion. Go's `ReverseProxy` forwards 1xx before `ModifyResponse` and copies trailers after the body, so it does not provide the same guarantee (installed Go source: `/home/paulca/.local/go-dist/src/net/http/httputil/reverseproxy.go:560`, `:599`, `:639`; existing limitations: `internal/edge/cookiescope.go:57`, `:63`). Never log bodies, Authorization, archives or response tokens.
-The alias bypasses site/tenant probe-burst counters, request-protection catalogue, password gates, usage billing, asset cache, shared response cache, gzip and static tree caches. Its canonical method/path gate is the edge admission boundary; console create/status/claim limits remain authoritative, with existing cross-box containment retained. This is an intentional narrow security-policy choice, reviewed in Task 2, not an exemption transferable to other paths. Those layers normally run at `internal/edge/edge.go:2391`, `:2443`, `:2552`, `:2567`, `:2621`, `:2638`. Static kinds already bypass shared caching, but that alone does not cover the earlier asset catch. Explicit outbound identity encoding prevents transport-added gzip/decompression; skip edge recompression and keep the existing pooled transports. HTTP/2 clients stream through the existing HTTP/1.1 backhaul (`internal/edge/edge.go:4297`); no HTTP/2 hop or buffering is required. No body limit is duplicated; console timeout, archive cap and 413 body remain at `internal/console/apidemo.go:317`, `:389`.
+The alias bypasses site/tenant probe-burst counters, request-protection catalogue, password gates, usage billing, asset cache, shared response cache, gzip and static tree caches. Retain **`rateAdmit` on local console delivery, including verified hops**, console create/status/claim limits and cross-box containment. The hook skips edge abuse/5xx records (`observeRecords`/`emitEdgeError`, `internal/edge/edge.go:2378`). This is an intentional narrow security-policy choice, reviewed in Task 2, not an exemption transferable to other paths. Those layers normally run at `internal/edge/edge.go:2391`, `:2443`, `:2552`, `:2567`, `:2621`, `:2638`. Static kinds already bypass shared caching, but that alone does not cover the earlier asset catch. Explicit outbound identity encoding prevents transport-added gzip/decompression; skip edge recompression and keep the existing pooled transports. HTTP/2 clients stream through the existing HTTP/1.1 backhaul (`internal/edge/edge.go:4297`); no HTTP/2 hop or buffering is required. No body limit is duplicated; console timeout, archive cap and 413 body remain at `internal/console/apidemo.go:317`, `:389`.
No CORS grant or Origin rewrite is added. The current anonymous handlers are directly registered, outside account/session/CSRF wrappers (`internal/console/apidemo.go:276`). Stripping cookies cannot confer account authority; a console bearer remains limited by the actual handler. Rewriting Host to the configured canonical console avoids retired-host redirects (`internal/console/server.go:2352`). Browser claim/report CSRF doors are excluded. The post-merge claim follow-up must apply the same proof gate and prove absent-Origin agent requests work and hostile Origin requests keep the merged console's refusal; never loosen its checks to accommodate this alias.
@@ -91,7 +91,7 @@ No CORS grant or Origin rewrite is added. The current anonymous handlers are dir
**Risk/review:** security gate and redirect/link authority; independent task review required. No root, termination, storage or billing behavior change.
-**Files:** Create `internal/console/demo_api_origin.go`, `internal/console/demo_api_origin_test.go`; modify `internal/console/server.go:568`, `:1769`, `internal/console/apidemo.go:455`, `internal/console/domainpolicy.go:66`, `cmd/console/main.go:483`, and Plan 4 at its lines 81, 84 and 123. No website-repo edits in this platform plan.
+**Files:** Create `internal/console/demo_api_origin.go`, `internal/console/demo_api_origin_test.go`; modify `internal/console/server.go:568`, `:1769`, `internal/console/apidemo.go:455`, `internal/console/domainpolicy.go:66`, `cmd/console/main.go:483`, and Plan 4 at lines 81, 83, 84, 123, its blocked-host fixture (`:129`) and `verifyStartOrigin` (`:188`). No website-repo edits in this platform plan.
**Interfaces:** New `validateDemoAPIOrigin(raw string) (string, error)` and `(*Server).demoAPIOrigin() string`; new `Config.DemoAPIOrigin string` and `(*Server).requireDemoAPIProof(w http.ResponseWriter, r *http.Request) bool` (true admits; false has written refusal). Call the proof gate at the start of publish/status when configured. `NewServer` validates the origin; command startup loads `CONSOLE_DEMO_API_ORIGIN`. The helper returns configured public origin or existing `Origin`. Plan 4 consumes the configuration contract above, not a new platform API.
@@ -103,31 +103,31 @@ No CORS grant or Origin rewrite is added. The current anonymous handlers are dir
## Task 2: Forward the operator-selected site API
-**Risk/review:** security gate, cache and production routing; independent task review required, including the deliberate middleware exclusions. Root-binary census scope changes; no new root filesystem access, termination, storage or billing rules.
+**Risk/review:** security gate, cache and production routing; independent task review required, including P2-1's retained limiter and deliberate middleware exclusions. Edge and hostenv root-binary census scope changes; no new root filesystem access, termination, storage or billing rules.
-**Files:** Create `internal/edge/demo_api.go`, `internal/edge/demo_api_test.go`; modify `internal/edge/edge.go:504`, `:575`, `:841`, `:2009`. Keep registry schema and alias writers unchanged.
+**Files:** Create `internal/edge/demo_api.go`, `internal/edge/demo_api_test.go`; modify `internal/edge/edge.go:504`, `:575`, `:841`, `:2009`, `internal/hostenv/hostenv.go:73`, and its `hostenv_test.go`, `group_test.go`, `write_linux_test.go`. Keep registry schema and alias writers unchanged.
**Interfaces:** New `demoAPIAliasConfig{Origin, ConsoleOrigin string}`, `parseDemoAPIAliasConfig(getenv func(string) string) (demoAPIAliasConfig, error)`, `demoAPIPath(r *http.Request) (reserved, allowed bool)`, and `(*Edge).serveDemoAPIAlias(w http.ResponseWriter, r *http.Request, host string, hopped, hopPresent bool) bool` (true includes refusal). Store immutable config on Edge and a dedicated `demoAPIProxy http.Handler` on the exact console upstream, built in Reload from the eligible local proxy. New `demoAPIResponseWriter` owns its header map and exposes `Unwrap() http.ResponseWriter`. Existing `hopTo` accepts error/response hooks (`internal/edge/edge.go:4196`); use them without changing ordinary hops. A false `hopTo` result can mean it already wrote admission refusal, not permission to write again.
-- [ ] **Step 1: Add failing tests.** `TestDemoAPIAliasBoundary`: both origins unset, partial/invalid settings, exact hosts, static/platform-attached source, unrelated tenant `/api/demo`, every listed/excluded method/path, encoded traversal/separators, queries, upgrades, forged target Host, wrong-account/alias/tunnel/forward console rows and missing target. `TestDemoAPIAliasIsolation`: cookies in both directions and 103/trailers; duplicate/empty Authorization; preserved Origin; preseeded shared/asset cache; `_headers` cache/cookie rules, static redirects and Markdown negotiation; gzip enabled; existing burst cooldown; no tenant usage debit. Verify each API request reaches the console once, ordinary pages stay unchanged, and all API exits are no-store.
-- [ ] **Step 2: Run** `go test ./internal/edge -run 'TestDemoAPIAlias(Boundary|Isolation)' -count=1`; expect FAIL.
-- [ ] **Step 3: Implement** the dispatch, configuration, proxy and header contracts above. Source and destination consume the same fixed allowlist. Require keys, exact eligible console identity and one-hop containment. Do not add a mesh key reader, persisted route type, public-HTTP redirect or tenant opt-in.
+- [ ] **Step 1: Add failing tests.** `TestDemoAPIAliasBoundary`: both origins unset, partial/invalid settings, exact hosts, static/platform-attached source, unrelated tenant `/api/demo`, every listed/excluded method/path, encoded traversal/separators, queries, upgrades, forged target Host, wrong-account/alias/tunnel/forward console rows and missing target. `TestDemoAPIAliasIsolation`: cookies in both directions and 103/trailers; duplicate/empty Authorization; preserved Origin; preseeded shared/asset cache; `_headers` cache/cookie rules, static redirects and Markdown negotiation; gzip enabled; existing burst cooldown; no tenant usage debit. With `CARLOS_RATE_LIMIT=enforce`, test both site and console hosts, local and verified-hop delivery: one console-host/client bucket, refusal before handler entry and released slots. Admitted requests reach the console once; pages stay unchanged and API exits are no-store. `TestDemoAPIHostEnv` covers both new optional names through Seed/Fetch and FetchGroup, render/write/parse, and absent values; preserve sorted Optional (`hostenv_test.go:431`) and per-box authority exclusions (`demo_test.go:5`).
+- [ ] **Step 2: Run** `go test ./internal/edge -run 'TestDemoAPIAlias(Boundary|Isolation)' -count=1` and `go test ./internal/hostenv -run 'TestDemo(APIHostEnv|BoxKeys)|TestSingleTenantIsAnAllowedHostEnvVariable' -count=1`; expect FAIL for the new behavior.
+- [ ] **Step 3: Implement** the dispatch, hostenv delivery, proxy and header contracts above. Source and destination consume the same fixed allowlist. Require keys, exact eligible console identity and one-hop containment. Do not add a mesh key reader, persisted route type, public-HTTP redirect or tenant opt-in.
- [ ] **Step 4: Rerun Step 2** plus existing alias, static Markdown, cookie and forward-proof regressions; expect PASS. Check removal/reload leaves no dedicated proxy reachable and route replacement selects the new console endpoint atomically.
- [ ] **Step 5: Commit during implementation:** `feat: forward selected demo API paths from a site host`.
-## Task 3: Prove delivery, close census and switch on dev
+## Task 3: Prove delivery, close census and hand off activation
**Risk/review:** integration tests and release evidence; whole-branch review, with census approval. Any new security/root/termination/storage behavior returns to its owning task within the same review budget.
**Files:** Create `internal/console/demo_api_alias_integration_test.go`, `internal/edge/demo_api_integration_test.go` (package `edge_test`) and `internal/edge/demo_api_export_test.go`; extend Task 2 tests; update the anonymous-demo operator section at `README.md:624` after copy review. Generate census proposal/card with repository tooling, not hand-edited seals.
-**Interfaces:** Consume real `edge.New`, `Edge.ServeHTTP`, `Reload`, console server and existing local test stores. Use `EnableStatic` and `ArmHomeMap` for real proof keys (`internal/edge/homemap.go:399`). Follow the test-only export pattern at `internal/edge/forwardha_export_test.go:22`: new `NewDemoAPITestIngress(t *testing.T, consoleHandler http.Handler) (*http.Client, string)` builds two ingresses and a console-home edge, returning a site-only client and site origin. Reuse loopback TLS/port seams from `internal/edge/backhaul_e2e_test.go:729`; clean up listeners/global overrides with `t.Cleanup`, no parallel use. External edge tests supply a real `console.NewServer`/`console.Open` (`internal/console/server.go:1749`; `internal/console/store.go:107`) without an import cycle or production test API. Console-package tests retain access to private budget fixtures. No public network or cloud account is required. Producer contract is unchanged JSON plus the configured origin.
+**Interfaces:** External `edge_test` tests drive real `edge.New`, `ServeHTTP`, `Reload`, `EnableStatic` and `ArmHomeMap` (`internal/edge/homemap.go:399`). Test-only `NewDemoAPITestIngress(t, consoleHandler, releases)` builds two ingresses and a console-home edge, with `Client(ingress, sourceAddr)` returning a site-only HTTP client/origin; bind its dialer's `LocalAddr` to distinct loopback source IPs. Expose test-only controls for route reload, home/key changes and disabled-config reconstruction. Share the release store/key fixtures with `console.NewServer`/`console.Open` (`internal/console/server.go:1749`; `store.go:107`; `edgeproof.go:138`). Follow `internal/edge/forwardha_export_test.go:22`; keep TLS/port overrides inside edge's test build (`backhaul_e2e_test.go:578`), with `t.Cleanup` and no parallel use. Console-package tests use their own private fixtures, never this export. No cloud account or public network.
-- [ ] **Step 1: Add integration witnesses.** `TestDemoAPIAliasClientIP` drives real console admission/status budgets through same-box and cross-box/region fixtures, with no console row on the source; attacker XFF, Forwarded, duplicate proof and forged hop headers cannot change attribution. Test key absence/rotation and stale homes, plus an already-hopped request requiring a second hop. Assert shared client budgets across ingresses and distinct real clients remain distinct. `TestDemoAPIAliasStreaming` uses HTTP/1.1 and HTTP/2 clients, unknown-length/chunked uploads, 100-continue, >5,000,000 bytes, slow upload, early console refusal, cancellation and mid-body failure; count one POST even on dropped connection. Compare console 202/400/401/409/413/429/503 bodies and Retry-After field values byte-for-byte through the alias. Assert no whole-upload buffer and first response bytes arrive before an open response stream finishes.
-- [ ] **Step 2: Add** `TestDemoAPIAliasJourney`: one configured site serves static `/start` and API publish/status/update; backend sees canonical console Host, real IP and no cookies; returned status never names console; claim link is handed off without a fetch. Deny the test client's access to the console hostname. Exercise route reload and setting removal with zero extra store reads beyond existing mirrors/console operations. Claims remain excluded until the post-merge follow-up proves all four APIs the same way.
+- [ ] **Step 1: Add attribution witnesses.** In `edge_test`, `TestDemoAPIAliasClientIP` drives a real console's **status** limiter, which needs no worker (`internal/console/apidemo.go:517`). Send well-formed unknown job IDs: 60 requests from one socket-source IP across local and remote ingresses return JSON 404, then 429; another real source IP still gets 404. Remote ingress has no console row. Forged XFF/Forwarded/proof/hop headers cannot choose attribution; key absence/rotation mismatch, stale home and second-hop attempts refuse. In package `console`, `TestDemoAPIAliasBudgetIdentity` uses `demoTestServer`/`demoTestWorker` (`apidemo_test.go:26`, `:34`) and signed requests to prove publish/status share `clientIP` and create check/spend use that IP (`apidemo.go:371`, `:383`, `:517`). Invalid archives spend create attempts before validation; inspect budgets for the signed client, peer and forged IP, and prove another client remains independent. This fixture proves create attribution locally, not a real cross-box publish.
+- [ ] **Step 2: Add transport witnesses in `edge_test`.** `TestDemoAPIAliasStreaming` uses a **recording console handler** for 202/400/401/409/413/429/503 body/Retry-After comparisons, early refusal and mid-body failure; real publish needs a connected worker (`apidemo.go:379`, `:704`). Exercise HTTP/1.1 and HTTP/2, unknown-length uploads, 100-continue, >5,000,000 bytes, slow upload and cancellation. Count one POST on a dropped connection, verify streaming before upload/response completion, and compare direct-handler versus alias bytes. This proves transport fidelity; existing console tests own the real cap/refusals. `TestDemoAPIAliasJourney` also uses the recording handler for publish/status/update and returned-link fixtures, with real static `/start`, route reload and disabled-config reconstruction. Count store reads: none added beyond existing mirrors/console operations. Assert canonical console Host, verified client proof, no cookies, site status links and no claim-link fetch; client transport refuses the console hostname. Task 1 tests real URL construction; Switch-on witnesses actual publish. Claims wait for the post-merge follow-up.
- [ ] **Step 3: Run** `go test ./internal/console ./internal/edge -run 'TestDemo(PublicAPIOrigin|APIProofRequired|APIHostOwnership|APIAlias)' -count=1`; expect PASS. Demonstrate the IP/cache/body witnesses fail when their respective protection is disconnected. Obtain approved operator copy before writing README changes.
-- [ ] **Step 4: Census and final gate.** Expect `make census-card` to report changed edge units/envelopes and new helper units because edge belongs to the root binary, even though only the unprivileged edge executes this feature (`AGENTS.md:300`, `:322`). Console-only files are excluded. No registry fields, root file opens, termination or production storage operations are added; new environment inputs and routing authority still require reviewer decisions. Write claims, run `make census-propose NAME=demo-api-site-route CLAIMS=<claims-file>`, and independently review every unit/envelope against amadan main. Record reviewer and tip on #280. Run the repository's build/vet/full-test/gofmt and prescribed cross-build gate once, then tip CI (`AGENTS.md:245`). None runs during plan authoring.
-- [ ] **Step 5: Commit during implementation:** `test: prove site demo API delivery and origin isolation`. Describe/push the branch to amadan, obtain whole-branch review and green tip CI, squash-land with the checked 40-character tip, inspect main CI, and follow Switch-on. No flagship activation.
+- [ ] **Step 4: Census and final gate.** Expect `make census-card` to report edge units/envelopes, new helpers and **hostenv's Optional/envelope change**: both packages belong to the root binary (`AGENTS.md:300`, `:322`; `internal/provision/testdata/census-base.tsv:5386`). Review the expanded operator-parameter surface used by root's host-env writer as well as routing. Console-only files are excluded. No registry fields, root file opens, termination or production storage operations are added; new environment inputs and routing authority still require reviewer decisions. Write claims, run `make census-propose NAME=demo-api-site-route CLAIMS=<claims-file>`, and independently review every unit/envelope against amadan main. Record reviewer and tip on #280. Run the repository's build/vet/full-test/gofmt and prescribed cross-build gate once, then tip CI (`AGENTS.md:245`). None runs during plan authoring.
+- [ ] **Step 5: Commit during implementation:** `test: prove site demo API delivery and origin isolation`. Describe/push the branch to amadan, obtain whole-branch review and green tip CI, squash-land with the checked 40-character tip, inspect main CI, then **the build controller hands Switch-on to the program controller**, which arranges the dev release and activation. The build controller does not follow Switch-on or activate flagship.
## Copy review required
@@ -141,21 +141,24 @@ No new end-user response text: new refusals have empty bodies; existing console
## Rollback
-Restore Plan 4's previous build first if it has switched consumers. Clear `CONSOLE_DEMO_API_ORIGIN` and restart console so new job links again use its original origin; remove both edge settings and restart all participating ingresses. The site then owns `/api/demo/*` exactly as before. No registry migration, alias row, bucket object, cache entry or background worker remains. Previously returned URLs are not rewritten retrospectively, so complete or stop active test journeys before disabling. Leave the ordinary console/demo services running.
+Restore Plan 4's previous build first if consumers switched. Clear `CONSOLE_DEMO_API_ORIGIN` and restart console so new links use its original origin; remove both edge parameters and host.env values, including replacement-box delivery. Restart participating edges as **announced downtime**, checking one before proceeding. The site regains `/api/demo/*`; no registry/bucket migration or worker cleanup is needed. Returned URLs are not rewritten, so finish or stop active journeys first. Leave ordinary console/demo services running.
## Switch-on
-1. **Dev, landing day:** inspect the current routes, fleet/ingress inventory and console configuration through console/CLI before choosing destinations. Checked-in evidence names dev console box `carlos-dev-ie` (`README.md:280`; the deployment file calls it sophie at `/home/paulca/amadan.net/carlos/platform-infrastructure/dev/region-ie.tf:24`). These are topology hints, not live verification. Set `SITE_ORIGIN` to the actual dev static-site origin and `CONSOLE_ORIGIN` to the configured canonical dev console origin, currently documented as `https://platform.dev.carlosframework.com` (`README.md:282`). Preserve the site's existing claim, static release and region placement.
-2. Roll the reviewed edge binary to **every public site ingress in every region and the console home edge**, then the console binary, following dev-first release ordering (`README.md:276`). No demo-worker roll or mesh-key grant is needed for this feature. Install root-owned console drop-in `40-demo-api.conf` containing `Environment="CONSOLE_DEMO_API_ORIGIN=<SITE_ORIGIN>"`; daemon-reload/restart through the deployment's existing operator workflow. Then install the edge drop-in of the same name on those ingresses with `Environment="CARLOS_DEMO_API_ORIGIN=<SITE_ORIGIN>"` and `Environment="CARLOS_DEMO_API_CONSOLE_ORIGIN=<CONSOLE_ORIGIN>"`; daemon-reload/restart. Settings ride this roll, not a new polling loop. Keep `CONSOLE_ORIGIN`, demo admission/protection and worker console URLs unchanged.
-3. Through each ingress, using the new binaries and actual TLS host, verify `/start`, an unknown API path's plain 404, create/status/update, console 413/429, no cookies/cache, actual originating IP and missing-console 503. Confirm a region without the console route forwards directly to its home. Keep cloud-agent egress allowlisted to the site only. Use an existing authorized dev demo and clean up this witness through existing APIs; do not create infrastructure under this plan without scoped approval (`AGENTS.md:129`). This authoring task grants no rollout permission.
-4. Amend Plan 4 as Task 1 specifies. Its later website build uses `CARLOS_START_SITE_ORIGIN=<SITE_ORIGIN>`, `CARLOS_START_DEMO_API_ORIGIN=<SITE_ORIGIN>` and retains `CARLOS_START_CONSOLE_ORIGIN=<CONSOLE_ORIGIN>`. Public claim instructions wait for Plan 3 to merge, the four-path follow-up, and its contract tests. That follow-up is code, not a mutable operator allowlist, and does not reopen Plan 3's design.
-5. **Flagship, later operator step only:** public site operator value is `https://carlosframework.com`; obtain the current canonical console origin from deployed configuration, never infer it from the site or historic DNS. Historical deployment files place the console in IE (`/home/paulca/github.com/carlosframework/carloku-infrastructure/region-ie.tf:64`) and describe old console names (`README.md:29` in that repo); do not treat those as current. After separately scoped rollout approval, repeat ingress-wide settings/readiness checks, set console `CONSOLE_DEMO_API_ORIGIN=https://carlosframework.com`, and use that same value for edge `CARLOS_DEMO_API_ORIGIN` and Plan 4's site/demo API origins. Apply release-tag/module rules where relevant (`AGENTS.md:515`). This removes the second host from the agent journey, not the console service or its human browser host.
+1. **Dev, landing day:** inspect the current routes, fleet/ingress inventory and console configuration through console/CLI before choosing destinations. Checked-in evidence names dev console box `carlos-dev-ie` (`README.md:280`; the deployment file calls it sophie at `/home/paulca/amadan.net/carlos/platform-infrastructure/dev/region-ie.tf:24`). These are topology hints, not live verification. Set `SITE_ORIGIN` to the actual dev static-site origin and `CONSOLE_ORIGIN` to the configured canonical dev console origin, currently documented as `https://platform.dev.carlosframework.com` (`README.md:282`). First confirm the site host is already claimed by the intended account; preserve that claim, static release and region placement.
+2. **Edges before console.** Confirm group/replacement bootstrap releases include the new hostenv allowlist before adding operator parameters. Immediately before rolling each edge, place both settings in its root-owned host.env: group boxes use the reviewed `system host-env write --group` without `--install`; fixed boxes use their existing file workflow. Set `CARLOS_DEMO_API_ORIGIN=<SITE_ORIGIN>` and `CARLOS_DEMO_API_CONSOLE_ORIGIN=<CONSOLE_ORIGIN>` in operator parameters for future group/replacement boots too. The old edge binary ignores them; the roll's own restart reads them. **Stop at the first box** until startup, ordinary tenant traffic, alias 404 and forwarded status pass; stop on failure, never continue fleet-wide. Cover every public ingress and console home edge, then install console `40-demo-api.conf` with `Environment="CONSOLE_DEMO_API_ORIGIN=<SITE_ORIGIN>"` just before the console roll's restart, including daemon-reload. Until then links retain console origin. No extra edge restart, worker roll or mesh-key grant; keep other console/protection settings unchanged (`README.md:276`).
+3. Witness **every public ingress**, using the new binary and actual TLS host: `/start`, unknown `/api/demo/not-a-route` gets the alias's empty plain 404/no-store, and a well-formed unknown job gets console JSON 404/no-store. Stop if any ingress fails. Verify actual create/status/update, console 413/429, no cookies/cache, original IP and missing-console 503; a region without a console route must reach its home. Keep agent API egress site-only. Use an authorized dev demo and existing APIs for cleanup. Infrastructure changes need scoped approval (`AGENTS.md:129`); this authoring task grants none.
+4. Plan 4's later website build uses `CARLOS_START_SITE_ORIGIN=<SITE_ORIGIN>` for page and API and retains `CARLOS_START_CONSOLE_ORIGIN=<CONSOLE_ORIGIN>` for browser/CLI links. Apply Task 1's amendment and non-mutating release check. Public claim instructions wait for merged Plan 3, the four-path code follow-up and its tests; no mutable operator path list.
+5. **Flagship, separately approved later:** use site origin `https://carlosframework.com`; read the canonical console origin from deployed configuration. Historical files place console in IE (`/home/paulca/github.com/carlosframework/carloku-infrastructure/region-ie.tf:64`), not evidence of current topology. Confirm the site claim, then repeat **all edges first, console second**, placing settings immediately before each roll's restart, stopping at the first box and checking every public ingress. Console and edge public origins equal Plan 4's `siteOrigin`. Follow release-tag/module rules (`AGENTS.md:515`).
-## Review budget and self-review
+## Review budget
-Independent review rounds used: **0**. No agents ran. Carry this count and findings by invariant into briefs using `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md:12`; for a Codex author, use Opus or Fable for authority/census review. Stop at the first round with no P1, apply P2 fixes without another general round, retain the census/new-security checks, and list P3 follow-ups. Maximum three rounds; two consecutive rounds in one fault family invoke the stop-and-choose rule (`AGENTS.md:44`). Do not review against unmerged Plan 3.
+**Round 1: Opus, READY AFTER FIXES; P2s applied. One round used.** Findings and fault families: `docs/superpowers/plans/REVIEW-DEMO-API-SITE-ROUTE-R1.md` (edge admission, every public ingress, activation downtime, one-host journey, client attribution). No further plan review round. P2-1's security behavior is checked at Task 2's implementation review; the census still applies, including hostenv. Carry this history into implementation briefs (`docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md:12`); retain the three-round limit and two-round fault-family stop rule. Do not review against unmerged Plan 3.
-Self-review: requirements a/e/j map to Task 1 and the path/authority decisions; b/c/d/f/i to Task 2 and Task 3's real transport witnesses; g/h to Task 3 and Switch-on. Each Review Focus has a named test. Origin fields, allowlist and response policy agree across tasks. No product bodies are specified, no generic proxy framework is introduced, and every new runtime state is process-local. Existing Plan 1/2 rulings remain settled, including never-reused demo hosts and the shared edge-proof cache exception (`docs/superpowers/notes/agent-start-demo-1-rulings.md:27`; `docs/superpowers/notes/agent-start-demo-2-rulings.md:38`).
+**P3 follow-ups**
+
+- Reconcile Plan 4:85's saved-row check at the permanent app URL with site-only agent egress before the later claim journey ships.
+- Consider safe edge abuse/5xx observability for these paths without logging tokens or archives.
## Open questions
diff --git a/docs/superpowers/plans/REVIEW-DEMO-API-SITE-ROUTE-R1.md b/docs/superpowers/plans/REVIEW-DEMO-API-SITE-ROUTE-R1.md
new file mode 100644
index 000000000..aeef4e4b1
--- /dev/null
+++ b/docs/superpowers/plans/REVIEW-DEMO-API-SITE-ROUTE-R1.md
@@ -0,0 +1,132 @@
+# Review, round 1: demo API site route plan (commit 4a27835c)
+
+Reviewer: Opus subagent. No live boxes checked, so two facts are unknown: whether
+any group-launched box takes public traffic today, and whether any deployment
+sets `CARLOS_RATE_LIMIT=enforce`.
+
+## P1
+
+None.
+
+## P2
+
+### 1. The alias silently drops the edge rate limit (plan:60, :86; Task 2)
+
+The bypass list never names `rateAdmit`, and the requirement is "body and rate
+limits unchanged". The plan cites `edge.go:2638` without saying it is the rate
+limit. The console row is `Kind` instance, so today it is judged at
+`internal/edge/ratelimit.go:127-146`; defaults ClientShare 16, Rate 300, Burst
+1000 (`internal/ratelimit/settings.go:48`). The hook returns at about
+`edge.go:2009`, before that check, and the console-host arm returns there too.
+
+Failure: with `CARLOS_RATE_LIMIT=enforce`, unlimited `POST /api/demo/apps` with a
+bogus bearer each reach `LookupDemoToken` (`internal/console/apidemo.go:328-345`)
+with no console budget in front; the anonymous path does a database check per
+request after the create budget is spent (`:367-374`). In observe mode (default,
+`ratelimit.go:68`) the observation is lost.
+
+Fix: on local console delivery, including a verified hop, call
+`e.rateAdmit(w, r, consoleUpstream)` before the proxy and honour its release. It
+keys on the route host and `clientIP(r)`, which uses the hop chain
+(`analytics.go:100`), so buckets match today's. Add an enforce-mode case to
+`TestDemoAPIAliasIsolation` on both hosts. Name the limiter in plan:86 as retained.
+
+Family: edge admission boundary, "rate limits unchanged".
+
+### 2. Hand-installed drop-ins do not reach group-launched or replaced ingresses (plan:56, Switch-on 2)
+
+The plan requires "every public site ingress" but its only delivery is a
+hand-written file. Group boxes get a fixed drop-in set at boot
+(`infra/modules/region-host/group-init.sh.tftpl:87`, `:296`); `host.env` comes from
+`system host-env write --group` (`:332`), limited to the `hostenv` allowlist. The
+plan keeps these settings out of `hostenv.Optional`, calling the exclusion
+"explicit", which overstates it: `hostenv.go:53` allows an endpoint override
+because only operators can write the parameter paths.
+
+Failure: a group or replaced box takes site traffic with the alias off, so
+`/api/demo/*` falls through to the static site: a non-retryable 404, intermittent
+per ingress, invisible to page checks.
+
+Fix, pick one: add the two names to `hostenv.Optional`; or add the drop-in through
+provisioning; or a Switch-on stop with a per-ingress check.
+
+Family: every public ingress carries the alias.
+
+### 3. Switch-on and Rollback use bare edge restarts while claiming to ride the roll (plan:144, :149)
+
+Step 2 rolls binaries, installs the edge drop-in, then restarts again: about 11 s of
+refused connections per box (project history, 2026-11-01). Bad settings fail startup
+(plan:54) and with `Restart=always` a typo takes every tenant on that box down.
+
+Fix: install the edge drop-in just before the roll (the old binary ignores it, the
+roll's restart picks it up); install the console setting just before the console's
+roll restart; add a stop-at-first-box check; mark Rollback's edge restart as
+announced downtime. This reverses plan:58's order, which is safe if Switch-on first
+confirms the site host is already claimed by the intended account: the hook never
+consults claims, and with the edge on first the console keeps returning console-origin
+links. The plan's order has the opposite gap: the console hands out site `statusUrl`s
+before the edges serve them.
+
+Family: operator activation must not cause tenant downtime.
+
+### 4. The Plan 4 amendment misses the contract line that matters most (plan:94)
+
+Task 1 edits Plan 4 lines 81, 84, 123. Plan 4 line 83 still says "Explain one exact
+console hostname to allow". `verifyStartOrigin` (Plan 4:188) checks only the page and
+starter, so a site with the alias off passes.
+
+Fix: add line 83 and its `blocked host` transcript fixture (Plan 4 Task 2 Step 2) to
+the amendment. Add a non-mutating check to `verifyStartOrigin`: a well-formed unknown
+`GET /api/demo/jobs/<id>` must return the console's JSON 404 with no-store.
+
+Family: one host for the agent journey.
+
+### 5. The real-budget cross-box witness cannot be written as split (plan:124, :126-127)
+
+`NewDemoAPITestIngress` is visible only to `edge_test`; TLS and port seams are private
+to edge (`backhaul_e2e_test.go:578`). Console-package tests have the private fixtures
+(`apidemo_test.go:26-45`) but cannot reach those seams. In `edge_test`,
+`SpendDemoCreate` (`apidemo.go:383`) sits behind `demoPublishReady` (`:378`, `:704`),
+which needs a connected worker; without one, create returns 503 and spends nothing.
+The helper returns one client, so distinct real IPs have no path either.
+
+Fix, say which: connect a real worker over `/api/box/demo-builds` and let the helper
+accept a source address; or witness cross-box attribution through the real status
+limiter (no peer needed, `apidemo.go:517-523`) and prove in the console package that
+create and status share `clientIP`.
+
+Family: production-wired witness for client attribution.
+
+## P3 (follow-up list; no round)
+
+- `withForwardKey` runs at `edge.go:2034`, after the hook. The hook must call it as
+ `replicaconsole.go:38` does, or every local delivery is unsigned and gets 503.
+- `hostPlatform` also closes `apiplacements.go:478` to operators, plus
+ `domaincatchall.go:60`, `domainbuy.go:97` and the plan cap at `plancaps.go:246`.
+ Harmless for a static site; plan:58 does not list them.
+- `carlos-edge.service:15` should be `:18`. The `Environment=` survival claim matters
+ only for `console.service`, because `carlos-edge` is not a stamped route.
+- Cuts: `StartConfig.demoAPIOrigin` must equal `siteOrigin`, so it carries no
+ information; the 1xx and trailer machinery guards against console behaviour these
+ handlers do not have.
+- The hook skips `observeRecords` and `emitEdgeError`, so abuse and 5xx on these paths
+ leave no edge record. A loss worth stating, not a leak.
+- Plan 4:85 verifies a saved row at the permanent URL, which conflicts with Switch-on
+ 3's site-only egress allowlist.
+- Flagship Switch-on 5 does not state an edge/console order.
+
+## Checked and true
+
+IP chain (same-box and hop; forged hops stripped at `homemap.go:1412-1414`; proof gate
+breaks no legitimate path). Dispatch (earlier branches are host-specific; `:80` never
+reaches `ServeHTTP`). Destination (`internal/host/edgesfile.go:620-640`, `ExactHome`,
+`hopTo` hooks at `edge.go:4196`, `proofnamed.go:141`). Authority (static ship goes
+through channels, so deploys keep working; hook reads only process environment).
+Delivery (`appconfig/dropin.go:41-47`, `guardexec.go:106`). Tokens (no path to logs).
+Generality. Agent contract (only `statusUrl` and `claimUrl` carry the console origin,
+`apidemo.go:455`, `:459`). Census (`Makefile:49-53`, `AGENTS.md:296-322`).
+
+## Verdict
+
+**READY AFTER FIXES.** No P1s. P2s 1 to 5 are fixed without another round. The census
+and the review of newly changed security behaviour (P2 1) still check the fixes.