plans: apply Paul's rulings to plans 2 and 4, add static markdown twins
Banner inserted by the edge, box-local traffic counting, website stays static with a general Markdown-twin feature in the edge.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+224
−173
docs/superpowers/plans/2026-11-04-agent-start-demo-2-edge-protections.md+91 −122docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md+38 −51docs/superpowers/plans/2026-11-04-static-markdown-twins.md+95 −0
CI passed — run details
Intent
Human
Yes
Human
<task-notification> <task-id>b3xsc60pf</task-id> <tool-use-id>toolu_01MGocwQwLE8JTW3ugCNkYYC</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/922e5421-5be4-4525-bbbf-75f2657df9b6/tasks/b3xsc60pf.output</output-file> <status>completed</status> <summary>Background command "Wait for both plan revisions" completed (exit code 0)</summary> </task-notification>
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| index ec760a9a3..dc0830863 100644 |
| --- 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 |
| @@ -2,23 +2,25 @@ |
| > **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 a protected warning banner, restrictive browser policy, lifetime traffic limits, and operator abuse controls. |
| +**Goal:** Serve anonymous demos with an edge-inserted warning banner, restrictive browser policy, lifetime traffic limits, and operator abuse controls. |
| -**Architecture:** The edge serves a trusted banner page around a sandboxed app on a different origin; both names use the existing demo wildcard. The assigned demo box checks a durable console ledger before dispatch and before releasing a bounded response, so ingress count, restarts and updates cannot multiply the allowance. Operator controls use the console API and CLI, and takedown reuses Plan 1 retirement. |
| +**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, SQLite transactions, existing fleet authentication and forwarding, browser CSP and iframe sandbox; browser integration tests on the development machine. |
| +**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. The current code, rather than Plan 1's proposed signatures, is the implementation baseline. |
| +**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, seven 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 7. |
| +- 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. |
| @@ -28,11 +30,11 @@ |
| ## Review Focus |
| -1. A hostile app uses scripts, CSS, SVG, navigation or malformed HTML to hide the warning: Task 2's real-browser test must keep the warning visible and the parent inaccessible. |
| -2. Parallel requests through two ingresses race the last request/byte while processes restart: Tasks 3-4 must never replenish or overspend the lifetime ledger. |
| -3. Compression, ranges, cached bodies, trailers, upgrades or a hung body bypass a response wrapper: Tasks 1 and 4 must cover every exit and refuse unsupported representations before app bytes escape. |
| -4. Kill/takedown races publication, an admitted request or console failure: Tasks 4-5 must deny new delivery immediately at the console fence and retain retryable cleanup. |
| -5. A report, CLI credential or forged host names another tenant, reflects script, or leaks a claim token: Tasks 5-6 must restrict authority, escape display and disclose no secret. |
| +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. |
| --- |
| @@ -42,75 +44,63 @@ Read against `2914921ceabd4218b0363a9780f8e4db890aab4c`. Line anchors below refe |
| | 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 app origin. | |
| -| 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. No new registry alias or second app route for the banner. | |
| +| 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. New banner names stay one label deep under that same parent. | |
| +| 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 5 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 and traffic rows. | |
| -| 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. Use these contracts for demand-driven traffic RPCs. | |
| -| Host wiring | `internal/host/agent.go:1133` supplies the `*edge.Edge` startup callback. Wire the budget client there, alongside existing edge integrations. No root control-socket method or background worker 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`. A banner shell must never satisfy that probe. | |
| +| 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 browser containment and banner assets; Task 3 owns shared traffic protocol and SQL ledger; Task 4 owns edge delivery/client wiring; Task 5 owns operator control and retirement adaptation; Task 6 owns the report queue; Task 7 owns end-to-end evidence and the census overlay. Each task updates the tests beside its implementation. No generic middleware or queue framework. |
| +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 containment (my call) |
| +### Banner insertion (Paul's fixed ruling, 2026-11-04) |
| -An injected div, iframe, closed shadow root or top-layer element inside the app's own document is removable by that app's scripts. Mutation observers cannot supply the promised boundary. Preserve useful same-origin JavaScript and cookies by separating the document that contains the warning from the app document. |
| +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. |
| -For `shop.example.com` as an illustrative demo host, reserve `view-shop.example.com` as its edge-owned presentation origin. In real names this is `view-<public-name>.<DemoDomain>`, still a single label and covered by the same wildcard. The inverse mapping must round-trip through a valid Plan 1 public name and its exact valid demo route. The `view-` prefix cannot collide with Plan 1's three-component generated names (`internal/demo/identity.go:45`, word lists at `internal/demo/names.go:5` and `:23`). R19b reserves the derived name forever with the original name; no separate registry row, app policy, instance, DNS record or certificate. |
| +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 presentation page contains a non-dismissable warning and one iframe pointing to the original app host at the same path/query. The iframe uses `sandbox="allow-scripts allow-same-origin allow-forms"`. No top navigation, popups, downloads, fullscreen, pointer lock or modal permissions. The parent loads only edge-owned markup and a fixed same-origin stylesheet at `/.carlos/demo/banner.css`; it has no script, message listener, document.domain assignment, app HTML, app cookies or app-selected styles. Use a grid with an auto-sized warning row and a remaining-height iframe, usable at 320 px width and 200% zoom. App overflow stays inside the frame. |
| +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. |
| -At the original app host, browser top-level GET/HEAD navigations receive a 303 to the derived view host, preserving only the parsed path/query. No user-supplied origin or return URL. Requests missing Fetch Metadata also get that redirect for GET/HEAD; other methods without metadata get a plain 400. A same-origin browser fetch has `Sec-Fetch-Dest: empty` and continues normally. Only `iframe` navigations receive app documents; foreign embedding is blocked by the exact frame-ancestors policy. Browser navigation POSTs inside the iframe work without replay; top-level POSTs are refused. This is an automatic frame around the app, not an interstitial or consent click. |
| +### Policy and representations |
| -`Sec-Fetch-*` is browser context, not authentication. Command-line callers can forge it and receive app bytes; they still pass all traffic and lifecycle gates. Readiness deliberately sets `Sec-Fetch-Dest: iframe` and `Sec-Fetch-Mode: navigate`, keeps its exact host/version check, and spends the ordinary allowance. A shell has no `X-Carlos-Version` and cannot make a broken app live. The view handler refuses a request missing Fetch Metadata with the compatibility page before constructing an iframe, preventing redirect loops. Older browsers without Fetch Metadata cannot run the demo; do not weaken containment. |
| +Set this single edge-owned enforced CSP on every demo response, including redirects, errors, HEAD, 304 and platform pages: |
| -“Reliably” means app HTML/CSS/scripts cannot access, remove, restyle or cover the parent warning in supported browsers. It does not mean browser extensions, developer tools, a non-browser client, a saved copy, or a browser vulnerability cannot remove it. The app can still display deceptive content inside its frame; CSP is not proof that an app is safe. The accepted script-set parent-domain cookie risk in design §4.4 remains; the trusted shell ignores cookies and holds no account/session secrets. |
| +`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'` |
| -Browser basis: cross-origin frames and sandbox restrictions are defined in [https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-sandbox](https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-sandbox). This origin split is our design inference from that boundary, verified by Task 2 browser tests. Fetch Metadata's browser-controlled context is specified in [https://www.w3.org/TR/fetch-metadata/](https://www.w3.org/TR/fetch-metadata/). |
| +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. |
| -### Policy and representations (my call) |
| +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. |
| -Use one edge-owned enforced CSP on every demo response, including redirects, errors, HEAD, 304 and platform pages. Replace app CSP and report-only headers, remove reporting endpoints and trailers that could reintroduce them. Never accept policy input from the app. App meta policies can only further restrict the enforced header; the policy composition rules are in [https://www.w3.org/TR/CSP3/](https://www.w3.org/TR/CSP3/). |
| +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. |
| -The exact common directives are: |
| +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. |
| -`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'` |
| +### Durable local counting |
| -App responses add `frame-src 'none'; frame-ancestors https://<derived-view-host>; sandbox allow-scripts allow-same-origin allow-forms`. Presentation responses instead add `frame-src https://<original-demo-host>; frame-ancestors 'none'`, omit CSP sandbox, and narrow style-src to `'self'`. Other platform responses use `frame-src 'none'; frame-ancestors 'none'`. The four fixed directives remain exactly `'self'` on all surfaces. Inline styles preserve Fiesta compatibility only inside the isolated app. Inline scripts/handlers are blocked; the demo fixture uses external same-origin JavaScript. |
| +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. |
| -Also force `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 X-Frame-Options on the app surface so the chosen CSP ancestor can work; use `DENY` on the shell. Remove app Refresh, Link, CORS grants, reporting headers, Clear-Site-Data and Service-Worker-Allowed. Reject worker/serviceworker/sharedworker request destinations before dispatch. No existing worker can survive onto a new name because names are never reused. |
| +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. |
| -Allow app HTTP redirects only when resolving Location against the app origin yields the same HTTPS origin, no credentials, and a valid path/query. Relative redirects keep their meaning. Refuse cross-origin, scheme-relative foreign, control-character or ambiguous duplicate Locations with the plain 502 page. Frame restrictions and browser witnesses cover scripted/meta navigation; do not claim CSP alone prohibits every possible data leak. |
| +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. |
| -Strip every Domain attribute, case-insensitively, from each separate Set-Cookie field. Preserve name/value and other valid attributes, especially Expires commas, Path, Secure, HttpOnly, SameSite, Max-Age and Partitioned. Do not comma-split or coalesce cookies. Drop malformed cookies rather than forward ambiguous syntax. Drop cookie/policy trailers altogether; declared trailers and Go's `Trailer:` keys both count. Script-written Domain cookies remain the explicit design exception. |
| +`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. |
| -No shared response cache, asset catch, app 304/206, range delivery, upgrades, SSE or edge-held streams for demos in this slice. Strip conditional/range request headers and request identity encoding from the app; bounded-decode gzip if it ignores that, refuse other encodings. HTML is accepted only as `text/html` UTF-8 (absent charset means UTF-8); XHTML and other active document types are refused. Ordinary JSON, CSS, JS, images and text retain validated MIME types with nosniff. Do not stream an unexamined body, forward informational responses, or sniff arbitrary bytes into HTML. |
| +### Serving controls without request-path console calls |
| -### Durable accounting and immediate stop (my call) |
| +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. |
| -Use the console SQLite database as the single ledger keyed by `(demo_id, lifetime)`, independent of build generation and ingress. The assigned resident box calls Begin before waking/proxying, and Commit after buffering/sanitizing the response but before writing any app response to the tunnel/client. Authentication uses the existing active box credential plus exact assigned-box, account, fleet, host and lifetime checks. No IP or client-supplied header is a quota exemption. |
| - |
| -Begin atomically spends one request and creates a random 128-bit ticket bound to box and lifetime, expiring in 30 seconds. Exactly the first 2,000 Begin calls succeed; concurrent requests already admitted may complete. Commit permits an already-issued ticket even when Begin has spent the last request; it still rechecks expiry, serving, retirement and byte exhaustion. Commit consumes a ticket once and atomically charges the final body length only if it fits the remaining byte allowance. A non-fitting body is discarded in full and permanently latches the byte cap for that lifetime. A timed-out/lost Begin response still spends its request; a lost Commit response may spend bytes but must never be retried for delivery. No refunds, no offline allowance, no cached grants. Lost responses can exhaust a demo early but cannot expand its allowance. |
| - |
| -The 200 MB cap is response-body bytes released by the resident edge, after normalization, including app-generated error bodies; HTTP/TLS framing and request uploads are excluded. Disable compression for demos at every hop, making body bytes exact rather than an estimate of later compression. HEAD/204 bodies cost zero; every app request including HEAD, assets, failed dispatch and readiness spends a request. The edge's fixed shell, its stylesheet, redirects to the shell, report UI and refusal pages are platform overhead, excluded from the app ledger, bounded to 8 KiB per response and still subject to the edge's ordinary request-abuse controls. A visitor page load spends one app-document request plus its assets, not a second app request for the shell. |
| - |
| -Each app response is at most 2,097,152 decoded bytes with a 10 MiB transport header-read ceiling and a 32 KiB accepted header block, a 1,048,576-byte app request-body cap, a 25-second execution/read deadline and a 5-second output deadline. At most 8 buffered responses per demo box (16 MiB body capacity, at most 80 MiB transient response-header parsing); excess is 503 before admission. Unsupported or oversized responses become fixed platform errors; their Begin is still spent. No partial app response is emitted at the cap. These are deliberate demo limitations, not changes to ordinary apps. |
| - |
| -The SQL serving switch is initially false. `CARLOS_DEMO_EDGE_PROTECTIONS=1` sets `demo.Config.EdgeProtections bool` on console and all participating edges (unset is false; any other value is a configuration error); `carlos system demos serving on|off` changes the durable serving switch. Effective serving requires both. Off also refuses new creates/updates, in addition to the existing admission switch. Cleanup and reports remain available. A missing client, SQL failure or console outage refuses app serving with 503, not an unmetered fallback. |
| - |
| -Kill and takedown serialize with Begin/Commit. Once the control transaction commits, no new ticket or response Commit succeeds anywhere. A body already committed before the stop can finish within the 5-second write deadline; bytes already sent cannot be recalled. This is the precise immediate-stop guarantee, independent of route refresh or S3 convergence. In-progress execution is bounded and cannot release a response after the fence. Cap pages are 429, stopped service 503, expired/unknown/retired names the same plain 404. All are no-store. The cap is not retirement: data and the token remain until original expiry/claim. |
| - |
| -Presentation shells need no authority-bearing box credential: `GET /api/demo/hosts/{host}/edge-state` returns only public presentation state, after a SQL-only host/lifetime/switch/cap check. No job, account, assigned box or token fields. It is demand-driven and uncached; unavailability gives 503. It does not grant app delivery or alter counters. It lets a stale ingress show stopped/retired instead of an apparently live shell. Apply the existing canonical client-IP limiter pattern with a separate bounded map (60/minute/IP, 4,096 entries, 2-minute idle expiry) and 100 concurrent state reads; never proxy arbitrary URLs. |
| +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 |
| @@ -120,86 +110,67 @@ Presentation shells need no authority-bearing box credential: `GET /api/demo/hos |
| **Interfaces:** |
| - Consumes `registry.Route.IsDemo() bool`, `(*Edge).demoHost(string) bool`, `(*Edge).demoReserved(string) bool` and `(*Edge).demoRouteOK(string, registry.Route) bool`. |
| -- Produces `type demoSurface uint8` with `demoAppSurface`, `demoViewSurface`, `demoPlainSurface`; `demoCSP(surface demoSurface, appHost, viewHost string) string`; `rewriteDemoCookies(h http.Header) error`; `sanitizeDemoHeaders(h http.Header, surface demoSurface, appHost, viewHost string) error`. |
| +- 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 4 is connected. There is no raw-response escape through Unwrap/ResponseController. |
| +- [ ] **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: Put the warning outside app control |
| +## Task 2: Insert the warning into demo HTML |
| -**Risk/review:** security gate, redirect. Independent task review required; browser evidence is required, not just string assertions. |
| +**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/demo/presentation.go`, `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/demo.go:81`, `internal/edge/edge.go:1564`/`:1890`, `internal/console/demo_publish.go:228`; test `internal/demo/presentation_test.go`, `internal/edge/demo_banner_test.go`, `internal/console/demo_publish_test.go`. |
| +**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/render functions and existing exact demo lookup. |
| -- Produces shared `demo.EdgeState` in presentation.go with `State string; ExpiresAt int64`, states `live|limit|stopped|gone|unavailable`; unknown and expired both mean gone. Produces `demo.PresentationHost(appHost, domain string) (string, error)` and `demo.AppHostForPresentation(viewHost, domain string) (string, error)` with exact public-name round-trip validation. |
| -- Produces `(*Edge).serveDemoPresentation(w http.ResponseWriter, r *http.Request, appHost string, state demo.EdgeState)`, consuming the shared state value owned by this task; `(*Edge).demoPresentationRoute(viewHost string) (registry.Route, bool)` checks the canonical app's existing route, never inserts an alias. Unit tests supply a state directly until Task 4 wires the client. |
| - |
| -- [ ] **Step 1: Write failing tests.** `TestDemoPresentationBinding`: exact one-label mapping, collision refusal, no alias/ordinary route substitution, matching wildcard, no per-host issuance, no app bytes/version/cookies on the view origin, safe escaped path/query and no open redirect. `TestDemoProbeCannotPassOnShell`: shell 200 never passes readiness; the iframe-context probe must reach a real 2xx app with the exact expected version. `TestDemoBannerBrowserBoundary`: hostile external same-origin app JS attempts parent DOM/style removal, document.domain, top navigation, popup/fullscreen, frame replacement, meta refresh, foreign frame navigation, CSS full-screen overlay, SVG and document.write; banner remains visible, no foreign navigation/request succeeds in the fixtures. Also exercise form POST, cookie-backed session, same-origin fetch and external self script with the locked Rastrillo/Fiesta fixture, inline-script refusal, mobile width/zoom, direct/deep-link navigation and missing metadata. |
| -- [ ] **Step 2: Run** `go test ./internal/demo ./internal/edge ./internal/console -run 'TestDemo(PresentationBinding|ProbeCannotPassOnShell)' -count=1`; expect FAIL. Run `CARLOS_DEMO_BROWSER_TESTS=1 go test ./internal/edge -run TestDemoBannerBrowserBoundary -count=1` on the development machine against installed Chromium and Firefox; expect FAIL before the containment implementation. Implement the Go browser harness with W3C WebDriver HTTP calls using net/http and encoding/json, starting installed chromedriver/geckodriver on 127.0.0.1 and using their installed browsers; no new runtime module dependency. Local HTTPS test origins use an ephemeral test certificate/browser trust override limited to the isolated test profile, never the production HTTP client. Missing either browser/driver is outstanding evidence, never a passing skip. |
| -- [ ] **Step 3: Implement** the presentation mapping, embedded stylesheet, sandbox shell and navigation rules above. Keep app origin routing unchanged through the fleet tunnel. View-origin handling occurs before ordinary lookup and serves only edge-owned responses after resolving its canonical app. Preserve the original app's Host/Origin on app traffic. Reserve the whole view origin, not just one HTML path; never forward view-origin asset requests to the app. Build the fixture with the checked-in demobuild lock's Rastrillo v0.30.2 closure and a real local SQLite database; implement --socket/--db flags. Update readiness with iframe metadata, without a quota bypass or a bearer secret in the URL. Support current Chromium, Firefox and Safari; verify Safari manually in Task 7. |
| -- [ ] **Step 4: Rerun** Step 2; expect PASS, with browser assertions observing DOM visibility and actual attempted network traffic, not merely finding a sandbox attribute. Existing demo routing tests remain green. |
| -- [ ] **Step 5: Commit** these files with subject `feat: isolate demo warnings from app content`. |
| - |
| -## Task 3: Add the lifetime ledger and demand-driven traffic API |
| - |
| -**Risk/review:** security gate, storage, billing limits. Independent task review required. These counters are abuse allowances, not a replacement for existing billable usage meters. |
| - |
| -**Files:** Create `internal/demo/traffic.go`, `internal/console/demo_traffic.go`, `internal/console/apidemotraffic.go`; modify `internal/demo/config.go:22`, `internal/console/demo_store.go:51`/`:400`, `internal/console/apidemo.go:259`, `internal/console/server.go:534`; test `internal/demo/traffic_test.go`, `internal/console/demo_traffic_test.go`, `internal/console/apidemotraffic_test.go`. |
| - |
| -**Interfaces:** |
| -- Shared `demo.TrafficIdentity` has `ID, Lifetime, Host string`; `demo.TrafficTicket` has `ID string; ExpiresAt int64`; `demo.EdgeState` is consumed unchanged from Task 2. Unknown and expired both map to gone without revealing existence. |
| -- `demo.TrafficClient` interface: `Begin(context.Context, TrafficIdentity) (TrafficTicket, EdgeState, error)`; `Commit(context.Context, TrafficIdentity, TrafficTicket, int64) (EdgeState, error)`. An allowed Commit returns `live`; the ticket cannot be reused. JSON is lowerCamelCase and rejects unknown fields, duplicates, wrong types and oversized bodies. |
| -- Store methods: `beginDemoTraffic(ctx context.Context, box string, id demo.TrafficIdentity, now time.Time) (demo.TrafficTicket, demo.EdgeState, error)`; `commitDemoTraffic(ctx context.Context, box string, id demo.TrafficIdentity, ticket demo.TrafficTicket, bodyBytes int64, now time.Time) (demo.EdgeState, error)`; `demoEdgeState(ctx context.Context, host string, now time.Time) (demo.EdgeState, error)`. |
| -- Routes: authenticated `POST /api/box/demo-traffic/begin` and `/commit`; public `GET /api/demo/hosts/{host}/edge-state`. Begin body is identity, Commit body is identity plus ticket plus bodyBytes. API transport/auth errors use ordinary 404/400/503; valid decisions are JSON 200 with state. Request and response bodies at most 4 KiB; clients use a two-second timeout, validate the configured HTTPS origin, reject malformed/unknown states and never follow redirects. Public state reads return no CORS grants. |
| +**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.** `TestDemoTrafficLifetimeAtomic`: two Store handles, parallel Begin at 1,999/2,000, concurrent Commit at 199,999,999/200,000,000 bytes, oversize refusal, restart and generation update; counters never reset or exceed caps. `TestDemoTrafficTicketFencing`: forged/reused/expired/wrong-box/lifetime tickets, lost replies, zero-byte HEAD, cap latching, transaction rollback, negative/overflow sizes. `TestDemoTrafficNoStoreIO`: counting release.Store records zero operations on all three endpoints. `TestDemoTrafficPublicState`: no secrets, identity enumeration reduced to public state, expiry/unknown same response, bounded read limiter. `TestDemoTrafficMigration`: old console opens additively, admission off leaves cleanup/API available, expired traffic/report rows can later be pruned without deleting permanent tombstones. |
| -- [ ] **Step 2: Run** `go test ./internal/demo ./internal/console -run 'TestDemoTraffic' -count=1`; expect FAIL for missing ledger/API. |
| -- [ ] **Step 3: Implement** shared protocol and SQL-only methods. Add `demo_serving(id=1, enabled=false, changed_at, changed_by)`; `demo_traffic(demo_id, lifetime, requests, body_bytes, byte_exhausted, request_cap, byte_cap)` with composite primary key and nonnegative CHECKs; `demo_traffic_tickets(id PRIMARY KEY, demo_id, lifetime, box, expires_at)` with expiry index. New demo reservation creates its ledger in the same transaction. Existing demos lacking a row refuse serving and never receive a fresh allowance implicitly. Load `CARLOS_DEMO_REQUEST_CAP` (default 2000, range 1..1000000) and `CARLOS_DEMO_BANDWIDTH_CAP_BYTES` (default 200000000, range 1..10000000000) into int64 fields of demo.Config; snapshot them per lifetime. Configuration changes affect new demos only. Register/authenticate doors even when creates are off, retaining the configured demo tuple. Every mutation uses `demoTx`, rereads switch/state/lifetime/assignment, and refuses claims mode. Expired tickets are removed during Begin/Commit and the existing expiry maintenance pass; ledger rows follow seven-day post-purge retention. |
| -- [ ] **Step 4: Rerun** Step 2; expect PASS. Include a transaction race where a stop or retirement commits between Begin and Commit, which must return stopped/gone with no body debit or delivery authorization. |
| -- [ ] **Step 5: Commit** with subject `feat: persist demo lifetime traffic allowances`. |
| +- [ ] **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 4: Enforce the ledger on the serving box |
| +## Task 3: Persist and enforce assigned-box lifetime counters |
| -**Risk/review:** security gate, cache, billing limits. Independent task review required. |
| +**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_client.go`, `internal/edge/demo_traffic.go`, `internal/host/demo_traffic.go`; modify `internal/edge/edge.go:1890`/`:2486`/`:2532`/`:2547`/`:2601`, `internal/host/agent.go:1133`; test `internal/edge/demo_traffic_test.go`, `internal/edge/demo_forward_test.go`, `internal/host/demo_traffic_test.go`. |
| +**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:** |
| -- Consumes Tasks 1-3 and the existing activator/proxy. Produces `demo.NewTrafficClient(origin string, credentials func() (string, string, bool), client *http.Client) (TrafficClient, error)` and `demo.ReadEdgeState(ctx context.Context, client *http.Client, origin, host string) (EdgeState, error)`. |
| -- Produces `(*Edge).SetDemoTraffic(client demo.TrafficClient, state func(context.Context, string) (demo.EdgeState, error))` and `(*Edge).serveDemoTraffic(w http.ResponseWriter, r *http.Request, up upstream)`. Host startup supplies credentials and a pinned configured console origin; ingresses receive only the public state reader. Missing setup always refuses marked app routes. |
| -- The response collector is private to demo_traffic.go, with an owned header map, fixed body/header bounds, cancellation and no Hijack/Unwrap/ReaderFrom bypass. No reusable generic buffering API. |
| +- `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 hubs forward to one assigned resident; all methods/assets/errors share the ledger and are charged once, while forged identity/skip headers change nothing. `TestDemoTrafficResponseBounds`: gzip expansion, unknown encoding, MIME/charset, 1xx, 304, 206, Range, trailers, SSE, websocket, held streams, body never finishing, partial client write and all eight buffer slots; nothing bypasses normalization or leaks a partial app body. `TestDemoTrafficStopsBeforeDelivery`: kill/takedown between body collection and Commit, console timeout, stale routes, restart, copied route and missing client all refuse. `TestDemoTrafficCacheBypass`: seed both old caches, then verify no lookup/fill/asset response/compression for demo traffic and unchanged ordinary paths. `TestDemoTrafficForwardFailurePolicy`: hub-generated 502/503 also carries policy, no-store and the bounded plain page. |
| +- [ ] **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 bounded resident path. Reject demo held markers before `classifyHold` at `internal/edge/edge.go:2129`; skip far asset catch at `:2111` for reserved names. Place the resident dispatch after route/door/tenancy and request-abuse checks, before the held branch at `:2459`, upgrade, asset, cache, compression and activation branches; invoke the existing plan throttle and rate admission once inside this path; forward routes retain authenticated tunnel dispatch and never debit. Use a two-second timeout for each console RPC within the 30-second ticket life. Begin precedes activation; normalize the bounded response; Commit exact normalized body length; only then flush sanitized headers/body. Set and clear a five-second response write deadline at final response output on every forwarding hop as well as the resident, so a slow client cannot stretch delivery after a stop. A wrapper exposes a bounded deadline method, not raw-writer Unwrap. Send explicit `Accept-Encoding: identity` so Go does not add/decode gzip automatically; normalize any app-supplied gzip explicitly. The existing generation transport at `internal/edge/genproxy.go:210` uses net/http defaults, including the 10 MiB header-read ceiling; reject accepted header blocks above 32 KiB in the collector, and cancel on overflow. Retain existing usage metering around actual delivered bytes, separate from conservative quota accounting. On every hop replace demo transport errors with platform copy. A terminal unknown/expired reserved host is answered locally with 404, never sent to a catch-all. Preserve no-store and policy across forwarding. Public presentation state is checked on every shell request; cap/stopped/gone responses replace the shell. |
| -- [ ] **Step 4: Rerun** Step 2 and `go test ./internal/edge -run 'Test(Demo|ForwardResponseCarriesTheBoxVersionOnce)' -count=1`; expect PASS. Count store calls using the existing instrumented store fixture; demand-driven traffic must add zero S3 operations even after reconnect/reload. |
| -- [ ] **Step 5: Commit** with subject `feat: enforce demo traffic limits before response delivery`. |
| +- [ ] **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 5: Add serving control and immediate takedown |
| +## Task 4: Add serving control and takedown |
| -**Risk/review:** security gate, termination, storage. Independent task review required, explicitly including 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. |
| +**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/retirement.go:13`, `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`, `system_demos_test.go`. |
| +**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{}, ...)`, the ledger and Plan 1 signed retirement. |
| +- 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 a confirmed action/state (including explicitly reported pending 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, counters, caps and cleanup status, never tokens/IPs/source. Mutations are idempotent. |
| +- 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 view alias. `TestDemoKillFence`: off survives restart, blocks creates/updates/Begin/Commit, 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 response after fence, offline box cleanup pending, replay stops before delete and retries to permanent tombstone. Test races with publication and an already-retiring row. `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 -run 'TestDemo(Operator|Kill|Takedown)' -count=1` and `go test . -run TestSystemDemosRemote -count=1`; expect FAIL. |
| -- [ ] **Step 3: Implement** the operator API/CLI and extract retirement. Commit the SQL fence before external cleanup; return 200 when purged or 202 with `serving:false, cleanup:"pending"` after the fence. 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. The CLI verifies the returned off/retiring state and prints 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 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 6: Store abuse reports in a small operator queue |
| +## Task 5: Store abuse reports in a small operator queue |
| **Risk/review:** security gate, storage, redirect. Independent task review required. |
| @@ -217,43 +188,41 @@ Presentation shells need no authority-bearing box credential: `GET /api/demo/hos |
| - [ ] **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 7: Prove the complete slice and prepare dev activation |
| +## 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. |
| +**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: presentation/state 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. |
| +**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, cap reached exactly, report recorded/listed/resolved, serving off/on, takedown with offline worker then resumed purge. `TestDemoProtectionsNoBucketTraffic`: zero added S3 calls for browser traffic, counters, state, 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 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 console-dependency, accounting exclusions, iframe/browser restrictions, cap snapshots, stop semantics 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_traffic, demo_traffic_tickets and demo_reports as refusal-only demo_id scopes; 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 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 app and view 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. |
| +- [ ] **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-6 each need independent review for the risks marked above; Task 7 gets the whole-branch and census review, not another mechanical task review. Use an explicit other-family reviewer for Codex-authored census work. |
| +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 for this document: §4.3 traffic/banner/CSP map to Tasks 1-4, §4.4 cookies to Task 1, §4.6 stop/takedown/report to Tasks 5-6, and ordinary-behavior/lifecycle/store-cost witnesses to Task 7. Existing create/IP/global budgets and abuse-log retention remain Plan 1 responsibilities; no duplicate budget mechanism for publishing. All five Review Focus conditions have named tests. The view host adds no registry alias or certificate. Shared protocol types have one owner, no task relies on a Plan 3 claim implementation, and the fixed warning text is not yet approved copy. This is a plan, not evidence that tests ran. |
| +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 7 supplies exact assembled help/docs prose for the same review. |
| +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 | Warning, always visible | This app was built by an AI. It is temporary. Do not enter real passwords or sensitive information. | |
| +| 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-FRAME-TITLE | Iframe accessible title | Temporary demo app | |
| | 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 | Console/transport failure | This demo cannot be checked right now. Try again shortly. | |
| -| DEMO-RESPONSE | Unsupported/oversize app response | This demo returned a response that cannot be shown. | |
| -| DEMO-BROWSER | Unsupported browser/navigation | Open this demo in a current browser. | |
| +| 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 | |
| @@ -264,18 +233,18 @@ Draft candidates only. Every new human-facing string, including accessibility te |
| | 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; Requests; Response bytes; Request cap; Byte cap; Cleanup; Serving; On; Off; Pending; Complete | |
| -| DEMO-CLI-OFF | Confirmed switch off | Demo serving is off. Responses already being sent may finish. | |
| +| 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 | Confirmed fence, cleanup pending | This demo has stopped serving. Cleanup is pending. | |
| +| 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, console-outage refusal, iframe limitations, migration, retirement verification and rollback from Task 7. Review the complete prose, not this content brief. | |
| +| 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. The origin split, bounded response delivery, console ledger, browser requirements and fresh-lifetime activation are my call within the approved design. Copy review is still required before implementation ships; it is not an unresolved build decision. |
| +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-4-start-page.md b/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md| index 706306f6e..2b641df8a 100644 |
| --- 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 |
| @@ -4,33 +4,33 @@ |
| **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. A small website-owned Go server negotiates `/start` and serves the existing built site; 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. |
| +**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 `net/http` and `embed` for the website server; Rastrillo v0.30.2, embedded Fiesta 1.1.0 CSS and SQLite for the starter. |
| +**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. Plan 3 is the producer of the declared claim interface described below. |
| +**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 writes only this plan: no product code, other repository writes, agents, commits, pushes or full tests. |
| +- 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. |
| -- All switches default off. 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 Plans 2 and 3 to be merged, enabled and verified, then accompanies the approved website release. Do not land an unused preparatory slice separately. |
| +- 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. Any proposed platform change requires a separate scope decision and the census process; do not smuggle it into website work. |
| +- 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: Task 3, `TestStartNegotiation` and `TestStartRepresentationIsolation`. |
| +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, `TestStartHTMLParity` and `start-pages.test.mjs`. |
| +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. |
| --- |
| @@ -45,9 +45,8 @@ Read against platform `2914921ceabd4218b0363a9780f8e4db890aab4c` and website `ef |
| | 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 selects files by path and redirects directories to slash form. It has no `Accept`/fetcher selector. A `.md` twin or `_headers` file alone cannot implement §4.7. | |
| -| `internal/console/apidomains.go:917`; `domains_cli.go:427`; `internal/domains/aliases.go:515` | The console has a prefix-map write API and the CLI reads it, but path targets require co-location with the hostname's own route. Do not assume a `/start` prefix target would work across a globally served static website. | |
| -| `internal/edge/edge.go:3005`, `:3043`; `internal/edge/cache.go:91`; `internal/edge/compress.go:241` | `no-store` excludes negotiated pages from edge caching; `Vary` must include both selection headers and preserve any compression variant. No platform cache changes are required. | |
| +| `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 `./`. | |
| @@ -55,11 +54,11 @@ Read against platform `2914921ceabd4218b0363a9780f8e4db890aab4c` and website `ef |
| | `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` | Current website deploy is static via console/CLI, not an automatic push deploy. Binary serving requires an explicit rollout and rollback. Public CLI releases already have a link; install is post-claim only. | |
| +| 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. | |
| -**My call: website-owned negotiation.** Add a standard-library Go binary that embeds only built `_site/` output. It serves `/start` and `/start/` directly, with no redirect between them, and serves the remaining built pages/assets normally. This keeps server-specific negotiation out of the platform and adds no new external provider. Public release becomes a binary-site rollout; it must not run the existing static deploy recipe unchanged. Task 5 rehearses that transition on dev and requires scoped approval before changing the flagship's routes. The existing static release remains the rollback target. A single normal website instance is sufficient initially; it trades the static handler's every-edge file serving for ordinary app availability and latency (my call). Do not enable HA, add a fleet or change account placement as part of this plan. |
| +**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, not a question for Paul.** Plan 1 is merged and live. Plans 2 and 3 are not assumed merged. Plan 3's draft is now available at `docs/superpowers/plans/2026-11-04-agent-start-demo-3-claim.md:70`; the contract below consumes that declaration, not an API on today's main. Task 2 verifies the declaration against the merged producer before implementation. Claim-dependent implementation, independent review and activation wait for Plan 3 to merge; public activation also waits for Plan 2. Keep one design in flight per area and carry the same review history forward. |
| +**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 | |
| |---|---| |
| @@ -132,38 +131,26 @@ One source, `W/src/start/agent.md`, contains the following ordered directives. ` |
| - [ ] **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: Serve one /start URL as Markdown or HTML |
| +## Task 3: Build static HTML and Markdown from one source |
| -**Risk/review:** security gate (served-file boundary), cache and redirect behaviour, production serving path. Independent task review required. No root, billing or production-storage change; process termination is limited to the new website server and is reviewed here. |
| +**Risk/review:** build-time content only; whole-branch review. Plan A owns serving, cache, redirect and platform census review. |
| **Files:** |
| -- Create W `go.mod` (module `amadan.net/carlos/website`, Go `1.26.10`, standard library only), `assets.go`, `cmd/website/main.go`, `internal/site/{handler.go,negotiate.go,handler_test.go,negotiate_test.go}`, `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`, W `.gitignore`; remove W `src/start/index.html` after its replacement is covered. Keep passthrough copies for `start.css` and `start-tabs.js`; explicitly exclude the raw starter module and agent Markdown from Eleventy rendering. |
| +- 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. Produce `_site/start/index.html`, `_site/start/agent.md`, versioned starter archive/manifest/source files, and `_site/start/config.json` for the embedded server only. Consume Task 2's `renderAgent`; render its Markdown with HTML disabled and the existing Markdown-it dependency; code fences remain complete. Disabled builds produce only the account introduction and no anonymous guide/downloads. |
| -- `NewHandler(files fs.FS) (http.Handler, error)` receives `fs.Sub` of embedded `_site`, validates the config and required artifacts once, and never reads the working directory or network. `selectStartRepresentation(accept, userAgent string) (mediaType string, acceptable bool)` owns negotiation. `run(args []string) error` in `cmd/website` requires `--socket`; accepts `--db` for platform compatibility without opening it; uses no TCP listener and shuts down on SIGTERM within 5 seconds. Set `ReadHeaderTimeout=5s`, `IdleTimeout=60s`, `MaxHeaderBytes=32768`; allow GET/HEAD only, otherwise 405 with `Allow: GET, HEAD`. |
| -- Both `/start` and `/start/` return 200 directly. Explicit Markdown preference wins at quality ties with HTML. Honour media-range specificity and `q=0`; ignore malformed ranges, and return 406 if a nonempty Accept leaves neither representation acceptable. For absent/`*/*` Accept, known fetcher product tokens `Claude-User`, `ChatGPT-User`, `OAI-SearchBot`, `GPTBot`, `ClaudeBot` and `Perplexity-User` select Markdown (my call); no generic `bot`, `curl`, `Codex` or substring guessing. Explicit HTML preference wins over fetcher detection; otherwise browsers/unknown clients get HTML. Fetcher detection is a convenience, never authentication. |
| -- Responses set `Content-Type: text/markdown; charset=utf-8` or `text/html; charset=utf-8`, `Vary: Accept, User-Agent`, `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`. HEAD has GET's headers and no body. Direct `/start/agent.md` is Markdown with no negotiation and no-store. Negotiated pages have no shared ETag. No runtime API probes, cookies or token collection. |
| -- Remaining site paths serve only regular embedded build files, directory index pages and relative slash canonicalisation. No directory listing, arbitrary filesystem root, config/source repository exposure or Host-derived redirect. Immutable starter archives use `Cache-Control: public, max-age=31536000, immutable`; other files use `no-cache` with content-derived ETags. `/.well-known/agent-skills/` and docs Markdown remain accessible. Never serve `_headers`, `_redirects` or `start/config.json`; fail the build if rule files appear until their semantics are deliberately supported. Present tree has no such files. |
| +- `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 tests.** `TestStartNegotiation`: explicit Markdown/HTML, weighted lists, specificity, mixed case, `q=0`, malformed ranges, unknown agent, each pinned product token and an embedded-token impostor. `TestStartRepresentationIsolation`: alternating Markdown/HTML requests, HEAD and conditional requests retain correct media/body/header selection; responses remain no-store. `TestStartHTMLParity`: every directive, request example, limit, claim state and starter link in Markdown is present in the visible HTML section. `TestSiteFileBoundary`: traversal/encoded traversal/dotfiles/config/unknown directory refused, known docs/skills/assets served, relative slash redirect safe with hostile Host. `start-build.test.mjs`: one source for both outputs, off default, invalid origins refused, missing producer fixture refused and no secret fixtures shipped. Pin the key assertions as follows: |
| - |
| -```text |
| -TestStartNegotiation: Accept="text/markdown" => 200 Markdown; Accept="text/html" => 200 HTML |
| -TestStartNegotiation: Accept="text/markdown;q=0,text/html" + UA="Claude-User/1.0" => HTML |
| -TestStartNegotiation: Accept="text/markdown;q=0,text/html;q=0" => 406 |
| -TestStartNegotiation: Accept="*/*" + UA="Claude-User/1.0" => Markdown; UA="NotClaude-User/1.0" => HTML |
| -TestStartRepresentationIsolation: Vary includes Accept and User-Agent; Cache-Control == no-store; HEAD body bytes == 0 |
| -TestStartHTMLParity: renderedAgentSection == renderMarkdown(servedAgentMarkdown) |
| -``` |
| - |
| -- [ ] **Step 2: Observe failure.** `node --test test/start-build.test.mjs`; after the Go module skeleton exists, `go test ./internal/site -run 'Test(Start|Site)' -count=1`. Confirm absent handler/build integration fails, not an empty test selection. |
| -- [ ] **Step 3: Implement the interfaces.** First review all human `/start` copy, including the introduction, heading, metadata, clipboard labels and server diagnostics, from the copy table with Paul using the copy-review skill, and put approved bytes in `start-copy.json`. Use stdlib HTTP and embedded build bytes, no Node in production. Make `_site` the only embed input with the explicit `all:` pattern needed to include its underscore directory and `.well-known`; filter served paths as above. Strip build metadata from public output in the handler. Add `npm run build:server` to build site, cache-bust local assets with release version, then compile the Go server for the target architecture. Do not embed the repository or `copy-review` directory. |
| -- [ ] **Step 4: Verify.** Repeat the targeted tests; run `npm run check`, then compile and launch the new binary on a scratch Unix socket with both flags. GET `/`, both `/start` forms, `/docs/`, docs `.md`, skills index and an asset through that socket. Test SIGTERM completion. All checks run on the author/CI machine; remove socket/binary scratch afterward. |
| -- [ ] **Step 5: Commit.** After independent review, subject `feat: serve start instructions as Markdown and HTML`. |
| +- [ ] **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 |
| @@ -184,12 +171,12 @@ TestStartHTMLParity: renderedAgentSection == renderMarkdown(servedAgentMarkdown) |
| - [ ] **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 build-time content and binary serving exception accurately. These documentation changes use the copy-table review too. |
| +- [ ] **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 rollout; obtain a scoped independent check if rollout changes routing beyond Task 3's reviewed mechanism. No extra review round for test-only evidence. |
| +**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:** |
| @@ -199,15 +186,15 @@ TestStartHTMLParity: renderedAgentSection == renderMarkdown(servedAgentMarkdown) |
| **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 2/Plan 3 SHAs, 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. Binary and prior static rollback artifacts are retained until verification succeeds. |
| +- 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 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 current static dev site and record the expected negotiation/content failure. No test result may silently pass because a live case skipped. |
| -- [ ] **Step 2: Build and enable the dev release.** Discover the dev console/site destination through its documented console/CLI configuration, record it, and use the existing designated dev scope. Build the website binary with `CARLOS_START_DEMO=1` and the exact dev origins. Deploy it as a normal binary website instance outside the quarantined demo fleet. Rehearse switching the dev website's domain claim from its static route to the binary route through console/CLI, retaining the old route/channel and a reverse operation; never assume shipping a binary changes a static route's kind. If the existing designated scope lacks this website instance/route change, prepare the concrete scoped approval before executing it. Admission is the console drop-in, already live from Plan 1, not an ingress setting. |
| +- [ ] **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, `go build ./...`, `go vet ./...`, `go test ./... -count=1` for the small website module, its gofmt check, 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 producer dependencies merge, carrying the review history below. Follow the target repo's reviewed-branch landing policy and green tip CI. Publish the visible dev slice on landing. For the flagship, first record the actual console/account/region, all three current website hosts from W `AGENTS.md:199`, exact route/claim transitions to the verified binary instance, previous static channel/version, expected additional instance cost, traffic effect, duration, rollback and cleanup. Obtain the required scoped approval for that concrete migration; it is not authorised by this document. On approved public activation, use production origins, verify both representations and existing docs/skills on every hostname, and repeat the exact canonical paste-line check. Roll back domain routing and version on failure. Remove only acceptance apps/data and scratch created by this run, stop local processes, and retain dev activation as planned. Commit subject `test: verify the start journey on dev`. |
| +- [ ] **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 |
| @@ -221,17 +208,17 @@ This is an inventory of meanings and fixed literals, not approved shipping copy. |
| | `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.http.badRequest`, `start.http.notFound`, `start.http.notAcceptable`, `start.http.method`, `start.config.error` | New server errors, unsupported representation/method and operator configuration diagnostics; retain correct status codes without exposing local paths or configuration. | |
| -| `start.docs.product`, `start.docs.build`, `start.docs.deploy`, `start.docs.acceptance` | Website product/build/deploy documentation and human acceptance report, including the server exception, switch-on, rollback and observed limitations. Do not silently repair unrelated old README claims. | |
| +| `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. Tasks 1 and 3 need independent task reviews; other tasks are covered by one whole-branch 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 claim-dependent work against an unmerged Plan 3. These dependencies do not reset the count later. |
| +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. Website server rollout is included because static hosting cannot negotiate. 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. |
| +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. The merged Plan 3 wire contract, reviewed human copy, real harness witnesses and scoped flagship rollout approval are explicit execution gates, not unresolved design choices. |
| +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. |