carlos / platform Public

edge: serve Markdown twins of static HTML pages by Accept

A static site can ship page.md beside page.html (index.md beside
index.html). The edge serves the Markdown at the same URL when Accept
strictly prefers text/markdown, HTML otherwise, with Vary: Accept.
Tags are keyed by content type. Census overlay approved by Opus (#280).
Docs in docs/site/cli.md after a Luna copy pass.

Squashed from static-markdown-twins into main.
Co-Authored-By: codex <codex~paul@keymail.dev>
claude agent, operated by paul@keymail.dev ffcf01b5eb85d9df38571c8d81c22636ac6d522d parent df66050
16 files changed, +1,928 −25
  • docs/site/cli.md +30 −0
  • docs/superpowers/notes/census-proposal-static-markdown-twins.md +25 −0
  • docs/superpowers/notes/census-static-markdown-twins-claims.tsv +3 −0
  • docs/superpowers/plans/2026-11-04-agent-start-demo-2-edge-protections.md +250 −0
  • docs/superpowers/plans/2026-11-04-agent-start-demo-3-claim.md +387 −0
  • docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md +224 −0
  • docs/superpowers/plans/2026-11-04-static-markdown-twins.md +95 −0
  • docs/superpowers/plans/CONTROLLER-BRIEF-static-markdown-twins.md +33 −0
  • docs/superpowers/reviews/OPUS-REVIEW-BRIEF-static-markdown-twins.md +39 −0
  • docs/superpowers/specs/LUNA-COPY-BRIEF-STATIC-MARKDOWN-TWINS.md +27 −0
  • internal/edge/static.go +48 −18
  • internal/edge/static_cache_test.go +7 −7
  • internal/edge/static_markdown.go +156 −0
  • internal/edge/static_markdown_test.go +593 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-static-markdown-twins.tsv +10 −0

CI failed — run details

diff --git a/docs/site/cli.md b/docs/site/cli.md
index 20646aa0c..57f8da9d1 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -403,6 +403,36 @@ app is served only at its own platform address, so `--host` and
carlos deploy --temporary --ttl 3d ./dist
```
+#### Markdown variants for a static site
+
+Put `shop/index.html` beside `shop/index.md` to offer HTML and Markdown at
+`/shop/`. For a page at `/page.html`, put `page.html` beside `page.md`.
+Ship both files. No application server or configuration switch is needed.
+
+The edge serves the Markdown file when the request's `Accept` header gives
+`text/markdown` a positive quality value (`q`) strictly higher than
+`text/html`. This request prefers Markdown.
+
+```sh
+curl -H 'Accept: text/markdown;q=1, text/html;q=0.5' https://example.com/shop/
+```
+
+If `q` is omitted, its quality is 1. A more specific media range takes
+precedence over a wildcard when determining each type's quality. If
+qualities are equal, `Accept` is missing, or neither type is acceptable, the
+edge serves HTML. A page without a Markdown twin continues to serve HTML. A
+Markdown file alone does not create a page or a directory index.
+
+The served Markdown has the content type `text/markdown; charset=utf-8`. For
+a page with a twin, both representations include `Vary: Accept`, including
+HEAD, conditional and range responses. Existing `Vary` values are preserved,
+with `Accept-Encoding` included when the response is compressed.
+
+The existing slash redirects and `_redirects` rules apply before selecting
+a representation. For example, `/shop` still redirects to `/shop/` unless
+your redirect rules override that behaviour. You can request
+`/shop/index.md` or `/page.md` directly as ordinary files.
+
#### Redirects for a static site
Put a file named `_redirects` at the top of the site directory. It uses the
diff --git a/docs/superpowers/notes/census-proposal-static-markdown-twins.md b/docs/superpowers/notes/census-proposal-static-markdown-twins.md
new file mode 100644
index 000000000..f3b5605b4
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-static-markdown-twins.md
@@ -0,0 +1,25 @@
+# Census approval: static-markdown-twins
+
+Ruling `census-ruling-static-markdown-twins`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/edge/static.go` `staticSite.serveFile` | body | unchanged (2) | Accepts a forced representation content type for ordinary and non-200 responses, including tag fallback; existing os.Open and open-file Stat now operate on the selected HTML or Markdown file inside the extracted digest-verified tree; no additional read site and no root decision. |
+| `internal/edge/static.go` `staticSite.serveTree` | body | unchanged (2) | Selects an existing regular Markdown sibling only after HTML resolution and redirects, checks the selected target against the hard tier, adds Vary: Accept and passes path/info/type to serveFile; existing Stat sites are unchanged; the selector adds the sibling Lstat described below; no root decision. |
+
+Envelopes re-pinned: `internal/edge`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/edge/static.go` `staticSite.serveFile`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; serveTree's former Open and open-file Stat of the file serveTree resolved inside the extracted, digest-verified tree, unchanged, plus a non-200 branch that copies the same open file under a _redirects 404 status; no root decision;rev3=census-ruling-static-headers;basis=takes the in-memory _headers lookup result (extra) and, on the 200 branch only, wraps the writer in headerWriter, which sets those header values on 200/206/304 at status time; the same Open and open-file Stat of the same resolved file; no read added, no root decision
+- `internal/edge/static.go` `staticSite.serveTree`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the same index-aware Stat lookup inside the extracted tree, now run at most twice (the request path, then once for a _redirects rewrite destination cleaned rooted inside the same tree); the Open moves to serveFile; the _redirects file itself is never answered; no root decision;rev3=census-ruling-edge-protection-2;basis=consults the edge protection matcher (internal/edgeguard, pure and in-memory) on the request path (probe tier, only when no file and no _redirects rule names it) and on a rewrite target (hard tier, only when the file is there), and may answer the guard's 404 block page through guardDecide before a redirect or the rewritten file; the _redirects lookup gains an in-memory names check; the same index-aware Stat lookups inside the extracted tree, unchanged; no read added;rev3=census-ruling-static-dir-slash;basis=A directory requested without its trailing slash now answers a 301 to a relative "./<base>/" (query kept) instead of serving its index.html, unless the request was rewritten, the path ends in "/", a _redirects rule names the path, or the rules would redirect its slash form (redirectsSlashForm, the existing in-memory resolve with exists=true). It opens and stats exactly the files it did before; the new branch only writes a Location header and a status, from the request path and the rules it already parsed.;rev3=census-ruling-static-headers;basis=computes the in-memory _headers lookup once on the cleaned request path and host and passes it to serveFile; the _headers file itself is never answered (found excludes it, as _redirects); the same index-aware Stat lookups inside the extracted tree; no read added;rev3=census-ruling-probe-burst-limit;basis=where the guard already checks the probe tier for a path the tree does not have, it also asks whether the path is in the catalogue (staticBurstHit, the in-memory edgeguard matcher) and, for a client in a probe-burst cool-down, may answer the 429 burst refusal (staticBurstDecide, the in-memory limiter) before a redirect or rewrite; the same index-aware Stat lookups inside the extracted tree; no new root read or write kind
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/edge/static_markdown.go:selectStaticRepresentation`: reads +file:Lstat; written legacy, accepted-legacy, frozen
+
+Seal: `657f81eeea52785b75f92a42064f63f218787f712ef313e2acf44f7e664e16b9` → `ec831d3206622f34511bfbc2ec0cccb131fbd3861ec4c6a33a2dc6dff9a1791e`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-static-markdown-twins.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-static-markdown-twins-claims.tsv b/docs/superpowers/notes/census-static-markdown-twins-claims.tsv
new file mode 100644
index 000000000..5e19c8147
--- /dev/null
+++ b/docs/superpowers/notes/census-static-markdown-twins-claims.tsv
@@ -0,0 +1,3 @@
+internal/edge/static.go:staticSite.serveFile Accepts a forced representation content type for ordinary and non-200 responses, including tag fallback; existing os.Open and open-file Stat now operate on the selected HTML or Markdown file inside the extracted digest-verified tree; no additional read site and no root decision.
+internal/edge/static.go:staticSite.serveTree Selects an existing regular Markdown sibling only after HTML resolution and redirects, checks the selected target against the hard tier, adds Vary: Accept and passes path/info/type to serveFile; existing Stat sites are unchanged; the selector adds the sibling Lstat described below; no root decision.
+internal/edge/static_markdown.go:selectStaticRepresentation Adds file:Lstat of the .md sibling of an already resolved regular .html file inside the extracted digest-verified tree; refuses symlinks and non-regular twins, then selects only on strict positive Accept preference; edge runs as carlos, with no root decision.
diff --git a/docs/superpowers/plans/2026-11-04-agent-start-demo-2-edge-protections.md b/docs/superpowers/plans/2026-11-04-agent-start-demo-2-edge-protections.md
new file mode 100644
index 000000000..dc0830863
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-04-agent-start-demo-2-edge-protections.md
@@ -0,0 +1,250 @@
+# Edge protections for demo hosts Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Serve anonymous demos with an edge-inserted warning banner, restrictive browser policy, lifetime traffic limits, and operator abuse controls.
+
+**Architecture:** The assigned demo box inserts edge-owned markup into HTML and enforces lifetime request/response-byte caps with durable local counters. All demo traffic reaches that box through existing forwarding; no console call authorizes an individual request or response. Operator controls use the console API/CLI and existing box stream; takedown reuses Plan 1 retirement.
+
+**Tech Stack:** Go 1.26, net/http, local SQLite transactions, existing fleet authentication/forwarding and job stream, streaming HTML rewriting and browser CSP.
+
+**Spec:** `docs/superpowers/specs/2026-11-02-agent-start-demo-design.md` §§4.3, 4.4, 4.6 and 5; merged `docs/superpowers/plans/2026-11-02-agent-start-demo-1-anonymous-apps.md`, especially lines 88-96; `docs/superpowers/notes/agent-start-demo-1-rulings.md`, including amendments R19b, R20a and R23b. Paul's 2026-11-04 banner and local-counting rulings supersede this plan's earlier shell and central-accounting choices. The current code, rather than Plan 1's proposed signatures, is the implementation baseline.
+
+## Global Constraints
+
+- Plan 2 of 4 only. No claim implementation, website, new builder, replication, infrastructure provisioning or production activation.
+- Fixed requirements: “24 hours, no extension without claiming”; “nothing is backed up”; “no outbound network at all”; “no email, object storage, schedules, sidecars or custom domains”. Keep Plan 1 enforcement.
+- Paul's ruling 9 is fixed: `form-action`, `connect-src`, `img-src`, `script-src` limited to `'self'`; no first-visit warning page. No nonce, external origin, `data:`, `blob:`, inline-script or eval exception to those four directives.
+- Banner markup and its same-origin stylesheet live under edge control at `/.carlos/demo/`; a deliberately hostile app can hide or remove the banner. CSP, lifetime caps, 24-hour expiry and takedown bound abuse. Readiness still probes the actual app unchanged.
+- Local counters are keyed by demo ID and lifetime, survive restarts/updates, and are removed with local purge. Persist before dispatch/output: crash overservice bound is zero requests and zero bytes; failed delivery can conservatively spend allowance. No console traffic RPC, whole-response buffer or per-response size cap.
+- Defaults: 2,000 requests and 200 MB per lifetime; MB means 1,000,000 bytes, hence 200,000,000 bytes. Positive operator settings; no unlimited sentinel.
+- Provider-neutral core. No new S3 reads/writes on traffic, report, status or kill-switch paths; no new per-box polling. Existing retirement keeps its existing storage work.
+- Off by default. With a configured demo domain, disabled protection/serving refuses demos; it never restores unprotected Plan 1 serving. No demo configuration means ordinary behavior remains unchanged.
+- One branch, six tasks, one visible merge: banner, caps, report and operator controls together. Switch-on date: dev when this plan lands, in that landing session; Carloku when `/start` ships after Plans 3 and 4. Paul is the requester and sees the protected live demo in Task 6.
+- Dev facts, 2026-11-04: app launch takes `--socket` and `--db` flags; certificates come from the housekeeper, not ingress; demo boxes have 2 GB RAM and never compile tests; one `*.trycarlos.com` wildcard covers single-label names; admission is a console drop-in; public demo names are never reused (R19b); SQLite is local to its assigned box, with no replica.
+- Keep additive wire compatibility. Old boxes must not serve demos during activation. Do not assume an old edge understands a new switch.
+- Examples use `shop` and `example.com`. `trycarlos.com` is a deployment value, never a provider-specific core default. All proposed human-facing strings are in the one copy table below; implementation requires copy review. No em dashes in copy.
+- This authoring session changes only this document, with no product code, commits, pushes, agents or full test run. Commands and commits below are instructions for the later implementation session.
+- Tests and browser profiles run on a development machine, with disk scratch, normal Go caches, isolated credentials, and servers bound to loopback or the approved Tailscale address. Delete scratch and stop processes afterward.
+- Production/shared-account resource changes require separately scoped authorization. This document does not authorize them.
+
+## Review Focus
+
+1. HTML without a body, malformed markup, compression or a partial response loses the warning: Task 2 tests insertion/fallback and readiness; browser tests explicitly demonstrate the accepted hostile-script removal limit.
+2. Parallel requests through two ingresses race a cap or a process crashes during disk/output writes: Task 3 tests one assigned-box counter, durable debits, zero crash overservice and no allowance reset.
+3. Compression, ranges, trailers, cached bodies or long streams escape accounting/policy: Tasks 1-3 test final streaming bytes, cap truncation and every response exit without banning ordinary representations.
+4. Stop/takedown races publication, a running response or a disconnected box: Tasks 3-4 test local fencing, bounded control expiry and truthful pending/confirmed stop status.
+5. A report, CLI credential or forged host names another tenant, reflects script, or leaks a claim token: Tasks 4-5 test operator authority, escaping and secret exclusion.
+
+---
+
+## Baseline evidence and file map
+
+Read against `2914921ceabd4218b0363a9780f8e4db890aab4c`. Line anchors below refer to that checkout. All new names and signatures below are proposed, not existing APIs.
+
+| Existing interface | Evidence and consequence |
+|---|---|
+| Demo identity | `internal/registry/demo.go:5`: `Route.IsDemo() bool` treats a partial descriptor as marked. `internal/edge/demo.go:18` recognizes a direct demo label without a route; `:27` validates lifetime, exact host, account and fleet; `:47` strips aliases/path overrides; `:81` refuses catch-all fallback. Keep those checks for the demo host. |
+| Forwarding | `internal/edge/edge.go:977` builds the forward arm; `:3847` forwards via the assigned fleet tunnel. `internal/edge/demo_test.go:32` tests forbidden aliases, shadow sockets and reserved names. All ingress paths converge on that assigned box; only it debits traffic and rewrites app HTML. |
+| Response ordering | `internal/edge/edge.go:1890` starts request handling, `:1996` resolves the route, `:2327` meters output, `:2486` admits upgrades, `:2532` serves local assets, `:2547` compresses, `:2601` admits shared-cache use, and `:2643` activates/proxies. `:3222` supplies ordinary unknown-host fallback. Demo controls must precede all of these response exits. |
+| Cookie trailers | `internal/edge/edge.go:2900` already recognizes ordinary and `Trailer:` forms of Set-Cookie. Demo processing must account for both, rather than sanitize only the initial header block. |
+| Domain/TLS | `internal/edge/demo.go:72` adds the demo parent to wildcard domains. `internal/edge/edge.go:1564` is `Allowed`; `internal/host/agent.go:1093` supplies the housekeeper issuer gate. Use the existing public demo name and wildcard unchanged. |
+| Identity storage/transactions | `internal/console/demo_store.go:29` defines `DemoRow`; `:51` migrates demo tables; `:88` serializes SQLite writers; `:364` implements `withDemoLocked(context.Context, string, func(DemoRow, AppLife) error) error`. `:388` refuses expired/retired rows, so takedown retries need a separate lock-and-reread helper, not that live-only callback. |
+| Retirement | `internal/console/demo_expiry.go:76` is `expireDemoLocked(context.Context, DemoRow, time.Time) error`; `:92` currently refuses early retirement. `:97` binds a signed receipt to the original lifetime and assigned box; `:125` fences generation, token and jobs; `:241` completes purge and writes the permanent host tombstone. The signed receipt validator at `internal/demobuild/retirement.go:25` also requires Tombstone >= ExpiresAt. Task 4 must extend that signed format explicitly for operator retirement, not fake either clock. `internal/host/demo_cleanup.go:20` checks the signature and stored receipt/tombstone before purge; `internal/instancectl/demo_cleanup.go:90` still checks the original descriptor and releasing hold. |
+| Retention | `internal/console/demo_store.go:400` prunes identifying abuse data seven days after confirmed purge; `:410` keeps the permanent host tombstone. Extend this same pass for reports. Local counters instead leave with local purge. |
+| Box authentication | `internal/console/apidemobox.go:93` is `demoBoxAuth(*http.Request) (name, token string, ok bool)` and verifies active fleet credentials; `:191` sends pending work/retirements. `internal/host/interactive.go:153` loads the fleet name/token; `internal/host/demo_jobs.go:525` validates the configured HTTPS console origin. Reuse this authenticated stream for serving controls; its existing 10-second heartbeat carries renewals without a new poller. |
+| Host wiring | `internal/host/agent.go:1133` supplies the `*edge.Edge` startup callback. Wire the local counter store and serving gate there. No new root control-socket method is needed for traffic. `internal/console/tempstore.go:130` already permits marking a temporary demo deleted before expiry while preserving its original expiry. |
+| Readiness | `internal/console/demo_publish.go:228` currently makes a redirect-refusing GET of the app host and requires 2xx plus the expected `X-Carlos-Version` at `:249`. Insertion must preserve that app status/version check; no synthetic HTML success may satisfy it. |
+| Console admission | `internal/demo/config.go:31` parses switches; `internal/console/apidemo.go:259` registers demo routes; `:295` checks admission. `cmd/console/main.go:478` loads demo configuration and `:718` starts the existing jobs loop. Stopping admission alone does not stop already-live traffic. |
+| Operator authority | `internal/console/apisystemupdate.go:144` is `apiSystemRoller`, accepting a human ops owner or `CARLOS_SYSTEM_OPERATORS`; `internal/console/authcli.go:1046` shows `cliRoute` with empty `svcrole.Set`. Do not use `apiSystemOperator` at `internal/console/apisystem.go:44`: it is the storage-scanning operator gate. |
+| SQL guards | `internal/console/store_gate.go:190` inventories tables; `:191` uses refusal-only demo identity scopes. New demo-scoped tables need the same claims-mode refusal, with `internal/console/claim_invariant_test.go:188` witnesses. |
+| CLI and launch | `system.go:43`/`:62` parse and dispatch system families; `main.go:193` dispatches `system`. `internal/activator/backend_exec.go:2530` and `:2733` pass socket/database flags. The fixture at `internal/demobuild/testdata/starter/main.go:5` has an empty main, so it is not a working browser fixture. |
+
+File ownership: Task 1 owns response policy; Task 2 owns HTML insertion and stylesheet; Task 3 owns local counters, streaming enforcement and box wiring; Task 4 owns operator control/stream delivery and retirement; Task 5 owns reports; Task 6 owns integration and census evidence. Tests live beside their implementation. No generic middleware or queue framework.
+
+## Decisions and cross-task contracts
+
+### Banner insertion (Paul's fixed ruling, 2026-11-04)
+
+Serve the app at its original host/path, with no presentation host, navigation redirect or Fetch Metadata routing. Insert an edge-owned warning and report link at the start of `<body>` in every HTML response, including HTML errors and platform pages. Link the embedded same-origin `/.carlos/demo/banner.css`; reserve `/.carlos/demo/` before app dispatch. CSS uses a fixed top warning with readable contrast and spacing, usable at 320 px and 200% zoom. The app supplies neither markup nor stylesheet URL. Escape the canonical host in the report URL; no private claim link enters the document.
+
+Use `golang.org/x/net/html` tokenization with at most 64 KiB of prefix buffering, preserving original bytes. On an actual body start token, insert immediately after it; ignore text resembling tags inside comments/scripts. On EOF or the prefix bound without a body, insert the fixed-position equivalent before the buffered document, retaining a leading doctype ahead of it when present. This bound selects a fallback; it never rejects a larger document. Stream the remainder. The edge injects once on the assigned box, not again at forwarding ingresses. Platform renderers include the same banner directly; empty HEAD/204/304 responses have no document to rewrite.
+
+The warning is a notice, not a security boundary against its own document. A deliberately hostile app's same-origin scripts can remove it or CSS can cover it. Browser tests must demonstrate this limit rather than promise containment. Keep the strict CSP, caps, original expiry, report link and takedown. Readiness remains the existing redirect-refusing GET with exact 2xx/version checks: no special headers, synthetic success, exemption or change to the probe.
+
+### Policy and representations
+
+Set this single edge-owned enforced CSP on every demo response, including redirects, errors, HEAD, 304 and platform pages:
+
+`default-src 'none'; form-action 'self'; connect-src 'self'; img-src 'self'; script-src 'self'; script-src-attr 'none'; style-src 'self' 'unsafe-inline'; font-src 'self'; media-src 'self'; object-src 'none'; base-uri 'none'; worker-src 'none'; manifest-src 'none'; frame-ancestors 'none'`
+
+The four ruling-9 directives remain exactly `'self'`. Replace app CSP/report-only headers and policy trailers. There is no sandbox or shell-specific frame policy; default-src still refuses child frames. Also force `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, `Cache-Control: no-store`, `X-DNS-Prefetch-Control: off` and `Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), fullscreen=(), document-domain=()`. Remove app Refresh, Link, CORS grants, reporting endpoints, Clear-Site-Data and Service-Worker-Allowed. Refuse worker/serviceworker/sharedworker destinations. Names are never reused.
+
+Allow an app HTTP redirect only when its Location resolves to the same HTTPS origin without credentials or ambiguous/control-character syntax. Relative redirects retain meaning; invalid or duplicate Locations get the plain 502 page. This does not promise to prevent every scripted navigation or data leak. Strip every Domain attribute case-insensitively from separate Set-Cookie fields; preserve valid attributes and Expires commas, never comma-split/coalesce cookies, and drop malformed cookies. Drop cookie/policy trailers in both declared and Go `Trailer:` forms. Script-written parent-domain cookies remain the design's accepted exception.
+
+Compression and ranges are allowed. Decode/re-encode compressed HTML as a stream around insertion; negotiate supported encodings (identity/gzip) upstream for HTML rewriting and refuse an unsupported HTML encoding/charset rather than silently omit the warning. Keep UTF-8 `text/html` (absent charset means UTF-8); continue refusing XHTML/other active document types. Non-HTML representations keep normal compression/range semantics. For partial or conditional HTML, retry an idempotent GET once without range/conditional headers to obtain a full document; refuse if it still cannot be transformed. Clear stale Content-Length, validators, digest and range headers on changed HTML; HEAD keeps its no-body semantics. These are transformation rules, not accounting restrictions.
+
+Keep demo no-store and bypass shared caches, including preexisting entries, so neither a cached document nor a local asset shortcut bypasses insertion/counting. Count asset responses through the resident path. Ordinary streams/SSE may run until expiry, stop or quota; no buffer-slot, response-size or ledger timeout restrictions. Retain refusal of protocol upgrades: the HTTP policy/cookie wrapper must not hand an app a raw socket. Ordinary-host behavior is unchanged.
+
+### Durable local counting
+
+The assigned box is the sole counter owner. Use an edge-owned SQLite database beside its registry (`demo-traffic.db`, inaccessible to demo processes), with `synchronous=FULL` and a composite `(demo_id, lifetime)` key. Each row stores requests, body_bytes, caps and terminal state. Build generation is not a key. Create the row once from authenticated initial demo assignment before readiness; updates never create/reset one. A missing row for an already-initialized demo, corrupt database, disk error or mismatched assignment refuses serving. A replacement box cannot start a fresh allowance. Purge stops dispatch/writers, deletes the matching counter row and completes through existing retirement; a stale route can never recreate it.
+
+Debit one request durably before activation/dispatch. All app methods, assets, errors and readiness count, including HEAD and failed dispatch. Debit final response-body bytes after banner insertion and compression, immediately before each output chunk, in chunks of at most 32 KiB. Include injected markup in those bytes. Never transform/recompress them on a later hop; exclude HTTP/TLS framing and request uploads. Fixed edge stylesheet/refusal pages and console reports are platform overhead, excluded from lifetime counters and still subject to ordinary abuse limits; edge refusal pages remain bounded to 8 KiB.
+
+Serialize debit transactions across concurrent requests/processes. Admission refuses either exhausted cap; nonnegative SQL checks and checked int64 arithmetic reject invalid/overflowing debits. A byte debit returns at most the remaining allowance; write only that prefix, cancel the upstream and abort the incomplete response if more bytes are attempted. Do not append an HTML limit page to an already-started body. Later requests receive 429. Exactly the request cap may be admitted; already-admitted requests can finish while byte allowance remains. HEAD/204/304 cost zero body bytes. No refunds after a successful debit: a crash/short write may spend undelivered bytes, but durable totals never under-count delivered bytes across restarts. **Crash overservice: zero requests, zero bytes.** There is no whole-response buffer or per-response size limit; the lifetime byte cap is the only output-size ceiling.
+
+`CARLOS_DEMO_REQUEST_CAP` defaults to 2000 (range 1..1000000); `CARLOS_DEMO_BANDWIDTH_CAP_BYTES` defaults to 200000000 (range 1..10000000000). Parse as int64 and snapshot caps in the original assignment/local row; later configuration affects new lifetimes only. Counter exhaustion keeps data/token until original expiry/claim. Console totals are optional and omitted in this slice; operator status reports lifecycle, caps and stop/cleanup state, never guessed usage. No accounting RPC, public state lookup or new polling is introduced.
+
+### Serving controls without request-path console calls
+
+Effective serving requires `CARLOS_DEMO_EDGE_PROTECTIONS=1` (unset false; other values invalid), the durable console serving switch, a current assigned-box control snapshot and a live local lifetime. The switch starts false; off also refuses creates/updates, while cleanup/reporting remain available. Task 4 sends controls through the existing authenticated demo job stream on change and its existing 10-second heartbeat. Each snapshot echoes the box's latest heartbeat probe and expires no later than 30 seconds after that probe was sent, measured by the box's monotonic clock. It lists only unexpired, non-retired assigned lifetimes (including starting demos for readiness); delayed delivery cannot extend validity. A box starts closed after restart, closes immediately on disconnect, and refuses expired, replayed, mismatched or malformed controls. No browser request contacts the console.
+
+The console transaction fences admission/publication immediately. The assigned box fences new dispatch/output when it applies off/retirement or its snapshot expires; retirement never reopens on a later global on. Cancel active response contexts, and bound an already-started output write to five seconds on every forwarding hop. The resident-stop bound is 35 seconds from the console fence (30-second maximum remaining validity plus five seconds for an in-flight write); buffered bytes already handed to transport cannot be recalled. A control operation reports pending until box acknowledgement or that bound, rather than falsely claiming an immediate distributed fence. Disconnection/console outage therefore closes serving without a synchronous request dependency. Cap pages are 429, stopped/unavailable 503, expired/unknown/retired names the same plain 404, all with policy/no-store.
+
+## Task 1: Enforce demo response policy and safe fallback
+
+**Risk/review:** security gate, redirect, cache. Independent task review required.
+
+**Files:** Create `internal/edge/demo_response.go`, `internal/edge/demo_copy.go`; modify `internal/edge/demo.go:18`, `internal/edge/edge.go:1890`, `:3222`; test `internal/edge/demo_response_test.go` and existing `internal/edge/demo_test.go`.
+
+**Interfaces:**
+- Consumes `registry.Route.IsDemo() bool`, `(*Edge).demoHost(string) bool`, `(*Edge).demoReserved(string) bool` and `(*Edge).demoRouteOK(string, registry.Route) bool`.
+- Produces `demoCSP() string`; `rewriteDemoCookies(h http.Header) error`; `sanitizeDemoHeaders(h http.Header, host string) error`.
+- Produces `serveDemoPlain(w http.ResponseWriter, r *http.Request, status int, copyID string)` and `(*Edge).beginDemoResponse(w http.ResponseWriter, r *http.Request) http.ResponseWriter`. The latter owns a private header map and sanitizes every final write; it suppresses 1xx/trailers and never exposes Hijack for a demo. It does not authorize an app request.
+
+- [ ] **Step 1: Write failing tests.** `TestDemoPolicyEveryExit`: assert exact CSP on 200/204/303/304/400/404/429/502/503, HEAD, tunnel failure, invalid marked routes, unknown/apex/nested reserved hosts and mixed-case authority; no ordinary fallback redirect or app dispatch for invalid identity. `TestDemoCookieRewrite`: assert two cookies stay separate, all duplicate/mixed-case Domain attributes disappear, Expires and security attributes survive, malformed values and both trailer forms cannot escape. `TestDemoHeaderIsolation`: mutating the upstream header map after WriteHeader cannot alter the enforced policy or ordinary cached headers.
+- [ ] **Step 2: Run** `go test ./internal/edge -run 'TestDemo(PolicyEveryExit|CookieRewrite|HeaderIsolation)' -count=1`; expect FAIL for missing enforcement.
+- [ ] **Step 3: Implement** the interfaces and the policy above. Classify reserved demo names at request entry, before fallback/backhaul/error exits, and marked routes again after lookup. Normalize the host once for demo classification, rejecting invalid authority rather than letting mixed case/ports/trailing dots bypass controls. Keep `demoRouteOK` as the binding authority; refuse disabled demo serving until Task 3 is connected. There is no raw-response escape through Unwrap/ResponseController.
+- [ ] **Step 4: Rerun** the targeted command plus `go test ./internal/edge -run 'TestDemoDomain' -count=1`; expect PASS, including unchanged ordinary-host behavior.
+- [ ] **Step 5: Commit** the files above with subject `feat: enforce demo response policy and host-only cookies`.
+
+## Task 2: Insert the warning into demo HTML
+
+**Risk/review:** security policy and redirect handling. Independent task review and real-browser evidence required; banner visibility is not an authority boundary.
+
+**Files:** Create `internal/edge/demo_banner.go`, `internal/edge/demo_assets/banner.css`, `internal/edge/demo_banner_browser_test.go`, `internal/edge/testdata/demo-protections/main.go`, `internal/edge/testdata/demo-protections/app.js`, `internal/edge/testdata/demo-protections/style.css`, `internal/edge/testdata/demo-protections/go.mod`, `internal/edge/testdata/demo-protections/go.sum`; modify `internal/edge/edge.go:1890`, `internal/edge/demo_copy.go`; test `internal/edge/demo_banner_test.go`, `internal/console/demo_publish_test.go`. The production readiness probe is unchanged.
+
+**Interfaces:** Consumes Task 1 policy/rendering and canonical demo identity. Produces `injectDemoBanner(dst io.Writer, src io.Reader, host, reportOrigin string) error` for decoded UTF-8 HTML and `(*Edge).serveDemoAsset(w http.ResponseWriter, r *http.Request) bool` for the reserved stylesheet path. Task 3 places injection before final compression and accounting; platform HTML rendering uses the same edge markup without double insertion.
+
+- [ ] **Step 1: Write failing tests.** `TestDemoBannerInsertion`: body at start/after head, mixed case, comments/script lookalikes, malformed/no-body/empty HTML, prefix over 64 KiB and a large streaming body; exactly one edge warning/style link, original app bytes preserved, no size rejection. `TestDemoBannerRepresentations`: gzip, full/partial/conditional HTML, non-HTML ranges, HEAD/204/304, content metadata and platform HTML errors. `TestDemoProbeStillChecksApp`: real app 2xx/version succeeds; wrong version, redirect or app failure cannot be hidden by insertion; reserved assets never carry an app version. An empty successful app response retains its actual status/version. `TestDemoBannerBrowser`: normal Rastrillo/Fiesta app, forms/cookies/self fetch/self external script, inline-script refusal, direct/deep links, absent Fetch Metadata, mobile width/zoom; hostile same-origin JS can remove the notice, while enforced CSP still blocks foreign form/fetch/image/script targets.
+- [ ] **Step 2: Run** `go test ./internal/edge ./internal/console -run 'TestDemo(Banner|ProbeStillChecksApp)' -count=1`; expect FAIL. Run `CARLOS_DEMO_BROWSER_TESTS=1 go test ./internal/edge -run TestDemoBannerBrowser -count=1` with installed Chromium/Firefox and loopback chromedriver/geckodriver using W3C WebDriver via net/http/encoding/json. Isolate test profiles and HTTPS trust overrides; a missing browser is outstanding evidence, never a passing skip.
+- [ ] **Step 3: Implement** insertion, embedded stylesheet, reserved-path handling and the representation rules above. Build the working fixture from the demobuild lock's Rastrillo v0.30.2 closure with --socket/--db and local SQLite. Keep all navigation on the original host and the production probe unchanged. Use only edge-configured report origin and escaped canonical host. Include the banner in platform HTML once.
+- [ ] **Step 4: Rerun** Step 2 and existing demo routing tests; expect PASS. Observe actual DOM and network behavior, including the hostile-removal limitation. Safari is verified in Task 6.
+- [ ] **Step 5: Commit** with subject `feat: insert warnings into demo HTML responses`.
+
+## Task 3: Persist and enforce assigned-box lifetime counters
+
+**Risk/review:** security gate, local storage, cache and abuse allowances. Independent task review required. These counters do not replace billable usage meters.
+
+**Files:** Create `internal/demo/traffic.go`, `internal/edge/demo_traffic.go`, `internal/host/demo_traffic.go`; modify `internal/demo/config.go:22`, `internal/edge/edge.go:1890`/`:2532`/`:2547`/`:2601`, `internal/host/agent.go:1133`, `internal/host/demo_jobs.go`, `internal/host/demo_cleanup.go`; test `internal/edge/demo_traffic_test.go`, `internal/edge/demo_forward_test.go`, `internal/host/demo_traffic_test.go`, `internal/host/demo_cleanup_test.go`.
+
+**Interfaces:**
+- `demo.TrafficIdentity` has `ID, Lifetime, Host string`; `demo.TrafficCaps` has `Requests, BodyBytes int64`. `demo.TrafficCounter` supplies `Admit(context.Context, TrafficIdentity) error` and `DebitBytes(context.Context, TrafficIdentity, int64) (int64, error)`. Exhaustion returns `demo.ErrTrafficLimit`; storage/binding failure is unavailable, never a reset.
+- `host.openDemoTraffic(path string) (*demoTrafficStore, error)` opens the local database; its `Initialize(ctx context.Context, id demo.TrafficIdentity, caps demo.TrafficCaps) error` is called only during authenticated first assignment, and `Purge(ctx context.Context, id demo.TrafficIdentity) error` only after local retirement stops writers. Close the store at shutdown. SQL debit commits precede dispatch/output.
+- `(*Edge).SetDemoTraffic(counter demo.TrafficCounter, serving func(registry.Route, time.Time) bool)` wires local enforcement. `(*Edge).serveDemoTraffic(w http.ResponseWriter, r *http.Request, up upstream)` consumes Tasks 1-2 and Task 4's local serving gate. Forwarding ingresses sanitize policy but neither debit nor rewrite/recompress resident bodies. The resident checks exact host/account/fleet/assigned-box/lifetime against its route, never a client skip header.
+
+- [ ] **Step 1: Write failing tests.** `TestDemoTrafficAcrossIngresses`: two ingresses, one assigned box, every method/asset/error/readiness charged once, forged headers/copied routes refused. `TestDemoTrafficDurability`: two database handles race 1,999/2,000 requests and 199,999,999/200,000,000 bytes; kill/reopen around each debit/output boundary, short writes, generation updates, missing/corrupt rows, disk-full/fsync failure and replacement box; no delivered byte/request escapes durable accounting or resets allowance. `TestDemoTrafficStreaming`: body larger than the former 2 MiB limit, compressed HTML/non-HTML, ranges, SSE/Flush, io.Copy/ReaderFrom, trailers, zero-body statuses, partial cap write and a never-ending stream; 429 thereafter, no full-body buffer and no transformation on later hops. `TestDemoTrafficPurge`: active writes fenced before row removal, retry after interruption, stale routes cannot recreate rows. `TestDemoTrafficNoConsole`: request path makes no console/S3 calls; ordinary metering/compression/cache behavior unchanged.
+- [ ] **Step 2: Run** `go test ./internal/edge ./internal/host -run 'TestDemoTraffic' -count=1`; expect FAIL.
+- [ ] **Step 3: Implement** the local store and resident pipeline: identity/control checks → durable request debit → activation/proxy or local asset → policy/banner → negotiated compression → durable byte debit → output. Keep existing plan throttles/request-abuse checks once, skip shared cache/asset shortcuts, and prevent Hijack/Unwrap/ReaderFrom bypasses while supporting Flush for streams. Enforce expiry/control cancellation on active responses as well as new requests. A zero-byte debit error before headers gets the platform page; an error after output begins aborts the response. Recheck control before each write; use five-second write deadlines on every hop. Wire initialization before first readiness and deletion into existing local purge before acknowledgement, without broadening root deletion paths. Existing initialized demos lacking counters remain refused.
+- [ ] **Step 4: Rerun** Step 2 plus `go test ./internal/edge -run 'Test(Demo|ForwardResponseCarriesTheBoxVersionOnce)' -count=1`; expect PASS. Instrument actual resident output to prove durable debits bound delivered bytes across crashes. Local storage failure never falls back to in-memory counters.
+- [ ] **Step 5: Commit** with subject `feat: enforce durable local demo traffic caps`.
+
+## Task 4: Add serving control and takedown
+
+**Risk/review:** security gate, termination, storage. Independent task review required, explicitly including authenticated stream control authority, the signed early-retirement trust boundary and its root-facing consumer. Root's purge method and path/hold checks stay unchanged; the reviewed change is the console-signed permission to retire before expiry.
+
+**Files:** Create `internal/console/apidemooperator.go`, `system_demos.go`, `system_demos_api.go`; modify `internal/demobuild/job.go:160`, `internal/demobuild/retirement.go:13`, `internal/console/demo_store.go:51`, `internal/console/apidemobox.go:191`, `internal/host/demo_jobs.go`, `internal/host/demo_traffic.go`, `internal/console/demo_expiry.go:76`, `internal/console/apidemo.go:295`, `internal/console/authcli.go:1046`, `system.go:43`/`:62`, `docs/site/cli.md`; test `internal/demobuild/retirement_test.go`, `internal/host/demo_retirement_stream_test.go`, `internal/console/demo_operator_test.go`, `internal/console/demo_expiry_test.go`, `internal/host/demo_serving_test.go`, `system_demos_test.go`.
+
+**Interfaces:**
+- Consumes `apiSystemRoller`, `cliRoute(..., svcrole.Set{}, ...)`, Task 3 local counters and Plan 1 signed retirement.
+- Add optional `Serving *demo.ServingControl` to `demobuild.StreamMessage` and optional `ServingProbe uint64` and `ServingAck int64` to the existing worker heartbeat. Define `demo.ServingControl` in `internal/demo/traffic.go`: `Revision, ValidUntil int64; Probe uint64; Enabled bool; Demos []ServingDemo`; `ServingDemo` contains `Identity TrafficIdentity; Caps TrafficCaps; ExpiresAt int64`. Controls are scoped to the authenticated stream's assigned box. Revision is durable, increases on control/assignment changes, and acknowledgements identify the installed revision only after active writes are drained/cancelled; they cannot confirm a newer revision or another stream session. On each existing heartbeat the worker records a fresh probe and monotonic send time (retain at most four); the console echoes it with ValidUntil no later than issuance plus 30 seconds. Accept only a probe from the current connection; refuse older revisions and non-increasing renewal deadlines. Local validity ends at the earlier of that absolute deadline or probe-send time plus 30 seconds, so skew/delay cannot enlarge the stop bound. Clock rollback closes serving. Missing fields preserve old wire decoding but never enable new protected serving. Older serving boxes must be drained before activation.
+- Implement `(*demoWorker).applyDemoServing(control demo.ServingControl, now time.Time) error` and `(*demoWorker).demoServingAllowed(route registry.Route, now time.Time) bool`. Keep its lock shared with local dispatch/write admission; retired identities remain fenced. Persist revision/state, start closed after restart, and initialize a counter only for a newly assigned, not already-initialized lifetime. Serialize control issuance with the console mutation/retirement fence so it cannot renew obsolete authority. A fresh stream must receive current state before accepting work.
+- Produces `(*Server).retireDemoLocked(ctx context.Context, d DemoRow, now time.Time, reason string) error`, accepting only `expired|operator`; `expireDemoLocked` keeps its expiry predicate and then calls this common implementation. The operator path locks the app, rereads identity/lifecycle even when retiring, and calls it without altering the original expiry/lifetime. Retiring retries resume cleanup even before original expiry by rereading their existing signed receipt. Add `Reason string` with JSON `reason,omitempty` to demobuild.Retirement. Omitted reason retains the exact v1 validation and wire shape; only signed reason `operator` permits a positive Tombstone earlier than ExpiresAt. Unknown reasons fail. Keep the signing domain and existing public SignRetirement/VerifyRetirement signatures; the optional field is signed. Old strict decoders reject operator receipts, while new readers accept all old expiry receipts. No new control-socket payload or purge paths.
+- Produces `runSystemDemos(args []string)` in system_demos.go, called from runSystem. CLI family `carlos system demos`: `status`, `serving on|off`, `takedown --host <exact-public-host>`, and `takedown-status --host <exact-public-host>`. All use the configured remote console; no registry/AWS/on-box fallback. Exit 0 for an accepted action/state (including explicitly reported pending serving/cleanup), 2 for usage errors, 1 for transport/authentication/server failure.
+- Routes: `GET /api/cli/system/demos`; `PUT /api/cli/system/demos/serving` with `{enabled:bool}`; `POST /api/cli/system/demos/takedown` with `{host:string}`; `GET /api/cli/system/demos/takedown?host=...`. Status exposes serving/configured caps and demos' public host, state, caps and separate serving/cleanup confirmation status, never tokens/IPs/source. Mutations are idempotent.
+
+- [ ] **Step 1: Write failing tests.** `TestDemoOperatorAuthority`: ops owner/listed system operator succeeds; service/app credentials, non-ops members and forged identities get indistinguishable refusal; host must select an actual demo, never an ordinary app or an alias. `TestDemoKillFence`: off survives restart, blocks creates/updates and pushes local serving off, on does not revive retired/expired demos or reset counters, cleanup/reporting still works. `TestDemoTakedownBeforeExpiry`: receipt retains actual expiry, token/generation/jobs fenced, no new dispatch/output after the local fence, offline box serving/cleanup pending until the stated resident-stop bound, replay stops before delete and retries to permanent tombstone. Test races with publication and an already-retiring row. `TestDemoServingStream`: no extra polling, 10-second renewals, 30-second monotonic probe expiry, clock skew, delayed/replayed/old-session controls, clock rollback, missing fields, restart, disconnect, active streaming cancellation, five-second write bound, acknowledgements and stale on after retirement. `TestDemoOperatorRetirementWire` asserts old expiry receipts still verify, unsigned reason edits and unknown reasons fail, early expiry receipts fail, signed operator receipts succeed, and a legacy strict decoder refuses them. Exercise the full worker receipt/tombstone/hold/purge path before original expiry. `TestSystemDemosRemote`: exact API requests, output/exit codes, no local registry fallback, credentials from `carlosTestEnv`, subprocess Dir in scratch.
+- [ ] **Step 2: Run** `go test ./internal/demobuild ./internal/console ./internal/host -run 'TestDemo(Operator|Kill|Takedown|ServingStream)' -count=1` and `go test . -run TestSystemDemosRemote -count=1`; expect FAIL.
+- [ ] **Step 3: Implement** the operator API/CLI and extract retirement. Persist `demo_serving(id=1, enabled=false, revision, changed_at, changed_by)` and per-lifetime cap snapshots in demo identity storage. Commit the SQL fence before stream notification/external cleanup. Return 202 while serving confirmation or cleanup is pending, with separate `servingDesired` (bool), `servingConfirmed` (bool) and `cleanup` (`pending|complete`) fields; return 200 only when the requested stop is confirmed (and, for takedown, purge is complete). A cleanup failure never rolls serving back on. The existing jobs/expiry loop retries retirement, using its existing signed receipt and worker stream. Report fence failure as failure, not accepted takedown. Never label an unacknowledged offline box stopped before its 35-second bound. The CLI prints desired state and separate pending/confirmed serving and cleanup status; `takedown-status` completes verification remotely. Audit actor, host, reason and timestamp without credentials. Add the CLI heading and examples, with prose included in copy review.
+- [ ] **Step 4: Rerun** Step 2 plus `go test ./internal/console ./internal/host -run 'TestDemo.*Retirement|TestDemo.*Expiry' -count=1` and `go test ./internal/docsite -count=1`; expect PASS. Observe no new root method or expanded filesystem deletion scope; explicitly review the new signed operator-reason acceptance.
+- [ ] **Step 5: Commit** with subject `feat: add operator demo stop and takedown controls`.
+
+## Task 5: Store abuse reports in a small operator queue
+
+**Risk/review:** security gate, storage, redirect. Independent task review required.
+
+**Files:** Create `internal/console/demo_reports.go`, `internal/console/apidemoreports.go`, `internal/console/templates/demo_report.html`; modify `internal/console/demo_store.go:51`/`:400`, `internal/console/apidemo.go:259`, `internal/console/authcli.go:1046`, `internal/edge/demo_banner.go`, `system_demos.go`, `system_demos_api.go`, `docs/site/cli.md`; test `internal/console/demo_reports_test.go`, `internal/edge/demo_banner_test.go`, `system_demos_test.go`.
+
+**Interfaces:**
+- Banner links directly to the configured console origin's `/demo/report?host=<canonical-app-host>` using `target="_blank" rel="noopener noreferrer"`; no token, path, query, referrer or email. GET shows a form and never files a report.
+- Produces `(*Store).AddDemoReport(ctx context.Context, host, category, details, ip string, now time.Time) (string, error)` and `(*Store).ListDemoReports(ctx context.Context, after string, limit int) ([]DemoReport, string, error)`. `DemoReport` has `ID, Host, Category, Details, State string; CreatedAt int64`; no reporter identity in list output.
+- `POST /demo/report` accepts form category `phishing|harmful|other`, details at most 1,000 UTF-8 bytes, host and CSRF token. Console-host `__Host-carlos-demo-report` random signed double-submit cookie: Secure, HttpOnly, SameSite=Strict, Path=/, 15-minute expiry; require exact console Origin and matching token. Body cap 4 KiB. Confirmation is a rendered 200, not a supplied redirect.
+- CLI: `carlos system demos reports [--after <id>] [--limit <1..100>]` and `reports resolve --id <id>`; corresponding operator-only GET `/api/cli/system/demos/reports` and POST `/api/cli/system/demos/reports/{id}/resolve`. Default page size 50, ordered by creation time then ID, stable cursor.
+
+- [ ] **Step 1: Write failing tests.** `TestDemoReportQueue`: GET prefetch writes nothing; valid POST creates one open row; current/purged-within-retention host accepted; unknown and too-old names refused uniformly; list/resolve human-operator-only and idempotent. `TestDemoReportAbuse`: forged Origin/CSRF, missing cookie, duplicate form values, foreign host, oversize input, HTML/control characters, forged XFF and queue exhaustion; no redirect/SSRF and no script execution in UI/terminal. `TestDemoReportRetention`: restart retains reports, seven-day post-purge pruning removes them and hashed reporter metadata, permanent name tombstone survives. `TestDemoReportWhileStopped`: reports work while serving/admission is off and never touch release.Store. Extend CLI subprocess tests with isolation.
+- [ ] **Step 2: Run** `go test ./internal/console ./internal/edge -run 'TestDemoReport' -count=1` and `go test . -run TestSystemDemosReports -count=1`; expect FAIL.
+- [ ] **Step 3: Implement** one `demo_reports` table: ID primary key, demo_id, host, category, details, created_at, state (`open|resolved`), resolved_at, resolved_by, ip_hash. Persist attempts in `demo_report_attempts(ip_hash, attempted_at)` using the existing installation salt and canonical clientIP; allow 10 attempts/IP/hour, 500 global/day, 20 accepted reports/host/day, 2,000 retained rows total. Spend attempts before validation; reject a full queue without evicting. No attachments, email, notifications or automatic takedown. Escape HTML and JSON; strip terminal control characters in CLI rendering. Use the existing expiry pass to prune attempts older than 24 hours and reports seven days after purge. Anonymous report routes do not consult logged-in account sessions. Supply banner URL only from validated operator configuration.
+- [ ] **Step 4: Rerun** Step 2 and docsite tests; expect PASS. Confirm limits are durable through console restart and listing never exposes claim tokens or reporter IP hashes.
+- [ ] **Step 5: Commit** with subject `feat: add a demo abuse report queue`.
+
+## Task 6: Prove the complete slice and prepare dev activation
+
+**Risk/review:** integration evidence; whole-branch independent review required. Census review required for every changed root-binary unit/envelope; this is not exemption for edge-only Go changes.
+
+**Files:** Create `internal/console/demo_protections_e2e_test.go`, `docs/superpowers/notes/agent-start-demo-2-rulings.md`, `docs/superpowers/notes/census-agent-start-demo-2-claims.md`; modify Task 2's `internal/edge/testdata/demo-protections/main.go`, `app.js` and `style.css` fixtures, `README.md` demo operator section, `internal/console/claim_invariant_test.go`, `internal/console/store_gate.go:190`, `internal/console/claim_sql_census_test.go`, `internal/console/plan9_sql_seal_test.go` as required by their actual changed seams; generate `internal/provision/testdata/plan14-root-reads-agent-start-demo-2.tsv`, its chain entry, and `docs/superpowers/notes/census-proposal-agent-start-demo-2.md` using repository tools. Do not hand-edit seals to silence failures.
+
+**Interfaces:** Consumes all prior tasks. Leaves Plan 3 one narrow hook: local lifecycle handling calls `(*Edge).demoMovedPage(w http.ResponseWriter, r *http.Request, host string) bool` before the gone/limit branch, after the global serving check. Plan 2's implementation returns false and has no redirect-target field or claim authority. Plan 3 must supply authenticated lifecycle evidence and expiry-bound moved content; an app/header cannot select it. `/demo/claim#<token>` remains the private Plan 1/3 contract and never enters this hook, a banner or report.
+
+- [ ] **Step 1: Write failing integration tests.** `TestDemoProtectionsSourceToLimitAndTakedown`: real app using --socket/--db, two ingress paths, update preserving data and counters, stream cut at the byte cap, crash/restart preserving allowance, report recorded/listed/resolved, serving off/on, takedown with offline worker then resumed purge. `TestDemoProtectionsNoBucketTraffic`: zero browser-request console calls and zero added S3 calls for traffic, counters, reports and global switch; separately identify the existing retirement calls. `TestDemoProtectionsOrdinaryUnchanged`: ordinary app response headers/cache/compression/upgrades and unknown-host fallback unchanged. `TestDemoMovedHookInert`: no app-supplied moved response and expired hosts remain plain 404. Fixtures use relative self assets and a small external script; no test compilation on demo boxes.
+- [ ] **Step 2: Run** `go test ./internal/console ./internal/edge -run 'TestDemo(Protections|MovedHook)' -count=1`; expect FAIL for missing integrated behavior before fixture/wiring completion.
+- [ ] **Step 3: Complete** fixtures, moved hook and operator documentation. Record all my-call decisions and review history in the rulings file. Collect the copy table plus exact CLI/help/docs prose into the copy-review workflow; apply approved text verbatim before shipping. Document removable-banner limitations, durable local debit/short-write semantics, accounting exclusions, streaming cut behavior, cap snapshots, control-stream expiry/stop confirmation and why old lifetimes cannot be grandfathered with zero counters.
+- [ ] **Step 4: Verify** targeted tests and Chromium/Firefox browser witnesses, then run the required full repository gate once on the development machine: `go build ./...`, `go vet ./...`, `go test ./... -count=1`, `gofmt -l .` (empty output), plus `.amadan/ci.d/20-cross@5`'s `CGO_ENABLED=0 go build ./...` for darwin/arm64, darwin/amd64, linux/arm64, windows/amd64 and windows/arm64. Run `make census-card`; write unit claims; run `make census-propose NAME=agent-start-demo-2 CLAIMS=docs/superpowers/notes/census-agent-start-demo-2-claims.md`. Classify demo_reports as a refusal-only demo_id scope; local counter rows are box-local and absent from console SQL guards; demo_serving and demo_report_attempts are deployment-wide NonApp tables. Add claims-mode rejection witnesses for every app-scoped table and keep all demo operation handlers disabled in claims mode. Apply legitimate schema/record-write inventory additions with review. A cross-family reviewer reads the card and full diff, approves every changed unit/envelope with line evidence and records reviewer/tip on #280 during implementation. A skipped browser/live witness is listed as outstanding, never claimed as success.
+- [ ] **Step 5: Commit** the integration, approved copy and census files with subject `test: verify demo edge protections and operator controls`.
+- [ ] **Step 6: Land and activate** only in the later implementation session: push to amadan, describe validation/reviews, wait for green tip CI, squash through `amadan branch merge ... -expect <40-char-tip>`, then read main CI. In the approved dev scope, turn creates off with the console drop-in first. Roll every public ingress, housekeeper and demo serving box with serving off; remove/drain any old-version ingress from traffic before enablement. Takedown existing Plan 1 demos through the new CLI, waiting for confirmed purge, because their earlier lifetime usage was not recorded. Do not backfill zero counters. Verify the existing wildcard certificate from the housekeeper covers existing demo names, configure protections and the existing console origin on all edges, switch serving on through the CLI, then restore admission through the drop-in. Submit a fresh source fixture, verify banner and CSP in Safari as well as the automated browsers, hit small operator-configured caps on that fresh lifetime, report/list, stop, takedown and verify no serving through each ingress. Do not change DNS, IAM, certificates or production traffic without scoped authorization. On failure, serving off and admission off are the rollback; never roll back to unprotected serving.
+
+## Review budget and self-review
+
+Plan 2 external review history: zero rounds in this authoring session; no reviewer dispatched. Plan 1 finished whole-branch round 3 READY (`docs/superpowers/notes/agent-start-demo-1-rulings.md:86`); its design is merged and is not reopened. Carry the Plan 2 count across revisions, reviewers and handoffs. Use `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md` for task/branch reviews. Stop at the first round without P1, apply that round's P2s without reopening it, and defer P3s. Check the census and any new security/root/termination/storage behavior introduced by fixes within that budget. Maximum three rounds without Paul's approval; two successive rounds in one fault family trigger the refuse/cut/enforce-once choice. Tasks 1-5 each need independent review for the risks marked above; Task 6 gets the whole-branch and census review, not another mechanical task review. Use an explicit other-family reviewer for Codex-authored census work.
+
+Self-review performed against the spec and Paul's fixed 2026-11-04 rulings: §4.3 banner/CSP/local caps map to Tasks 1-3, §4.4 cookies to Task 1, §4.6 controls/report to Tasks 4-5, and lifecycle/ordinary-behavior/store-cost witnesses to Task 6. The five Review Focus items have named tests. The old shell, presentation routing, central traffic APIs, whole-response buffering and ledger-only representation/size limits are removed. Local debits have a stated zero-crash-overservice bound; stop confirmation uses the existing stream with an explicit 35-second resident-stop bound. Readiness is unchanged. Counter initialization/purge cannot reset an existing lifetime. Types have one owner, tasks are renumbered, and no Plan 3 claim authority is assumed. Existing publish budgets/log retention stay in Plan 1. Copy remains draft for later implementation review. This document is shorter than its predecessor; no product code or test execution is claimed.
+
+## Copy review required
+
+Draft candidates only. Every new human-facing string, including accessibility text, error detail, CLI help/output and operator-document prose, must be reviewed before implementation ships. Protocol identifiers, JSON keys, flags, enum values and test names are not copy. Reuse already-approved generic HTTP errors where possible; do not invent additional strings outside this table. Task 6 supplies exact assembled help/docs prose for the same review.
+
+| ID | Surface | Draft text or required content |
+|---|---|---|
+| DEMO-BANNER | Edge-inserted warning; app scripts can remove it | This app was built by an AI. It is temporary. Do not enter real passwords or sensitive information. |
+| DEMO-REPORT-LINK | Banner link | Report abuse |
+| DEMO-LIMIT | 429 page when claiming is available | This demo has hit its limit. Claim it to keep it running. Use the private claim link from your agent. |
+| DEMO-LIMIT-PRECLAIM | 429 page in Plan 2 dev | This demo has hit its limit. Claiming will let you keep it running when it becomes available. |
+| DEMO-STOPPED | 503 page | Demos are temporarily unavailable. |
+| DEMO-GONE | Unknown, expired or retired 404 | This demo is no longer available. |
+| DEMO-UNAVAILABLE | Local counter/control/transport failure | This demo cannot be checked right now. Try again shortly. |
+| DEMO-RESPONSE | HTML that cannot be transformed safely | This demo returned a response that cannot be shown. |
+| DEMO-REPORT-TITLE | Console report form | Report a demo |
+| DEMO-REPORT-HOST | Read-only host field | Demo address |
+| DEMO-REPORT-CATEGORY | Form label and choices | Reason; Phishing; Harmful content; Other |
+| DEMO-REPORT-DETAILS | Textarea and hint | Details; Do not include passwords or personal information. |
+| DEMO-REPORT-SUBMIT | Form button | Send report |
+| DEMO-REPORT-SENT | Confirmation | Your report has been sent to the operator. |
+| DEMO-REPORT-REFUSED | Validation/CSRF error | This report could not be accepted. Reload the form and try again. |
+| DEMO-REPORT-BUSY | Rate/queue error | Reports are temporarily limited. Try again later. |
+| DEMO-CLI-HELP | Family help | Manage anonymous demos: status, serving on or off, takedown, takedown-status, reports. Commands use your configured console. |
+| DEMO-CLI-FLAGS | Flag help | Exact public demo hostname; Report ID; Continue after this report; Reports per page, from 1 to 100. |
+| DEMO-CLI-STATUS | CLI headers/state labels | Host; State; Request cap; Byte cap; Cleanup; Serving; On; Off; Pending; Complete |
+| DEMO-CLI-OFF | Stop confirmed after acknowledgement or expiry bound | Demo serving is off. Responses already being sent may finish. |
+| DEMO-CLI-ON | Confirmed switch on | Demo serving is on. |
+| DEMO-CLI-TAKEDOWN | Serving stop confirmed, cleanup pending | This demo has stopped serving. Cleanup is pending. |
+| DEMO-CLI-PURGED | Confirmed purge | This demo has been removed. |
+| DEMO-CLI-REPORTS | Queue headers/resolution | ID; Host; Reason; Details; Created; State; Open; Resolved; Report resolved. |
+| DEMO-CLI-INVALID | Invalid CLI arguments | Check the command arguments. Run carlos system demos help. |
+| DEMO-CONFIG-PROTECTIONS | Operator configuration error | Demo edge protection settings are missing or invalid. |
+| DEMO-OPERATOR-DOCS | README/CLI prose | Exact operator workflow, cap units/snapshots, excluded platform overhead, local-disk failure, control-stream expiry, removable-banner limitations, pending stop, migration, retirement verification and rollback from Task 6. Review the complete prose, not this content brief. |
+
+Plan 2 always uses DEMO-LIMIT-PRECLAIM. Plan 3 replaces it with DEMO-LIMIT only when its real claim flow is available; there is no public claim button or token-bearing URL in this plan.
+
+## Open questions
+
+None. Banner insertion and assigned-box local accounting are Paul's fixed rulings. Durable pre-debits, streaming truncation, bounded stop confirmation and fresh-lifetime activation are specified above. Copy review remains a later implementation gate, not an unresolved design choice.
diff --git a/docs/superpowers/plans/2026-11-04-agent-start-demo-3-claim.md b/docs/superpowers/plans/2026-11-04-agent-start-demo-3-claim.md
new file mode 100644
index 000000000..e7c0595b0
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-04-agent-start-demo-3-claim.md
@@ -0,0 +1,387 @@
+# Claim a demo by email Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Let a person keep an anonymous demo through email proof, receiving a permanent app with the same binary and SQLite data in an account they choose.
+
+**Architecture:** The console owns a durable claim operation, separate from email proof and from the demo's existing expiry clock. An authenticated worker freezes the assigned demo, exports its local database, and sends it to the console; normal provisioning starts a fresh account app through a gated seed. A durable commit consumes the token, opens the destination, and drives Plan 1 retirement while an independent moved notice lasts until the original expiry.
+
+**Tech Stack:** Go, console SQLite, existing email challenges and Keymail OAuth, Ed25519 work envelopes, the existing demo WebSocket, provider-neutral release stores, nested instances, SQLite seeds and the edge import gate.
+
+**Spec:** `docs/superpowers/specs/2026-11-02-agent-start-demo-design.md`, especially §4.5 and §5; `docs/superpowers/specs/2026-10-21-console-email-signin-design.md`, including §15; `docs/superpowers/specs/2026-10-08-seeded-instances-design.md`. Read Plan 1 and `docs/superpowers/notes/agent-start-demo-1-rulings.md` as amended by the 2026-11-04 dev facts in the commissioning brief.
+
+## Global Constraints
+
+- “TTL: 24 hours, no extension without claiming.” Preserve the original `apps.expires_at`; proof, retries, copying and the moved page never extend it.
+- “The claim token is single-use and dies with the claim.” A failed pre-commit claim leaves it usable until expiry; successful commitment destroys its hash.
+- “The chosen account's plan limits apply, and the user must be allowed to create apps in it.” Reserve capacity before freezing the source; no plan upgrades, payment changes or extra free-account allowance.
+- “Keymail addresses finish in the browser.” Use sign-in discovery and OAuth, including its public-lookup fallback behavior; do not email a code to an address discovered as Keymail.
+- Provider-neutral core. Use `release.Store`, authenticated console HTTP and existing object layouts; no AWS SDK, presigned S3 upload or direct box administration in the claim flow.
+- No new per-box polling. Extend the existing demo stream and shared change watch; idle claims cause zero additional object-store requests.
+- Operator switch `CARLOS_DEMO_CLAIM=1`, unset by default. **Switch-on date: dev when this plan lands**, with capability checks and the acceptance witness complete. Console admission is configured in its drop-in. Production remains a separately scoped rollout.
+- The binary receives `--socket` and `--db` flags. Demo boxes have 2 GB RAM; build test binaries elsewhere, never compile tests on them.
+- The housekeeper issues certificates. Existing `*.trycarlos.com` covers all demo names; do not introduce `*.dev.trycarlos.com` or per-demo certificate issuance.
+- R19b: demo hosts are never reused. Keep the permanent host tombstone even after the moved notice expires.
+- Plan 1 SQLite is local-only on its assigned box. Never substitute an empty database, fetch a nonexistent replica, enable demo replication, or move the source to another box.
+- No agent account/deploy credential is issued. The normal CLI login is the next workflow. Copy remains subject to the single table below; no em dashes or real tenant names in new examples.
+- One implementation branch and one visible merge: successful email-to-permanent-app claim. All eight task commits land together; no separate scaffolding merge. This authoring session writes only this plan, with no commits, push, deployment, full suite or subagents.
+
+## Review Focus
+
+1. A code for another demo, another flow or an older email must grant nothing, including when two verifies race. Task 1: `TestDemoClaimProofBinding`.
+2. Multiple memberships, a removed membership, and a concurrent ordinary create must not silently select an account or overbook its plan. Task 2: `TestDemoClaimAccountRace`.
+3. A stopped process with committed data still in WAL, or an agent restart during export, must preserve the data and keep the source fenced. Task 3: `TestDemoClaimSnapshotWAL` and `TestDemoClaimFreezeRecovery`.
+4. Console failure between opening the destination and retiring the source must never resume two independently writable apps. Task 5: `TestDemoClaimCommitRecovery`.
+5. A cached old demo response, forged destination URL, or browser returning under a different Keymail identity must not disclose data or cause an unintended claim. Tasks 6 and 7: `TestDemoMovedPrecedesCache` and `TestDemoClaimBrowserIdentity`.
+
+---
+
+## Existing interfaces and boundaries
+
+Read against main checkout `2914921ceabd4218b0363a9780f8e4db890aab4c`. These are existing-code anchors; interfaces introduced below are proposals. Plan 2 has not landed in this checkout. Do not review against its unmerged implementation; Task 6 supplies the minimum hook here.
+
+| Existing mechanism | Evidence and consequence |
+|---|---|
+| Plan 1 extension points | `docs/superpowers/plans/2026-11-02-agent-start-demo-1-anonymous-apps.md:88`: token lookup, lifecycle lock, reserved fragment link and local-only SQLite. R13 and R19 replace the original plan's root-policy assumptions; R19b prohibits host reuse (`docs/superpowers/notes/agent-start-demo-1-rulings.md:37`, `:56`, `:27`). R15 (`:21`) permits a self-inflicted init-marker case; claim export never treats that marker as proof of a database. |
+| Token and lifecycle | `internal/console/demo_store.go:292`, `:323`, `:364`: strict 32-byte token decode, constant-time comparison, live anonymous predicate and app mutex. `:58` has a SQL CHECK permitting only anonymous/retiring/retired. Keep those states; put transfer phases in a separate table. |
+| Existing claim response | `internal/console/apidemo.go:259`, `:439`: `/demo/claim` is a 503 stub and create returns `claimAvailable:false`. Extend these without changing publish/status field names. |
+| Email discovery | `internal/console/emailsignin.go:90`, `:104`, `:124`, `:132`; `internal/console/server.go:3789`, `:3854`: canonical address, public Keymail discovery, mail readiness, async send and flow serialization. Discovery is not a membership lookup. |
+| Proof and limits | `internal/console/emailsignin_store.go:29`, `:101`, `:133`, `:156`, `:299`: purpose-bound challenges, held unsent challenge, destructive successful take, process-key code MAC. `internal/console/emailsignin_limits.go:18`, `:230`, `:313`: shared send/guess budgets. |
+| Identity and browser login | `internal/console/emailsignin.go:258` resolves a sign-in method, opens a session and calls current-account landing; `internal/console/server.go:3087` uses MRU before minting. Agent proof must reuse identity resolution without calling this session/landing wrapper. Keymail OAuth starts at `internal/console/server.go:3889`; `safeNext` is `internal/console/emailsignin.go:240`. |
+| Account authorization | `internal/console/store.go:1375` lists memberships. `internal/console/apicli.go:228`, `:381` admits a person through membership for ordinary create; ordinary members as well as owners can create. `internal/console/server.go:3145` mints an account; it does not itself enforce the free-account cap. |
+| Plans and locks | `internal/console/plancaps.go:106`, `:167`, `:230`, `:277`, `:310`: running things count apps plus instance records, free-account check, account/person locking. `internal/console/apicli.go:505` holds the account lock through count and create. A claim creates two counted things, not one. |
+| Fresh permanent app | `internal/console/server.go:5417` `claimAppWith` refuses demo placement, adopts only when permitted, and uses zero expiry for permanent apps. Use `ownerClaim=false`. `internal/console/regionclaim.go:105` resolves normal region; `internal/console/apiinstances.go:1806` inherits it. `internal/console/apex.go:31` derives `<app>.<sqid>.<AppsDomain>`. |
+| Artifact publication | `internal/console/demo_publish.go:38`, `:131`, `:140`: demo version, `release.ShipSpooled`, signed promotion. `:228` checks exact-host readiness. Copy and verify the selected artifact into the destination namespace; do not repoint the demo manifest or rebuild source. |
+| Assigned source and transport | `internal/console/demo_publish.go:193` records FleetBox; `internal/console/apidemobox.go:93`, `:191` authenticate workers and replay work. `internal/demobuild/job.go:139`, `:160` define readiness and stream envelopes; `internal/host/demo_jobs.go:335` reconnects. |
+| Local data and stop | `internal/activator/demo_durability.go:36`, `:110` retain the lease without replication and refuse lost established data. `internal/activator/maintenance.go:105` provides owner-bound `FenceAndStopAs`; `internal/activator/activator.go:6044` provides `Quiesced`; `internal/activator/maintenance.go:244` lifts only its own fence. In-memory fences alone do not survive restart. |
+| Root start and retirement | `internal/instancectl/demo_policy.go:20` already refuses starts on held demo rows under `lockDemo`; `internal/instancectl/demo_cleanup.go:77` validates binding and proves stop before deletion. `internal/host/demo_cleanup.go:20` verifies a receipt and current object before acting. Reuse that trust split, not a new root reader of tenant SQLite. |
+| Offline move does not fit | `internal/host/movesoffline.go:92`, `:387`, `:822` supply hold/fence precedents. `internal/host/movesoffline_seal.go:307` seals a replica-based move of the same instance. This claim changes account and host and has no replica; do not invoke the move state machine. |
+| Seeds partly fit | `internal/console/apiinstanceseed.go:257` restores from a replica and `:563` refuses demo sources. `internal/provision/seedswap.go:74` requires an existing address route for import. Neither public door can perform this claim. Reuse snapshot keys (`internal/seeds/seeds.go:121`), bounded scratch (`internal/console/seedscratch.go:86`), create-only snapshot upload (`internal/console/apiinstanceimport.go:659`), first-wake restore (`internal/activator/seedplace.go:99`) and first replica confirmation (`:531`). |
+| Seed restrictions and gate | `internal/console/seedfloor.go:35`, `internal/console/apiinstanceseed.go:114`, `internal/console/apiinstanceimport.go:131`: seed capability floor, normal hosted placement and data residency. `internal/edge/importgate.go:12`, `:34` gates before cache/wake and strips `Carlos-Import-Verify`. A fresh claim seed needs its own kind, not a fake legacy route or replica TXID. |
+| Safe database primitives | `internal/instancefs/instancefs_linux.go:84`, `:138` open beneath a directory without following symlinks. `internal/lease/check.go:44`, `:202` integrity-check and checkpoint SQLite. Use these on a private copied DB/WAL, never run SQLite as root on source data. |
+| Retirement is currently time-only | `internal/console/demo_expiry.go:76`, `:92`, `:125`, `:174`, `:241`: early calls are no-ops; retirement fences jobs and token, trashes, waits for cleanup acknowledgment, purges, preserves host tombstones. Extract a reasoned retirement entry point; do not falsify expiry to trigger it. |
+| Routing and cheap refresh | `internal/edge/demo.go:18`, `:27`, `:81` validate exact demo hosts independently of routes. `internal/edge/edge.go:1890` is the request entry. `internal/release/changeindex.go:50` enumerates indexed scopes; `internal/host/changeindex.go:55`, `:180` share a watch and distinguish control scopes. `internal/console/demo_jobs.go:371`, `:447` own recovery/backstop work. |
+| Binary flags | `internal/activator/backend_exec.go:2530`, `:2733` pass `--socket` and `--db`. The 2026-11-04 commissioning facts override older fixture descriptions using environment variables. |
+
+## Decisions and protocol
+
+Eight tasks, one branch. All additional choices in this section are **my call**.
+
+### Authentication and account choice
+
+`POST /api/demo/claims` accepts `{claimToken,email,flowToken?}`. It returns `202 {state:"email_required",flowToken,expiresAt}` for every valid email-bound send outcome, including throttled/unsent challenges. A Keymail discovery returns `200 {state:"browser_required",claimUrl}` with the original `/demo/claim#token` link, no flow credential or account list. No-mailer returns 503 before send-limit decisions. Invalid demo tokens use the existing uniform token refusal.
+
+`POST /api/demo/claims/verify` accepts `{flowToken,code}`. `POST /api/demo/claims/select` accepts `{flowToken,accountId}`. A successful verify resolves the person through `ResolveSignIn(MethodEmail, provedAddress, now)` without issuing a console session or CLI token. Zero memberships: take the person lock, reread, check `checkNewFreeAccount`, and mint one personal account. One membership: choose it. Several: return `200 {state:"account_required",accounts:[{id,name,role}]}` and wait for an exact sqid. Never use MRU, silently filter to one permissible account, or accept an account name as identity. Recheck membership/role, account liveness and caps at reservation and commitment. Unknown/foreign account IDs have the same 404.
+
+`GET /api/demo/claims/status` uses `Authorization: Bearer <flowToken>`. After proof this capability authorizes only that demo's account selection, one claim attempt and its result. It grants no account enumeration beyond the verified person's membership choices, no deploy, no general API session and no database download. Return `202 {state:"claiming",phase,retryAfter:2}` while working and `200 {state:"claimed",accountId,app,url,next:"cli_login"}` only after public readiness and durable retirement initiation. All responses are `no-store`; secrets never enter URLs, logs or error payloads. This narrowly bounded continuation is not a post-claim account credential.
+
+`flowToken` is 32 random bytes, base64url; only its SHA-256 is stored. Its proof/selection lifetime is `min(now+15 minutes, demo expiry)`, not extended on resend. Its post-reservation use is status-only; the result is readable until original demo expiry plus 24 hours, then erased. Losing it means repeat email proof while anonymous, or use normal account login after success. Starting a second email flow does not cancel an already reserved transfer. Code proof alone never freezes a demo with several memberships.
+
+### Transfer and commit
+
+Keep `demo_apps.state` unchanged. Add `demo_claim_flows` for proof binding and `demo_claim_ops` for durable work, with a unique active operation per demo. Operation IDs use `demobuild.NewJobID()` and its validation, independently of all bearer tokens. Bind every operation to demo ID, original lifetime/expiry, source generation, assigned box, selected binary digest/version, verified person, destination account/name/host/lifetime, seed ID, phase and deadline. Destination identity is immutable once reserved. Retain unfinished operations until resolved; prune terminal operation metadata seven days after source purge, with the flow capability erased on its shorter schedule.
+
+| Phase | Durable effect and recovery rule |
+|---|---|
+| `reserved` | Fresh permanent app and reserved seed record count against normal caps. No public destination or source pause yet. Reject updates/new claims through a claim-operation guard shared with enqueue, publication and expiry. |
+| `freezing` | Signed command requests a hold on the assigned source. A durable record hold plus local hold blocks every wake, adoption and generation restart; root proves all instance cgroups empty. |
+| `copying` | Source remains held. Copy DB and WAL into private scratch, checkpoint that copy, integrity-check and stream one bounded snapshot to the console. No source file is altered or deleted. |
+| `verifying` | The same artifact is shipped/promoted under the new app. A fresh `demo-claim` seed starts normally but its edge traffic gate admits only the console's verify GET. Wait for `placed` and the destination's own first replica. |
+| `committed` | In one console transaction consume the demo token, record the irreversible decision and enqueue destination gate opening, moved publication and reasoned retirement. Never resume the source from this phase. Replay side effects on restart. |
+| `done` | Destination gate is open, exact-host GET is 2xx with the pinned version, and Plan 1's retirement receipt is durable. Clear the destination's pending-operation marker so all normal account operations work. Source cleanup acknowledgment may still be pending. |
+| `aborting` / `aborted` | Only before commitment. Close/abort destination seed, prove destination stopped and remove only operation-owned records/data; then release the source hold if unexpired and not independently retired. An ambiguous stop keeps the hold and reports recovery pending. |
+
+Lock order: person lock for mint only; account locks in sorted sqid order; app locks in sorted `(sqid,app)` order; hostname locks last. Release locks during transfer/network waits. Reacquire and reread generation, life, membership, reservation and phase before each write. `withDemoLocked` remains the anonymous entry gate; recovery gets a separate operation-aware lock helper, since its existing live predicate is false after commit.
+
+Normal destination name starts with `d.Name`, without `tmp-demo-`. If occupied, try `<d.Name>-<8 lowercase hex characters of SHA256(operationID || attempt)>`, attempts 1 through 16, checked by the normal fresh-name machinery. Never adopt an existing prefix, overwrite an app or accept a destination URL from the client. Use configured `AppsDomain` (`oncarlos.com` on the public deployment), normal region choice and normal size/egress/replication defaults; no Demo descriptor, fleet placement or source secrets are copied.
+
+The initial implementation supports the existing seed-supported normal hosted placement: nested linux-arm64, claims mode off, non-HA, and the console's data region. Run normal placement first; an incompatible result is a clear refusal **before** source freeze, not a forced demo-fleet placement or an instruction to move data manually. The new fresh seed does not inherit legacy import's one-box restriction. Add a capability floor for its readers before emitting the new kind. Cross-region seed delivery and HA seed support remain outside this plan; do not silently change the account's normal placement to hide their absence.
+
+Bound the operation to five minutes from reservation and no later than original demo expiry. Stop proof gets 30 seconds, snapshot/check/upload 120 seconds, destination readiness 60 seconds, all within that overall deadline. Source DB plus WAL and the final snapshot each cap at 268,435,456 bytes (256 MiB); reject oversized data with its reason. Reserve at most 768 MiB disk scratch per transfer and 256 MiB helper memory; one export per demo box, serialized with its build slot. No byte buffering proportional to the database. Small-app acceptance aims for under one minute; the five-minute bound is a failure bound, not a success claim.
+
+Deadline expiry before commit initiates abort; source expiry still wins. Deadline expiry after commit never undoes ownership or resumes the source: finish opening/retiring through recovery. A disconnected worker cannot self-release a hold when its deadline passes. Transport retry never grants authority; the console's latest operation decision does.
+
+## Task map
+
+| Task | Responsibility | Main new files |
+|---|---|---|
+| 1 | Email proof and claim-only continuation | `internal/console/demo_claim_auth.go`, `demo_claim_store.go` |
+| 2 | Account selection, caps and fresh destination reservation | `internal/console/demo_claim_target.go` |
+| 3 | Signed work, durable freeze and local SQLite export | `internal/democlaim/work.go`, `internal/host/demo_claim.go`, `internal/instancectl/demo_claim.go`, `internal/democlaim/snapshot.go` |
+| 4 | A gated fresh seed through normal provisioning | `internal/provision/demo_claim_seed.go` |
+| 5 | Artifact copy, coordinator, commit, abort and retirement | `internal/console/demo_claim_transfer.go` |
+| 6 | Moved notice independent of source app records | `internal/democlaim/moved.go`, `internal/host/demo_moved.go`, `internal/edge/demo_moved.go` |
+| 7 | Browser fallback and Keymail return | `internal/console/demo_claim_page.go`, `internal/console/templates/demo_claim.html`, `internal/console/static/demo_claim.js` |
+| 8 | Integration proof, copy and activation | `internal/console/demo_claim_e2e_test.go`, `internal/host/demo_claim_dev_linux_test.go` |
+
+### Task 1: Bind email proof to one demo
+
+**Risk/review:** security gate and storage. Independent task review required. Console-only files are outside root census scope.
+
+**Files:**
+- Create: `internal/console/demo_claim_auth.go`, `internal/console/demo_claim_store.go`.
+- Modify: `internal/console/emailsignin_store.go:101`, `internal/console/emailsignin.go:317`, `internal/console/apidemo.go:259`, `internal/console/demo_store.go:51`, `internal/console/server.go:3854`.
+- Test: `internal/console/demo_claim_auth_test.go`, `internal/console/demo_claim_store_test.go`.
+
+**Interfaces:**
+- Consumes: `LookupDemoToken`, `withDemoLocked`, `canonicalAddress`, `keymailAddress`, `mailReady`, `sendChallengeAsync`, `ResolveSignIn`, `LiveEmailChallenge`, `TakeEmailCode` and the shared `emailLimits` object.
+- Produces: `const ChallengeDemoClaim = "demo-claim"`; bind this purpose by `flow_hash`, independently of signin/stepup.
+- Produces: `claimFlow` with `Hash, DemoID, Lifetime, Address, Person, Method string; Generation int64; ExpiresAt time.Time`; `(*Store).demoClaimFlow(ctx context.Context, raw string, now time.Time) (claimFlow, error)`.
+- Produces: `(*Server).handleDemoClaimStart`, `handleDemoClaimVerify`, `handleDemoClaimSelect`, `handleDemoClaimStatus`, each `(w http.ResponseWriter, r *http.Request)`; selection/reservation delegates to Task 2 and returns unavailable until wired.
+- Produces: `(*Server).proveDemoClaim(ctx context.Context, flow claimFlow, method, address, ip string, now time.Time) (claimFlow, error)` for email and Task 7's authenticated browser path. It records only canonical resolved person/method, not a caller-supplied person ID.
+
+- [ ] **Step 1: Write failing tests with these assertions.**
+
+```text
+TestDemoClaimProofBinding: otherDemo/otherFlow/signinCode/stepupCode/oldResend => noProof; concurrentVerify => oneProof; expiresAt <= min(start+15m,demoExpiry)
+TestDemoClaimEmailPrivacy: sent/throttled/unknownEmail => sameStatusAndShape; noMailer => 503BeforeSendLimit; KeymailHost => zeroSMTP; publicLookupFailure => emailAsSignin
+TestDemoClaimSharedLimits: submit=30/IP/hour; sends=5/address/hour,20/address/day,10/IP/hour,200/global/hour; gap=60s; badCodes=5/challenge,10/address/day,30/IP/hour
+TestDemoClaimCodeRestart: oldCode => refused; freshResend => works; plaintextCode/token absentFromSQLAndLogs; noSessionOrCLICredentialIssued
+```
+
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestDemoClaim(Proof|Email|Shared|Code)' -count=1`; expect missing handlers or failed assertions.
+- [ ] **Step 3: Implement the interfaces and protocol above.** Strict JSON, 4 KiB body, no duplicate/unknown fields, no cookies as authority on agent endpoints, same-origin rejection when browser headers are present, no permissive CORS. Additive migration only. Resend uses the supplied flow and cannot rebind it to another demo/email. Share send/guess limits with ordinary sign-in so changing doors buys no extra allowance. Preserve unsent-challenge behavior. Reuse the process-key MAC and atomic consume logic; a crash after consuming proof may require a new email, but cannot grant authority. Count new people through `PersonWouldBeNew` and `limits.newPerson`. Email link redemption gets a dedicated purpose dispatch: GET never spends; POST requires the existing nonce/origin protection and records claim proof without falling into `finishSignin`.
+- [ ] **Step 4: Rerun Step 2**, plus `go test ./internal/console -run 'TestEmail' -count=1`; expect PASS and unchanged ordinary sign-in/step-up behavior.
+- [ ] **Step 5: Commit** the task files with subject `feat: bind demo claims to email proof`.
+
+### Task 2: Choose and reserve the permanent destination
+
+**Risk/review:** security gate, billing and production storage. Independent task review required.
+
+**Files:**
+- Create: `internal/console/demo_claim_target.go`.
+- Modify: `internal/console/demo_claim_store.go` (Task 1), `internal/console/store.go:1865`, `internal/console/plancaps.go:106`, `internal/console/server.go:5417`, `internal/console/apicli.go:228`, `internal/console/apiinstances.go:1806`.
+- Test: `internal/console/demo_claim_target_test.go`, `internal/console/demo_claim_caps_test.go`.
+
+**Interfaces:**
+- Produces: `claimTarget` with `AccountID int64; Sqid, App, Host, Lifetime, Region, SeedID string`; `(*Server).chooseDemoClaimAccount(ctx context.Context, f claimFlow, selected string) (*Account, []Account, error)`.
+- Produces: `(*Server).reserveDemoClaim(ctx context.Context, f claimFlow, acct *Account, rq regionReq) (claimOp, error)`; `claimOp` holds the durable fields in Transfer and commit, with `ID, FlowHash, DemoID, SourceLifetime, SourceBox, Person, Version, ArtifactSHA256, Phase string; Generation int64; Target claimTarget; Deadline time.Time`.
+- Produces: `(*Server).demoClaimMutationRefusal(ctx context.Context, accountID int64, app string) *doorRefusal`; only the operation-owned internal context may mutate an unfinished destination. Reuse this check at person and service mutation gates, browser writes and internal lifecycle writers.
+
+- [ ] **Step 1: Write failing tests.**
+
+```text
+TestDemoClaimAccounts: 0 => onePersonalAccount; 1 => thatAccount; 2 => listAndNoAppUntilExactChoice; MRU => ignored; owner/member => normalCreatePermission; foreign/deleted => identical404
+TestDemoClaimAccountRace: memberRemovedAfterProof => refused; ordinaryCreateRacingClaim => totalWithinCap; duplicateClaimsSamePerson => oneNewPersonalAccount; sameDemoTwoPeople => oneReservation
+TestDemoClaimReservation: appPlusInstance == 2RunningThings; cap/freeAccount/placementRefusal => sourceStillServingAndTokenUsable; takenName => freshSuffix; ownerAdoption == false
+TestDemoClaimTargetIsolation: ordinaryShip/promote/delete/seed/run/serviceToken => cannotMutatePendingTarget; retryAfterPartialReservation => sameTargetAndNoDoubleCharge
+```
+
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestDemoClaim(Accounts|AccountRace|Reservation|TargetIsolation)' -count=1`; expect FAIL.
+- [ ] **Step 3: Implement account choice and reservation.** Extract the normal fresh-create validation into callable helpers without weakening the ordinary doors. Check `checkRunningThings(ctx, acct, 2)` under the account lock. Record a reservation before external writes; count outstanding claim reservations in the same plan counting function used by normal creates, subtracting each app/instance only when its durable row/record is already counted. A partial failure retains its reservation until confirmed cleanup; do not decrement merely because a request failed. Use normal lifetime enrollment, apex protection, default pipeline and region selection. Persist a destination `demo_claim_op` marker in the same row insert, not afterward, and close every mutation door while pending. Require the new source/destination/edge capabilities before freezing. A refused plan or placement returns a safe reason and leaves the demo running.
+- [ ] **Step 4: Rerun Step 2**, then targeted existing `TestPlan`/`TestAPICreateApp` tests in console; expect PASS with plans enabled and disabled.
+- [ ] **Step 5: Commit** with subject `feat: reserve account capacity for demo claims`.
+
+### Task 3: Freeze and export the assigned demo's local database
+
+**Risk/review:** security gate, root, termination and storage. Independent task review and root census required.
+
+**Files:**
+- Create: `internal/democlaim/work.go`, `internal/democlaim/snapshot.go`, `internal/host/demo_claim.go`, `internal/instancectl/demo_claim.go`, `internal/host/units/carlos-demo-snapshot@.service`.
+- Modify: `main.go:20` (private worker dispatch), `internal/host/bootstrap.go` (embedded unit installation), `internal/demobuild/job.go:139`, `:160`, `internal/console/apidemobox.go:191`, `internal/host/demo_jobs.go:335`, `internal/host/agent.go:988`, `internal/instancectl/demo_policy.go:20`, `internal/instancectl/server.go:474`, `internal/provision/provision.go:125`, `internal/provision/reconcile.go:118`.
+- Test: `internal/democlaim/work_test.go`, `internal/democlaim/snapshot_test.go`, `internal/host/demo_claim_test.go`, `internal/instancectl/demo_claim_test.go`.
+
+**Interfaces:**
+- Produces: `democlaim.Work {ID string; Demo demo.Descriptor; Account, App, Fleet, Box string; Generation uint64; Action string; Deadline time.Time}`; Action is exactly `freeze`, `export` or `abort`. Sign/verify with Ed25519 and separator `carlos demo claim work v1\n`: `SignWork(priv ed25519.PrivateKey, w Work) ([]byte,error)` and `VerifyWork(pub ed25519.PublicKey, wire []byte, now time.Time) (Work,error)`. Freeze/export deadlines cannot exceed demo expiry; an abort gets a fresh 30-second delivery deadline even after expiry, but may never resume an expired demo.
+- Produces: `(*demoWorker).claimDemo(ctx context.Context, wire []byte) error`; `(*instancectl.Client).FreezeDemo(ctx context.Context, d demo.Descriptor, operationID string) error` over `POST /demo-freeze` on the existing control socket.
+- Produces: `democlaim.ExportSQLite(ctx context.Context, dbDir, dbBase, scratchDir string) (Snapshot,error)`; `Snapshot {Path, SHA256 string; Bytes int64}`. All paths are derived locally, never wire parameters; Path never leaves the box.
+- Produces: `(*instancectl.Client).SnapshotDemo(ctx context.Context, d demo.Descriptor, operationID string, db io.Reader, dbBytes int64, wal io.Reader, walBytes int64) (io.ReadCloser,error)` on `POST /demo-snapshot`; fixed multipart fields carry bytes and lengths, never filenames. The response streams the checked snapshot. `democlaim.RunSnapshotWorker(ctx context.Context) error` handles private `__demo-snapshot` dispatch, like `__registry-child` at `main.go:36`, outside the public command switch.
+- Adds optional `provision.Record.DemoClaim *democlaim.Hold`, with `ID string; Generation uint64`; this is a console-owned source hold, not ownership-transfer authority. Ordinary writers preserve it and cannot set or clear it. A hold carries no auto-resume time.
+- Adds `StreamMessage.Claim []byte` and `WorkerReady.ClaimCapability string`, value `anonymous-demo-claim-v1`; old workers remain valid for builds but cannot receive claim work.
+
+- [ ] **Step 1: Write failing tests.**
+
+```text
+TestDemoClaimWorkBinding: wrongBox/fleet/lifetime/generation/signature/action => noEffect; replayCurrent => sameOperation; replayAborted => cannotFreezeAgain
+TestDemoClaimSnapshotWAL: committedWALOnlyRow => inSnapshot; DBAndWALSourceHashes => unchanged; missingDBEvenWithPendingMarker/symlink/hardlink/nonregular/corrupt/over256MiB => refused; noEmptyFallback
+TestDemoClaimFreezeRecovery: wake/update/adopt/generationStartDuringHold => refused; restartBeforeAck => heldAndStopReproved; otherHold => untouched; unprovenStop => zeroDataReads
+TestDemoClaimExportBounded: oneExportPerBox; helperMemory<=256MiB; scratch<=768MiB; elapsed<=120s; credentialsAndSiblingData => inaccessible; cancel => noHelperOrScratch
+```
+
+- [ ] **Step 2: Run** `go test ./internal/democlaim ./internal/host ./internal/instancectl -run 'TestDemoClaim(Work|Snapshot|Freeze|Export)' -count=1`; expect FAIL.
+- [ ] **Step 3: Implement the source protocol.** Verify signed work in the agent, then confirm its current operation through an authenticated console pickup before executing, so a signed stale abort/freeze cannot win after commit. Install the persistent source hold before fencing; restore holds before serving or reconciling on startup, including newly minted routes. Use `FenceAndStopAs` with owner `demo-claim/<operationID>` and matching generation; root's fixed freeze verb reuses the stop/cgroup proof from purge without deleting files. The freeze verb receives identity only; neither root door reads the source DB or accepts a path, argv or mount instruction. Root start gates must retain the hold for every covered binary generation. A false `Quiesced` or unknown cgroup state prevents export.
+
+ The agent opens only the derived DB and optional WAL through no-follow descriptors after stop proof; reject multiple hardlinks and changing inode/size. Stream them into the fixed snapshot door. Root rechecks the exact held demo/operation, accepts only bounded bytes, and writes fixed names under root-created `/var/lib/carlos-demo-snapshots/<operationID>/`; it never opens an agent-supplied source path. SHM is transient and is recreated in this private scratch. The unit runs the shipped binary's private worker as a dynamic UID with only that scratch writable, no network/credentials/sibling data, `MemoryMax=268435456`, `MemorySwapMax=0`, `CPUQuota=50%`, `TasksMax=32`, `RuntimeMaxSec=120`, `TimeoutStopSec=5`, and `KillMode=control-group`. Reserve/enforce the 768 MiB disk budget before accepting input. The helper checkpoints the private copy with `lease.TruncateWAL`, runs `lease.CheckDBContext`, and hashes its completed DB. Serialize it with the builder slot; kill/reap before returning or cleaning scratch, including restart recovery. Upload its response by streaming to the console, never granting the demo box destination-account store permissions. An abort can lift only this operation's hold after the console proves destination rollback; retirement replaces the hold through the existing retirement path.
+- [ ] **Step 4: Rerun Step 2**, plus existing demo durability/cleanup tests. Run the actual cgroup/no-follow witness only using prebuilt binaries in the explicitly approved dev scope; a skip is not proof.
+- [ ] **Step 5: Commit** with subject `feat: freeze demo data for a bounded claim export`.
+
+### Task 4: Start a fresh normal app from a gated claim seed
+
+**Risk/review:** security gate, storage, root-linked provisioning and termination. Independent task review and census required.
+
+**Files:**
+- Create: `internal/provision/demo_claim_seed.go`.
+- Modify: `internal/seeds/seeds.go:23`, `internal/seeds/row.go:11`, `internal/provision/seed.go:16`, `internal/provision/reconcile.go`, `internal/provision/forward.go`, `internal/activator/seedplace.go:84`, `:99`, `:531`, `internal/console/seedfinish.go:60`, `internal/console/seedsweep.go`, `internal/edge/importgate.go:34`, `internal/host/edgesfile.go`, `internal/status/snapshot.go` (capability publication).
+- Test: `internal/provision/demo_claim_seed_test.go`, `internal/activator/demo_claim_seed_test.go`, `internal/edge/demo_claim_seed_test.go`, `internal/console/demo_claim_seed_test.go`.
+
+**Interfaces:**
+- Produces: `const seeds.KindDemoClaim = "demo-claim"`; optional `SeedSource.ClaimID string`. States: `reserving -> ready -> placed -> committed`; `aborted` allowed before committed. No `Replaces`, replica `From`, TXID or swap journal.
+- Produces: `provision.SeedPublishDemoClaim(id, claimID, sha string, bytes int64, verifyHash string) func(*Record) error` and `provision.SeedCommitDemoClaim(id, claimID string) func(*Record) error`, both CAS transitions through `SetRecordSeed`.
+- Consumes: existing seed snapshots, restore, leases, first replica confirmation, `ImportGate` and its verify header. New seed kind remains a permanent ordinary destination after commit.
+- Produces: destination and ingress capability `demo-claim-seed-v1` through existing status/edges-file publication, checked alongside `seedRegionReady(ctx, region, false)`; include current and rollback binaries in activation readiness.
+
+- [ ] **Step 1: Write failing tests.**
+
+```text
+TestDemoClaimFreshSeed: noExistingRoute => normalNestedInstance; demoDescriptor/fleet/replaces/fakeTXID => refused; concurrentWake => oneLease; missingSnapshot => neverEmpty
+TestDemoClaimSeedGate: GETWithoutToken/POST/alias/pathRoute/run/schedule => blocked; verifyGET => snapshotThenApp; token => stripped; placedRequiresOwnReplica == true
+TestDemoClaimSeedCommit: committed => ordinaryReplicationAndWake; oldReaders => admissionRefused; rollback/retry => deletesOnlyMatchingSeedAndLifetime; ordinaryReplicaAndImport => unchanged
+```
+
+- [ ] **Step 2: Run** `go test ./internal/provision ./internal/activator ./internal/edge ./internal/console -run 'TestDemoClaim(FreshSeed|SeedGate|SeedCommit)' -count=1`; expect FAIL.
+- [ ] **Step 3: Implement the new kind as a fresh seed, not an import takeover.** Enumerate every parser/validator/serializer of `SeedSource` and `RowSeed`, including forwarding, run/schedule blockers, expiry, sweep, CLI rendering and fingerprints; update their closed switches and tests. Absent optional fields keep old wire bytes/fingerprints unchanged. Mint the route with its gate in the same registry transaction; no interval with an ungated empty destination. Use the replica seed's first-wake placement and lease path but require claim commitment before removing the gate. Aborting a fresh claim seed must fence/stop its destination, prove the cgroup empty, then remove only matching seed-marked data and the matching lifetime/record; no legacy row is restored. Retain the seed's own replica after commitment and delete the temporary snapshot through existing placement cleanup. The console alone keeps the verify token; derive it by HMAC-SHA256 of `carlos demo claim verify v1\n` plus operation ID under the configured console signing-key seed, and persist only the matching hash. A changed signing key before commit forces safe abort/reproof, never gate bypass. Preserve normal seeds' compatibility and all unsupported placement refusals; a claim kind must never enter legacy import swap/rollback code.
+- [ ] **Step 4: Rerun Step 2** and targeted existing seed/import tests in those packages; expect PASS. Count unchanged watch ticks: zero new store calls.
+- [ ] **Step 5: Commit** with subject `feat: seed claimed apps behind the existing traffic gate`.
+
+### Task 5: Coordinate copy, permanent commit and source retirement
+
+**Risk/review:** security gate, termination, billing and production storage. Independent task review; census for any root-linked changes.
+
+**Files:**
+- Create: `internal/console/demo_claim_transfer.go`.
+- Modify: `internal/console/demo_claim_store.go`, `internal/console/demo_jobs.go:371`, `:447`, `internal/console/demo_expiry.go:76`, `internal/console/demo_publish.go:43`, `internal/console/demo_store.go:329`, `internal/console/apidemobox.go`, `cmd/console/main.go:710`.
+- Test: `internal/console/demo_claim_transfer_test.go`, `internal/console/demo_claim_recovery_test.go`.
+
+**Interfaces:**
+- Produces: `(*Server).advanceDemoClaim(ctx context.Context, operationID string) error`, `(*Server).ReconcileDemoClaims(ctx context.Context, restart bool) error`, `(*Server).abortDemoClaim(ctx context.Context, operationID, reasonCode string) error`.
+- Produces: `(*Server).retireDemoLocked(ctx context.Context, d DemoRow, now time.Time, reason demoRetireReason) error`; reasons `demoRetireExpired` and `demoRetireClaimed`. Existing `expireDemoLocked` remains a wrapper. Claimed retirement requires the durable commit row; expiry retains its original time check.
+- Produces: authenticated `POST /api/box/demo-claims/{operationID}/pickup`, `/snapshot`, `/ack`; use `demoBoxAuth` plus exact assigned box, claim phase, generation and lifetime. Snapshot metadata is digest and byte count; body is raw SQLite, not a path or archive. Duplicate identical snapshot is idempotent; changed bytes are refused.
+
+- [ ] **Step 1: Write failing tests.**
+
+```text
+TestDemoClaimTransfer: frozenArtifactSHA == destinationArtifactSHA; destinationData == latestCommittedSourceData; destinationDemoFields == empty; permanentExpiry == 0; sourceNoReplicaReads == true
+TestDemoClaimCommitRecovery: crashAtEverySQL/ObjectBoundary => oneDestination; beforeCommit => rollbackPossible; afterCommit => neverResumeSource; lostHTTPResponse => sameResultWithFlowToken
+TestDemoClaimExpiryRace: beforeCommitAt24h => expiryWins; afterCommitAt24h => permanentSurvives; activeBuild/rollbackSettlement => refuseBeforeFreeze; oldResult => cannotPublish
+TestDemoClaimRetirement: success => tokenHashNull,receiptDurable,sourceStopped; offlineCleanup => liveSlotHeld; originalExpiryUnchanged; permanentHostTombstone == retained
+TestDemoClaimRequestCost: idle/repeatedStatus/unchangedTick => zeroAdditionalStoreRequests; snapshotPUTs == 1PerSuccessfulAttempt; sameWorkerReconnect => noDuplicateExport
+```
+
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestDemoClaim(Transfer|CommitRecovery|ExpiryRace|Retirement|RequestCost)' -count=1`; expect FAIL.
+- [ ] **Step 3: Implement the phase table and bounded recovery.** Pin the last settled live generation and channel artifact under the source lock; refuse any queued/building/starting/settling update. Extend enqueue and every publication boundary with the operation guard, not just the HTTP handler. Copy the manifest with only account/app namespace changes and stream/hash-check the same linux-arm64 artifact through `ShipSpooled`; use normal default pipeline and signed promotion. Write the destination record before its seed object, upload create-only and compare matching duplicates after ambiguous writes. Reserve scratch before accepting bytes, check digest/size/integrity, then publish the seed and verify exact HTTPS host without following redirects. Require 2xx, the pinned `X-Carlos-Version`, and seed `placed` before commitment.
+
+ Commitment rechecks identity, cap reservation, source hold acknowledgment, lifetime and deadline under the ordered locks. At this point use `checkRunningThings(ctx, acct, 0)` because the reservation already counts; do not count the app and instance twice. Atomically record the irreversible decision, clear the claim token hash, invalidate other flows and enqueue all completion work. Seed opening follows that decision. A durable outbox retries opening, moved publication and Plan 1 retirement; status stays `claiming` until these finish. Extend the existing job runner/startup/backstop to drain SQL work and react to stream acknowledgments; status reads SQL only. The source's original expiry remains intact, but the reasoned retirement entry point permits an early committed claim. Preserve signed receipt validation, stop-before-delete, data-initialization-marker cleanup, acknowledgment and ceiling release. Do not let the expiry loop purge an uncommitted source before aborting its destination; once expired, it can never be resumed.
+
+ Before commitment, abort closes all destination traffic first, CASes only this seed to aborted, and waits for normal seed/instance cleanup proof before releasing source. Retain uncertain cleanup and report it through status; console unavailability is not permission for either box to reopen. After commitment, errors are recovery work, never rollback. Keep unfinished work running when admission is switched off.
+- [ ] **Step 4: Rerun Step 2**, including existing demo publication/expiry/settlement regressions. Inject failures before and after every irreversible boundary; expect PASS without a second claim or data loss.
+- [ ] **Step 5: Commit** with subject `feat: commit demo claims and retire their anonymous source`.
+
+### Task 6: Serve the moved notice until the original expiry
+
+**Risk/review:** security gate, redirect destination validation and cache. Independent task review and census required. The response is a page, not an HTTP redirect.
+
+**Files:**
+- Create: `internal/democlaim/moved.go`, `internal/console/demo_claim_moved.go`, `internal/host/demo_moved.go`, `internal/edge/demo_moved.go`.
+- Modify: `internal/release/changeindex.go:50`, `internal/host/changeindex.go:180`, `internal/edge/demo.go:18`, `internal/edge/edge.go:1890`, `internal/registry/registry.go`.
+- Test: `internal/democlaim/moved_test.go`, `internal/host/demo_moved_test.go`, `internal/edge/demo_moved_test.go`.
+
+**Interfaces:**
+- Produces: `democlaim.Moved {DemoID, Host, TargetHost string; ExpiresAt int64}` and `SignMoved(priv ed25519.PrivateKey, rows []Moved) ([]byte,error)`, `VerifyMoved(pub ed25519.PublicKey, wire []byte) ([]Moved,error)`; separator `carlos demo moved v1\n`.
+- Produces: `(*Server).publishDemoMoved(ctx context.Context) error`, `(*Edge).serveDemoMoved(w http.ResponseWriter, r *http.Request, host string) bool`.
+- Console publishes `control/demo-moved.json`, a complete signed snapshot capped at 1 MiB/10,000 entries, after a committed destination is open. SQL source is independent of `apps` and source purge. Registry stores the verified snapshot separately from live routes; Edge revalidates signed bytes on load.
+
+- [ ] **Step 1: Write failing tests.**
+
+```text
+TestDemoMovedPrecedesCache: oldCached200/noLiveRoute/pendingRoute => movedPage; targetOnlyServerDerived; escapedLink; noToken/noCookie/noAppHTML/noWake; POST => noForward
+TestDemoMovedExpiry: now<originalExpiry => page; now>=originalExpiry => noMovedLink; sourcePurged => stillPageUntilExpiry; hostNeverReused
+TestDemoMovedDelivery: changedScope => oneSnapshotRead; unchangedTicks => zeroReads; invalidSignature => noNewMapping; restart => verifiedPersistedMapping; ordinaryHost => baseline
+```
+
+- [ ] **Step 2: Run** `go test ./internal/democlaim ./internal/host ./internal/edge -run 'TestDemoMoved' -count=1`; expect FAIL.
+- [ ] **Step 3: Implement the minimal Plan 2 hook.** Register one control scope on the existing watch. Load at startup and on its changed generation in the existing pass, not in a new ticker; require the shared watch for activation. Preserve a verified mapping across refresh failure only until its signed expiry. Extend the existing demo stream with the same signed snapshot if a serving demo-fleet edge needs it; it never polls the bucket. Require exact one-label demo hosts and derive TargetHost from the committed target account/app, under configured AppsDomain, with no scheme/path/port supplied by users. Reject overflow before claim commitment by reserving notice capacity. Keep notices monotonic for a never-reused host.
+
+ At the demo-domain entry, before lookup, cache, caps, upgrade or activation, serve a small escaped HTML page for GET and headers-only HEAD; other methods receive 410 and no forwarding. Use 200 for the page, `Cache-Control: no-store`, `Referrer-Policy: no-referrer`, `X-Content-Type-Options: nosniff`, and restrictive CSP with no scripts/forms/external resources. Link to `https://` plus TargetHost only; no automatic redirect, cookie or claim link. Plan 2 can call this hook before its generic demo states when it lands. Purging the source must never delete this independent notice or the permanent name tombstone.
+- [ ] **Step 4: Rerun Step 2**, plus existing `TestDemo` edge tests and change-index request-count tests; expect PASS.
+- [ ] **Step 5: Commit** with subject `feat: show moved notices for claimed demo hosts`.
+
+### Task 7: Complete the browser fallback and Keymail path
+
+**Risk/review:** security gate and redirect. Independent task review required.
+
+**Files:**
+- Create: `internal/console/demo_claim_page.go`, `internal/console/templates/demo_claim.html`, `internal/console/static/demo_claim.js`.
+- Modify: `internal/console/apidemo.go:269`, `internal/console/emailsignin.go:258`, `internal/console/server.go:3889`, Task 1 purpose-link dispatch and flow storage.
+- Test: `internal/console/demo_claim_page_test.go`, `internal/console/demo_claim_browser_test.go`.
+
+**Interfaces:**
+- Produces: `(*Server).handleDemoClaimPage(w http.ResponseWriter,r *http.Request)` and `handleDemoClaimBrowserProof` with the same signature; `POST /demo/claim/intent`, `/demo/claim/prove`, `/demo/claim/select` are same-origin CSRF-protected browser doors over Tasks 1/2.
+- Produces: HttpOnly, Secure, SameSite=Lax `carlos_demo_claim_flow` cookie, path `/demo/claim`, maximum 15 minutes. Store its hash and purpose, never the raw demo token. Browser GET renders only; explicit POST is required to claim.
+- Consumes: normal `/auth/continue`, Keymail state/PKCE and `next=/demo/claim`; browser proof calls `proveDemoClaim` with the authenticated session identity, never the address originally typed into discovery.
+
+- [ ] **Step 1: Write failing tests.**
+
+```text
+TestDemoClaimFragment: token => POSTBodyOnly; historyFragmentCleared; logs/referrer/analytics/query => noToken; scannerGET => noProofOrClaim
+TestDemoClaimBrowserIdentity: KeymailActualIdentity != typed => actualIdentityShownAndExplicitConfirmation; noSession => signin; multipleAccounts => mandatoryPicker; staleSession => freshAuthLast
+TestDemoClaimBrowserCSRF: wrongOrigin/missingNonce/crossFlow => refused; membershipFailure => 404BeforeFreshAuth; externalNext => dropped; emailedLinkGET => noConsumption
+TestDemoClaimBrowserRecovery: returnFromOAuth => sameIntent; pageReload => status; expiredIntent => normalRefusal; committedTokenReuse => cannotClaimAgain
+```
+
+- [ ] **Step 2: Run** `go test ./internal/console -run 'TestDemoClaim(Fragment|Browser)' -count=1`; expect FAIL.
+- [ ] **Step 3: Implement the page and browser adapters.** First script copies the fragment to memory, clears it with `history.replaceState`, and exchanges it for the claim-only cookie via same-origin POST. No analytics, third-party assets or localStorage on this page. Use the email/code UI over the same proof mechanism; the claim email link can finish in another browser through the existing nonce-confirmed purpose handler. Keymail uses ordinary sign-in and returns to the intent. Do not auto-claim merely because OAuth finished or a session already exists: show the actual person, target account where unique, and require confirmation. For several accounts, selection is that confirmation.
+
+ Avoid MRU landing side effects for this specific return: extract identity/session completion from account landing, leaving ordinary sign-in unchanged. Claim-side zero-account mint must pass Task 2's cap/person lock, including a new Keymail user. Apply browser session, CSRF and membership gates before `requireFreshAuth` where fresh proof is required; Keymail never downgrades to email step-up. Agent JSON endpoints issue no browser session and browser cookies cannot authorize them. List completed account/app/URL and the normal CLI next step; no deploy credential.
+- [ ] **Step 4: Rerun Step 2** and sign-in callback/step-up regression tests; expect PASS. Verify browser fragment removal and keyboard operation using a local mock, bound to loopback.
+- [ ] **Step 5: Commit** with subject `feat: finish demo claims in the console browser`.
+
+### Task 8: Prove the complete claim and activate dev
+
+**Risk/review:** whole-branch review covers test/doc wiring. Any new security/root/storage behavior found necessary belongs back in its owning task's review budget.
+
+**Files:**
+- Create: `internal/console/demo_claim_e2e_test.go`, `internal/host/demo_claim_dev_linux_test.go`.
+- Modify: `internal/demo/config.go:22`, `cmd/console/main.go:478`, `internal/console/apidemo.go:439`, `README.md` anonymous-demo operator section; Task 7 page copy and claim API documentation alongside that section.
+- Generate during implementation: `internal/provision/testdata/plan14-root-reads-agent-start-demo-3.tsv`, census chain entry and `docs/superpowers/notes/census-proposal-agent-start-demo-3.md` with proposal tooling and independent dispositions.
+
+**Interfaces:**
+- Produces: `demo.Config.ClaimEnabled bool`, parsed from `CARLOS_DEMO_CLAIM`, unset or `1` only; `(*Server).demoClaimReady(ctx context.Context) error`, cached for 45 seconds like existing admission checks with an independent 10-second context.
+- Claim availability requires mail/Keymail path readiness, worker export capability, ordinary arm64 seed placement, seed floor, serving-edge moved/gate capability, policy writer and change delivery. `claimAvailable` reflects that readiness, not just the setting.
+- Switching off prevents new proof/selection/reservation. It leaves status, committed-work recovery, abort, retirement and moved notices operational. Register their routes independently of create admission so a console restart with admission off cannot strand claims.
+
+- [ ] **Step 1: Write failing end-to-end tests.**
+
+```text
+TestDemoClaimEmailToPermanent: sourceStartedWithSocketAndDBFlags; writeSQLiteThenUpdateThenClaim => exactLatestDataAndArtifact; newAccountOrSelectedExisting; targetOutsideDemoFleet; claimTokenDead; ordinaryCLIWorkflowPossible
+TestDemoClaimFailureKeepsDemo: cap/wrongCode/unsupportedPlacement/copyFailure => noPermanentServingApp; demoStillWorksAfterConfirmedAbort; noTTLReset
+TestDemoClaimDevAcceptance: actualWALDataCopied; sourceFrozenDuringCopy; destinationGatedUntilCommit; originalHostMovedThenExpires; rootPurgeAck; smallAppClaimElapsed<1m
+TestDemoClaimOffCompatibility: switchUnset => noNewBehaviorOrStorePolls; switchedOffMidClaim => recoveryCompletes; ordinaryEmail/seed/import/apps => baseline
+```
+
+- [ ] **Step 2: Run** `go test ./internal/console ./internal/host -run 'TestDemoClaim(EmailToPermanent|FailureKeepsDemo|DevAcceptance|OffCompatibility)' -count=1`; demonstrate the integration witness fails with the coordinator disconnected. A gated dev skip is outstanding evidence.
+- [ ] **Step 3: Finish activation wiring and approved copy.** Run the copy review table through the repository's copy workflow before putting strings in product files. Update operator/API documentation and `claimAvailable`; no CLI verb is added. Build test binaries on the workstation and exercise the real dev boxes through APIs with those binaries. Use the existing demo wildcard and housekeeper certificate path, console drop-in and normal destination placement. Record account selection, plan refusal, WAL contents, artifact digest, destination first replica, old URL notice, expiry and interrupted-copy recovery. Dev switches on when the implementation lands; provisioning/DNS/IAM changes, if discovered necessary, need a concrete scoped approval before execution. This plan does not grant it.
+- [ ] **Step 4: Run the final implementation gate once.** Targeted tests first, then repository-required `go build ./...`, `go vet ./...`, `go test ./... -count=1`, whole-tree gofmt check and prescribed cross-build/CI gate. Use the default Go cache; no compilation on demo boxes. Run `make census-card`, write unit claims, then `make census-propose NAME=agent-start-demo-3 CLAIMS=<claims-file>`; independently review every unit/envelope against amadan main and record verdict on #280. Whole-branch review follows the budget below. These commands belong to the future implementation session; none is required for authoring this document.
+- [ ] **Step 5: Commit** with subject `test: prove email claims preserve demo apps and data`. Describe, push and squash-land the implementation branch through amadan after tip CI is green; inspect main CI afterward. Stop at this one visible merge.
+
+## Copy review required
+
+This is a string inventory, not approved wording. All new human-facing strings belong here, including dynamic error templates and operator messages. Existing email sign-in text remains unchanged unless explicitly listed. No product copy is written in this document-only session.
+
+| Copy ID / surface | Meaning to draft and review before implementation |
+|---|---|
+| CLAIM-EMAIL | Email label, placeholder, submit/resend controls, code entry and confirmation controls, help and accessible labels. |
+| CLAIM-MAIL | Claim-specific email subject/body, code, expiry, demo identification, safe browser link and unsolicited-message explanation. No account authority or misleading ordinary-signin claim. |
+| CLAIM-KEYMAIL | Browser-required response and link explanation; authenticated identity confirmation when the actual Keymail person differs from the typed address. |
+| CLAIM-PROOF | Malformed email, invalid/expired/replaced code or flow, wrong nonce/origin, resend and mailbox-unavailable messages; preserve non-enumeration. |
+| CLAIM-ACCOUNT | Account picker title, account/role labels, confirmation, new personal account explanation and inaccessible-account response. |
+| CLAIM-CAP | App plus instance cap, free-account cap, create-rate limit and other normal plan refusals; demo continues to its original expiry. Review adapted existing cap text if it contains an em dash. |
+| CLAIM-BUSY | Existing build/settlement/claim, source briefly paused, copy/verification progress, retry timing and recovery pending. |
+| CLAIM-DATA | Assigned box unavailable, missing/corrupt SQLite, WAL failure, 256 MiB limit, scratch exhaustion, timeout and safe abort; no false recovery promise. |
+| CLAIM-PLACEMENT | No eligible ordinary arm64 destination, unsupported region/HA/fleet, missing seed floor/capability and unavailable policy writer. |
+| CLAIM-RESULT | Success, permanent URL, account/app identity, original host expiry, no account credential issued and normal CLI login/deploy next step. |
+| CLAIM-MOVED | Page title/body/link and accessibility text, HEAD behavior and non-GET refusal. No automatic forwarding, claim token or app-supplied markup. |
+| CLAIM-RETIRED | Invalid/spent token, expired demo, interrupted operation after expiry and unavailable status; no account detail before proof. |
+| CLAIM-OPERATOR | Switch/readiness, pending cleanup, failure reason codes rendered for operators, audit messages, activation/rollback and API documentation. |
+| DEMO-DATA amendment | Existing absolute “cannot be copied” refusal must distinguish unsupported generic move/import from this verified claim transfer, without promising a demo backup. |
+
+## Review budget and self-review
+
+Independent plan review rounds in this authoring session: **0**. No agents were spawned. Plan 1's controller rulings and review history remain settled dependencies; this is a new Plan 3 change, not a reopening of Plan 1. Use `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md` for implementation briefs, carrying the round history and each finding's invariant. Tasks 1 through 7 require independent review for their marked risks; Task 8 receives the whole-branch review. For a Codex author, use Opus or Fable for other-family census and authority review.
+
+Stop at the first round with no P1. Apply that round's P2 fixes without a new general review, retaining census and checks of newly changed security/root/termination/production-storage behavior. Record P3s as follow-ups. Maximum three rounds; a fourth needs Paul's decision. Two consecutive rounds in one fault family trigger the stop-and-choose rule. No review against unmerged Plan 2. The implementation session owns this one plan and ends at its merge; carry the three-day/three-compaction and 24-hour reporting limits from AGENTS.md.
+
+Self-review: design §4.5 maps to Tasks 1/7 (email and Keymail), 2 (account choice/authorization/caps), 3/4/5 (same artifact and quiesced local SQLite into a normal permanent app), 5 (single-use token and retirement), 6 (moved page), and 8 (visible dev activation). The no-credential decision avoids granting an agent service roles, account scope or credential recovery; Task 1's continuation dies as a mutation capability when the one operation is reserved. The five Review Focus cases have named owning tests. Shared operation/flow/seed identities and signatures match across tasks. No production function bodies or full test suite were run or written during planning. The supported-placement boundary is explicit: ordinary placement is checked first, existing seed restrictions are retained, and an unsupported result refuses before stopping the demo.
+
+## Open questions
+
+None for Paul. Builder choices above are marked “my call”; copy approval and any scoped infrastructure rollout approval are execution gates, not unresolved product decisions.
diff --git a/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md b/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md
new file mode 100644
index 000000000..2b641df8a
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md
@@ -0,0 +1,224 @@
+# /start and the homepage Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** A person pastes one line into their coding agent, describes a small app, gets a working demo, claims it, and learns the normal development path.
+
+**Architecture:** The website builds Markdown and HTML from one agent-instruction source and ships a versioned source starter beside them. The website stays static: the platform edge negotiates `_site/start/index.html` and its `index.md` twin through Plan A; the console remains the only publish, build, status and claim authority. The homepage and human introduction use Paul's reviewed copy, with no browser API client.
+
+**Tech Stack:** Existing Eleventy, Markdown-it, plain HTML/CSS and clipboard enhancement; Go 1.26.10 for the starter only; Rastrillo v0.30.2, embedded Fiesta 1.1.0 CSS and SQLite for the starter.
+
+**Spec:** Platform `docs/superpowers/specs/2026-11-02-agent-start-demo-design.md`, especially §§3, 4.7 and the fixed §5 rulings. Read merged Plan 1, `docs/superpowers/plans/2026-11-02-agent-start-demo-1-anonymous-apps.md:88`, and its build rulings, `docs/superpowers/notes/agent-start-demo-1-rulings.md:5`, before implementation. Paul’s fixed 2026-11-04 ruling keeps the website static and supersedes §4.7’s fetcher detection: negotiation uses Accept only, with complete visible HTML instructions as fallback. Plan A is `docs/superpowers/plans/2026-11-04-static-markdown-twins.md`; Plan 3 produces the claim interface below.
+
+## Global Constraints
+
+- This is Plan 4 only. Its implementation files belong to `/home/paulca/amadan.net/carlos/website`, abbreviated **W** below. Unprefixed evidence paths belong to the platform worktree. This authoring session revises this plan and writes Plan A: no product code, other repository writes, agents, commits, pushes or full tests.
+- Preserve the approved limits: 24 hours with no extension by updating, no backups, one binary, SQLite at most, no outbound network, email, object storage, schedules, sidecars or custom domains. Route larger projects and existing-app migrations to the account path before submitting source.
+- Go 1.26.10; module `demo.local/app`; `amadan.net/rastrillo/rastrillo v0.30.2`; complete Plan 1 module closure and checksums; `CGO_ENABLED=0`; entry package `.`; linux-arm64 output. Fiesta is embedded assets, not an added module. Do not run `go mod tidy`, use `@latest`, add `replace`, or change the lock to accommodate the starter.
+- Source is one gzip stream containing ordinary USTAR files/directories: at most 5,000,000 compressed bytes, 20,000,000 expanded file bytes, 256 files, 2,000,000 bytes per file, and 256 directories. Output binary cap: 33,554,432 bytes. No symlinks, hardlinks, PAX/GNU extension records, sparse files, VCS tree, vendor tree or workspace files.
+- Binary apps read `--socket` and `--db` flags. Demo SQLite stays on its assigned box with no replica. Public demo hosts are never reused. Do not infer a hostname, database recovery or a replacement app from an earlier run.
+- Provider-neutral website and starter; no cloud SDK, vendor build service, bucket reader, background health polling or new per-box polling. Only an active agent polls its returned console job URL, at bounded intervals.
+- The demo journey switches default off; Plan A needs no off switch because sites without twins retain their existing behaviour. Website build switch `CARLOS_START_DEMO=1` selects the new journey; unset builds the account path without anonymous-publish instructions. Console admission remains its existing drop-in switch `CARLOS_DEMO_APPS=1`. Neither switch enables the other. **Switch-on date: dev on the day this plan lands.** Public activation waits for Plan A on the serving edges and Plans 2 and 3 merged, enabled and verified, then accompanies the approved website release. Do not land an unused preparatory slice separately.
+- The dev acceptance target is the existing `dev.trycarlos.com` setup. The console origin is a separate configuration value, never inferred from that name. One `*.trycarlos.com` certificate covers direct demo names; it does not cover invented names below `dev.trycarlos.com`. Use returned URLs and verify their actual TLS. The issuer is the housekeeper, not the ingress. This plan creates no DNS records or certificates.
+- Demo boxes have 2 GB RAM: no test compilation, browser installation or test suite there. Author/CI checks run off-box; the existing remote builder compiles submitted apps only. Preserve default Go caches; scratch goes under `$TMPDIR` or `~/.cache` and is removed.
+- Website HTML remains usable without JavaScript. Reuse local clipboard and disclosure scripts, existing light/dark styling and drawn marks. No new browser framework, CDN assets, analytics, client-side publishing or hidden agent instructions.
+- Examples use `shop` and `example.com`, never customer names. Deployment hostnames are configuration, not core defaults. Copy uses no em dashes. All human-facing text is inventoried once in the copy table; agent-directed instructions are exempt by Paul's instruction for this plan.
+- All tasks land as one reviewed website branch with an observable dev journey. Platform root source is unchanged, so no root-read census overlay is expected. Plan A owns the separate platform change and its census review.
+
+## Review Focus
+
+1. Browser, agent and mixed `Accept` requests must receive the right representation without sharing the wrong cached body: Plan A’s edge tests and Task 5’s `verifyStartOrigin`.
+2. A default tar command, missing module checksum or an environment-only starter must fail locally before spending demo admission: Task 1, `TestWebsiteStarterContract` and `TestStarterFlagsAndPersistence`.
+3. A blocked API host, lost create response or expired token must not trigger repeated anonymous creates, broaden network access or leak credentials: Task 2, `start-protocol.test.mjs` transcript cases.
+4. An HTML-only fetcher and a phone user with denied clipboard access must still reach the complete instructions and copy the exact line: Tasks 3 and 4, `start-build.test.mjs` HTML parity assertions and `start-pages.test.mjs`.
+5. A claim with several accounts, unavailable claiming or an asynchronous data transfer must not be presented as permanent success: Tasks 2 and 5, claim-contract fixtures and the real cloud-agent witness.
+
+---
+
+## Evidence and boundaries
+
+Read against platform `2914921ceabd4218b0363a9780f8e4db890aab4c` and website `ef3def7d546504dab3e2b35e2cdfc10f6c880808`. These are discovery anchors, not permission to ignore later merged producer interfaces. New file/function names below are decisions, not existing APIs.
+
+| Evidence | Consequence |
+|---|---|
+| W `AGENTS.md:26`, `:63`, `:126`, `:176`; W `README.md:17`; W `eleventy.config.js:49`, `:62`, `:206` | Homepage and `/start` are hand-authored passthrough files today. Eleventy builds `_site/`; footer and disclosure are added after rendering. Never edit vendored `src/docs/`, `src/_data/docs*.json` or `src/well-known/`. |
+| W `PRODUCT.md:51`, `:61`, `:72`; W `DESIGN.md:130`, `:207`, `:267`, `:281`; W `AGENTS.md:65`, `:74` | Keep the website's house style, system fonts, light/dark modes and approved clipboard exception. The newly approved journey supersedes the older developer-only primary action in `PRODUCT.md:23`. |
+| W `src/index.html:27`; W `src/start/index.html:29`; W `src/start/start-tabs.js:1` | The hero contains numeric multipliers inside a human-marked block. The existing start flow asks for tools before deploying. Replace only the authorised hero/start journey after Paul's copy review; preserve unrelated human-certified sections. Reuse clipboard attributes and fallback selection. |
+| W `src/llms.njk:9`; W `AGENTS.md:160` | Point new-app agents to `/start` before the older install-first skill path; keep skills and account reference links. Do not rewrite the vendored skills. |
+| `internal/edge/static.go:585`, `:599`, `:632`, `:668` | Static serving resolves files and redirects directories to slash form. Plan A adds general Accept negotiation for existing HTML/Markdown twins; `/start` keeps the static redirect to `/start/`. |
+| `internal/edge/edge.go:2536`, `:2570`, `:2601`; `internal/edge/static.go:793`; `internal/edge/compress.go:241` | Static routes bypass the shared response cache. Plan A preserves content tags per selected file and `Vary: Accept` alongside compression’s `Accept-Encoding`. |
+| `internal/console/apidemo.go:264`, `:293`, `:310`, `:371`, `:437`, `:496`, `:553`, `:580` | Actual create/update endpoint, gzip content type, bearer selects update, returned fields, Retry-After/status states and live URL. Claim availability is currently false. |
+| `internal/demo/config.go:13`, `:31`; `internal/console/demo_store.go:238`, `:329`; `internal/console/demo_jobs.go:45` | Exact source cap, 60 update attempts, off-by-default admission, fixed 24-hour expiry and at most one active job per demo. Do not promise concurrent updates or unlimited repair attempts. |
+| `internal/demobuild/source.go:24`, `:51`, `:190`, `:207`, `:227`, `:273`; `internal/demobuild/lock.go:18`, `:127`, `:170`; `internal/demobuild/probe.go:42` | Exact archive grammar and module closure; local imports under `demo.local/app` are allowed, direct transitive imports are not. The probe demonstrates ordinary USTAR packaging without leading `./`. |
+| `internal/demobuild/runner.go:36`; `internal/console/testdata/demo/go.mod:1`; `internal/console/testdata/demo/main.go:16`; `internal/activator/backend_exec.go:2530`, `:2733` | Copy the lock files, not the fixture's environment-based entrypoint. Real runtime launches pass flags. Offline builds use a prewarmed closure and no toolchain download. |
+| `internal/activator/demo_durability.go:18`, `:94`, `:105`; `internal/provision/demo_policy.go:15`; `internal/edge/demo.go:18`, `:27`, `:72`; Plan 1 rulings `:19`, `:27`, `:33`, `:34` | Local-only data, fixed assignment, root-owned demo-box isolation, never-reused hosts and the corrected wire fields are binding. R23b forbids a substitute fake starter as acceptance evidence. |
+| Rastrillo module-cache `amadan.net/rastrillo/rastrillo@v0.30.2/serve.go:70`, `:133`, `:145`, `:385`, `:823` | `rastrillo.Options` accepts `Router func(*sql.DB) (*http.ServeMux, error)`, `DBPath`, `Migrations` and `Socket`; `rastrillo.Serve(Options) error` opens SQLite and serves the socket. Set flags explicitly so its TCP fallback is unreachable. |
+| `internal/console/static/fiesta/VERSION:2`; Fiesta commit `4ee76b5e651ff4fb5a4bae12d7508f55a2531eff`, `README.md:11`, `:63`, `:75`, `releases/1.1.0/SHA256SUMS:1`, `:9` | Pin Fiesta 1.1.0 assets from that commit. Day, Plain and Signal exist; preserve MPL-2.0 notice. No Fiesta Go dependency is needed. |
+| W `AGENTS.md:195`; W `hack/cache-bust.mjs:14`; `docs/site/cli.md:54`, `:316`, `:348`, `:1362`; W `src/start/index.html:33` | Website deploy remains static via console/CLI, with the previous static version as rollback. Public CLI releases already have a link; install is post-claim only. |
+
+**Fixed serving decision (Paul, 2026-11-04).** Build `/start/index.html` with the human introduction and full visible “for your agent” section, plus `/start/index.md` with the agent directives from the same source. Plan A owns Accept negotiation; no User-Agent detection is needed. HTML-only fetchers receive the complete instructions. Keep the website’s static route, build and release workflow.
+
+**Dependency gate.** Plan 1 is merged and live. Before implementing or independently reviewing Plan 4’s website tasks, Plan A must be merged and released to the edge serving the target website; record its merged SHA, release and an observed negotiation check. The claim step also waits for Plan 3 to merge: Task 2 binds its declared contract to the merged handlers. Dev acceptance and public activation require Plans 2 and 3 enabled and verified there, and Plan A on that destination’s serving edges. Do not review against unmerged producers; these gates do not reset review history.
+
+| Plan 3 declared interface, not shipped yet | Website instruction contract |
+|---|---|
+| Plan 3 `:72`: `POST /api/demo/claims`, JSON `{claimToken,email,flowToken?}` | Initial call omits `flowToken`; resends retain it. `202 {state:"email_required",flowToken,expiresAt}` means ask for the emailed code, not that delivery is guaranteed. `200 {state:"browser_required",claimUrl}` means open the returned link; no fabricated flow token. |
+| Plan 3 `:74`: `POST /api/demo/claims/verify`, JSON `{flowToken,code}`; `POST /api/demo/claims/select`, JSON `{flowToken,accountId}` | `account_required` returns `accounts:[{id,name,role}]`. Ask the person, submit the exact selected ID, never the display name or MRU account. Zero/one membership is resolved by the server. |
+| Plan 3 `:76`: `GET /api/demo/claims/status`, `Authorization: Bearer <flowToken>` | `202 {state:"claiming",phase,retryAfter:2}` remains pending. `200 {state:"claimed",accountId,app,url,next:"cli_login"}` alone authorises the success explanation and normal CLI path. Wait at least the returned `retryAfter` seconds between polls, respecting a longer HTTP Retry-After. |
+| Plan 3 `:78`, `:100`, `:102` | Proof/selection expires at the earlier of 15 minutes and demo expiry; resend does not extend it. Transfer has a five-minute bound before commitment; recovery after commitment can continue. Stop automatic waiting after five minutes and explain pending recovery without creating another app. Result reads use the flow token until original expiry plus 24 hours. |
+
+The flow token is distinct from the demo update token and from a CLI credential. Never send either secret to the app origin, install it as an account credential, or discard the flow token before recording successful completion. Plan 3 grants no post-claim deploy credential. Browser completion may require normal sign-in to discover the permanent app if no flow token was returned; never guess its address.
+
+## Agent content contract
+
+One source, `W/src/start/agent.md`, contains the following ordered directives. `W/hack/build-start.mjs` substitutes only validated deployment values and release metadata, producing both the Markdown response and the complete visible HTML agent section. The HTML introduction is separate reviewed copy. Do not hide the directives in comments, a collapsed disclosure or JavaScript.
+
+1. **Ask first.** Ask what the person wants to make and wait. Offer a booking page, shop, tracker or team tool only if they are stuck. Infer experience from their language; ask one light clarifying question if needed. Ask how the UI should feel. Confirm the small first version before generating or uploading anything.
+2. **Adapt the explanation.** Experienced developers get the Go/Rastrillo/Fiesta/SQLite stack, remote build, 24-hour expiry, claim and later CLI workflow. Newcomers get plain language without product/framework names unless they ask. Everyone is told the app is public, temporary and has no backup; use invented data, no real passwords or sensitive information. Do not describe demo storage as replicated or durable across box loss.
+3. **Choose scope and style.** One binary and one local SQLite database; no outbound calls or restricted capabilities. Existing-app migrations take the account path with an honest rootfs/managed-fleet explanation at the user's level, not an automatic rewrite. Map calm/everyday to `day`, minimal to `plain`, bold to `signal`, and playful to `day` with small local presentation changes (my call). Explain that the three themes are starting points, not four invented theme packages. Keep the initial app to one useful screen and one persisted entity.
+4. **Fetch the pinned starter.** Use its same-origin immutable archive and checksum or the complete source listing beside it. Keep `go.mod` and `go.sum` unchanged. No CLI, Go installation, package manager or local compilation is required of the demo user. Use an already available archive/HTTP tool in the agent's environment. A cloud agent without Go must complete the flow. A chat application unable to make outbound requests is out of scope.
+5. **Pack the source.** Regular USTAR entries rooted at `go.mod`, `go.sum`, `main.go`, `templates/`, `static/` and `LICENSE.fiesta`, with relative clean names and no enclosing directory or leading `./`. Include new application files explicitly; exclude tests, `.git`, credentials, SQLite files and the output archive. A GNU tar example uses `tar --format=ustar -czf <outside-source>/source.tar.gz go.mod go.sum main.go templates static LICENSE.fiesta`; a Python standard-library alternative specifies `tarfile.USTAR_FORMAT`, enumerates only regular allowlisted files, and assigns the same relative names. Never use an unqualified `tar ... .`. Do not execute generators or change dependency versions to repair an error.
+6. **Publish through the console origin.** Send raw archive bytes to `POST <consoleOrigin>/api/demo/apps`, `Content-Type: application/gzip`, `X-Carlos-Client: <actual harness>`, without Authorization on the first create. No multipart, base64 or JSON wrapper. On 202 retain `jobId`, `name`, `statusUrl`, Unix-seconds `expiresAt`, `claimToken`, `claimUrl`, and `claimAvailable` in private agent state; never in the app, repository, public transcript or screenshots. Give the user the returned secret claim link once, privately, as recovery information. Do not claim it works if `claimAvailable` is false.
+7. **Wait and repair.** GET the returned `statusUrl` without a bearer token. Poll no faster than its `Retry-After` (2 seconds on main); use 5 seconds if absent, respect longer retry values and allow at most five minutes of automatic waiting (my call). `building`/`starting` are pending; only `live` plus `url` is success. `failed` carries `diagnostics`, `diagnosticsTruncated` and `message`; fix source and resubmit with `Authorization: Bearer <claimToken>` to the same publish endpoint. Retain the original claim fields because update replies omit them. Make at most two automatic repair submissions before explaining the problem; do not consume the lifetime's 60 attempts in a loop. Do not promise rollback unless the response says it occurred.
+8. **Handle refusals without creating a second app.** 400/413/415 require source correction; 409 means wait for the active update; 429 can mean a request budget or the lifetime update limit, so follow its response rather than retry indefinitely; 503 means unavailable, not permission to rotate identity. 401/404/410 or unavailable claims never fall back to anonymous create. A lost create response is an unknown outcome with a potentially lost one-time token: stop automatic submission and explain, since main has no create idempotency/recovery endpoint. A transport-level host block is distinct from an API error. Explain one exact console hostname to allow under the agent's internet/network permissions, why it is needed and that settings differ by product; then retry once authorised. Never suggest disabling the sandbox or allowing wildcard domains.
+9. **Share the result.** Hand over the returned live URL unchanged, formatted as a full Markdown link, and explain the actual `expiresAt`, fixed 24-hour lifetime and claim availability. Updates use the same bearer and do not extend expiry. Do not synthesize URLs from `name`, shorten a claim link, lose its fragment, or send a token to the live app. HTTP tooling must not follow a credential-bearing request to another origin; validate HTTPS console origin before using returned status/claim endpoints, while preserving valid returned URLs byte-for-byte.
+10. **Claim through Plan 3 (declared dependency).** When claiming is available, ask whether they want to keep it; then ask for email, start the declared challenge and ask for the emailed code. Keymail uses the returned browser link. If multiple accounts are returned, ask the person to choose explicitly; do not choose the most recently used account. Plan-limit/permission refusals leave the demo on its original expiry. Follow Plan 3's completion/status contract through data transfer; verification or account choice alone is not success. Share the returned permanent URL only after successful completion, verify a previously saved row there, and discard the consumed demo credential. Do not manufacture a scoped account credential.
+11. **The right way after claim.** Offer, rather than silently start, the permanent workflow. Download the matching CLI binary and published checksums from the public `carlosframework/releases` release page; never `go install` the private platform module. Sign in with `carlos auth login --console <consoleOrigin>` and browser code approval, inspect `carlos auth whoami`, select the claimed account/app, put source in the user's chosen repository, and keep tokens/databases/build output out of it. Build the app for the deployment's supported architecture in a development environment, then `carlos deploy --console <consoleOrigin> --account <claimedAccount> --app <claimedApp> ./shop-linux-arm64`. Preserve the database and verify both the new UI and saved row. Do not run `apps create` for an already claimed app. For newcomers explain each step and defer setup until they choose it; the no-install promise applies to the demo, not all future development.
+
+## Task 1: Publish a locked, flag-based Rastrillo and Fiesta starter
+
+**Risk/review:** storage, security gate (the archive/dependency boundary and public writable example), and the form's same-origin redirect. Independent task review required. No root, termination or billing change.
+
+**Files:**
+
+- Create W `src/start/starter/v1/{main.go,go.mod,go.sum,templates/index.html,static/fiesta.css,static/fiesta-plain.css,static/fiesta-signal.css,LICENSE.fiesta,manifest.json}`.
+- Create W `hack/pack-starter.py`, `hack/check-starter.mjs`, `test/starter/main_test.go.txt`, `test/starter/website_starter_contract_test.go.txt`, `test/starter-pack.test.mjs`.
+- Modify W `package.json` to expose `check:starter`; change passthrough wiring with Task 3. No source Go test files enter the submitted archive.
+
+**Interfaces:**
+
+- Consumes the exact Plan 1 lock and fixture `go.mod`/`go.sum`. Lock-file SHA-256 is `a858eb184a5255068a4a56470e3549a2a7d4718635a90fe69f40e9faff3948c5`; fixture mod/sum hashes are `78a1f3d56026dc3efa3a9456dc7a39c63672bafcf0bb04944c075eac6e601180` and `688bf53e93ba1ba280fc924446986ab2cf32fba7c4f16efaf80a8c6e36848b49`.
+- Produces `parseFlags(args []string) (socket, dbPath string, err error)` and `newRouter(db *sql.DB) (*http.ServeMux, error)` in the starter. Both flags are required absolute paths; missing flags fail before listening, regardless of `CARLOS_SOCKET`/`CARLOS_DB`. Call `rastrillo.Serve` with the parsed socket/database and additive `items(id INTEGER PRIMARY KEY, name TEXT NOT NULL)` migration.
+- Routes: `GET /` renders escaped rows, `POST /items` accepts one `name` (1-120 Unicode characters, body at most 4096 bytes), then returns 303 to `/`; `GET /static/{file}` serves only the three embedded CSS files. Use same-origin POST checking with nonempty Origin required; no destructive or credential features. Store at most 100 rows for the starter (my call). All UI strings use the copy-table IDs.
+- `pack_starter(source: Path, output: Path) -> None` writes sorted USTAR entries with fixed modes, zero mtime/uid/gid, empty owner names and deterministic gzip metadata; output must be outside source. Its input inventory excludes `manifest.json`, which describes the archive rather than being included in it. Reject links, unsafe paths and cap breaches. Publish `/start/starter/v1/source.tar.gz` plus `manifest.json` with `schema:1`, `archiveSHA256:string`, `files:[{path:string,sha256:string}]`, `platformCommit:string`, `lockSHA256:string`, and `fiesta:{version:string,commit:string}` (the `StarterManifest` shape). Never replace v1 bytes after publication; fixes get v2.
+- Fiesta combined CSS hashes from the pinned release: Day `141597a63cdc616bc33c7bec0ee6bcda47bd5d279726ed9f44fa6ddf3671b68a`; Plain `47f6911af8efc962d268cb4f1bedeaf6ac921c2fef6a29cfa57be0ab0ce01b43`; Signal `b8d5337117166c9156271762e39e0dec1f44bb8459ce98f9632dff31322a999a`. Embed and serve locally; no CDN requests, inline scripts or JavaScript dependency. Choose one stylesheet in the template.
+
+- [ ] **Step 1: Write failing tests.** `TestStarterFlagsAndPersistence`: environment variables absent; launch with both flags; GET succeeds; POST saves a row; restart and rebuild/update preserve it; missing flags never listen on TCP; hostile markup renders escaped; cross-origin POST is refused; unknown asset is 404. `starter-pack.test.mjs`: deterministic hash, no directory wrapper/`./`, no links/PAX records, explicit source inventory, each cap boundary, unchanged lock files and all three Fiesta hashes. `TestWebsiteStarterContract`: the generated archive passes real `demobuild.ValidateSource` with `DefaultLock`; deliberately altered dependency, removed checksum and PAX fixture fail.
+- [ ] **Step 2: Run and observe failure.** `node --test test/starter-pack.test.mjs` and `node hack/check-starter.mjs --platform <read-only-platform-checkout>` fail on missing packer/starter. The latter uses a Go `-overlay` mapping to supply `website_starter_contract_test.go` to the existing `internal/demobuild` package without editing that checkout, and runs only `TestWebsiteStarterContract`. It copies the starter and its runtime test into disk scratch, never the live demo box.
+- [ ] **Step 3: Implement the declared starter and packer.** Before writing the template, review the starter UI entries from the copy table with Paul using the copy-review skill; Task 4 does not reopen this approved copy. Use `html/template`, parameterised SQL and Rastrillo's database lifecycle; no source generation or direct SQLite-driver import. Copy verified module/asset bytes from the cited sources. Generate the archive, checksum and browsable source listing from the same inventory.
+- [ ] **Step 4: Verify.** Repeat Step 2; download the locked closure once on the author/CI machine with normal checksum verification, then build the scratch starter offline using Go 1.26.10, `GOWORK=off GOTOOLCHAIN=local GOENV=off GOFLAGS= GOPROXY=off GOSUMDB=off CGO_ENABLED=0`, using `go build -mod=readonly -trimpath -buildvcs=false -o <scratch-binary> .` (the worker command at `internal/host/units/carlos-demo-build@.service:11`), for both local runtime testing and `GOOS=linux GOARCH=arm64`. Assert `go.mod`/`go.sum` stayed byte-identical and binary size is within cap. Actual remote build remains Task 5's evidence, with no fake substitute.
+- [ ] **Step 5: Commit.** Stage only Task 1 files after its independent review; subject `feat: add pinned anonymous demo starter`.
+
+## Task 2: Write and test the agent journey against producer contracts
+
+**Risk/review:** security-sensitive credential instructions, covered by whole-branch review; this task grants no new API authority. No new security gate, root, termination, storage, billing or redirect implementation; no separate task review.
+
+**Files:**
+
+- Create W `src/start/agent.md`, `src/_data/start-config.mjs`, `src/_data/start-claim-contract.json`, `hack/start-content.mjs`, `test/start-protocol.test.mjs`, `test/fixtures/start-protocol.json`.
+- Modify W `src/llms.njk:9` to distinguish the anonymous new-app path from account development.
+
+**Interfaces:**
+
+- `loadStartConfig(env: Record<string,string|undefined>) -> StartConfig`; fields `enabled:boolean`, `siteOrigin:string`, `consoleOrigin:string`, `accountUrl:string`, `starterVersion:string`, `claimContractRevision:string`. `CARLOS_START_DEMO` is unset or `1`; enabled builds require `CARLOS_START_SITE_ORIGIN`, `CARLOS_START_CONSOLE_ORIGIN`, `CARLOS_START_ACCOUNT_URL`. Origins must be HTTPS, without credentials/query/fragment/path; account URL must be same-console-origin HTTPS. No origin from a request Host, query parameter or model guess. Starter version is `v1`.
+- Production site origin is [https://carlosframework.com](https://carlosframework.com); its console origin is [https://console.carloku.com](https://console.carloku.com). Dev values come from the active dev destination, recorded during Task 5. Public copy still contains the single canonical paste line; dev acceptance uses the equivalent deployed dev `/start` URL and verifies the public line separately.
+- Produces `renderAgent(template: string, config: StartConfig, claimContract: ClaimContract, starter: StarterManifest) -> string` in `hack/start-content.mjs`; replace named deployment/contract placeholders only, reject unresolved placeholders, and preserve all other Markdown bytes. Task 3 consumes this renderer.
+- Create/update/status consume the actual fields in the Agent content contract. `start-claim-contract.json` has the `ClaimContract` shape and is a website-side documentation fixture, **not a new console endpoint or wire format**. Its keys are `producerCommit`, `producerPlan`, `start`, `verify`, `chooseAccount`, `status`, `browser`, `complete`; each operation records Plan 3's exact method/path/auth/request/response fixture. It contains synthetic secrets only. The build refuses enabled claim instructions without a pinned merged producer revision and complete fixtures.
+
+- [ ] **Step 1: Bind the declared Plan 3 dependency.** Once Plan 3 is merged, encode the declared interface table above in `start-claim-contract.json`, cite producer handler file:line and merged SHA, and compare every field to the handlers. Carry account selection, Keymail browser completion, retry/expiry and asynchronous data transfer exactly. If the producer has changed, update this consumer contract before implementing it; if absent, keep this task pending. Do not review against an unmerged producer. Paul need not design the wire protocol.
+- [ ] **Step 2: Write failing transcript tests.** Fixtures cover novice, experienced developer, playful/minimal UI, existing-app migration, external API request, blocked host, failed build then bearer update, 429, lost 202 response, expired token and `claimAvailable:false`. Assertions pin ask-before-build, no demo install, bounded polling/repair, unchanged URLs, secret-free public output, no second create and explicit account path. Claim fixtures cover zero/one/multiple accounts, wrong code, Keymail, plan refusal, pending copy, successful permanent URL and consumed token. A canned transcript is contract coverage, not proof of LLM behaviour.
+- [ ] **Step 3: Run to verify failure.** `node --test test/start-protocol.test.mjs`; expect missing directives/config/fixtures to fail. Assertions must inspect parsed request transcripts and rendered instructions, not only keyword presence.
+- [ ] **Step 4: Write the Agent content contract into the single source.** Include complete request/response examples, GNU tar and Python packaging recipes, link to the pinned starter and all required fields. Render the exact merged claim examples from the fixture. Add the public releases link, verified CLI sequence and source-preservation guidance after claim. `llms.txt` gets an anonymous-demo exception to its general replicated-storage description.
+- [ ] **Step 5: Verify and commit.** Repeat the transcript tests; compare each rendered wire example to its producer fixture. Commit subject `docs: add the agent demo and claim journey`.
+
+## Task 3: Build static HTML and Markdown from one source
+
+**Risk/review:** build-time content only; whole-branch review. Plan A owns serving, cache, redirect and platform census review.
+
+**Files:**
+
+- Create W `hack/build-start.mjs`, `test/start-build.test.mjs`, `src/_includes/start.njk`, `src/_data/start-copy.json`.
+- Modify W `eleventy.config.js:49`, `:62`, W `package.json`; remove W `src/start/index.html` after its generated replacement is covered. Replace the broad start passthrough with explicit CSS/script copies; exclude raw starter source and agent Markdown from Eleventy rendering and publish only the generated inventory.
+
+**Interfaces:**
+
+- `buildStart(outputDir: string, config: StartConfig) -> Promise<void>` runs in `eleventy.after` before footer/disclaimer injection. Consume Task 2’s `renderAgent` once; write its bytes to `_site/start/index.md` and render those same bytes with the existing Markdown-it dependency, HTML disabled, into the complete visible HTML agent section. `_site/start/index.html` also contains the separately reviewed human introduction. Publish Task 1’s versioned starter archive/manifest/source listing. Config and claim fixtures stay build inputs, not public files.
+- Disabled builds emit only the account introduction; remove any previous `index.md` and anonymous starter outputs, including on a reused output directory. Enabled builds require validated origins and the pinned merged claim contract. Keep complete code fences and links in both formats.
+- Plan A supplies Markdown only when Accept prefers it, HTML otherwise, with `Vary: Accept` on both variants. `/start` follows existing static slash canonicalisation to `/start/`; explicit `/start/index.md` is also a file. No new website runtime or routing exception.
+
+- [ ] **Step 1: Write failing build tests.** In `start-build.test.mjs`, assert `index.md === renderAgent(...)` and `visibleAgentSection === renderMarkdown(index.md)`; check every directive, request example, limit, claim state and starter link. Assert the human introduction remains outside the agent section, default-off produces the account path, enabled-to-disabled rebuild removes stale downloads/Markdown, invalid origins and missing producer fixtures fail, and config/secrets/raw templates are absent from the public tree.
+- [ ] **Step 2: Observe failure.** Run `node --test test/start-build.test.mjs`; expect missing generated outputs/build integration to fail, not an empty test selection.
+- [ ] **Step 3: Review copy and implement the build.** Submit all human `/start` copy from the table to Paul through copy review before writing it into `start-copy.json`; apply approved bytes verbatim. Implement `buildStart` and wire Eleventy’s existing static build. Keep clipboard/disclosure assets and the existing docs/skills outputs.
+- [ ] **Step 4: Verify.** Repeat build tests and `npm run check`; inspect generated `/start` files, docs Markdown, skills and assets. Task 5 verifies negotiation through the released platform edge, not a new website test server.
+- [ ] **Step 5: Commit.** Subject `feat: build static start HTML and Markdown twins`.
+
+## Task 4: Review and build the human introduction and homepage hero
+
+**Risk/review:** presentation only; none of security gate, root, termination, storage, billing or redirect. Whole-branch review only. Paul's copy review is required independently of technical review.
+
+**Files:**
+
+- Create W `test/start-pages.test.mjs`; use W `copy-review/strings.json`, `copy-review/preview/` and archived approved results according to the website workflow.
+- Modify W `src/_data/start-copy.json`, `src/index.html:27`, `src/_includes/start.njk`, `src/start/start-tabs.js:1`, `src/start/start.css`, `src/home.css`, `hack/build-start.mjs`, `PRODUCT.md:23`, `AGENTS.md:26`, `:195`, `README.md:10`, `:62`.
+
+**Interfaces:**
+
+- `start-copy.json` uses the exact IDs in the copy table. Build-time placeholders map each ID to every HTML occurrence. Homepage and `/start` reuse one paste-line value: “Follow the directions on [https://carlosframework.com/start](https://carlosframework.com/start)”; the copied value is plain text, not Markdown syntax.
+- Homepage replaces the numeric hero promise with Paul's reviewed modest claim and makes the paste line plus copy control its primary action. Keep architecture/reference links secondary. The authorised hero change supersedes its existing human-marker protection only after Paul approves its replacement; do not edit unrelated certified text.
+- `/start` has a short human explanation, copy line, temporary/no-backup notice, claim explanation, account-path link and an always-visible `#for-your-agent` section containing Task 2's complete instructions. Use visible AI attribution for agent-authored prose per W `AGENTS.md:40`; retain approved attribution rules for human-certified copy.
+- Reuse `data-copy-target`, `data-original`, `data-copied`. Hide the copy control until enhanced; native text selection remains available without scripts. Clipboard rejection selects the entire line and exposes a reviewed, polite live-region instruction. No network calls from the copy button.
+
+- [ ] **Step 1: Prepare Paul's copy review.** Draft the remaining homepage and documentation table entries into the website string index with context and previews before writing copy into source. Tasks 1 and 3 already obtained approval for the starter and start page; carry those approved bytes forward. Use `/home/paulca/.agents/skills/copy-review/SKILL.md`, run its preview check, submit to Paul and apply his result verbatim. Keep one review per logical surface. The instruction Markdown is exempt; its visible section heading is not. No delegated model approval substitutes for Paul.
+- [ ] **Step 2: Write failing page tests.** `start-pages.test.mjs` checks exact copied plain-text line, one primary action, no numeric multiplier in the hero, unique copy targets, visible complete agent section, approved copy IDs/bytes, no unreviewed aria/meta/error strings, and no client-side API fetch. Browser checks at 390px and 1280px cover light/dark, keyboard focus, reduced motion, script-disabled reading and denied clipboard permission.
+- [ ] **Step 3: Run to verify failure.** `node --test test/start-pages.test.mjs`; expect the old hero and install-first start page to fail these assertions.
+- [ ] **Step 4: Implement the approved surfaces.** Preserve existing layout/styles where practical; add the readable prompt and agent section without a redesign. Update the website's product/deploy documentation to describe the generated HTML/Markdown twins, Plan A dependency and unchanged static deployment accurately. These documentation changes use the copy-table review too.
+- [ ] **Step 5: Verify and commit.** Run page tests and `npm run check`; manually inspect the stated browser cases, including the clipboard fallback and all agent content below the fold. Subject `feat: invite visitors to build a demo with their agent`.
+
+## Task 5: Prove the complete journey with a real cloud agent on dev
+
+**Risk/review:** deployment touches production serving paths when later activated publicly; security/storage/claim assertions are acceptance evidence, not new implementations. Whole-branch review covers the final slice and existing static release workflow. No extra review round for test-only evidence.
+
+**Files:**
+
+- Create W `test/start-live.test.mjs`, `docs/start-demo-acceptance.md`, `hack/release-start.mjs`.
+- Modify W `package.json` to include the focused checks in the website gate. Keep live checks explicitly opt-in and out of normal CI.
+
+**Interfaces:**
+
+- `verifyStartOrigin(origin: URL) -> Promise<Verification>`, where `Verification={origin:string,version:string,markdownSHA256:string,starterSHA256:string,checks:Record<string,boolean>}`, in the live test checks real negotiated responses, TLS, content hash, release header and starter checksum. It never creates apps by being imported or through the default test command.
+- Acceptance record holds website/platform/Plan A/Plan 2/Plan 3 SHAs and the serving edge release, starter archive digest, console/site origins, returned public demo/permanent URLs, elapsed times, request counts, agent/harness and result for each scenario. Redact claim links, bearer tokens, email codes, personal email and cookies. Approved human report prose uses the copy table; raw machine evidence is kept separately.
+- Release script requires explicit console/account/app/channel/site-origin arguments and a clean merged commit. Build artifacts on the author/CI machine and deploy with the public CLI. No implicit flagship defaults, infrastructure provisioning, IAM, direct bucket writes or SSH. Retain the previous static release/version for rollback; ship only built `_site/` output.
+
+- [ ] **Step 1: Establish prerequisites and expected failure.** With the feature off, verify the account path remains usable and no anonymous instructions are advertised. Confirm Plan A is merged and released to the website’s serving edge, and Plans 2 and 3 are merged/live and claim availability is true before claiming a complete journey. Run `node --test test/start-live.test.mjs` against the dev site before the new static content is deployed and record the expected content failure. No test result may silently pass because a live case skipped.
+- [ ] **Step 2: Build and enable the dev release.** Discover and record the dev console/site destination through documented console/CLI configuration and use the existing designated dev scope. Build `_site/` with `CARLOS_START_DEMO=1` and the exact dev origins; deploy through the existing static-site CLI workflow. Keep the route kind, domain claims and placement unchanged. Verify `/start` follows its slash redirect and `/start/` returns HTML or Markdown as Plan A specifies; compare the Markdown bytes with `/start/index.md`. Admission remains the console drop-in already live from Plan 1.
+- [ ] **Step 3: Run the decisive cloud-agent witness.** In a fresh real cloud coding-agent session, initially without Go or the CLI, paste only the dev equivalent of the homepage line. Use a phone browser for the human side. Describe a small shop list, answer the experience/feel questions, and approve the small build. Permit at most the one explained console-host allowlist step if blocked. Have the agent fetch the served instructions, obtain/modify/pack the starter, POST source, poll the returned status URL and share the actual live URL. Create a row in the app, ask for one visible change, and verify the bearer update preserves that row and the expiry. Inject one compile error to exercise diagnostics/repair. Target less than five minutes from paste to first working URL; record measured time and network intervention rather than claiming success from a mock.
+- [ ] **Step 4: Complete claim and normal development.** Through that agent, use a designated test email and Plan 3's real challenge to keep the app. Verify the copied row at the returned permanent URL, the demo's moved page, and rejection of the old demo token. Record email-verification time separately from transfer time, with the design's under-one-minute claim target. Exercise account-choice, unavailable-claim and Keymail branches through fixtures plus designated real test identities where available; clearly label any live branch not witnessed. After the person opts in, obtain the public CLI release, sign in, place source in a private scratch repo without secrets, deploy a second visible change to the claimed app and verify its existing row. Do not weaken the no-install demo path to make this post-claim check pass.
+- [ ] **Step 5: Check required harnesses and the release gate.** Run at least the create/live/update journey in Claude Code local and cloud, Codex local and cloud, and Cursor; include phone operation of the real cloud witness. Unknown fetcher UAs must still work from visible HTML. Record actual harness versions and pass/fail, not guessed UA coverage. On the author/CI machine run `npm run check`, all new Node tests and the starter’s targeted checks once. These are future website gates, not a platform full-suite instruction for this authoring session. A missing harness witness remains outstanding acceptance work.
+- [ ] **Step 6: Review, land, release and clean up.** Obtain one whole-branch review after the dependency gates pass, carrying the history below. Follow the website’s reviewed-branch landing policy and green tip CI; publish the visible dev slice on landing. Public activation uses its existing static release workflow, approved production origins and the previous static version for rollback. Verify Plan A’s edge release and both representations, existing docs/skills and the canonical paste line on all three website hosts from W `AGENTS.md:199`. This plan authorises no new infrastructure or domain/route changes; any expansion needs separately scoped approval. Roll back the static version on failure. Remove only this run’s acceptance apps/data and scratch, stop local processes, and retain the planned dev activation. Commit subject `test: verify the start journey on dev`.
+
+## Human-facing strings: copy review required
+
+This is an inventory of meanings and fixed literals, not approved shipping copy. Each row becomes individual strings where several surfaces need different wording. Draft and submit via the website copy-review workflow before implementation; Paul reviews the human surfaces. The agent directives, protocol identifiers and synthetic fixture fields are LLM-facing and exempt. Any additional human-facing string discovered during implementation joins this same table/index before use.
+
+| IDs | Surface and content to review |
+|---|---|
+| `home.hero.promise`, `home.hero.intro`, `home.hero.action`, `home.meta.description`, `home.og.description` | Modest hero promise such as Paul's “better, faster, more secure apps”, short invitation and accessible action. No numeric multipliers. Meta/social descriptions match the journey. |
+| `start.prompt` | Exact shared paste line: Follow the directions on [https://carlosframework.com/start](https://carlosframework.com/start). Copied as plain text with the complete URL. |
+| `start.title`, `start.meta.description`, `start.intro`, `start.steps`, `start.lifetime`, `start.data`, `start.claim`, `start.account`, `start.agent.heading`, `start.authorship` | Page title/metadata, what happens, temporary/public app and no-backup explanation, keeping it by email, account/migration link, visible “for your agent” heading and AI attribution. |
+| `copy.label`, `copy.done`, `copy.fallback`, `copy.aria` | Button label, success status, selection/manual-copy fallback and accessible names. Shared across homepage and start page. |
+| `start.disabled.title`, `start.disabled.body`, `start.disabled.account` | Account-only path when the website journey is disabled; no promise of a working demo or claim. |
+| `starter.title`, `starter.empty`, `starter.name`, `starter.add`, `starter.invalid`, `starter.full`, `starter.error`, `starter.aria` | One-screen shop-list starter: title, empty state, field and submit labels, input/row-limit errors, generic database failure and accessible names. No live credentials, personal information or framework jargon. |
+| `start.config.error` | Build-time configuration diagnostics; do not expose secrets. |
+| `start.docs.product`, `start.docs.build`, `start.docs.deploy`, `start.docs.acceptance` | Website product/build/deploy documentation and human acceptance report, including static twins, the edge dependency, switch-on, rollback and observed limitations. Do not silently repair unrelated old README claims. |
+
+## Review budget and self-review
+
+Plan review history: **zero independent rounds** in this document-only session; no agents spawned. Task 1 needs independent task review; other website tasks are covered by one whole-branch review. Plan A carries its separate platform serving/cache/census review. Use platform `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md` for severity, invariant/fault-family names and three-way verdict. A Codex author's security/production review uses Opus or Fable from the other family. Do not review website work before Plan A’s merge/release gate or claim-dependent work against an unmerged Plan 3. These dependencies do not reset the count later.
+
+Stop at the first round with no P1; apply its P2 fixes without reopening, record P3s as follow-ups. The census and newly changed security/root/termination/production-storage checks still apply within that budget. A fourth round requires Paul's go; two successive rounds in one fault family trigger the repository stop-and-choose rule. The target repo's implementation gate applies; do not run platform suites for this website-only change.
+
+Self-review: design §3's conversation, style, scope, source submission, repair, sharing and later workflow map to Task 2, with real behaviour checked in Task 5. §4.7's shared URL and visible fallback map to Task 3; starter to Task 1; hero and copy to Task 4. All five Review Focus items have named checks. Core paths/flags/fields/limits are grounded in main; claim wire syntax consumes Plan 3's declared interface and is explicitly gated on its merge. Paul’s static-site ruling is implemented by generated twins, with negotiation owned by Plan A and verified on the serving edge. Tasks use one starter version, config shape and content source; no production function bodies are transcribed. No build-time or live test has been run by this authoring session.
+
+## Open questions
+
+None for Paul about what gets built. Plan A’s merge and serving-edge release, the merged Plan 3 wire contract, reviewed human copy and real harness witnesses are explicit execution gates, not unresolved design choices.
diff --git a/docs/superpowers/plans/2026-11-04-static-markdown-twins.md b/docs/superpowers/plans/2026-11-04-static-markdown-twins.md
new file mode 100644
index 000000000..e73dcba3e
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-04-static-markdown-twins.md
@@ -0,0 +1,95 @@
+# Static Markdown twins Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Let any static site ship Markdown beside an HTML page and serve it at the same URL when the request prefers Markdown.
+
+**Architecture:** Resolve the existing HTML file first, then select its regular-file Markdown sibling using Accept quality values. Keep the static serving path, file validators, compression and shared-response-cache bypass; no application server is added.
+
+**Tech Stack:** Existing Go edge, `net/http`, filesystem static trees and Go tests; no new dependency.
+
+**Spec:** Paul's fixed 2026-11-04 ruling in this task: general platform negotiation for `index.html`/`index.md` and `page.html`/`page.md`, with HTML otherwise. This supersedes the website-server approach and User-Agent selection in `docs/superpowers/specs/2026-11-02-agent-start-demo-design.md:297`. That design motivates the first consumer; the feature has no demo-specific paths or configuration.
+
+## Global Constraints
+
+- A twin must exist beside an already resolved HTML page. Never generate Markdown, manufacture a missing HTML route or select an unrelated file. Examples use `shop` and `example.com`.
+- Markdown wins only when its effective quality is positive and strictly greater than HTML's. Ties, absent Accept and an unacceptable pair fall back to HTML; no new 406 or User-Agent rules.
+- Always send `Vary: Accept` on both representations of a twin-bearing page, including HEAD, conditional and range responses. Preserve existing Vary values, including compression's `Accept-Encoding`. Pages without twins retain existing behaviour.
+- Negotiated Markdown is exactly `text/markdown; charset=utf-8`, including when tag computation is busy or fails. HTML keeps its existing MIME behaviour. Explicit `.md` requests keep working through existing file serving; changing their MIME policy is outside this slice.
+- No off-by-default switch is needed: without a shipped twin, representation selection does not change. Activation is the edge release; the first merge includes working negotiation and its docs. Plan 4 waits for this plan merged and released to the edges serving its website.
+- Human-facing runtime strings: none expected. Task 2's `docs/site` prose requires Paul's copy review before writing; any new diagnostic found necessary joins that review. This session writes plans only, with no product code, commits, pushes or other agents.
+
+## Review Focus
+
+1. Specificity, explicit `q=0`, malformed quality values and repeated Accept fields must not select the wrong body: Task 1's `TestStaticMarkdownPreference`.
+2. A missing/non-regular twin, rewrite or directory redirect must preserve the existing file and guard boundaries: Task 1's `TestStaticMarkdownResolution`.
+3. Identical HTML/Markdown bytes and tag-budget exhaustion must still yield correct types and validators: Task 1's `TestStaticMarkdownValidators`.
+4. Alternating Accept and Accept-Encoding, including HEAD/304/206, must not reuse the other representation: Task 2's `TestStaticMarkdownDelivery`.
+5. Adding/removing a twin on release or rollback must not leave a shared cached body or stale version: Task 2's `TestStaticMarkdownRelease`.
+
+---
+
+## Evidence and file map
+
+| Current code | Implementation boundary |
+|---|---|
+| `internal/edge/static.go:577`, `:599`, `:632`, `:668`, `:691`, `:702` | Resolve HTML and existing redirects first; select the sibling immediately before `serveFile`. Keep slash/index canonicalisation and `_redirects` precedence. |
+| `internal/edge/static.go:647`, `:746`, `:789` | Preserve target hard-tier guards and open-file checks; the selected Markdown path is also a target to check. Archive extraction rejects links at `:553`. |
+| `internal/edge/static.go:819`, `:874`, `:922`, `:969` | Tags cover bytes plus MIME type. Memoised/in-flight entries must distinguish a forced negotiated type from ordinary extension/sniff selection. |
+| `internal/edge/edge.go:2536`, `:2570`, `:2601`; `internal/edge/compress.go:128`, `:196`, `:241` | Compression already supports text types and owns a private header map. Static routes bypass shared cache lookup and storage, including tunnel-served static routes; preserve this. |
+| `internal/edge/headerwriter.go:67`; `internal/edge/static_headers_test.go:262`, `:292` | `_headers` applies at response commitment; test its coexistence with Vary and the existing static-cache bypass witnesses. |
+| `docs/site/cli.md:363`, `:406`, `:450` | Add the Markdown-twin contract beside the static deployment/redirect/header documentation. |
+
+## Task 1: Negotiate existing twins and preserve file validators
+
+**Risk/review:** serving boundary, cache and root-binary source. Independent cross-family review and census approval required for the final diff; carry the budget below.
+
+**Files:** Create `internal/edge/static_markdown.go`, `internal/edge/static_markdown_test.go`; modify `internal/edge/static.go:702`, `:746`, `:874`, `:922`, `:969` and affected calls in `internal/edge/static_cache_test.go`.
+
+**Interfaces:**
+
+- `prefersMarkdown(accept http.Header) bool`: combine all Accept field lines. Resolve quality independently for `text/markdown; charset=utf-8` and `text/html; charset=utf-8`, by most-specific matching media range, then matching media parameters; equally specific duplicates use the highest quality. No match means zero; absent Accept accepts both equally. Media types/parameter names are case-insensitive. Parse quoted parameters without splitting embedded commas; parameters before `q` must match the representation. Quality defaults to 1 and accepts only HTTP qvalue grammar (0–1, at most three decimal places); ignore malformed ranges, never interpret invalid/NaN/out-of-range quality as 1.
+- `selectStaticRepresentation(fp string, fi os.FileInfo, accept http.Header) staticRepresentation`, with `staticRepresentation{path string, info os.FileInfo, contentType string, varies bool}`. Only a resolved regular `.html` file can have a twin; replace that suffix with `.md` and require a regular non-symlink sibling. `varies` is true whenever that twin exists, even for an HTML request. A selected twin sets `contentType` to the exact Markdown type; other selections leave it empty.
+- Add `contentType string` after `fi` to `(*staticSite).serveFile`, `(*tagCache).tag` and `(*tagCache).hash`; empty preserves existing inference. Use `staticTagKey{path, contentType string}` for both tag memo and in-flight maps. Hash the actual forced type with the file bytes and set it before `ServeContent` even on the no-tag fallback. Keep existing tag limits, waits, cancellation and file-identity checks; update old callers with `""`.
+- In `serveTree`, select after existing resolution/redirects, enforce the existing hard-tier guard on the selected target, add Accept to Vary when `varies`, and pass the selected path/info/type to `serveFile`. Missing twins fall back to HTML; errors opening a selected file retain existing refusal handling, never another page's bytes. Do not change URL, query, header-rule matching, rewrite status or default cache policy.
+
+- [ ] **Step 1: Write failing tests.** `TestStaticMarkdownPreference` uses this assertion table; repeat cases through separate header lines, case variants and reordered ranges:
+
+ ```text
+ Accept prefersMarkdown
+ (absent), */*, text/*, text/markdown,text/html false
+ text/markdown true
+ text/markdown;q=0.8,text/html;q=0.2 true
+ text/markdown;q=0.2,text/html;q=0.8 false
+ text/markdown;q=0,text/*;q=1 false
+ text/html;q=0,text/*;q=0.5 true
+ text/markdown;q=0,text/html;q=0 false
+ text/markdown;q=NaN,text/html false
+ text/markdown;q=1.001,text/html false
+ text/markdown;charset=iso-8859-1,text/html false
+ text/markdown;q=0.2,text/markdown;q=0.8,text/html;q=0.5 true
+ ```
+
+ `TestStaticMarkdownResolution` asserts exact HTML/Markdown bodies for `/shop/` and `/page.html`; absent or directory/symlink twins leave HTML, a lone `index.md` creates no index page, `/shop` and `/shop/index.html` keep their redirects/query, and rewritten HTML can negotiate without bypassing hard-tier refusals. Explicit `.md` still serves its file; an HTML-only tree stays unchanged. `TestStaticMarkdownValidators` asserts identical bytes with different types yield different ETags, a cross-variant validator returns 200, a matching one returns 304, and tag-budget failure still sends Markdown's exact type with no false tag.
+- [ ] **Step 2: Observe failure.** Run `go test ./internal/edge -run '^TestStaticMarkdown' -count=1`; expect missing selectors/negotiated responses, not a skipped test set.
+- [ ] **Step 3: Implement the interfaces.** Add the small selector, wire it into existing serving and type-aware tagging, and update affected callers. Preserve the existing file boundary and compression wrapper order.
+- [ ] **Step 4: Verify.** Repeat the focused tests and `go test ./internal/edge -run 'Test(Static|Tag|ServesShippedTree|ChannelAdvance)' -count=1`; expect PASS.
+- [ ] **Step 5: Commit during implementation.** Subject `feat: negotiate Markdown twins for static HTML pages`. Keep both tasks on one branch until Task 2's gate; this authoring session makes no commit.
+
+## Task 2: Prove edge delivery, document and release
+
+**Files:** Extend `internal/edge/static_markdown_test.go`; modify `docs/site/cli.md:406`. Generate the census overlay/card under the implementation branch's name using the repository census tooling.
+
+**Interfaces:** Consume Task 1's selector through real `Edge.ServeHTTP`, using the existing shipped-tree/cache-enabled fixtures and gzip switch. Publish a platform release with the merged SHA and the serving-edge version recorded for consumers.
+
+- [ ] **Step 1: Add regression tests.** `TestStaticMarkdownDelivery` alternates both representations and identity/gzip through a static route with `_headers` max-age and the shared cache enabled. Assert decoded bytes/type/ETag belong to the selected file, Vary always includes Accept (plus Accept-Encoding on compressed delivery), HEAD has no body, matching conditional requests return 304 with Vary, and ranges return 206 of the chosen bytes. Seed the shared cache with the wrong variant and assert it is ignored; neither response is stored there. `TestStaticMarkdownRelease` advances and rolls back a shipped tree while adding/removing/changing its twin; assert current bytes, type, ETag and `X-Carlos-Version`, including after a prior cacheable HTML response.
+- [ ] **Step 2: Verify.** Run `go test ./internal/edge -run 'TestStatic(Markdown|Headers|WithMaxAge|Ignores)' -count=1`; expect PASS. These integration checks may pass immediately if Task 1 is complete; record the result without inventing a red phase.
+- [ ] **Step 3: Update static-site docs, copy review required.** In `docs/site/cli.md`, document `shop/index.html` plus `shop/index.md`, `page.html` plus `page.md`, strict Accept preference with q-values, HTML ties/fallback, Vary, existing slash redirects and explicit `.md` access. Use `example.com`; describe no application-server or switch requirement. Submit this prose to Paul through copy review and apply approved text verbatim before writing it into the docs page.
+- [ ] **Step 4: Run the implementation gate and review.** Run `make census-card`, write per-unit claims and `make census-propose NAME=<branch> CLAIMS=<file>`. Have an independent other-family reviewer decide every changed unit/envelope and the serving/cache diff; record the verdict on #280 with reviewer and tip. Then run `go build ./...`, `go vet ./...`, `go test ./... -count=1` and `gofmt -l .` once; require clean results and repository cross-build/CI gates. Do not run these product suites during plan authoring.
+- [ ] **Step 5: Land and release during implementation.** Commit subject `test: verify and document static Markdown variants`; describe/push the reviewed branch to amadan, land as one squash only with green tip CI, and read main's run. Use the existing authorised platform release workflow; any new production infrastructure scope needs approval. Record the release and verify an existing authorised static site with a twin on each serving edge before a consumer calls this dependency satisfied. No website conversion or demo-specific feature ships here.
+
+## Review budget and self-review
+
+Independent review rounds: **zero in this document-only session**. Serving/cache/census checks share the repository review budget; use `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, carry the history with the change, stop at the first round without P1, apply P2s without restarting, and record P3 follow-ups. A fourth round needs Paul's go; two consecutive rounds in one fault family trigger the repository stop-and-choose rule. Review newly changed security/root/storage behaviour and the census within that same budget.
+
+Self-review: Task 1 covers selection, missing twins, headers and validators; Task 2 covers compression, shared-cache isolation, release changes and reviewed docs. All five Review Focus items have named tests. There are no product edits or executed product tests in this authoring session.
diff --git a/docs/superpowers/plans/CONTROLLER-BRIEF-static-markdown-twins.md b/docs/superpowers/plans/CONTROLLER-BRIEF-static-markdown-twins.md
new file mode 100644
index 000000000..54115fc8a
--- /dev/null
+++ b/docs/superpowers/plans/CONTROLLER-BRIEF-static-markdown-twins.md
@@ -0,0 +1,33 @@
+# Controller brief: build static-markdown-twins
+
+You are the build controller for `docs/superpowers/plans/2026-11-04-static-markdown-twins.md` in carlos/platform. Paul approved the design (`docs/superpowers/specs/2026-11-02-agent-start-demo-design.md`), this plan and its rulings on 2026-11-04, and chose subagent-driven execution. Worktree: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-markdown-twins`, branch `static-markdown-twins` (cut from `agent-start-demo-plans` at 3e466eb3, which is main plus the plan documents). Read AGENTS.md (stopping rules, census, Build & test) and, for demo work, `docs/superpowers/notes/agent-start-demo-1-rulings.md`.
+
+Push the branch (`git push origin static-markdown-twins`, no `-u`) and describe it (`amadan branch describe carlos/platform static-markdown-twins -summary ...`) before Task 1. Commit as `git -c user.name=claude -c user.email='claude~paul@keymail.dev' commit` (Codex: `--author "codex <codex~paul@keymail.dev>"`). Subjects under 80 characters. "packed-refs.lock" / "credential storage lock" messages on push are the sandbox; check `git ls-remote`.
+
+## How to run it
+
+Use `superpowers:subagent-driven-development`, adapted:
+1. **Implementers are Astra via Codex.** One run per task: extract the brief with the skill's `scripts/task-brief` plus Global Constraints and that task's Review Focus lines; launch a script with the sandbox off via `setsid nohup`: `codex exec -m gpt-6-astra -c model_reasoning_effort="high" --dangerously-bypass-approvals-and-sandbox -o <final.md> - < <prompt> > <log> 2>&1; touch <done>`. Within 20 s check the log says `model: gpt-6-astra` and `reasoning effort: high` and grows. Wait on the `.done` marker with a background until-loop, never on pgrep. Scratch under `/home/paulca/.cache/tmp/claude-1001/static-markdown-twins/`, deleted at the end. The Codex prompt says: commit with the codex author; spawn no agents; no copy-review skill or review server; no `.claude/HANDOFF.md`; leave Go caches at defaults; targeted tests only; bind servers to 127.0.0.1 and stop them; never touch AWS, DNS or real boxes.
+2. **Reviews:** an **Opus** subagent (model `opus`) reviews each task the plan marks for independent review, briefed from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`; one whole-branch Opus review at the end, one fix wave, one scoped re-review. AGENTS.md stopping rules apply: stop at the first round with no P1, three rounds max, two rounds in one fault family means stop and offer Paul the choice.
+3. **Census:** follow the plan and `make census-card` / `census-propose`; Opus is the cross-model reviewer for Codex-authored census changes; record verdicts on #280. Never ask Paul for a census ruling.
+4. **Copy:** human-facing strings in the plan's copy table go through a Luna copy pass (pattern: `docs/superpowers/specs/LUNA-COPY-*`), applied verbatim, unless the plan says Paul reviews them himself; then collect them and post on the branch for Paul.
+5. CI on amadan is the full gate; targeted tests locally, niced and serial.
+
+## Landing
+
+When the whole-branch review is clean and CI is green on the exact tip, you may merge: re-merge main if it moved and wait for CI again, then run exactly `amadan branch merge carlos/platform static-markdown-twins -squash -expect <full 40-char sha>` with a subject under 80 characters and a short body. **`-squash` is mandatory** (an earlier controller forgot it). Keep the worktree until the merge succeeds. Never cut a release.
+
+## Scope note
+
+This is a general platform feature, not demo work. Merging is allowed; no dev roll is needed (it ships with the next release). Its docs page copy goes to a Luna pass, then post the final strings on the branch for Paul.
+
+## Never
+
+- Release, roll to flagship, or touch flagship boxes, its console or trycarlos.com.
+- Touch AWS, DNS, Openprovider or a real box except as this brief allows.
+- `git worktree prune`, `git clean -fdx` outside scratch, `sudo`, `GOCACHE` changes, bare `amadan branch merge`, deleting lock files you did not create, chaining setup commands with `;`.
+- Name a tenant in code, tests or docs (use shop, example.com).
+
+## Keep the branch page true
+
+One amadan task per plan task (plus copy pass, whole-branch review, landing); Started at dispatch, Done at review clean. Push after each task. Questions only Paul can answer go in a discussion on the branch; keep going on everything else. When you finish or stop, write the branch handoff and end with: what was built, test and review results, every ruling (with what it costs if wrong), the merge sha or tip. Clean up scratch and processes.
diff --git a/docs/superpowers/reviews/OPUS-REVIEW-BRIEF-static-markdown-twins.md b/docs/superpowers/reviews/OPUS-REVIEW-BRIEF-static-markdown-twins.md
new file mode 100644
index 000000000..84b4ac65f
--- /dev/null
+++ b/docs/superpowers/reviews/OPUS-REVIEW-BRIEF-static-markdown-twins.md
@@ -0,0 +1,39 @@
+# Review brief: branch static-markdown-twins (whole branch + census), round 1 of 3
+
+Repo carlos/platform, branch `static-markdown-twins`, commit 70cab1d6 (code tip; 80912cf5 adds only a copy brief).
+Under review: the diff `a921b59b..70cab1d6` (three Codex-authored commits: feature, tests + draft docs, census overlay).
+Authorities: the plan `docs/superpowers/plans/2026-11-04-static-markdown-twins.md` (its Global Constraints and Review Focus 1-5 are binding; Paul approved it 2026-11-04) and AGENTS.md "The census: the reviewer decides".
+
+You are an independent reviewer from the other model family than the author. Read the plan, then the diff, and check every claim against the code.
+
+## Fixed: do not re-argue
+
+- The plan's design: negotiation only beside an already resolved HTML file; strict positive preference; HTML on ties; no 406 or User-Agent rules; no switch; explicit `.md` MIME policy unchanged.
+- Controller rulings: no release in this branch; docs prose in `docs/site/cli.md` is a draft that a separate copy pass rewrites (judge its facts, not its wording); local runs were targeted, CI runs the full gate.
+- Task 1 was reviewed READY in round 1 (`.superpowers/sdd/2026-11-04-static-markdown-twins/task-1-review.md`); its three P3s are listed in `.superpowers/sdd/2026-11-04-static-markdown-twins/progress.md`. Say whether any of them must be fixed before merge.
+
+## What to check
+
+1. Whole branch: Review Focus 4 and 5 (`TestStaticMarkdownDelivery`, `TestStaticMarkdownRelease`) through real `Edge.ServeHTTP`: alternating Accept and Accept-Encoding, HEAD/304/206, shared-cache isolation (wrong variant seeded, nothing stored), release advance and rollback adding/removing a twin. Do the tests prove what they claim and fail if the feature broke?
+2. Interaction across tasks: compression wrapper order, `_headers` Vary coexistence, tunnel-served static routes still bypass the shared cache.
+3. Docs facts in `docs/site/cli.md` match the code.
+4. Census: give a verdict (approve / reject, citing the lines you read) for each unit and the envelope in `docs/superpowers/notes/census-proposal-static-markdown-twins.md`: `staticSite.serveFile` (body), `staticSite.serveTree` (body), new `selectStaticRepresentation` (+file:Lstat, legacy accepted-legacy), envelope `internal/edge`. Apply AGENTS.md's rejection rules: reject if the change lets root (or the edge) 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, or if the diff cannot settle it. Note the edge runs as user carlos and serves tenant-shipped trees: the `.md` sibling is tenant-named content inside an extracted tree; judge whether the Lstat + regular-file check + hard-tier guard keeps it inside the existing boundary.
+5. The CLAIMS file sits at `testdata/static-markdown-twins-claims.tsv` (repo root); other branches keep theirs under `docs/superpowers/notes/`. Say if that matters.
+
+## 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.)
+- **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 location, the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant or trust boundary it breaks (its fault family). Then the census verdict per unit and envelope. End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn subagents. Do not run the full test suites.
diff --git a/docs/superpowers/specs/LUNA-COPY-BRIEF-STATIC-MARKDOWN-TWINS.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-STATIC-MARKDOWN-TWINS.md
new file mode 100644
index 000000000..c92d59416
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-STATIC-MARKDOWN-TWINS.md
@@ -0,0 +1,27 @@
+# Copy pass brief: Markdown twins for static sites (branch static-markdown-twins)
+
+You are reviewing a new docs section for a hosting platform's static-site documentation (`docs/site/cli.md`, the page that already documents `_redirects` and `_headers`). Paul, the owner, delegated this review to you. Apply his house rules and return improved strings.
+
+The feature: a static site can ship a Markdown file beside an HTML page (`shop/index.md` beside `shop/index.html`, `page.md` beside `page.html`). The edge serves the Markdown at the same URL when the request's `Accept` header prefers it, and HTML otherwise. The audience is a developer deploying a static site, often so that AI agents fetching the page get Markdown. The deck is `.superpowers/sdd/2026-11-04-static-markdown-twins/task-2-copy-deck.md` (the draft as written into the page).
+
+## House rules
+
+- Plain words, short sentences, no marketing tone, no exclamation marks. Ordinary sentence case, full stops.
+- No em dashes or en dashes used as dashes. Where you would use one, end the sentence and start a new one.
+- Match the neighbouring sections' voice: "Put a file named `_headers` at the top of the site directory...". Second person, direct.
+- The heading should match its siblings (`#### Redirects for a static site`, `#### Response headers for a static site`). Drop the "(draft)" marker. Return `remove` for the DRAFT HTML comment row.
+- Leave header names, media types, paths, `q`, code and the curl command exactly as they are. Neutral examples only (`shop`, `example.com`).
+- Do not name the product.
+
+## Facts that must stay true
+
+- Markdown is served only when a Markdown file sits beside an HTML file the site already serves at that URL. A Markdown file alone creates no page and no directory index.
+- Markdown wins only when its quality is positive and strictly higher than HTML's. Ties, no `Accept` header, or neither acceptable: HTML. The more specific media range decides each type's quality; `q` defaults to 1.
+- Served Markdown has content type `text/markdown; charset=utf-8`.
+- Both versions of a page that has a twin carry `Vary: Accept` (also HEAD, 304 and range responses); other `Vary` values are kept.
+- Slash redirects and `_redirects` rules apply first; `/shop` still redirects to `/shop/`. `.md` files can still be fetched directly at their own path.
+- No server and no setting to turn on.
+
+## Output
+
+Do not edit any file. Answer with one markdown table, `| line | new | why |`, one row per deck block in deck order, every row included, `unchanged` in why when you keep a block, `remove` in new for a block to delete. Keep the block's Markdown (backticks, code fences) intact; write line breaks inside a cell as `<br>`. Then a short **Flags** list for anything you could not fix within these rules. Nothing else.
diff --git a/internal/edge/static.go b/internal/edge/static.go
index e0057e5d0..13ff63fbf 100644
--- a/internal/edge/static.go
+++ b/internal/edge/static.go
@@ -699,7 +699,23 @@ func (s *staticSite) serveTree(tree servedTree, w http.ResponseWriter, r *http.R
w.WriteHeader(http.StatusMovedPermanently)
return
}
- s.serveFile(fp, p, fi, status, extra, w, r)
+ rep := selectStaticRepresentation(fp, fi, r.Header)
+ if guard {
+ // Check the file we will send, including an index reached through
+ // a directory and a Markdown sibling selected by negotiation.
+ target, err := filepath.Rel(tree.dir, rep.path)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ if hit, ok := edgeguard.CheckTier("/"+filepath.ToSlash(target), "", reqrec.TierHard); ok && guardDecide(w, r, hit) {
+ return
+ }
+ }
+ if rep.varies {
+ w.Header().Add("Vary", "Accept")
+ }
+ s.serveFile(rep.path, p, rep.info, rep.contentType, status, extra, w, r)
return
}
}
@@ -743,7 +759,7 @@ func staticBurstDecide(w http.ResponseWriter, r *http.Request) bool {
// 200 path takes it, through a headerWriter that applies it if ServeContent
// answers 200, 206 or 304 and leaves its 412s and 416s as they are: a 404 page
// marked immutable would pin a typo in every browser for a year.
-func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, status int, extra http.Header, w http.ResponseWriter, r *http.Request) {
+func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, contentType string, status int, extra http.Header, w http.ResponseWriter, r *http.Request) {
f, err := os.Open(fp)
if err != nil {
// ServeFile's mapping, kept: a file that vanished since the Stat is
@@ -762,7 +778,10 @@ func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, status int, extra h
}
defer f.Close()
if status != http.StatusOK {
- ctype := mime.TypeByExtension(filepath.Ext(fp))
+ ctype := contentType
+ if ctype == "" {
+ ctype = mime.TypeByExtension(filepath.Ext(fp))
+ }
if ctype == "" {
var head [512]byte
n, _ := io.ReadFull(f, head[:])
@@ -786,11 +805,14 @@ func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, status int, extra h
defer hw.finish()
w = hw
}
+ if contentType != "" {
+ w.Header().Set("Content-Type", contentType)
+ }
// Stat the OPEN file: its identity is what a remembered tag is checked
// against, and it is the file whose bytes are about to be sent.
if ofi, err := f.Stat(); err == nil && !ofi.IsDir() {
fi = ofi
- if tag, ctype, err := staticTags.tag(r.Context(), fp, f, fi); err == nil {
+ if tag, ctype, err := staticTags.tag(r.Context(), fp, f, fi, contentType); err == nil {
// The type the tag was computed over is the type sent: set here,
// ServeContent leaves it alone.
w.Header().Set("ETag", tag)
@@ -870,8 +892,8 @@ func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, status int, extra h
// demand, which costs hashing and never correctness.
type tagCache struct {
mu sync.Mutex
- entries map[string]tagEntry
- flights map[string]chan struct{} // closed when the hash for that path is done
+ entries map[staticTagKey]tagEntry
+ flights map[staticTagKey]chan struct{} // closed when this representation's hash is done
sem chan struct{}
wait time.Duration
@@ -883,6 +905,10 @@ type tagCache struct {
hold func()
}
+type staticTagKey struct {
+ path, contentType string
+}
+
type tagEntry struct {
fi os.FileInfo
tag, ctype string
@@ -901,8 +927,8 @@ var errTagBusy = errors.New("static tag: hashers busy")
func newTagCache() *tagCache {
return &tagCache{
- entries: map[string]tagEntry{},
- flights: map[string]chan struct{}{},
+ entries: map[staticTagKey]tagEntry{},
+ flights: map[staticTagKey]chan struct{}{},
sem: make(chan struct{}, tagHashers),
wait: tagWait,
}
@@ -919,11 +945,12 @@ func (e tagEntry) current(fi os.FileInfo) bool {
// hashing it if no current entry exists. f is left positioned at its start.
// ctx and the wait budget bound the WAITING — on another request's hash, or
// on a free hasher — never a hash in progress.
-func (c *tagCache) tag(ctx context.Context, fp string, f io.ReadSeeker, fi os.FileInfo) (tag, ctype string, err error) {
+func (c *tagCache) tag(ctx context.Context, fp string, f io.ReadSeeker, fi os.FileInfo, contentType string) (tag, ctype string, err error) {
+ key := staticTagKey{path: fp, contentType: contentType}
var budget <-chan time.Time
for {
c.mu.Lock()
- if e, ok := c.entries[fp]; ok && e.current(fi) {
+ if e, ok := c.entries[key]; ok && e.current(fi) {
c.mu.Unlock()
return e.tag, e.ctype, nil
}
@@ -932,7 +959,7 @@ func (c *tagCache) tag(ctx context.Context, fp string, f io.ReadSeeker, fi os.Fi
defer t.Stop()
budget = t.C
}
- if flight, ok := c.flights[fp]; ok {
+ if flight, ok := c.flights[key]; ok {
c.mu.Unlock()
c.waiting.Add(1)
select {
@@ -948,25 +975,25 @@ func (c *tagCache) tag(ctx context.Context, fp string, f io.ReadSeeker, fi os.Fi
}
}
done := make(chan struct{})
- c.flights[fp] = done
+ c.flights[key] = done
c.mu.Unlock()
- tag, ctype, err = c.hash(ctx, budget, f, fi)
+ tag, ctype, err = c.hash(ctx, budget, f, fi, contentType)
c.mu.Lock()
if err == nil {
if len(c.entries) >= tagCacheMax {
- c.entries = map[string]tagEntry{}
+ c.entries = map[staticTagKey]tagEntry{}
}
- c.entries[fp] = tagEntry{fi: fi, tag: tag, ctype: ctype}
+ c.entries[key] = tagEntry{fi: fi, tag: tag, ctype: ctype}
}
- delete(c.flights, fp)
+ delete(c.flights, key)
c.mu.Unlock()
close(done)
return tag, ctype, err
}
}
-func (c *tagCache) hash(ctx context.Context, budget <-chan time.Time, f io.ReadSeeker, fi os.FileInfo) (tag, ctype string, err error) {
+func (c *tagCache) hash(ctx context.Context, budget <-chan time.Time, f io.ReadSeeker, fi os.FileInfo, contentType string) (tag, ctype string, err error) {
if fi.Size() > tagInline {
select {
case c.sem <- struct{}{}:
@@ -997,7 +1024,10 @@ func (c *tagCache) hash(ctx context.Context, budget <-chan time.Time, f io.ReadS
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
return "", "", err
}
- ctype = mime.TypeByExtension(filepath.Ext(fi.Name()))
+ ctype = contentType
+ if ctype == "" {
+ ctype = mime.TypeByExtension(filepath.Ext(fi.Name()))
+ }
if ctype == "" {
ctype = http.DetectContentType(head[:n])
}
diff --git a/internal/edge/static_cache_test.go b/internal/edge/static_cache_test.go
index ccdbd09d9..1e89dcaa9 100644
--- a/internal/edge/static_cache_test.go
+++ b/internal/edge/static_cache_test.go
@@ -392,7 +392,7 @@ func TestTagCacheHashesAColdFileOnceForOverlappingRequests(t *testing.T) {
errs[i] = err
return
}
- tags[i], _, errs[i] = c.tag(context.Background(), fp, f, fi)
+ tags[i], _, errs[i] = c.tag(context.Background(), fp, f, fi, "")
}
wg.Add(1)
go call(0)
@@ -434,7 +434,7 @@ func TestTagCacheDoesNotQueueBehindLargeHashes(t *testing.T) {
}
fp, f, fi := openTagged(t, dir, "big.bin", strings.Repeat("x", tagInline+1))
- if _, _, err := c.tag(context.Background(), fp, f, fi); !errors.Is(err, errTagBusy) {
+ if _, _, err := c.tag(context.Background(), fp, f, fi, ""); !errors.Is(err, errTagBusy) {
t.Fatalf("a large file with no free hasher = %v, want errTagBusy", err)
}
if n := len(c.flights); n != 0 {
@@ -442,7 +442,7 @@ func TestTagCacheDoesNotQueueBehindLargeHashes(t *testing.T) {
}
fp, f, fi = openTagged(t, dir, "page.html", "<p>a small page</p>")
- tag, ctype, err := c.tag(context.Background(), fp, f, fi)
+ tag, ctype, err := c.tag(context.Background(), fp, f, fi, "")
if err != nil || tag == "" || !strings.HasPrefix(ctype, "text/html") {
t.Fatalf("a small file while every hasher is busy = %q %q %v; want it tagged at once", tag, ctype, err)
}
@@ -453,7 +453,7 @@ func TestTagCacheDoesNotQueueBehindLargeHashes(t *testing.T) {
<-c.sem
c.wait = time.Minute
fp, f, fi = openTagged(t, dir, "big.bin", strings.Repeat("x", tagInline+1))
- if tag, _, err := c.tag(context.Background(), fp, f, fi); err != nil || tag == "" {
+ if tag, _, err := c.tag(context.Background(), fp, f, fi, ""); err != nil || tag == "" {
t.Fatalf("a large file with a free hasher = %q, %v", tag, err)
}
}
@@ -469,7 +469,7 @@ func TestTagCacheTagCoversTheResolvedContentType(t *testing.T) {
// last run's mapping in place of an unknown one).
ext := fmt.Sprintf(".zzcarlos%d", time.Now().UnixNano())
fp, f, fi := openTagged(t, t.TempDir(), "notes"+ext, body)
- sniffedTag, sniffedType, err := c.tag(context.Background(), fp, f, fi)
+ sniffedTag, sniffedType, err := c.tag(context.Background(), fp, f, fi, "")
if err != nil || !strings.HasPrefix(sniffedType, "text/plain") {
t.Fatalf("an unknown extension = %q %v, want it sniffed as text/plain", sniffedType, err)
}
@@ -479,7 +479,7 @@ func TestTagCacheTagCoversTheResolvedContentType(t *testing.T) {
t.Fatal(err)
}
fp, f, fi = openTagged(t, t.TempDir(), "notes"+ext, body)
- knownTag, knownType, err := c.tag(context.Background(), fp, f, fi)
+ knownTag, knownType, err := c.tag(context.Background(), fp, f, fi, "")
if err != nil || !strings.HasPrefix(knownType, "text/markdown") {
t.Fatalf("a mapped extension = %q %v, want text/markdown", knownType, err)
}
@@ -585,7 +585,7 @@ func TestTagCacheRewindsTheFileWhenHashingFails(t *testing.T) {
_, _, fi := openTagged(t, t.TempDir(), "picture", "placeholder")
for _, good := range []int{100, 2000} { // fails inside the sniffed prefix, and after it
f := &failingFile{data: make([]byte, 4096), good: good}
- if _, _, err := c.tag(context.Background(), fmt.Sprintf("/nowhere/picture-%d", good), f, fi); err == nil {
+ if _, _, err := c.tag(context.Background(), fmt.Sprintf("/nowhere/picture-%d", good), f, fi, ""); err == nil {
t.Fatalf("hashing a file that fails after %d bytes reported no error", good)
}
if f.pos != 0 {
diff --git a/internal/edge/static_markdown.go b/internal/edge/static_markdown.go
new file mode 100644
index 000000000..fd7414229
--- /dev/null
+++ b/internal/edge/static_markdown.go
@@ -0,0 +1,156 @@
+package edge
+
+import (
+ "mime"
+ "net/http"
+ "os"
+ "strings"
+)
+
+const staticMarkdownType = "text/markdown; charset=utf-8"
+
+type staticRepresentation struct {
+ path string
+ info os.FileInfo
+ contentType string
+ varies bool
+}
+
+func selectStaticRepresentation(fp string, fi os.FileInfo, accept http.Header) staticRepresentation {
+ rep := staticRepresentation{path: fp, info: fi}
+ if !fi.Mode().IsRegular() || !strings.HasSuffix(fp, ".html") {
+ return rep
+ }
+ twin := strings.TrimSuffix(fp, ".html") + ".md"
+ ti, err := os.Lstat(twin)
+ if err != nil || !ti.Mode().IsRegular() {
+ return rep
+ }
+ rep.varies = true
+ if prefersMarkdown(accept) {
+ rep.path, rep.info, rep.contentType = twin, ti, staticMarkdownType
+ }
+ return rep
+}
+
+// prefersMarkdown compares the quality of the two UTF-8 representations.
+// Specificity wins before quality: an explicit refusal cannot be undone by
+// a wildcard with a higher qvalue.
+func prefersMarkdown(accept http.Header) bool {
+ type quality struct{ specificity, params, q int }
+ best := [2]quality{{specificity: -1}, {specificity: -1}}
+ for _, field := range accept.Values("Accept") {
+ for _, raw := range splitAccept(field, ',') {
+ parts := splitAccept(raw, ';')
+ q, boundary, valid := 1000, len(parts), true
+ for i, param := range parts[1:] {
+ name, value, _ := strings.Cut(param, "=")
+ name = strings.ToLower(strings.TrimSpace(name))
+ if name == "q" {
+ if boundary != len(parts) {
+ valid = false
+ break
+ }
+ boundary = i + 1
+ q, valid = staticAcceptQuality(strings.TrimSpace(value))
+ if !valid {
+ break
+ }
+ } else if i+1 > boundary {
+ // Extensions have their own parameter namespace. A bare
+ // token is also a valid Accept extension.
+ if !isToken(strings.TrimSpace(param)) {
+ if _, _, err := mime.ParseMediaType("text/plain;" + param); err != nil {
+ valid = false
+ break
+ }
+ }
+ } else if name != "charset" {
+ valid = false
+ break
+ }
+ }
+ if !valid {
+ continue
+ }
+ media, params, err := mime.ParseMediaType(strings.Join(parts[:boundary], ";"))
+ if err != nil {
+ continue
+ }
+ for name, value := range params {
+ if name != "charset" || !strings.EqualFold(value, "utf-8") {
+ valid = false
+ break
+ }
+ }
+ if !valid {
+ continue
+ }
+ for i, target := range []string{"text/markdown", "text/html"} {
+ specificity := -1
+ switch media {
+ case "*/*":
+ specificity = 0
+ case "text/*":
+ specificity = 1
+ case target:
+ specificity = 2
+ }
+ if specificity < 0 {
+ continue
+ }
+ b := &best[i]
+ count := len(params)
+ if specificity > b.specificity || (specificity == b.specificity &&
+ (count > b.params || (count == b.params && q > b.q))) {
+ *b = quality{specificity, count, q}
+ }
+ }
+ }
+ }
+ return best[0].q > 0 && best[0].q > best[1].q
+}
+
+// splitAccept leaves quoted delimiters and escaped quotes inside their value.
+// ParseMediaType rejects malformed ranges after the split.
+func splitAccept(value string, delimiter byte) []string {
+ var parts []string
+ start, quoted, escaped := 0, false, false
+ for i := 0; i < len(value); i++ {
+ switch {
+ case escaped:
+ escaped = false
+ case quoted && value[i] == '\\':
+ escaped = true
+ case value[i] == '"':
+ quoted = !quoted
+ case !quoted && value[i] == delimiter:
+ parts = append(parts, value[start:i])
+ start = i + 1
+ }
+ }
+ return append(parts, value[start:])
+}
+
+// staticAcceptQuality accepts only HTTP's qvalue grammar, in thousandths.
+func staticAcceptQuality(value string) (int, bool) {
+ if len(value) == 0 || (value[0] != '0' && value[0] != '1') {
+ return 0, false
+ }
+ q := int(value[0]-'0') * 1000
+ if len(value) == 1 {
+ return q, true
+ }
+ if value[1] != '.' || len(value) > 5 {
+ return 0, false
+ }
+ place := 100
+ for i := 2; i < len(value); i++ {
+ if value[i] < '0' || value[i] > '9' || (value[0] == '1' && value[i] != '0') {
+ return 0, false
+ }
+ q += int(value[i]-'0') * place
+ place /= 10
+ }
+ return q, true
+}
diff --git a/internal/edge/static_markdown_test.go b/internal/edge/static_markdown_test.go
new file mode 100644
index 000000000..2009c8a3c
--- /dev/null
+++ b/internal/edge/static_markdown_test.go
@@ -0,0 +1,593 @@
+package edge
+
+import (
+ "compress/gzip"
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/reqrec"
+)
+
+func TestStaticMarkdownPreference(t *testing.T) {
+ cases := []struct {
+ accept string
+ want bool
+ }{
+ {"", false},
+ {"*/*", false},
+ {"text/*", false},
+ {"text/markdown,text/html", false},
+ {"text/markdown", true},
+ {"text/markdown;q=0.8,text/html;q=0.2", true},
+ {"text/markdown;q=0.2,text/html;q=0.8", false},
+ {"text/markdown;q=0,text/*;q=1", false},
+ {"text/html;q=0,text/*;q=0.5", true},
+ {"text/markdown;q=0,text/html;q=0", false},
+ {"text/markdown;q=NaN,text/html", false},
+ {"text/markdown;q=1.001,text/html", false},
+ {"text/markdown;charset=iso-8859-1,text/html", false},
+ {"text/markdown;q=0.2,text/markdown;q=0.8,text/html;q=0.5", true},
+ {`text/markdown;charset="UTF-8";q=0.8,text/html;q=0.5`, true},
+ {"text/markdown;charset=utf-8;q=0,text/markdown;q=1,text/html;q=0.5", false},
+ {"text/*;charset=utf-8;q=1,text/markdown;q=0,text/html;q=0.5", false},
+ {"text/markdown;q=0.8;charset=iso-8859-1,text/html;q=0.5", true},
+ {"text/markdown;charset=utf-8;q=0.8;charset=iso-8859-1,text/html;q=0.5", true},
+ {"text/markdown;q=0.8;extension,text/html;q=0.5", true},
+ {"text/markdown;charset=utf-8;charset=utf-8;q=0.2,text/markdown;charset=utf-8;q=0.8,text/html;q=0.5", true},
+ {"text/markdown;unknown=value,text/html;q=0", false},
+ {"text/markdown;charset*=utf-8''utf-8,text/html;q=0", false},
+ {"application/json,text/html;q=0", false},
+ {"text/html;q=0,*/*;q=0.5", true},
+ {`text/markdown;note="a,text/html";q=1,text/html;q=0`, false},
+ {`text/markdown;q=1;note="a,\";b",text/html;q=0`, true},
+ {"text/markdown;q=0.001,text/html;q=0", true},
+ {"text/markdown;q=1.,text/html;q=0.", true},
+ }
+ for _, bad := range []string{"NaN", "Inf", "-1", "2", "1.001", "0.0001", ".5", "+0.5", "1e0", "", `"1"`} {
+ cases = append(cases, struct {
+ accept string
+ want bool
+ }{"text/markdown;q=" + bad + ",text/html;q=0", false})
+ }
+ for i, tc := range cases {
+ t.Run(fmt.Sprint(i), func(t *testing.T) {
+ // These quoted-comma cases stay whole; the remaining cases also
+ // exercise separate field lines and reversed range order.
+ variants := [][]string{{tc.accept}, {strings.ToUpper(tc.accept)}}
+ if !strings.Contains(tc.accept, `"`) {
+ parts := strings.Split(tc.accept, ",")
+ variants = append(variants, parts)
+ reversed := append([]string(nil), parts...)
+ for l, r := 0, len(reversed)-1; l < r; l, r = l+1, r-1 {
+ reversed[l], reversed[r] = reversed[r], reversed[l]
+ }
+ variants = append(variants, reversed, []string{strings.Join(reversed, ",")})
+ }
+ for _, fields := range variants {
+ h := make(http.Header)
+ for _, field := range fields {
+ if field != "" {
+ h.Add("Accept", field)
+ }
+ }
+ if got := prefersMarkdown(h); got != tc.want {
+ t.Errorf("Accept %q = %v, want %v", fields, got, tc.want)
+ }
+ }
+ })
+ }
+}
+
+func markdownDeliveryVary(t *testing.T, w *httptest.ResponseRecorder, want bool) {
+ t.Helper()
+ found := false
+ for _, name := range strings.Split(joinHeader(w.Header(), "Vary"), ",") {
+ found = found || strings.EqualFold(strings.TrimSpace(name), "Accept")
+ }
+ if found != want {
+ t.Errorf("Vary = %q, want Accept=%v", w.Header().Values("Vary"), want)
+ }
+}
+
+func markdownEdge(t *testing.T) (*Edge, func(*testing.T, string, map[string]string)) {
+ t.Helper()
+ t.Setenv("CARLOS_EDGE_GZIP", "1")
+ store := release.NewDirStore(filepath.Join(t.TempDir(), "store"))
+ priv, pub := testKeys(t)
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "example.com", Kind: "static", App: "shop", Channel: "canary/x", Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+ e.EnableStatic(store, pub, filepath.Join(t.TempDir(), "cache"))
+ e.SetStaticRecheck(0)
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ return e, func(t *testing.T, version string, files map[string]string) {
+ t.Helper()
+ if files != nil {
+ shipSite(t, store, "shop", version, files)
+ }
+ if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "shop", "canary/x", version); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func markdownEdgeRequest(e *Edge, method, path, accept, encoding string, extra http.Header) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(method, "http://example.com"+path, nil)
+ r.Header.Set("Accept", accept)
+ r.Header.Set("Accept-Encoding", encoding)
+ for name, values := range extra {
+ r.Header[name] = values
+ }
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, r)
+ return w
+}
+
+func markdownDecoded(t *testing.T, w *httptest.ResponseRecorder, compressed bool) string {
+ t.Helper()
+ if !compressed {
+ if got := w.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("Content-Encoding = %q, want identity", got)
+ }
+ return w.Body.String()
+ }
+ if w.Header().Get("Content-Encoding") != "gzip" {
+ t.Fatalf("Content-Encoding = %q, want gzip", w.Header().Get("Content-Encoding"))
+ }
+ if !strings.Contains(joinHeader(w.Header(), "Vary"), "Accept-Encoding") {
+ t.Errorf("compressed Vary = %q, want Accept-Encoding", w.Header().Values("Vary"))
+ }
+ gz, err := gzip.NewReader(w.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer gz.Close()
+ body, err := io.ReadAll(gz)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(body)
+}
+
+func markdownCacheSize(t *testing.T, e *Edge, want int) {
+ t.Helper()
+ e.cache.mu.Lock()
+ defer e.cache.mu.Unlock()
+ if got := len(e.cache.entries); got != want {
+ t.Fatalf("shared cache entries = %d, want %d", got, want)
+ }
+}
+
+func TestStaticMarkdownDelivery(t *testing.T) {
+ e, promote := markdownEdge(t)
+ bodies := map[string]string{
+ "text/html": strings.Repeat("<p>shop HTML</p>\n", 100),
+ "text/markdown": strings.Repeat("# shop Markdown\n", 120),
+ }
+ promote(t, "v1", map[string]string{
+ "shop/index.html": bodies["text/html"], "shop/index.md": bodies["text/markdown"],
+ "page.html": bodies["text/html"], "page.md": bodies["text/markdown"],
+ "_headers": "/*\n Cache-Control: public, max-age=300\n",
+ })
+ for _, path := range []string{"/shop/", "/page.html"} {
+ t.Run(path, func(t *testing.T) {
+ tags := make(map[string]string)
+ for _, accept := range []string{"text/html", "text/markdown"} {
+ w := markdownEdgeRequest(e, "GET", path, accept, "identity", nil)
+ if w.Code != 200 || markdownDecoded(t, w, false) != bodies[accept] || w.Header().Get("Content-Type") != accept+"; charset=utf-8" {
+ t.Fatalf("baseline %s = %d %v", accept, w.Code, w.Header())
+ }
+ tags[accept] = w.Header().Get("ETag")
+ markdownCacheSize(t, e, 0)
+ }
+ if tags["text/html"] == "" || tags["text/markdown"] == "" || tags["text/html"] == tags["text/markdown"] {
+ t.Fatalf("representation tags = %v, want distinct nonempty tags", tags)
+ }
+ for i, delivery := range []struct{ accept, encoding string }{
+ {"text/html", "identity"}, {"text/markdown", "gzip"},
+ {"text/html", "gzip"}, {"text/markdown", "identity"},
+ {"text/html", "identity"}, {"text/markdown", "gzip"},
+ } {
+ t.Run(fmt.Sprint(i), func(t *testing.T) {
+ accept, encoding := delivery.accept, delivery.encoding
+ other := "text/html"
+ if accept == other {
+ other = "text/markdown"
+ }
+ for _, request := range []struct {
+ name, method string
+ headers http.Header
+ status int
+ body string
+ }{
+ {"full", "GET", nil, 200, bodies[accept]},
+ {"head", "HEAD", nil, 200, ""},
+ {"matching tag", "GET", http.Header{"If-None-Match": {tags[accept]}}, 304, ""},
+ {"matching head", "HEAD", http.Header{"If-None-Match": {tags[accept]}}, 304, ""},
+ {"other tag", "GET", http.Header{"If-None-Match": {tags[other]}}, 200, bodies[accept]},
+ {"range", "GET", http.Header{"Range": {"bytes=0-15"}}, 206, bodies[accept][:16]},
+ } {
+ t.Run(request.name, func(t *testing.T) {
+ w := markdownEdgeRequest(e, request.method, path, accept, encoding, request.headers)
+ if w.Code != request.status {
+ t.Fatalf("status = %d, want %d: %v", w.Code, request.status, w.Header())
+ }
+ compressed := encoding == "gzip" && request.method == "GET" && request.status == 200
+ if got := markdownDecoded(t, w, compressed); got != request.body {
+ t.Errorf("decoded body = %q, want %q", got, request.body)
+ }
+ if request.status != 304 && w.Header().Get("Content-Type") != accept+"; charset=utf-8" {
+ t.Errorf("Content-Type = %q, want %s", w.Header().Get("Content-Type"), accept)
+ }
+ if w.Header().Get("ETag") != tags[accept] || w.Header().Get("X-Carlos-Version") != "v1" {
+ t.Errorf("validator/version = %v, want %s / v1", w.Header(), tags[accept])
+ }
+ if w.Header().Get("Cache-Control") != "public, max-age=300" {
+ t.Errorf("Cache-Control = %q", w.Header().Get("Cache-Control"))
+ }
+ if request.status == 206 && w.Header().Get("Content-Range") != fmt.Sprintf("bytes 0-15/%d", len(bodies[accept])) {
+ t.Errorf("Content-Range = %q", w.Header().Get("Content-Range"))
+ }
+ markdownDeliveryVary(t, w, true)
+ markdownCacheSize(t, e, 0)
+ })
+ }
+ })
+ }
+ for _, accept := range []string{"text/html", "text/markdown"} {
+ other := "text/html"
+ if accept == other {
+ other = "text/markdown"
+ }
+ for _, encoding := range []string{"identity", "gzip"} {
+ key := CacheKey{Host: "example.com", Method: "GET", Path: path}
+ seed := &CachedResponse{
+ StatusCode: 200, Body: []byte(bodies[other]), StoredAt: time.Now(), TTL: time.Minute,
+ Header: http.Header{"Content-Type": {other + "; charset=utf-8"}, "Etag": {tags[other]}, "X-Carlos-Version": {"v0"}},
+ }
+ e.cache.Put(key, "", seed)
+ r := httptest.NewRequest("GET", "http://example.com"+path, nil)
+ r.Header.Set("Accept", accept)
+ r.Header.Set("Accept-Encoding", encoding)
+ if got, hit := e.cache.GetFor(key, r); !hit || string(got.Body) != bodies[other] {
+ t.Fatal("wrong representation was not available as a shared cache hit")
+ }
+ w := markdownEdgeRequest(e, "GET", path, accept, encoding, nil)
+ if w.Code != 200 || markdownDecoded(t, w, encoding == "gzip") != bodies[accept] || w.Header().Get("Content-Type") != accept+"; charset=utf-8" || w.Header().Get("ETag") != tags[accept] || w.Header().Get("X-Carlos-Version") != "v1" {
+ t.Fatalf("seeded cache %s/%s = %d %v", accept, encoding, w.Code, w.Header())
+ }
+ markdownDeliveryVary(t, w, true)
+ markdownCacheSize(t, e, 1)
+ if got, hit := e.cache.GetFor(key, r); !hit || string(got.Body) != bodies[other] {
+ t.Fatal("static response replaced the seeded shared cache entry")
+ }
+ e.cache.PurgeHost("example.com")
+ }
+ }
+ })
+ }
+}
+
+func TestStaticMarkdownRelease(t *testing.T) {
+ e, promote := markdownEdge(t)
+ html := strings.Repeat("<p>shop HTML</p>\n", 100)
+ versions := []struct{ version, markdown string }{
+ {"v1", ""}, {"v2", strings.Repeat("# shop Markdown v2\n", 100)},
+ {"v3", strings.Repeat("# shop Markdown v3\n", 100)}, {"v4", ""},
+ }
+ tags := make(map[string]string)
+ previousTag := ""
+ for _, index := range []int{0, 1, 2, 3, 2, 1, 0} {
+ v := versions[index]
+ t.Run(v.version, func(t *testing.T) {
+ var files map[string]string
+ if tags[v.version] == "" {
+ files = map[string]string{"shop/index.html": html, "_headers": "/*\n Cache-Control: public, max-age=300\n"}
+ if v.markdown != "" {
+ files["shop/index.md"] = v.markdown
+ }
+ }
+ promote(t, v.version, files)
+ wantBody, wantType := html, "text/html; charset=utf-8"
+ if v.markdown != "" {
+ wantBody, wantType = v.markdown, "text/markdown; charset=utf-8"
+ }
+ w := markdownEdgeRequest(e, "GET", "/shop/", "text/markdown", "identity", http.Header{"If-None-Match": {previousTag}})
+ if w.Code != 200 || markdownDecoded(t, w, false) != wantBody || w.Header().Get("Content-Type") != wantType || w.Header().Get("X-Carlos-Version") != v.version {
+ t.Fatalf("release %s = %d %v", v.version, w.Code, w.Header())
+ }
+ markdownDeliveryVary(t, w, v.markdown != "")
+ markdownCacheSize(t, e, 0)
+ tag := w.Header().Get("ETag")
+ if tag == "" || tag == previousTag {
+ t.Fatalf("tag = %q, previous %q; want a new validator", tag, previousTag)
+ }
+ if old := tags[v.version]; old != "" && tag != old {
+ t.Errorf("rollback tag = %q, want original %q", tag, old)
+ }
+ if v.markdown == "" && tags["v1"] != "" && tag != tags["v1"] {
+ t.Errorf("unchanged HTML tag = %q, want %q", tag, tags["v1"])
+ }
+ tags[v.version], previousTag = tag, tag
+ for _, accept := range []string{"text/html", "text/markdown"} {
+ body, ctype, etag := wantBody, wantType, tag
+ if accept == "text/html" {
+ body, ctype, etag = html, "text/html; charset=utf-8", tags["v1"]
+ }
+ for _, encoding := range []string{"identity", "gzip"} {
+ w := markdownEdgeRequest(e, "GET", "/shop/", accept, encoding, nil)
+ if w.Code != 200 || markdownDecoded(t, w, encoding == "gzip") != body || w.Header().Get("Content-Type") != ctype || w.Header().Get("ETag") != etag || w.Header().Get("X-Carlos-Version") != v.version {
+ t.Errorf("%s/%s/%s = %d %v", v.version, accept, encoding, w.Code, w.Header())
+ }
+ if w.Header().Get("Cache-Control") != "public, max-age=300" {
+ t.Errorf("Cache-Control = %q", w.Header().Get("Cache-Control"))
+ }
+ markdownDeliveryVary(t, w, v.markdown != "")
+ markdownCacheSize(t, e, 0)
+ }
+ }
+ })
+ }
+}
+
+func markdownTree(t *testing.T, files map[string]string) servedTree {
+ t.Helper()
+ tree := servedTree{dir: t.TempDir()}
+ for name, body := range files {
+ fp := filepath.Join(tree.dir, name)
+ if err := os.MkdirAll(filepath.Dir(fp), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(fp, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var err error
+ tree.redirects, err = parseRedirects([]byte(files[redirectsFile]))
+ if err != nil {
+ t.Fatal(err)
+ }
+ tree.headers, err = parseHeaders([]byte(files[headersFile]))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return tree
+}
+
+func markdownRequest(tree servedTree, method, target string, headers http.Header, guard bool) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(method, "http://example.com"+target, nil)
+ r.Header = headers.Clone()
+ if guard {
+ out := &outcome{guard: &guardState{mode: guardBlock, mint: func(reqrec.Tier, string) string { return "test" }}}
+ r = r.WithContext(context.WithValue(r.Context(), answeredKey{}, out))
+ }
+ w := httptest.NewRecorder()
+ var dest http.ResponseWriter = w
+ if gw := newGzipWriter(w, r); gw != nil {
+ dest = gw
+ defer gw.finish()
+ }
+ dest.Header().Set("Cache-Control", "no-cache")
+ dest.Header().Add("Vary", "Origin")
+ (&staticSite{app: "shop"}).serveTree(tree, dest, r)
+ return w
+}
+
+func markdownVary(t *testing.T, w *httptest.ResponseRecorder, want bool) {
+ t.Helper()
+ values := strings.Split(strings.Join(w.Header().Values("Vary"), ","), ",")
+ found, origin := false, false
+ for _, v := range values {
+ found = found || strings.EqualFold(strings.TrimSpace(v), "Accept")
+ origin = origin || strings.EqualFold(strings.TrimSpace(v), "Origin")
+ }
+ if found != want || !origin {
+ t.Errorf("Vary = %q, want Accept=%v and preserved Origin", values, want)
+ }
+}
+
+func TestStaticMarkdownResolution(t *testing.T) {
+ tree := markdownTree(t, map[string]string{
+ "shop/index.html": "<p>shop</p>", "shop/index.md": "# shop",
+ "page.html": "<p>page</p>", "page.md": "# page",
+ "only.html": "HTML only", "directory.html": "HTML directory", "directory.md/child": "child",
+ "link.html": "HTML link", "orphan/index.md": "orphan",
+ ".git/index.html": "secret HTML", ".git/index.md": "secret Markdown",
+ redirectsFile: "/rewrite /page.html 200\n/missing /page.html 404\n/blocked /.git/index.html 200\n/blocked-dir /.git 200\n",
+ headersFile: "/rewrite\n Cache-Control: public, max-age=60\n/page.html\n Cache-Control: public, max-age=120\n",
+ })
+ if err := os.Symlink(filepath.Join(tree.dir, "page.md"), filepath.Join(tree.dir, "link.md")); err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ path, html, markdown string
+ twin bool
+ }{
+ {"/shop/", "<p>shop</p>", "# shop", true},
+ {"/page.html", "<p>page</p>", "# page", true},
+ {"/only.html", "HTML only", "HTML only", false},
+ {"/directory.html", "HTML directory", "HTML directory", false},
+ {"/link.html", "HTML link", "HTML link", false},
+ {"/page.md", "# page", "# page", false},
+ {"/rewrite?x=1", "<p>page</p>", "# page", true},
+ } {
+ for _, accept := range []string{"", "text/html", "text/markdown"} {
+ t.Run(tc.path+accept, func(t *testing.T) {
+ w := markdownRequest(tree, "GET", tc.path, http.Header{"Accept": {accept}}, false)
+ want := tc.html
+ if accept == "text/markdown" {
+ want = tc.markdown
+ }
+ if w.Code != 200 || w.Body.String() != want {
+ t.Fatalf("response = %d %q, want 200 %q", w.Code, w.Body.String(), want)
+ }
+ if tc.twin && accept == "text/markdown" && w.Header().Get("Content-Type") != "text/markdown; charset=utf-8" {
+ t.Errorf("Content-Type = %q", w.Header().Get("Content-Type"))
+ }
+ markdownVary(t, w, tc.twin)
+ wantCache := "no-cache"
+ if strings.HasPrefix(tc.path, "/rewrite") {
+ wantCache = "public, max-age=60"
+ } else if tc.path == "/page.html" {
+ wantCache = "public, max-age=120"
+ }
+ if got := w.Header().Get("Cache-Control"); got != wantCache {
+ t.Errorf("Cache-Control = %q, want %q", got, wantCache)
+ }
+ })
+ }
+ }
+ for _, tc := range []struct{ path, location string }{{"/shop?x=1", "./shop/?x=1"}, {"/shop/index.html?x=1", "./?x=1"}} {
+ w := markdownRequest(tree, "GET", tc.path, http.Header{"Accept": {"text/markdown"}}, false)
+ if w.Code != 301 || w.Header().Get("Location") != tc.location {
+ t.Errorf("%s = %d %q, want 301 %q", tc.path, w.Code, w.Header().Get("Location"), tc.location)
+ }
+ }
+ for _, target := range []string{"/orphan/", "/orphan", "/orphan/index.html"} {
+ w := markdownRequest(tree, "GET", target, http.Header{"Accept": {"text/markdown"}}, false)
+ if w.Code != 404 || strings.Contains(w.Body.String(), "orphan") {
+ t.Errorf("%s = %d %q, want missing HTML", target, w.Code, w.Body.String())
+ }
+ }
+ for _, target := range []string{"/blocked", "/blocked-dir"} {
+ w := markdownRequest(tree, "GET", target, http.Header{"Accept": {"text/markdown"}}, true)
+ if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || strings.Contains(w.Body.String(), "secret") {
+ t.Errorf("hard-tier rewrite %s = %d %q", target, w.Code, w.Body.String())
+ }
+ }
+ w := markdownRequest(tree, "GET", "/missing", http.Header{"Accept": {"text/markdown"}}, false)
+ if w.Code != 404 || w.Body.String() != "# page" || w.Header().Get("Content-Type") != "text/markdown; charset=utf-8" || w.Header().Get("ETag") != "" {
+ t.Errorf("404 rewrite = %d %q %v", w.Code, w.Body.String(), w.Header())
+ }
+ markdownVary(t, w, true)
+ only := markdownTree(t, map[string]string{"index.html": "HTML only"})
+ w = markdownRequest(only, "GET", "/", http.Header{"Accept": {"text/markdown"}}, false)
+ if w.Code != 200 || w.Body.String() != "HTML only" || w.Header().Get("Content-Type") != "text/html; charset=utf-8" {
+ t.Errorf("HTML-only tree = %d %q %v", w.Code, w.Body.String(), w.Header())
+ }
+ markdownVary(t, w, false)
+ t.Run("selected file disappears", func(t *testing.T) {
+ fp := filepath.Join(tree.dir, "page.html")
+ fi, err := os.Stat(fp)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rep := selectStaticRepresentation(fp, fi, http.Header{"Accept": {"text/markdown"}})
+ if rep.path != filepath.Join(tree.dir, "page.md") {
+ t.Fatalf("selected %q, want Markdown sibling", rep.path)
+ }
+ if err := os.Remove(rep.path); err != nil {
+ t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ (&staticSite{app: "shop"}).serveFile(rep.path, "/page.html", rep.info, rep.contentType, 200, nil, w, httptest.NewRequest("GET", "http://example.com/page.html", nil))
+ if w.Code != 404 || strings.Contains(w.Body.String(), "<p>page</p>") {
+ t.Errorf("removed twin = %d %q, want refusal", w.Code, w.Body.String())
+ }
+ })
+}
+
+func TestStaticMarkdownValidators(t *testing.T) {
+ body := strings.Repeat("same bytes for both representations\n", 100)
+ tree := markdownTree(t, map[string]string{"page.html": body, "page.md": body})
+ tags := make(map[string]string)
+ for _, accept := range []string{"text/html", "text/markdown"} {
+ w := markdownRequest(tree, "GET", "/page.html", http.Header{"Accept": {accept}}, false)
+ if w.Code != 200 || w.Body.String() != body || w.Header().Get("ETag") == "" {
+ t.Fatalf("%s = %d %v", accept, w.Code, w.Header())
+ }
+ tags[accept] = w.Header().Get("ETag")
+ }
+ if tags["text/html"] == tags["text/markdown"] {
+ t.Error("identical bytes with different types share an ETag")
+ }
+ for _, accept := range []string{"text/html", "text/markdown"} {
+ for tagType, tag := range tags {
+ w := markdownRequest(tree, "GET", "/page.html", http.Header{"Accept": {accept}, "If-None-Match": {tag}}, false)
+ want := 200
+ if tagType == accept {
+ want = 304
+ }
+ if w.Code != want || (want == 200 && w.Body.String() != body) || (want == 304 && w.Body.Len() != 0) {
+ t.Errorf("%s with %s tag = %d, want %d", accept, tagType, w.Code, want)
+ }
+ markdownVary(t, w, true)
+ }
+ for _, method := range []string{"GET", "HEAD"} {
+ w := markdownRequest(tree, method, "/page.html", http.Header{"Accept": {accept}, "Range": {"bytes=0-3"}}, false)
+ if w.Code != 206 || (method == "GET" && w.Body.String() != body[:4]) || (method == "HEAD" && w.Body.Len() != 0) {
+ t.Errorf("%s range %s = %d %q", accept, method, w.Code, w.Body.String())
+ }
+ if w.Header().Get("Content-Type") != accept+"; charset=utf-8" {
+ t.Errorf("range Content-Type = %q", w.Header().Get("Content-Type"))
+ }
+ markdownVary(t, w, true)
+ }
+ w := markdownRequest(tree, "GET", "/page.html", http.Header{"Accept": {accept}, "Accept-Encoding": {"gzip"}}, false)
+ if w.Header().Get("Content-Encoding") != "gzip" || !strings.Contains(joinHeader(w.Header(), "Vary"), "Accept-Encoding") {
+ t.Fatalf("gzip headers = %v", w.Header())
+ }
+ markdownVary(t, w, true)
+ gz, err := gzip.NewReader(w.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ decoded, err := io.ReadAll(gz)
+ gz.Close()
+ if err != nil || string(decoded) != body {
+ t.Fatalf("gzip body = %q, %v", decoded, err)
+ }
+ }
+ t.Run("forced type has its own memo and flight", func(t *testing.T) {
+ c := newTagCache()
+ fp, f, fi := openTagged(t, t.TempDir(), "page.html", body)
+ plain, _, err := c.tag(context.Background(), fp, f, fi, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ forced, ctype, err := c.tag(context.Background(), fp, f, fi, "text/markdown; charset=utf-8")
+ if err != nil || plain == forced || ctype != "text/markdown; charset=utf-8" || c.hashed.Load() != 2 {
+ t.Fatalf("forced tag = %q %q %v, ordinary %q, hashes %d", forced, ctype, err, plain, c.hashed.Load())
+ }
+ c = newTagCache()
+ c.wait = time.Millisecond
+ c.flights[staticTagKey{path: fp}] = make(chan struct{})
+ if _, _, err := c.tag(context.Background(), fp, f, fi, "text/markdown; charset=utf-8"); err != nil {
+ t.Fatalf("forced type waited on ordinary flight: %v", err)
+ }
+ })
+ t.Run("tag budget", func(t *testing.T) {
+ previous := staticTags
+ staticTags = newTagCache()
+ t.Cleanup(func() { staticTags = previous })
+ staticTags.wait = time.Millisecond
+ for i := 0; i < tagHashers; i++ {
+ staticTags.sem <- struct{}{}
+ }
+ large := strings.Repeat("x", tagInline+1)
+ tree := markdownTree(t, map[string]string{"page.html": "HTML", "page.md": large})
+ w := markdownRequest(tree, "GET", "/page.html", http.Header{"Accept": {"text/markdown"}, "If-None-Match": {tags["text/html"]}}, false)
+ if w.Code != 200 || w.Body.String() != large || w.Header().Get("ETag") != "" || w.Header().Get("Content-Type") != "text/markdown; charset=utf-8" {
+ t.Errorf("busy tag = %d, body length %d, headers %v", w.Code, w.Body.Len(), w.Header())
+ }
+ markdownVary(t, w, true)
+ })
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index b39f103e5..5b9c1382a 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -89,3 +89,4 @@ plan14-root-reads-stateless-coordinator-oneboxfleet.tsv face84b4c688cd3c179b0a34
plan14-root-reads-region-ha-group-rtb.tsv 526d434888d043a8b09d8fe196f6324782d6ca20d759b080f99daa528adf6a32
plan14-root-reads-region-ha-p3b1-fixes.tsv 86aa1e39a21072d17678411a4047983a756494b84a25f7719c0cdf4a61cd1b85
plan14-root-reads-stateless-failed-release-held.tsv 657f81eeea52785b75f92a42064f63f218787f712ef313e2acf44f7e664e16b9
+plan14-root-reads-static-markdown-twins.tsv ec831d3206622f34511bfbc2ec0cccb131fbd3861ec4c6a33a2dc6dff9a1791e
diff --git a/internal/provision/testdata/plan14-root-reads-static-markdown-twins.tsv b/internal/provision/testdata/plan14-root-reads-static-markdown-twins.tsv
new file mode 100644
index 000000000..ffa4c4bb7
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-static-markdown-twins.tsv
@@ -0,0 +1,10 @@
+# Census overlay static-markdown-twins, written by census-propose (#369). census-ruling-static-markdown-twins, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-static-markdown-twins.md.
+# 2 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 392266769a135ba47f8ec3d084be1a5133fac870b47a3b694c816de14e1d4b55 internal/edge/static.go staticSite.serveFile legacy accepted-legacy accepted-legacy;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; serveTree's former Open and open-file Stat of the file serveTree resolved inside the extracted, digest-verified tree, unchanged, plus a non-200 branch that copies the same open file under a _redirects 404 status; no root decision;rev3=census-ruling-static-headers;basis=takes the in-memory _headers lookup result (extra) and, on the 200 branch only, wraps the writer in headerWriter, which sets those header values on 200/206/304 at status time; the same Open and open-file Stat of the same resolved file; no read added, no root decision;rev3=census-ruling-static-markdown-twins;basis=Accepts a forced representation content type for ordinary and non-200 responses, including tag fallback; existing os.Open and open-file Stat now operate on the selected HTML or Markdown file inside the extracted digest-verified tree; no additional read site and no root decision. file:Open@165,file:Stat@1746 2c19c03112e08234ed04ae6f53f644b440466731ec31c26400429e11bca56c85
+@legacy 863ec330adedf2a0dff76d6cec165149fe3a1747f8f5e668530da16d81d89e91 internal/edge/static.go staticSite.serveTree legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the same index-aware Stat lookup inside the extracted tree, now run at most twice (the request path, then once for a _redirects rewrite destination cleaned rooted inside the same tree); the Open moves to serveFile; the _redirects file itself is never answered; no root decision;rev3=census-ruling-edge-protection-2;basis=consults the edge protection matcher (internal/edgeguard, pure and in-memory) on the request path (probe tier, only when no file and no _redirects rule names it) and on a rewrite target (hard tier, only when the file is there), and may answer the guard's 404 block page through guardDecide before a redirect or the rewritten file; the _redirects lookup gains an in-memory names check; the same index-aware Stat lookups inside the extracted tree, unchanged; no read added;rev3=census-ruling-static-dir-slash;basis=A directory requested without its trailing slash now answers a 301 to a relative "./<base>/" (query kept) instead of serving its index.html, unless the request was rewritten, the path ends in "/", a _redirects rule names the path, or the rules would redirect its slash form (redirectsSlashForm, the existing in-memory resolve with exists=true). It opens and stats exactly the files it did before; the new branch only writes a Location header and a status, from the request path and the rules it already parsed.;rev3=census-ruling-static-headers;basis=computes the in-memory _headers lookup once on the cleaned request path and host and passes it to serveFile; the _headers file itself is never answered (found excludes it, as _redirects); the same index-aware Stat lookups inside the extracted tree; no read added;rev3=census-ruling-probe-burst-limit;basis=where the guard already checks the probe tier for a path the tree does not have, it also asks whether the path is in the catalogue (staticBurstHit, the in-memory edgeguard matcher) and, for a client in a probe-burst cool-down, may answer the 429 burst refusal (staticBurstDecide, the in-memory limiter) before a redirect or rewrite; the same index-aware Stat lookups inside the extracted tree; no new root read or write kind;rev3=census-ruling-static-markdown-twins;basis=Selects an existing regular Markdown sibling only after HTML resolution and redirects, checks the selected target against the hard tier, adds Vary: Accept and passes path/info/type to serveFile; existing Stat sites are unchanged; the selector adds the sibling Lstat described below; no root decision. file:Stat@1301,file:Stat@1415 40e516ea7af516647a44bd22c45f3a6b010fa122d9b52b911d691ae6da56d3e7
+@legacy 9638867b5cdd5ca6638dd15de3401258c2369af0663e5c1d3c8667a5e23bd95e internal/edge/static_markdown.go selectStaticRepresentation legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-markdown-twins;basis=Adds file:Lstat of the .md sibling of an already resolved regular .html file inside the extracted digest-verified tree; refuses symlinks and non-regular twins, then selects only on strict positive Accept preference; edge runs as carlos, with no root decision. file:Lstat@292 798868afa1f365c942c7a5a72593fd5e18d818b874677fffcc3a45fa932930a4
+internal/edge/static.go staticSite.serveFile legacy accepted-legacy accepted-legacy;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; serveTree's former Open and open-file Stat of the file serveTree resolved inside the extracted, digest-verified tree, unchanged, plus a non-200 branch that copies the same open file under a _redirects 404 status; no root decision;rev3=census-ruling-static-headers;basis=takes the in-memory _headers lookup result (extra) and, on the 200 branch only, wraps the writer in headerWriter, which sets those header values on 200/206/304 at status time; the same Open and open-file Stat of the same resolved file; no read added, no root decision;rev3=census-ruling-static-markdown-twins;basis=Accepts a forced representation content type for ordinary and non-200 responses, including tag fallback; existing os.Open and open-file Stat now operate on the selected HTML or Markdown file inside the extracted digest-verified tree; no additional read site and no root decision. file:Open@165,file:Stat@1746 2c19c03112e08234ed04ae6f53f644b440466731ec31c26400429e11bca56c85
+internal/edge/static.go staticSite.serveTree legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the same index-aware Stat lookup inside the extracted tree, now run at most twice (the request path, then once for a _redirects rewrite destination cleaned rooted inside the same tree); the Open moves to serveFile; the _redirects file itself is never answered; no root decision;rev3=census-ruling-edge-protection-2;basis=consults the edge protection matcher (internal/edgeguard, pure and in-memory) on the request path (probe tier, only when no file and no _redirects rule names it) and on a rewrite target (hard tier, only when the file is there), and may answer the guard's 404 block page through guardDecide before a redirect or the rewritten file; the _redirects lookup gains an in-memory names check; the same index-aware Stat lookups inside the extracted tree, unchanged; no read added;rev3=census-ruling-static-dir-slash;basis=A directory requested without its trailing slash now answers a 301 to a relative "./<base>/" (query kept) instead of serving its index.html, unless the request was rewritten, the path ends in "/", a _redirects rule names the path, or the rules would redirect its slash form (redirectsSlashForm, the existing in-memory resolve with exists=true). It opens and stats exactly the files it did before; the new branch only writes a Location header and a status, from the request path and the rules it already parsed.;rev3=census-ruling-static-headers;basis=computes the in-memory _headers lookup once on the cleaned request path and host and passes it to serveFile; the _headers file itself is never answered (found excludes it, as _redirects); the same index-aware Stat lookups inside the extracted tree; no read added;rev3=census-ruling-probe-burst-limit;basis=where the guard already checks the probe tier for a path the tree does not have, it also asks whether the path is in the catalogue (staticBurstHit, the in-memory edgeguard matcher) and, for a client in a probe-burst cool-down, may answer the 429 burst refusal (staticBurstDecide, the in-memory limiter) before a redirect or rewrite; the same index-aware Stat lookups inside the extracted tree; no new root read or write kind;rev3=census-ruling-static-markdown-twins;basis=Selects an existing regular Markdown sibling only after HTML resolution and redirects, checks the selected target against the hard tier, adds Vary: Accept and passes path/info/type to serveFile; existing Stat sites are unchanged; the selector adds the sibling Lstat described below; no root decision. file:Stat@1301,file:Stat@1415 40e516ea7af516647a44bd22c45f3a6b010fa122d9b52b911d691ae6da56d3e7
+internal/edge/static_markdown.go selectStaticRepresentation legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-markdown-twins;basis=Adds file:Lstat of the .md sibling of an already resolved regular .html file inside the extracted digest-verified tree; refuses symlinks and non-regular twins, then selects only on strict positive Accept preference; edge runs as carlos, with no root decision. file:Lstat@292 798868afa1f365c942c7a5a72593fd5e18d818b874677fffcc3a45fa932930a4
+@coverage internal/edge 3f3ff9e696eb227bb4f0a2da386a71643b3ca13d8f4a2ac39e9fe37dc331ac24