plans: agent-start-demo plans 2-4 (Astra drafts, before simplification)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+905
−0
docs/superpowers/plans/2026-11-04-agent-start-demo-2-edge-protections.md+281 −0docs/superpowers/plans/2026-11-04-agent-start-demo-3-claim.md+387 −0docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md+237 −0
Intent
Attributed to this commit: 39.2 g CO₂e (4,757,943 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on agent-start-demo-plans, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/plans/2026-11-04-agent-start-demo-2-edge-protections.md b/docs/superpowers/plans/2026-11-04-agent-start-demo-2-edge-protections.md| new file mode 100644 |
| index 000000000..ec760a9a3 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-04-agent-start-demo-2-edge-protections.md |
| @@ -0,0 +1,281 @@ |
| +# Edge protections for demo hosts Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** Serve anonymous demos with a protected 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. |
| + |
| +**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. |
| + |
| +**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. |
| + |
| +## 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. |
| +- 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. |
| +- Dev facts, 2026-11-04: app launch takes `--socket` and `--db` flags; certificates come from the housekeeper, not ingress; demo boxes have 2 GB RAM and never compile tests; one `*.trycarlos.com` wildcard covers single-label names; admission is a console drop-in; public demo names are never reused (R19b); SQLite is local to its assigned box, with no replica. |
| +- Keep additive wire compatibility. Old boxes must not serve demos during activation. Do not assume an old edge understands a new switch. |
| +- Examples use `shop` and `example.com`. `trycarlos.com` is a deployment value, never a provider-specific core default. All proposed human-facing strings are in the one copy table below; implementation requires copy review. No em dashes in copy. |
| +- This authoring session changes only this document, with no product code, commits, pushes, agents or full test run. Commands and commits below are instructions for the later implementation session. |
| +- Tests and browser profiles run on a development machine, with disk scratch, normal Go caches, isolated credentials, and servers bound to loopback or the approved Tailscale address. Delete scratch and stop processes afterward. |
| +- Production/shared-account resource changes require separately scoped authorization. This document does not authorize them. |
| + |
| +## Review Focus |
| + |
| +1. 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. |
| + |
| +--- |
| + |
| +## Baseline evidence and file map |
| + |
| +Read against `2914921ceabd4218b0363a9780f8e4db890aab4c`. Line anchors below refer to that checkout. All new names and signatures below are proposed, not existing APIs. |
| + |
| +| Existing interface | Evidence and consequence | |
| +|---|---| |
| +| Demo identity | `internal/registry/demo.go:5`: `Route.IsDemo() bool` treats a partial descriptor as marked. `internal/edge/demo.go:18` recognizes a direct demo label without a route; `:27` validates lifetime, exact host, account and fleet; `:47` strips aliases/path overrides; `:81` refuses catch-all fallback. Keep those checks for the 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. | |
| +| 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. | |
| +| 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. | |
| +| 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. |
| + |
| +## Decisions and cross-task contracts |
| + |
| +### Banner containment (my call) |
| + |
| +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. |
| + |
| +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. |
| + |
| +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. |
| + |
| +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. |
| + |
| +`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. |
| + |
| +“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. |
| + |
| +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/). |
| + |
| +### Policy and representations (my call) |
| + |
| +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/). |
| + |
| +The exact common directives are: |
| + |
| +`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'` |
| + |
| +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. |
| + |
| +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. |
| + |
| +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. |
| + |
| +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. |
| + |
| +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. |
| + |
| +### Durable accounting and immediate stop (my call) |
| + |
| +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. |
| + |
| +## Task 1: Enforce demo response policy and safe fallback |
| + |
| +**Risk/review:** security gate, redirect, cache. Independent task review required. |
| + |
| +**Files:** Create `internal/edge/demo_response.go`, `internal/edge/demo_copy.go`; modify `internal/edge/demo.go:18`, `internal/edge/edge.go:1890`, `:3222`; test `internal/edge/demo_response_test.go` and existing `internal/edge/demo_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes `registry.Route.IsDemo() bool`, `(*Edge).demoHost(string) bool`, `(*Edge).demoReserved(string) bool` and `(*Edge).demoRouteOK(string, registry.Route) bool`. |
| +- Produces `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 `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 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 |
| + |
| +**Risk/review:** security gate, redirect. Independent task review required; browser evidence is required, not just string assertions. |
| + |
| +**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`. |
| + |
| +**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. |
| + |
| +- [ ] **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`. |
| + |
| +## Task 4: Enforce the ledger on the serving box |
| + |
| +**Risk/review:** security gate, cache, billing limits. Independent task review required. |
| + |
| +**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`. |
| + |
| +**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. |
| + |
| +- [ ] **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 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`. |
| + |
| +## Task 5: Add serving control and immediate 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. |
| + |
| +**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`. |
| + |
| +**Interfaces:** |
| +- Consumes `apiSystemRoller`, `cliRoute(..., svcrole.Set{}, ...)`, the ledger and Plan 1 signed retirement. |
| +- 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. |
| + |
| +- [ ] **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 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 |
| + |
| +**Risk/review:** security gate, storage, redirect. Independent task review required. |
| + |
| +**Files:** Create `internal/console/demo_reports.go`, `internal/console/apidemoreports.go`, `internal/console/templates/demo_report.html`; modify `internal/console/demo_store.go:51`/`:400`, `internal/console/apidemo.go:259`, `internal/console/authcli.go:1046`, `internal/edge/demo_banner.go`, `system_demos.go`, `system_demos_api.go`, `docs/site/cli.md`; test `internal/console/demo_reports_test.go`, `internal/edge/demo_banner_test.go`, `system_demos_test.go`. |
| + |
| +**Interfaces:** |
| +- Banner links directly to the configured console origin's `/demo/report?host=<canonical-app-host>` using `target="_blank" rel="noopener noreferrer"`; no token, path, query, referrer or email. GET shows a form and never files a report. |
| +- Produces `(*Store).AddDemoReport(ctx context.Context, host, category, details, ip string, now time.Time) (string, error)` and `(*Store).ListDemoReports(ctx context.Context, after string, limit int) ([]DemoReport, string, error)`. `DemoReport` has `ID, Host, Category, Details, State string; CreatedAt int64`; no reporter identity in list output. |
| +- `POST /demo/report` accepts form category `phishing|harmful|other`, details at most 1,000 UTF-8 bytes, host and CSRF token. Console-host `__Host-carlos-demo-report` random signed double-submit cookie: Secure, HttpOnly, SameSite=Strict, Path=/, 15-minute expiry; require exact console Origin and matching token. Body cap 4 KiB. Confirmation is a rendered 200, not a supplied redirect. |
| +- CLI: `carlos system demos reports [--after <id>] [--limit <1..100>]` and `reports resolve --id <id>`; corresponding operator-only GET `/api/cli/system/demos/reports` and POST `/api/cli/system/demos/reports/{id}/resolve`. Default page size 50, ordered by creation time then ID, stable cursor. |
| + |
| +- [ ] **Step 1: Write failing tests.** `TestDemoReportQueue`: GET prefetch writes nothing; valid POST creates one open row; current/purged-within-retention host accepted; unknown and too-old names refused uniformly; list/resolve human-operator-only and idempotent. `TestDemoReportAbuse`: forged Origin/CSRF, missing cookie, duplicate form values, foreign host, oversize input, HTML/control characters, forged XFF and queue exhaustion; no redirect/SSRF and no script execution in UI/terminal. `TestDemoReportRetention`: restart retains reports, seven-day post-purge pruning removes them and hashed reporter metadata, permanent name tombstone survives. `TestDemoReportWhileStopped`: reports work while serving/admission is off and never touch release.Store. Extend CLI subprocess tests with isolation. |
| +- [ ] **Step 2: Run** `go test ./internal/console ./internal/edge -run 'TestDemoReport' -count=1` and `go test . -run TestSystemDemosReports -count=1`; expect FAIL. |
| +- [ ] **Step 3: Implement** one `demo_reports` table: ID primary key, demo_id, host, category, details, created_at, state (`open|resolved`), resolved_at, resolved_by, ip_hash. Persist attempts in `demo_report_attempts(ip_hash, attempted_at)` using the existing installation salt and canonical clientIP; allow 10 attempts/IP/hour, 500 global/day, 20 accepted reports/host/day, 2,000 retained rows total. Spend attempts before validation; reject a full queue without evicting. No attachments, email, notifications or automatic takedown. Escape HTML and JSON; strip terminal control characters in CLI rendering. Use the existing expiry pass to prune attempts older than 24 hours and reports seven days after purge. Anonymous report routes do not consult logged-in account sessions. Supply banner URL only from validated operator configuration. |
| +- [ ] **Step 4: Rerun** Step 2 and docsite tests; expect PASS. Confirm limits are durable through console restart and listing never exposes claim tokens or reporter IP hashes. |
| +- [ ] **Step 5: Commit** with subject `feat: add a demo abuse report queue`. |
| + |
| +## Task 7: Prove the complete slice and prepare dev activation |
| + |
| +**Risk/review:** integration evidence; whole-branch independent review required. Census review required for every changed root-binary unit/envelope; this is not exemption for edge-only Go changes. |
| + |
| +**Files:** Create `internal/console/demo_protections_e2e_test.go`, `docs/superpowers/notes/agent-start-demo-2-rulings.md`, `docs/superpowers/notes/census-agent-start-demo-2-claims.md`; modify Task 2's `internal/edge/testdata/demo-protections/main.go`, `app.js` and `style.css` fixtures, `README.md` demo operator section, `internal/console/claim_invariant_test.go` `internal/console/store_gate.go:190`, `internal/console/claim_sql_census_test.go`, `internal/console/plan9_sql_seal_test.go` as required by their actual changed seams; generate `internal/provision/testdata/plan14-root-reads-agent-start-demo-2.tsv`, its chain entry, and `docs/superpowers/notes/census-proposal-agent-start-demo-2.md` using repository tools. Do not hand-edit seals to silence failures. |
| + |
| +**Interfaces:** Consumes all prior tasks. Leaves Plan 3 one narrow hook: 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. |
| + |
| +- [ ] **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 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 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. |
| + |
| +## 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. |
| + |
| +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. |
| + |
| +## 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. |
| + |
| +| 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-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-REPORT-TITLE | Console report form | Report a demo | |
| +| DEMO-REPORT-HOST | Read-only host field | Demo address | |
| +| DEMO-REPORT-CATEGORY | Form label and choices | Reason; Phishing; Harmful content; Other | |
| +| DEMO-REPORT-DETAILS | Textarea and hint | Details; Do not include passwords or personal information. | |
| +| DEMO-REPORT-SUBMIT | Form button | Send report | |
| +| DEMO-REPORT-SENT | Confirmation | Your report has been sent to the operator. | |
| +| DEMO-REPORT-REFUSED | Validation/CSRF error | This report could not be accepted. Reload the form and try again. | |
| +| DEMO-REPORT-BUSY | Rate/queue error | Reports are temporarily limited. Try again later. | |
| +| DEMO-CLI-HELP | Family help | Manage anonymous demos: status, serving on or off, takedown, takedown-status, reports. Commands use your configured console. | |
| +| DEMO-CLI-FLAGS | Flag help | Exact public demo hostname; Report ID; Continue after this report; Reports per page, from 1 to 100. | |
| +| DEMO-CLI-STATUS | CLI headers/state labels | Host; State; 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-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-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. | |
| + |
| +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. |
diff --git a/docs/superpowers/plans/2026-11-04-agent-start-demo-3-claim.md b/docs/superpowers/plans/2026-11-04-agent-start-demo-3-claim.md| new file mode 100644 |
| index 000000000..e7c0595b0 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-04-agent-start-demo-3-claim.md |
| @@ -0,0 +1,387 @@ |
| +# Claim a demo by email Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** Let a person keep an anonymous demo through email proof, receiving a permanent app with the same binary and SQLite data in an account they choose. |
| + |
| +**Architecture:** The console owns a durable claim operation, separate from email proof and from the demo's existing expiry clock. An authenticated worker freezes the assigned demo, exports its local database, and sends it to the console; normal provisioning starts a fresh account app through a gated seed. A durable commit consumes the token, opens the destination, and drives Plan 1 retirement while an independent moved notice lasts until the original expiry. |
| + |
| +**Tech Stack:** Go, console SQLite, existing email challenges and Keymail OAuth, Ed25519 work envelopes, the existing demo WebSocket, provider-neutral release stores, nested instances, SQLite seeds and the edge import gate. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-02-agent-start-demo-design.md`, especially §4.5 and §5; `docs/superpowers/specs/2026-10-21-console-email-signin-design.md`, including §15; `docs/superpowers/specs/2026-10-08-seeded-instances-design.md`. Read Plan 1 and `docs/superpowers/notes/agent-start-demo-1-rulings.md` as amended by the 2026-11-04 dev facts in the commissioning brief. |
| + |
| +## Global Constraints |
| + |
| +- “TTL: 24 hours, no extension without claiming.” Preserve the original `apps.expires_at`; proof, retries, copying and the moved page never extend it. |
| +- “The claim token is single-use and dies with the claim.” A failed pre-commit claim leaves it usable until expiry; successful commitment destroys its hash. |
| +- “The chosen account's plan limits apply, and the user must be allowed to create apps in it.” Reserve capacity before freezing the source; no plan upgrades, payment changes or extra free-account allowance. |
| +- “Keymail addresses finish in the browser.” Use sign-in discovery and OAuth, including its public-lookup fallback behavior; do not email a code to an address discovered as Keymail. |
| +- Provider-neutral core. Use `release.Store`, authenticated console HTTP and existing object layouts; no AWS SDK, presigned S3 upload or direct box administration in the claim flow. |
| +- No new per-box polling. Extend the existing demo stream and shared change watch; idle claims cause zero additional object-store requests. |
| +- Operator switch `CARLOS_DEMO_CLAIM=1`, unset by default. **Switch-on date: dev when this plan lands**, with capability checks and the acceptance witness complete. Console admission is configured in its drop-in. Production remains a separately scoped rollout. |
| +- The binary receives `--socket` and `--db` flags. Demo boxes have 2 GB RAM; build test binaries elsewhere, never compile tests on them. |
| +- The housekeeper issues certificates. Existing `*.trycarlos.com` covers all demo names; do not introduce `*.dev.trycarlos.com` or per-demo certificate issuance. |
| +- R19b: demo hosts are never reused. Keep the permanent host tombstone even after the moved notice expires. |
| +- Plan 1 SQLite is local-only on its assigned box. Never substitute an empty database, fetch a nonexistent replica, enable demo replication, or move the source to another box. |
| +- No agent account/deploy credential is issued. The normal CLI login is the next workflow. Copy remains subject to the single table below; no em dashes or real tenant names in new examples. |
| +- One implementation branch and one visible merge: successful email-to-permanent-app claim. All eight task commits land together; no separate scaffolding merge. This authoring session writes only this plan, with no commits, push, deployment, full suite or subagents. |
| + |
| +## Review Focus |
| + |
| +1. A code for another demo, another flow or an older email must grant nothing, including when two verifies race. Task 1: `TestDemoClaimProofBinding`. |
| +2. Multiple memberships, a removed membership, and a concurrent ordinary create must not silently select an account or overbook its plan. Task 2: `TestDemoClaimAccountRace`. |
| +3. A stopped process with committed data still in WAL, or an agent restart during export, must preserve the data and keep the source fenced. Task 3: `TestDemoClaimSnapshotWAL` and `TestDemoClaimFreezeRecovery`. |
| +4. Console failure between opening the destination and retiring the source must never resume two independently writable apps. Task 5: `TestDemoClaimCommitRecovery`. |
| +5. A cached old demo response, forged destination URL, or browser returning under a different Keymail identity must not disclose data or cause an unintended claim. Tasks 6 and 7: `TestDemoMovedPrecedesCache` and `TestDemoClaimBrowserIdentity`. |
| + |
| +--- |
| + |
| +## Existing interfaces and boundaries |
| + |
| +Read against main checkout `2914921ceabd4218b0363a9780f8e4db890aab4c`. These are existing-code anchors; interfaces introduced below are proposals. Plan 2 has not landed in this checkout. Do not review against its unmerged implementation; Task 6 supplies the minimum hook here. |
| + |
| +| Existing mechanism | Evidence and consequence | |
| +|---|---| |
| +| Plan 1 extension points | `docs/superpowers/plans/2026-11-02-agent-start-demo-1-anonymous-apps.md:88`: token lookup, lifecycle lock, reserved fragment link and local-only SQLite. R13 and R19 replace the original plan's root-policy assumptions; R19b prohibits host reuse (`docs/superpowers/notes/agent-start-demo-1-rulings.md:37`, `:56`, `:27`). R15 (`:21`) permits a self-inflicted init-marker case; claim export never treats that marker as proof of a database. | |
| +| Token and lifecycle | `internal/console/demo_store.go:292`, `:323`, `:364`: strict 32-byte token decode, constant-time comparison, live anonymous predicate and app mutex. `:58` has a SQL CHECK permitting only anonymous/retiring/retired. Keep those states; put transfer phases in a separate table. | |
| +| Existing claim response | `internal/console/apidemo.go:259`, `:439`: `/demo/claim` is a 503 stub and create returns `claimAvailable:false`. Extend these without changing publish/status field names. | |
| +| Email discovery | `internal/console/emailsignin.go:90`, `:104`, `:124`, `:132`; `internal/console/server.go:3789`, `:3854`: canonical address, public Keymail discovery, mail readiness, async send and flow serialization. Discovery is not a membership lookup. | |
| +| Proof and limits | `internal/console/emailsignin_store.go:29`, `:101`, `:133`, `:156`, `:299`: purpose-bound challenges, held unsent challenge, destructive successful take, process-key code MAC. `internal/console/emailsignin_limits.go:18`, `:230`, `:313`: shared send/guess budgets. | |
| +| Identity and browser login | `internal/console/emailsignin.go:258` resolves a sign-in method, opens a session and calls current-account landing; `internal/console/server.go:3087` uses MRU before minting. Agent proof must reuse identity resolution without calling this session/landing wrapper. Keymail OAuth starts at `internal/console/server.go:3889`; `safeNext` is `internal/console/emailsignin.go:240`. | |
| +| Account authorization | `internal/console/store.go:1375` lists memberships. `internal/console/apicli.go:228`, `:381` admits a person through membership for ordinary create; ordinary members as well as owners can create. `internal/console/server.go:3145` mints an account; it does not itself enforce the free-account cap. | |
| +| Plans and locks | `internal/console/plancaps.go:106`, `:167`, `:230`, `:277`, `:310`: running things count apps plus instance records, free-account check, account/person locking. `internal/console/apicli.go:505` holds the account lock through count and create. A claim creates two counted things, not one. | |
| +| Fresh permanent app | `internal/console/server.go:5417` `claimAppWith` refuses demo placement, adopts only when permitted, and uses zero expiry for permanent apps. Use `ownerClaim=false`. `internal/console/regionclaim.go:105` resolves normal region; `internal/console/apiinstances.go:1806` inherits it. `internal/console/apex.go:31` derives `<app>.<sqid>.<AppsDomain>`. | |
| +| Artifact publication | `internal/console/demo_publish.go:38`, `:131`, `:140`: demo version, `release.ShipSpooled`, signed promotion. `:228` checks exact-host readiness. Copy and verify the selected artifact into the destination namespace; do not repoint the demo manifest or rebuild source. | |
| +| Assigned source and transport | `internal/console/demo_publish.go:193` records FleetBox; `internal/console/apidemobox.go:93`, `:191` authenticate workers and replay work. `internal/demobuild/job.go:139`, `:160` define readiness and stream envelopes; `internal/host/demo_jobs.go:335` reconnects. | |
| +| Local data and stop | `internal/activator/demo_durability.go:36`, `:110` retain the lease without replication and refuse lost established data. `internal/activator/maintenance.go:105` provides owner-bound `FenceAndStopAs`; `internal/activator/activator.go:6044` provides `Quiesced`; `internal/activator/maintenance.go:244` lifts only its own fence. In-memory fences alone do not survive restart. | |
| +| Root start and retirement | `internal/instancectl/demo_policy.go:20` already refuses starts on held demo rows under `lockDemo`; `internal/instancectl/demo_cleanup.go:77` validates binding and proves stop before deletion. `internal/host/demo_cleanup.go:20` verifies a receipt and current object before acting. Reuse that trust split, not a new root reader of tenant SQLite. | |
| +| Offline move does not fit | `internal/host/movesoffline.go:92`, `:387`, `:822` supply hold/fence precedents. `internal/host/movesoffline_seal.go:307` seals a replica-based move of the same instance. This claim changes account and host and has no replica; do not invoke the move state machine. | |
| +| Seeds partly fit | `internal/console/apiinstanceseed.go:257` restores from a replica and `:563` refuses demo sources. `internal/provision/seedswap.go:74` requires an existing address route for import. Neither public door can perform this claim. Reuse snapshot keys (`internal/seeds/seeds.go:121`), bounded scratch (`internal/console/seedscratch.go:86`), create-only snapshot upload (`internal/console/apiinstanceimport.go:659`), first-wake restore (`internal/activator/seedplace.go:99`) and first replica confirmation (`:531`). | |
| +| Seed restrictions and gate | `internal/console/seedfloor.go:35`, `internal/console/apiinstanceseed.go:114`, `internal/console/apiinstanceimport.go:131`: seed capability floor, normal hosted placement and data residency. `internal/edge/importgate.go:12`, `:34` gates before cache/wake and strips `Carlos-Import-Verify`. A fresh claim seed needs its own kind, not a fake legacy route or replica TXID. | |
| +| Safe database primitives | `internal/instancefs/instancefs_linux.go:84`, `:138` open beneath a directory without following symlinks. `internal/lease/check.go:44`, `:202` integrity-check and checkpoint SQLite. Use these on a private copied DB/WAL, never run SQLite as root on source data. | |
| +| Retirement is currently time-only | `internal/console/demo_expiry.go:76`, `:92`, `:125`, `:174`, `:241`: early calls are no-ops; retirement fences jobs and token, trashes, waits for cleanup acknowledgment, purges, preserves host tombstones. Extract a reasoned retirement entry point; do not falsify expiry to trigger it. | |
| +| Routing and cheap refresh | `internal/edge/demo.go:18`, `:27`, `:81` validate exact demo hosts independently of routes. `internal/edge/edge.go:1890` is the request entry. `internal/release/changeindex.go:50` enumerates indexed scopes; `internal/host/changeindex.go:55`, `:180` share a watch and distinguish control scopes. `internal/console/demo_jobs.go:371`, `:447` own recovery/backstop work. | |
| +| Binary flags | `internal/activator/backend_exec.go:2530`, `:2733` pass `--socket` and `--db`. The 2026-11-04 commissioning facts override older fixture descriptions using environment variables. | |
| + |
| +## Decisions and protocol |
| + |
| +Eight tasks, one branch. All additional choices in this section are **my call**. |
| + |
| +### Authentication and account choice |
| + |
| +`POST /api/demo/claims` accepts `{claimToken,email,flowToken?}`. It returns `202 {state:"email_required",flowToken,expiresAt}` for every valid email-bound send outcome, including throttled/unsent challenges. A Keymail discovery returns `200 {state:"browser_required",claimUrl}` with the original `/demo/claim#token` link, no flow credential or account list. No-mailer returns 503 before send-limit decisions. Invalid demo tokens use the existing uniform token refusal. |
| + |
| +`POST /api/demo/claims/verify` accepts `{flowToken,code}`. `POST /api/demo/claims/select` accepts `{flowToken,accountId}`. A successful verify resolves the person through `ResolveSignIn(MethodEmail, provedAddress, now)` without issuing a console session or CLI token. Zero memberships: take the person lock, reread, check `checkNewFreeAccount`, and mint one personal account. One membership: choose it. Several: return `200 {state:"account_required",accounts:[{id,name,role}]}` and wait for an exact sqid. Never use MRU, silently filter to one permissible account, or accept an account name as identity. Recheck membership/role, account liveness and caps at reservation and commitment. Unknown/foreign account IDs have the same 404. |
| + |
| +`GET /api/demo/claims/status` uses `Authorization: Bearer <flowToken>`. After proof this capability authorizes only that demo's account selection, one claim attempt and its result. It grants no account enumeration beyond the verified person's membership choices, no deploy, no general API session and no database download. Return `202 {state:"claiming",phase,retryAfter:2}` while working and `200 {state:"claimed",accountId,app,url,next:"cli_login"}` only after public readiness and durable retirement initiation. All responses are `no-store`; secrets never enter URLs, logs or error payloads. This narrowly bounded continuation is not a post-claim account credential. |
| + |
| +`flowToken` is 32 random bytes, base64url; only its SHA-256 is stored. Its proof/selection lifetime is `min(now+15 minutes, demo expiry)`, not extended on resend. Its post-reservation use is status-only; the result is readable until original demo expiry plus 24 hours, then erased. Losing it means repeat email proof while anonymous, or use normal account login after success. Starting a second email flow does not cancel an already reserved transfer. Code proof alone never freezes a demo with several memberships. |
| + |
| +### Transfer and commit |
| + |
| +Keep `demo_apps.state` unchanged. Add `demo_claim_flows` for proof binding and `demo_claim_ops` for durable work, with a unique active operation per demo. Operation IDs use `demobuild.NewJobID()` and its validation, independently of all bearer tokens. Bind every operation to demo ID, original lifetime/expiry, source generation, assigned box, selected binary digest/version, verified person, destination account/name/host/lifetime, seed ID, phase and deadline. Destination identity is immutable once reserved. Retain unfinished operations until resolved; prune terminal operation metadata seven days after source purge, with the flow capability erased on its shorter schedule. |
| + |
| +| Phase | Durable effect and recovery rule | |
| +|---|---| |
| +| `reserved` | Fresh permanent app and reserved seed record count against normal caps. No public destination or source pause yet. Reject updates/new claims through a claim-operation guard shared with enqueue, publication and expiry. | |
| +| `freezing` | Signed command requests a hold on the assigned source. A durable record hold plus local hold blocks every wake, adoption and generation restart; root proves all instance cgroups empty. | |
| +| `copying` | Source remains held. Copy DB and WAL into private scratch, checkpoint that copy, integrity-check and stream one bounded snapshot to the console. No source file is altered or deleted. | |
| +| `verifying` | The same artifact is shipped/promoted under the new app. A fresh `demo-claim` seed starts normally but its edge traffic gate admits only the console's verify GET. Wait for `placed` and the destination's own first replica. | |
| +| `committed` | In one console transaction consume the demo token, record the irreversible decision and enqueue destination gate opening, moved publication and reasoned retirement. Never resume the source from this phase. Replay side effects on restart. | |
| +| `done` | Destination gate is open, exact-host GET is 2xx with the pinned version, and Plan 1's retirement receipt is durable. Clear the destination's pending-operation marker so all normal account operations work. Source cleanup acknowledgment may still be pending. | |
| +| `aborting` / `aborted` | Only before commitment. Close/abort destination seed, prove destination stopped and remove only operation-owned records/data; then release the source hold if unexpired and not independently retired. An ambiguous stop keeps the hold and reports recovery pending. | |
| + |
| +Lock order: person lock for mint only; account locks in sorted sqid order; app locks in sorted `(sqid,app)` order; hostname locks last. Release locks during transfer/network waits. Reacquire and reread generation, life, membership, reservation and phase before each write. `withDemoLocked` remains the anonymous entry gate; recovery gets a separate operation-aware lock helper, since its existing live predicate is false after commit. |
| + |
| +Normal destination name starts with `d.Name`, without `tmp-demo-`. If occupied, try `<d.Name>-<8 lowercase hex characters of SHA256(operationID || attempt)>`, attempts 1 through 16, checked by the normal fresh-name machinery. Never adopt an existing prefix, overwrite an app or accept a destination URL from the client. Use configured `AppsDomain` (`oncarlos.com` on the public deployment), normal region choice and normal size/egress/replication defaults; no Demo descriptor, fleet placement or source secrets are copied. |
| + |
| +The initial implementation supports the existing seed-supported normal hosted placement: nested linux-arm64, claims mode off, non-HA, and the console's data region. Run normal placement first; an incompatible result is a clear refusal **before** source freeze, not a forced demo-fleet placement or an instruction to move data manually. The new fresh seed does not inherit legacy import's one-box restriction. Add a capability floor for its readers before emitting the new kind. Cross-region seed delivery and HA seed support remain outside this plan; do not silently change the account's normal placement to hide their absence. |
| + |
| +Bound the operation to five minutes from reservation and no later than original demo expiry. Stop proof gets 30 seconds, snapshot/check/upload 120 seconds, destination readiness 60 seconds, all within that overall deadline. Source DB plus WAL and the final snapshot each cap at 268,435,456 bytes (256 MiB); reject oversized data with its reason. Reserve at most 768 MiB disk scratch per transfer and 256 MiB helper memory; one export per demo box, serialized with its build slot. No byte buffering proportional to the database. Small-app acceptance aims for under one minute; the five-minute bound is a failure bound, not a success claim. |
| + |
| +Deadline expiry before commit initiates abort; source expiry still wins. Deadline expiry after commit never undoes ownership or resumes the source: finish opening/retiring through recovery. A disconnected worker cannot self-release a hold when its deadline passes. Transport retry never grants authority; the console's latest operation decision does. |
| + |
| +## Task map |
| + |
| +| Task | Responsibility | Main new files | |
| +|---|---|---| |
| +| 1 | Email proof and claim-only continuation | `internal/console/demo_claim_auth.go`, `demo_claim_store.go` | |
| +| 2 | Account selection, caps and fresh destination reservation | `internal/console/demo_claim_target.go` | |
| +| 3 | Signed work, durable freeze and local SQLite export | `internal/democlaim/work.go`, `internal/host/demo_claim.go`, `internal/instancectl/demo_claim.go`, `internal/democlaim/snapshot.go` | |
| +| 4 | A gated fresh seed through normal provisioning | `internal/provision/demo_claim_seed.go` | |
| +| 5 | Artifact copy, coordinator, commit, abort and retirement | `internal/console/demo_claim_transfer.go` | |
| +| 6 | Moved notice independent of source app records | `internal/democlaim/moved.go`, `internal/host/demo_moved.go`, `internal/edge/demo_moved.go` | |
| +| 7 | Browser fallback and Keymail return | `internal/console/demo_claim_page.go`, `internal/console/templates/demo_claim.html`, `internal/console/static/demo_claim.js` | |
| +| 8 | Integration proof, copy and activation | `internal/console/demo_claim_e2e_test.go`, `internal/host/demo_claim_dev_linux_test.go` | |
| + |
| +### Task 1: Bind email proof to one demo |
| + |
| +**Risk/review:** security gate and storage. Independent task review required. Console-only files are outside root census scope. |
| + |
| +**Files:** |
| +- Create: `internal/console/demo_claim_auth.go`, `internal/console/demo_claim_store.go`. |
| +- Modify: `internal/console/emailsignin_store.go:101`, `internal/console/emailsignin.go:317`, `internal/console/apidemo.go:259`, `internal/console/demo_store.go:51`, `internal/console/server.go:3854`. |
| +- Test: `internal/console/demo_claim_auth_test.go`, `internal/console/demo_claim_store_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: `LookupDemoToken`, `withDemoLocked`, `canonicalAddress`, `keymailAddress`, `mailReady`, `sendChallengeAsync`, `ResolveSignIn`, `LiveEmailChallenge`, `TakeEmailCode` and the shared `emailLimits` object. |
| +- Produces: `const ChallengeDemoClaim = "demo-claim"`; bind this purpose by `flow_hash`, independently of signin/stepup. |
| +- Produces: `claimFlow` with `Hash, DemoID, Lifetime, Address, Person, Method string; Generation int64; ExpiresAt time.Time`; `(*Store).demoClaimFlow(ctx context.Context, raw string, now time.Time) (claimFlow, error)`. |
| +- Produces: `(*Server).handleDemoClaimStart`, `handleDemoClaimVerify`, `handleDemoClaimSelect`, `handleDemoClaimStatus`, each `(w http.ResponseWriter, r *http.Request)`; selection/reservation delegates to Task 2 and returns unavailable until wired. |
| +- Produces: `(*Server).proveDemoClaim(ctx context.Context, flow claimFlow, method, address, ip string, now time.Time) (claimFlow, error)` for email and Task 7's authenticated browser path. It records only canonical resolved person/method, not a caller-supplied person ID. |
| + |
| +- [ ] **Step 1: Write failing tests with these assertions.** |
| + |
| +```text |
| +TestDemoClaimProofBinding: otherDemo/otherFlow/signinCode/stepupCode/oldResend => noProof; concurrentVerify => oneProof; expiresAt <= min(start+15m,demoExpiry) |
| +TestDemoClaimEmailPrivacy: sent/throttled/unknownEmail => sameStatusAndShape; noMailer => 503BeforeSendLimit; KeymailHost => zeroSMTP; publicLookupFailure => emailAsSignin |
| +TestDemoClaimSharedLimits: submit=30/IP/hour; sends=5/address/hour,20/address/day,10/IP/hour,200/global/hour; gap=60s; badCodes=5/challenge,10/address/day,30/IP/hour |
| +TestDemoClaimCodeRestart: oldCode => refused; freshResend => works; plaintextCode/token absentFromSQLAndLogs; noSessionOrCLICredentialIssued |
| +``` |
| + |
| +- [ ] **Step 2: Run** `go test ./internal/console -run 'TestDemoClaim(Proof|Email|Shared|Code)' -count=1`; expect missing handlers or failed assertions. |
| +- [ ] **Step 3: Implement the interfaces and protocol above.** Strict JSON, 4 KiB body, no duplicate/unknown fields, no cookies as authority on agent endpoints, same-origin rejection when browser headers are present, no permissive CORS. Additive migration only. Resend uses the supplied flow and cannot rebind it to another demo/email. Share send/guess limits with ordinary sign-in so changing doors buys no extra allowance. Preserve unsent-challenge behavior. Reuse the process-key MAC and atomic consume logic; a crash after consuming proof may require a new email, but cannot grant authority. Count new people through `PersonWouldBeNew` and `limits.newPerson`. Email link redemption gets a dedicated purpose dispatch: GET never spends; POST requires the existing nonce/origin protection and records claim proof without falling into `finishSignin`. |
| +- [ ] **Step 4: Rerun Step 2**, plus `go test ./internal/console -run 'TestEmail' -count=1`; expect PASS and unchanged ordinary sign-in/step-up behavior. |
| +- [ ] **Step 5: Commit** the task files with subject `feat: bind demo claims to email proof`. |
| + |
| +### Task 2: Choose and reserve the permanent destination |
| + |
| +**Risk/review:** security gate, billing and production storage. Independent task review required. |
| + |
| +**Files:** |
| +- Create: `internal/console/demo_claim_target.go`. |
| +- Modify: `internal/console/demo_claim_store.go` (Task 1), `internal/console/store.go:1865`, `internal/console/plancaps.go:106`, `internal/console/server.go:5417`, `internal/console/apicli.go:228`, `internal/console/apiinstances.go:1806`. |
| +- Test: `internal/console/demo_claim_target_test.go`, `internal/console/demo_claim_caps_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: `claimTarget` with `AccountID int64; Sqid, App, Host, Lifetime, Region, SeedID string`; `(*Server).chooseDemoClaimAccount(ctx context.Context, f claimFlow, selected string) (*Account, []Account, error)`. |
| +- Produces: `(*Server).reserveDemoClaim(ctx context.Context, f claimFlow, acct *Account, rq regionReq) (claimOp, error)`; `claimOp` holds the durable fields in Transfer and commit, with `ID, FlowHash, DemoID, SourceLifetime, SourceBox, Person, Version, ArtifactSHA256, Phase string; Generation int64; Target claimTarget; Deadline time.Time`. |
| +- Produces: `(*Server).demoClaimMutationRefusal(ctx context.Context, accountID int64, app string) *doorRefusal`; only the operation-owned internal context may mutate an unfinished destination. Reuse this check at person and service mutation gates, browser writes and internal lifecycle writers. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestDemoClaimAccounts: 0 => onePersonalAccount; 1 => thatAccount; 2 => listAndNoAppUntilExactChoice; MRU => ignored; owner/member => normalCreatePermission; foreign/deleted => identical404 |
| +TestDemoClaimAccountRace: memberRemovedAfterProof => refused; ordinaryCreateRacingClaim => totalWithinCap; duplicateClaimsSamePerson => oneNewPersonalAccount; sameDemoTwoPeople => oneReservation |
| +TestDemoClaimReservation: appPlusInstance == 2RunningThings; cap/freeAccount/placementRefusal => sourceStillServingAndTokenUsable; takenName => freshSuffix; ownerAdoption == false |
| +TestDemoClaimTargetIsolation: ordinaryShip/promote/delete/seed/run/serviceToken => cannotMutatePendingTarget; retryAfterPartialReservation => sameTargetAndNoDoubleCharge |
| +``` |
| + |
| +- [ ] **Step 2: Run** `go test ./internal/console -run 'TestDemoClaim(Accounts|AccountRace|Reservation|TargetIsolation)' -count=1`; expect FAIL. |
| +- [ ] **Step 3: Implement account choice and reservation.** Extract the normal fresh-create validation into callable helpers without weakening the ordinary doors. Check `checkRunningThings(ctx, acct, 2)` under the account lock. Record a reservation before external writes; count outstanding claim reservations in the same plan counting function used by normal creates, subtracting each app/instance only when its durable row/record is already counted. A partial failure retains its reservation until confirmed cleanup; do not decrement merely because a request failed. Use normal lifetime enrollment, apex protection, default pipeline and region selection. Persist a destination `demo_claim_op` marker in the same row insert, not afterward, and close every mutation door while pending. Require the new source/destination/edge capabilities before freezing. A refused plan or placement returns a safe reason and leaves the demo running. |
| +- [ ] **Step 4: Rerun Step 2**, then targeted existing `TestPlan`/`TestAPICreateApp` tests in console; expect PASS with plans enabled and disabled. |
| +- [ ] **Step 5: Commit** with subject `feat: reserve account capacity for demo claims`. |
| + |
| +### Task 3: Freeze and export the assigned demo's local database |
| + |
| +**Risk/review:** security gate, root, termination and storage. Independent task review and root census required. |
| + |
| +**Files:** |
| +- Create: `internal/democlaim/work.go`, `internal/democlaim/snapshot.go`, `internal/host/demo_claim.go`, `internal/instancectl/demo_claim.go`, `internal/host/units/carlos-demo-snapshot@.service`. |
| +- Modify: `main.go:20` (private worker dispatch), `internal/host/bootstrap.go` (embedded unit installation), `internal/demobuild/job.go:139`, `:160`, `internal/console/apidemobox.go:191`, `internal/host/demo_jobs.go:335`, `internal/host/agent.go:988`, `internal/instancectl/demo_policy.go:20`, `internal/instancectl/server.go:474`, `internal/provision/provision.go:125`, `internal/provision/reconcile.go:118`. |
| +- Test: `internal/democlaim/work_test.go`, `internal/democlaim/snapshot_test.go`, `internal/host/demo_claim_test.go`, `internal/instancectl/demo_claim_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: `democlaim.Work {ID string; Demo demo.Descriptor; Account, App, Fleet, Box string; Generation uint64; Action string; Deadline time.Time}`; Action is exactly `freeze`, `export` or `abort`. Sign/verify with Ed25519 and separator `carlos demo claim work v1\n`: `SignWork(priv ed25519.PrivateKey, w Work) ([]byte,error)` and `VerifyWork(pub ed25519.PublicKey, wire []byte, now time.Time) (Work,error)`. Freeze/export deadlines cannot exceed demo expiry; an abort gets a fresh 30-second delivery deadline even after expiry, but may never resume an expired demo. |
| +- Produces: `(*demoWorker).claimDemo(ctx context.Context, wire []byte) error`; `(*instancectl.Client).FreezeDemo(ctx context.Context, d demo.Descriptor, operationID string) error` over `POST /demo-freeze` on the existing control socket. |
| +- Produces: `democlaim.ExportSQLite(ctx context.Context, dbDir, dbBase, scratchDir string) (Snapshot,error)`; `Snapshot {Path, SHA256 string; Bytes int64}`. All paths are derived locally, never wire parameters; Path never leaves the box. |
| +- Produces: `(*instancectl.Client).SnapshotDemo(ctx context.Context, d demo.Descriptor, operationID string, db io.Reader, dbBytes int64, wal io.Reader, walBytes int64) (io.ReadCloser,error)` on `POST /demo-snapshot`; fixed multipart fields carry bytes and lengths, never filenames. The response streams the checked snapshot. `democlaim.RunSnapshotWorker(ctx context.Context) error` handles private `__demo-snapshot` dispatch, like `__registry-child` at `main.go:36`, outside the public command switch. |
| +- Adds optional `provision.Record.DemoClaim *democlaim.Hold`, with `ID string; Generation uint64`; this is a console-owned source hold, not ownership-transfer authority. Ordinary writers preserve it and cannot set or clear it. A hold carries no auto-resume time. |
| +- Adds `StreamMessage.Claim []byte` and `WorkerReady.ClaimCapability string`, value `anonymous-demo-claim-v1`; old workers remain valid for builds but cannot receive claim work. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestDemoClaimWorkBinding: wrongBox/fleet/lifetime/generation/signature/action => noEffect; replayCurrent => sameOperation; replayAborted => cannotFreezeAgain |
| +TestDemoClaimSnapshotWAL: committedWALOnlyRow => inSnapshot; DBAndWALSourceHashes => unchanged; missingDBEvenWithPendingMarker/symlink/hardlink/nonregular/corrupt/over256MiB => refused; noEmptyFallback |
| +TestDemoClaimFreezeRecovery: wake/update/adopt/generationStartDuringHold => refused; restartBeforeAck => heldAndStopReproved; otherHold => untouched; unprovenStop => zeroDataReads |
| +TestDemoClaimExportBounded: oneExportPerBox; helperMemory<=256MiB; scratch<=768MiB; elapsed<=120s; credentialsAndSiblingData => inaccessible; cancel => noHelperOrScratch |
| +``` |
| + |
| +- [ ] **Step 2: Run** `go test ./internal/democlaim ./internal/host ./internal/instancectl -run 'TestDemoClaim(Work|Snapshot|Freeze|Export)' -count=1`; expect FAIL. |
| +- [ ] **Step 3: Implement the source protocol.** Verify signed work in the agent, then confirm its current operation through an authenticated console pickup before executing, so a signed stale abort/freeze cannot win after commit. Install the persistent source hold before fencing; restore holds before serving or reconciling on startup, including newly minted routes. Use `FenceAndStopAs` with owner `demo-claim/<operationID>` and matching generation; root's fixed freeze verb reuses the stop/cgroup proof from purge without deleting files. The freeze verb receives identity only; neither root door reads the source DB or accepts a path, argv or mount instruction. Root start gates must retain the hold for every covered binary generation. A false `Quiesced` or unknown cgroup state prevents export. |
| + |
| + The agent opens only the derived DB and optional WAL through no-follow descriptors after stop proof; reject multiple hardlinks and changing inode/size. Stream them into the fixed snapshot door. Root rechecks the exact held demo/operation, accepts only bounded bytes, and writes fixed names under root-created `/var/lib/carlos-demo-snapshots/<operationID>/`; it never opens an agent-supplied source path. SHM is transient and is recreated in this private scratch. The unit runs the shipped binary's private worker as a dynamic UID with only that scratch writable, no network/credentials/sibling data, `MemoryMax=268435456`, `MemorySwapMax=0`, `CPUQuota=50%`, `TasksMax=32`, `RuntimeMaxSec=120`, `TimeoutStopSec=5`, and `KillMode=control-group`. Reserve/enforce the 768 MiB disk budget before accepting input. The helper checkpoints the private copy with `lease.TruncateWAL`, runs `lease.CheckDBContext`, and hashes its completed DB. Serialize it with the builder slot; kill/reap before returning or cleaning scratch, including restart recovery. Upload its response by streaming to the console, never granting the demo box destination-account store permissions. An abort can lift only this operation's hold after the console proves destination rollback; retirement replaces the hold through the existing retirement path. |
| +- [ ] **Step 4: Rerun Step 2**, plus existing demo durability/cleanup tests. Run the actual cgroup/no-follow witness only using prebuilt binaries in the explicitly approved dev scope; a skip is not proof. |
| +- [ ] **Step 5: Commit** with subject `feat: freeze demo data for a bounded claim export`. |
| + |
| +### Task 4: Start a fresh normal app from a gated claim seed |
| + |
| +**Risk/review:** security gate, storage, root-linked provisioning and termination. Independent task review and census required. |
| + |
| +**Files:** |
| +- Create: `internal/provision/demo_claim_seed.go`. |
| +- Modify: `internal/seeds/seeds.go:23`, `internal/seeds/row.go:11`, `internal/provision/seed.go:16`, `internal/provision/reconcile.go`, `internal/provision/forward.go`, `internal/activator/seedplace.go:84`, `:99`, `:531`, `internal/console/seedfinish.go:60`, `internal/console/seedsweep.go`, `internal/edge/importgate.go:34`, `internal/host/edgesfile.go`, `internal/status/snapshot.go` (capability publication). |
| +- Test: `internal/provision/demo_claim_seed_test.go`, `internal/activator/demo_claim_seed_test.go`, `internal/edge/demo_claim_seed_test.go`, `internal/console/demo_claim_seed_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: `const seeds.KindDemoClaim = "demo-claim"`; optional `SeedSource.ClaimID string`. States: `reserving -> ready -> placed -> committed`; `aborted` allowed before committed. No `Replaces`, replica `From`, TXID or swap journal. |
| +- Produces: `provision.SeedPublishDemoClaim(id, claimID, sha string, bytes int64, verifyHash string) func(*Record) error` and `provision.SeedCommitDemoClaim(id, claimID string) func(*Record) error`, both CAS transitions through `SetRecordSeed`. |
| +- Consumes: existing seed snapshots, restore, leases, first replica confirmation, `ImportGate` and its verify header. New seed kind remains a permanent ordinary destination after commit. |
| +- Produces: destination and ingress capability `demo-claim-seed-v1` through existing status/edges-file publication, checked alongside `seedRegionReady(ctx, region, false)`; include current and rollback binaries in activation readiness. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestDemoClaimFreshSeed: noExistingRoute => normalNestedInstance; demoDescriptor/fleet/replaces/fakeTXID => refused; concurrentWake => oneLease; missingSnapshot => neverEmpty |
| +TestDemoClaimSeedGate: GETWithoutToken/POST/alias/pathRoute/run/schedule => blocked; verifyGET => snapshotThenApp; token => stripped; placedRequiresOwnReplica == true |
| +TestDemoClaimSeedCommit: committed => ordinaryReplicationAndWake; oldReaders => admissionRefused; rollback/retry => deletesOnlyMatchingSeedAndLifetime; ordinaryReplicaAndImport => unchanged |
| +``` |
| + |
| +- [ ] **Step 2: Run** `go test ./internal/provision ./internal/activator ./internal/edge ./internal/console -run 'TestDemoClaim(FreshSeed|SeedGate|SeedCommit)' -count=1`; expect FAIL. |
| +- [ ] **Step 3: Implement the new kind as a fresh seed, not an import takeover.** Enumerate every parser/validator/serializer of `SeedSource` and `RowSeed`, including forwarding, run/schedule blockers, expiry, sweep, CLI rendering and fingerprints; update their closed switches and tests. Absent optional fields keep old wire bytes/fingerprints unchanged. Mint the route with its gate in the same registry transaction; no interval with an ungated empty destination. Use the replica seed's first-wake placement and lease path but require claim commitment before removing the gate. Aborting a fresh claim seed must fence/stop its destination, prove the cgroup empty, then remove only matching seed-marked data and the matching lifetime/record; no legacy row is restored. Retain the seed's own replica after commitment and delete the temporary snapshot through existing placement cleanup. The console alone keeps the verify token; derive it by HMAC-SHA256 of `carlos demo claim verify v1\n` plus operation ID under the configured console signing-key seed, and persist only the matching hash. A changed signing key before commit forces safe abort/reproof, never gate bypass. Preserve normal seeds' compatibility and all unsupported placement refusals; a claim kind must never enter legacy import swap/rollback code. |
| +- [ ] **Step 4: Rerun Step 2** and targeted existing seed/import tests in those packages; expect PASS. Count unchanged watch ticks: zero new store calls. |
| +- [ ] **Step 5: Commit** with subject `feat: seed claimed apps behind the existing traffic gate`. |
| + |
| +### Task 5: Coordinate copy, permanent commit and source retirement |
| + |
| +**Risk/review:** security gate, termination, billing and production storage. Independent task review; census for any root-linked changes. |
| + |
| +**Files:** |
| +- Create: `internal/console/demo_claim_transfer.go`. |
| +- Modify: `internal/console/demo_claim_store.go`, `internal/console/demo_jobs.go:371`, `:447`, `internal/console/demo_expiry.go:76`, `internal/console/demo_publish.go:43`, `internal/console/demo_store.go:329`, `internal/console/apidemobox.go`, `cmd/console/main.go:710`. |
| +- Test: `internal/console/demo_claim_transfer_test.go`, `internal/console/demo_claim_recovery_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: `(*Server).advanceDemoClaim(ctx context.Context, operationID string) error`, `(*Server).ReconcileDemoClaims(ctx context.Context, restart bool) error`, `(*Server).abortDemoClaim(ctx context.Context, operationID, reasonCode string) error`. |
| +- Produces: `(*Server).retireDemoLocked(ctx context.Context, d DemoRow, now time.Time, reason demoRetireReason) error`; reasons `demoRetireExpired` and `demoRetireClaimed`. Existing `expireDemoLocked` remains a wrapper. Claimed retirement requires the durable commit row; expiry retains its original time check. |
| +- Produces: authenticated `POST /api/box/demo-claims/{operationID}/pickup`, `/snapshot`, `/ack`; use `demoBoxAuth` plus exact assigned box, claim phase, generation and lifetime. Snapshot metadata is digest and byte count; body is raw SQLite, not a path or archive. Duplicate identical snapshot is idempotent; changed bytes are refused. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestDemoClaimTransfer: frozenArtifactSHA == destinationArtifactSHA; destinationData == latestCommittedSourceData; destinationDemoFields == empty; permanentExpiry == 0; sourceNoReplicaReads == true |
| +TestDemoClaimCommitRecovery: crashAtEverySQL/ObjectBoundary => oneDestination; beforeCommit => rollbackPossible; afterCommit => neverResumeSource; lostHTTPResponse => sameResultWithFlowToken |
| +TestDemoClaimExpiryRace: beforeCommitAt24h => expiryWins; afterCommitAt24h => permanentSurvives; activeBuild/rollbackSettlement => refuseBeforeFreeze; oldResult => cannotPublish |
| +TestDemoClaimRetirement: success => tokenHashNull,receiptDurable,sourceStopped; offlineCleanup => liveSlotHeld; originalExpiryUnchanged; permanentHostTombstone == retained |
| +TestDemoClaimRequestCost: idle/repeatedStatus/unchangedTick => zeroAdditionalStoreRequests; snapshotPUTs == 1PerSuccessfulAttempt; sameWorkerReconnect => noDuplicateExport |
| +``` |
| + |
| +- [ ] **Step 2: Run** `go test ./internal/console -run 'TestDemoClaim(Transfer|CommitRecovery|ExpiryRace|Retirement|RequestCost)' -count=1`; expect FAIL. |
| +- [ ] **Step 3: Implement the phase table and bounded recovery.** Pin the last settled live generation and channel artifact under the source lock; refuse any queued/building/starting/settling update. Extend enqueue and every publication boundary with the operation guard, not just the HTTP handler. Copy the manifest with only account/app namespace changes and stream/hash-check the same linux-arm64 artifact through `ShipSpooled`; use normal default pipeline and signed promotion. Write the destination record before its seed object, upload create-only and compare matching duplicates after ambiguous writes. Reserve scratch before accepting bytes, check digest/size/integrity, then publish the seed and verify exact HTTPS host without following redirects. Require 2xx, the pinned `X-Carlos-Version`, and seed `placed` before commitment. |
| + |
| + Commitment rechecks identity, cap reservation, source hold acknowledgment, lifetime and deadline under the ordered locks. At this point use `checkRunningThings(ctx, acct, 0)` because the reservation already counts; do not count the app and instance twice. Atomically record the irreversible decision, clear the claim token hash, invalidate other flows and enqueue all completion work. Seed opening follows that decision. A durable outbox retries opening, moved publication and Plan 1 retirement; status stays `claiming` until these finish. Extend the existing job runner/startup/backstop to drain SQL work and react to stream acknowledgments; status reads SQL only. The source's original expiry remains intact, but the reasoned retirement entry point permits an early committed claim. Preserve signed receipt validation, stop-before-delete, data-initialization-marker cleanup, acknowledgment and ceiling release. Do not let the expiry loop purge an uncommitted source before aborting its destination; once expired, it can never be resumed. |
| + |
| + Before commitment, abort closes all destination traffic first, CASes only this seed to aborted, and waits for normal seed/instance cleanup proof before releasing source. Retain uncertain cleanup and report it through status; console unavailability is not permission for either box to reopen. After commitment, errors are recovery work, never rollback. Keep unfinished work running when admission is switched off. |
| +- [ ] **Step 4: Rerun Step 2**, including existing demo publication/expiry/settlement regressions. Inject failures before and after every irreversible boundary; expect PASS without a second claim or data loss. |
| +- [ ] **Step 5: Commit** with subject `feat: commit demo claims and retire their anonymous source`. |
| + |
| +### Task 6: Serve the moved notice until the original expiry |
| + |
| +**Risk/review:** security gate, redirect destination validation and cache. Independent task review and census required. The response is a page, not an HTTP redirect. |
| + |
| +**Files:** |
| +- Create: `internal/democlaim/moved.go`, `internal/console/demo_claim_moved.go`, `internal/host/demo_moved.go`, `internal/edge/demo_moved.go`. |
| +- Modify: `internal/release/changeindex.go:50`, `internal/host/changeindex.go:180`, `internal/edge/demo.go:18`, `internal/edge/edge.go:1890`, `internal/registry/registry.go`. |
| +- Test: `internal/democlaim/moved_test.go`, `internal/host/demo_moved_test.go`, `internal/edge/demo_moved_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: `democlaim.Moved {DemoID, Host, TargetHost string; ExpiresAt int64}` and `SignMoved(priv ed25519.PrivateKey, rows []Moved) ([]byte,error)`, `VerifyMoved(pub ed25519.PublicKey, wire []byte) ([]Moved,error)`; separator `carlos demo moved v1\n`. |
| +- Produces: `(*Server).publishDemoMoved(ctx context.Context) error`, `(*Edge).serveDemoMoved(w http.ResponseWriter, r *http.Request, host string) bool`. |
| +- Console publishes `control/demo-moved.json`, a complete signed snapshot capped at 1 MiB/10,000 entries, after a committed destination is open. SQL source is independent of `apps` and source purge. Registry stores the verified snapshot separately from live routes; Edge revalidates signed bytes on load. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestDemoMovedPrecedesCache: oldCached200/noLiveRoute/pendingRoute => movedPage; targetOnlyServerDerived; escapedLink; noToken/noCookie/noAppHTML/noWake; POST => noForward |
| +TestDemoMovedExpiry: now<originalExpiry => page; now>=originalExpiry => noMovedLink; sourcePurged => stillPageUntilExpiry; hostNeverReused |
| +TestDemoMovedDelivery: changedScope => oneSnapshotRead; unchangedTicks => zeroReads; invalidSignature => noNewMapping; restart => verifiedPersistedMapping; ordinaryHost => baseline |
| +``` |
| + |
| +- [ ] **Step 2: Run** `go test ./internal/democlaim ./internal/host ./internal/edge -run 'TestDemoMoved' -count=1`; expect FAIL. |
| +- [ ] **Step 3: Implement the minimal Plan 2 hook.** Register one control scope on the existing watch. Load at startup and on its changed generation in the existing pass, not in a new ticker; require the shared watch for activation. Preserve a verified mapping across refresh failure only until its signed expiry. Extend the existing demo stream with the same signed snapshot if a serving demo-fleet edge needs it; it never polls the bucket. Require exact one-label demo hosts and derive TargetHost from the committed target account/app, under configured AppsDomain, with no scheme/path/port supplied by users. Reject overflow before claim commitment by reserving notice capacity. Keep notices monotonic for a never-reused host. |
| + |
| + At the demo-domain entry, before lookup, cache, caps, upgrade or activation, serve a small escaped HTML page for GET and headers-only HEAD; other methods receive 410 and no forwarding. Use 200 for the page, `Cache-Control: no-store`, `Referrer-Policy: no-referrer`, `X-Content-Type-Options: nosniff`, and restrictive CSP with no scripts/forms/external resources. Link to `https://` plus TargetHost only; no automatic redirect, cookie or claim link. Plan 2 can call this hook before its generic demo states when it lands. Purging the source must never delete this independent notice or the permanent name tombstone. |
| +- [ ] **Step 4: Rerun Step 2**, plus existing `TestDemo` edge tests and change-index request-count tests; expect PASS. |
| +- [ ] **Step 5: Commit** with subject `feat: show moved notices for claimed demo hosts`. |
| + |
| +### Task 7: Complete the browser fallback and Keymail path |
| + |
| +**Risk/review:** security gate and redirect. Independent task review required. |
| + |
| +**Files:** |
| +- Create: `internal/console/demo_claim_page.go`, `internal/console/templates/demo_claim.html`, `internal/console/static/demo_claim.js`. |
| +- Modify: `internal/console/apidemo.go:269`, `internal/console/emailsignin.go:258`, `internal/console/server.go:3889`, Task 1 purpose-link dispatch and flow storage. |
| +- Test: `internal/console/demo_claim_page_test.go`, `internal/console/demo_claim_browser_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: `(*Server).handleDemoClaimPage(w http.ResponseWriter,r *http.Request)` and `handleDemoClaimBrowserProof` with the same signature; `POST /demo/claim/intent`, `/demo/claim/prove`, `/demo/claim/select` are same-origin CSRF-protected browser doors over Tasks 1/2. |
| +- Produces: HttpOnly, Secure, SameSite=Lax `carlos_demo_claim_flow` cookie, path `/demo/claim`, maximum 15 minutes. Store its hash and purpose, never the raw demo token. Browser GET renders only; explicit POST is required to claim. |
| +- Consumes: normal `/auth/continue`, Keymail state/PKCE and `next=/demo/claim`; browser proof calls `proveDemoClaim` with the authenticated session identity, never the address originally typed into discovery. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + |
| +```text |
| +TestDemoClaimFragment: token => POSTBodyOnly; historyFragmentCleared; logs/referrer/analytics/query => noToken; scannerGET => noProofOrClaim |
| +TestDemoClaimBrowserIdentity: KeymailActualIdentity != typed => actualIdentityShownAndExplicitConfirmation; noSession => signin; multipleAccounts => mandatoryPicker; staleSession => freshAuthLast |
| +TestDemoClaimBrowserCSRF: wrongOrigin/missingNonce/crossFlow => refused; membershipFailure => 404BeforeFreshAuth; externalNext => dropped; emailedLinkGET => noConsumption |
| +TestDemoClaimBrowserRecovery: returnFromOAuth => sameIntent; pageReload => status; expiredIntent => normalRefusal; committedTokenReuse => cannotClaimAgain |
| +``` |
| + |
| +- [ ] **Step 2: Run** `go test ./internal/console -run 'TestDemoClaim(Fragment|Browser)' -count=1`; expect FAIL. |
| +- [ ] **Step 3: Implement the page and browser adapters.** First script copies the fragment to memory, clears it with `history.replaceState`, and exchanges it for the claim-only cookie via same-origin POST. No analytics, third-party assets or localStorage on this page. Use the email/code UI over the same proof mechanism; the claim email link can finish in another browser through the existing nonce-confirmed purpose handler. Keymail uses ordinary sign-in and returns to the intent. Do not auto-claim merely because OAuth finished or a session already exists: show the actual person, target account where unique, and require confirmation. For several accounts, selection is that confirmation. |
| + |
| + Avoid MRU landing side effects for this specific return: extract identity/session completion from account landing, leaving ordinary sign-in unchanged. Claim-side zero-account mint must pass Task 2's cap/person lock, including a new Keymail user. Apply browser session, CSRF and membership gates before `requireFreshAuth` where fresh proof is required; Keymail never downgrades to email step-up. Agent JSON endpoints issue no browser session and browser cookies cannot authorize them. List completed account/app/URL and the normal CLI next step; no deploy credential. |
| +- [ ] **Step 4: Rerun Step 2** and sign-in callback/step-up regression tests; expect PASS. Verify browser fragment removal and keyboard operation using a local mock, bound to loopback. |
| +- [ ] **Step 5: Commit** with subject `feat: finish demo claims in the console browser`. |
| + |
| +### Task 8: Prove the complete claim and activate dev |
| + |
| +**Risk/review:** whole-branch review covers test/doc wiring. Any new security/root/storage behavior found necessary belongs back in its owning task's review budget. |
| + |
| +**Files:** |
| +- Create: `internal/console/demo_claim_e2e_test.go`, `internal/host/demo_claim_dev_linux_test.go`. |
| +- Modify: `internal/demo/config.go:22`, `cmd/console/main.go:478`, `internal/console/apidemo.go:439`, `README.md` anonymous-demo operator section; Task 7 page copy and claim API documentation alongside that section. |
| +- Generate during implementation: `internal/provision/testdata/plan14-root-reads-agent-start-demo-3.tsv`, census chain entry and `docs/superpowers/notes/census-proposal-agent-start-demo-3.md` with proposal tooling and independent dispositions. |
| + |
| +**Interfaces:** |
| +- Produces: `demo.Config.ClaimEnabled bool`, parsed from `CARLOS_DEMO_CLAIM`, unset or `1` only; `(*Server).demoClaimReady(ctx context.Context) error`, cached for 45 seconds like existing admission checks with an independent 10-second context. |
| +- Claim availability requires mail/Keymail path readiness, worker export capability, ordinary arm64 seed placement, seed floor, serving-edge moved/gate capability, policy writer and change delivery. `claimAvailable` reflects that readiness, not just the setting. |
| +- Switching off prevents new proof/selection/reservation. It leaves status, committed-work recovery, abort, retirement and moved notices operational. Register their routes independently of create admission so a console restart with admission off cannot strand claims. |
| + |
| +- [ ] **Step 1: Write failing end-to-end tests.** |
| + |
| +```text |
| +TestDemoClaimEmailToPermanent: sourceStartedWithSocketAndDBFlags; writeSQLiteThenUpdateThenClaim => exactLatestDataAndArtifact; newAccountOrSelectedExisting; targetOutsideDemoFleet; claimTokenDead; ordinaryCLIWorkflowPossible |
| +TestDemoClaimFailureKeepsDemo: cap/wrongCode/unsupportedPlacement/copyFailure => noPermanentServingApp; demoStillWorksAfterConfirmedAbort; noTTLReset |
| +TestDemoClaimDevAcceptance: actualWALDataCopied; sourceFrozenDuringCopy; destinationGatedUntilCommit; originalHostMovedThenExpires; rootPurgeAck; smallAppClaimElapsed<1m |
| +TestDemoClaimOffCompatibility: switchUnset => noNewBehaviorOrStorePolls; switchedOffMidClaim => recoveryCompletes; ordinaryEmail/seed/import/apps => baseline |
| +``` |
| + |
| +- [ ] **Step 2: Run** `go test ./internal/console ./internal/host -run 'TestDemoClaim(EmailToPermanent|FailureKeepsDemo|DevAcceptance|OffCompatibility)' -count=1`; demonstrate the integration witness fails with the coordinator disconnected. A gated dev skip is outstanding evidence. |
| +- [ ] **Step 3: Finish activation wiring and approved copy.** Run the copy review table through the repository's copy workflow before putting strings in product files. Update operator/API documentation and `claimAvailable`; no CLI verb is added. Build test binaries on the workstation and exercise the real dev boxes through APIs with those binaries. Use the existing demo wildcard and housekeeper certificate path, console drop-in and normal destination placement. Record account selection, plan refusal, WAL contents, artifact digest, destination first replica, old URL notice, expiry and interrupted-copy recovery. Dev switches on when the implementation lands; provisioning/DNS/IAM changes, if discovered necessary, need a concrete scoped approval before execution. This plan does not grant it. |
| +- [ ] **Step 4: Run the final implementation gate once.** Targeted tests first, then repository-required `go build ./...`, `go vet ./...`, `go test ./... -count=1`, whole-tree gofmt check and prescribed cross-build/CI gate. Use the default Go cache; no compilation on demo boxes. Run `make census-card`, write unit claims, then `make census-propose NAME=agent-start-demo-3 CLAIMS=<claims-file>`; independently review every unit/envelope against amadan main and record verdict on #280. Whole-branch review follows the budget below. These commands belong to the future implementation session; none is required for authoring this document. |
| +- [ ] **Step 5: Commit** with subject `test: prove email claims preserve demo apps and data`. Describe, push and squash-land the implementation branch through amadan after tip CI is green; inspect main CI afterward. Stop at this one visible merge. |
| + |
| +## Copy review required |
| + |
| +This is a string inventory, not approved wording. All new human-facing strings belong here, including dynamic error templates and operator messages. Existing email sign-in text remains unchanged unless explicitly listed. No product copy is written in this document-only session. |
| + |
| +| Copy ID / surface | Meaning to draft and review before implementation | |
| +|---|---| |
| +| CLAIM-EMAIL | Email label, placeholder, submit/resend controls, code entry and confirmation controls, help and accessible labels. | |
| +| CLAIM-MAIL | Claim-specific email subject/body, code, expiry, demo identification, safe browser link and unsolicited-message explanation. No account authority or misleading ordinary-signin claim. | |
| +| CLAIM-KEYMAIL | Browser-required response and link explanation; authenticated identity confirmation when the actual Keymail person differs from the typed address. | |
| +| CLAIM-PROOF | Malformed email, invalid/expired/replaced code or flow, wrong nonce/origin, resend and mailbox-unavailable messages; preserve non-enumeration. | |
| +| CLAIM-ACCOUNT | Account picker title, account/role labels, confirmation, new personal account explanation and inaccessible-account response. | |
| +| CLAIM-CAP | App plus instance cap, free-account cap, create-rate limit and other normal plan refusals; demo continues to its original expiry. Review adapted existing cap text if it contains an em dash. | |
| +| CLAIM-BUSY | Existing build/settlement/claim, source briefly paused, copy/verification progress, retry timing and recovery pending. | |
| +| CLAIM-DATA | Assigned box unavailable, missing/corrupt SQLite, WAL failure, 256 MiB limit, scratch exhaustion, timeout and safe abort; no false recovery promise. | |
| +| CLAIM-PLACEMENT | No eligible ordinary arm64 destination, unsupported region/HA/fleet, missing seed floor/capability and unavailable policy writer. | |
| +| CLAIM-RESULT | Success, permanent URL, account/app identity, original host expiry, no account credential issued and normal CLI login/deploy next step. | |
| +| CLAIM-MOVED | Page title/body/link and accessibility text, HEAD behavior and non-GET refusal. No automatic forwarding, claim token or app-supplied markup. | |
| +| CLAIM-RETIRED | Invalid/spent token, expired demo, interrupted operation after expiry and unavailable status; no account detail before proof. | |
| +| CLAIM-OPERATOR | Switch/readiness, pending cleanup, failure reason codes rendered for operators, audit messages, activation/rollback and API documentation. | |
| +| DEMO-DATA amendment | Existing absolute “cannot be copied” refusal must distinguish unsupported generic move/import from this verified claim transfer, without promising a demo backup. | |
| + |
| +## Review budget and self-review |
| + |
| +Independent plan review rounds in this authoring session: **0**. No agents were spawned. Plan 1's controller rulings and review history remain settled dependencies; this is a new Plan 3 change, not a reopening of Plan 1. Use `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md` for implementation briefs, carrying the round history and each finding's invariant. Tasks 1 through 7 require independent review for their marked risks; Task 8 receives the whole-branch review. For a Codex author, use Opus or Fable for other-family census and authority review. |
| + |
| +Stop at the first round with no P1. Apply that round's P2 fixes without a new general review, retaining census and checks of newly changed security/root/termination/production-storage behavior. Record P3s as follow-ups. Maximum three rounds; a fourth needs Paul's decision. Two consecutive rounds in one fault family trigger the stop-and-choose rule. No review against unmerged Plan 2. The implementation session owns this one plan and ends at its merge; carry the three-day/three-compaction and 24-hour reporting limits from AGENTS.md. |
| + |
| +Self-review: design §4.5 maps to Tasks 1/7 (email and Keymail), 2 (account choice/authorization/caps), 3/4/5 (same artifact and quiesced local SQLite into a normal permanent app), 5 (single-use token and retirement), 6 (moved page), and 8 (visible dev activation). The no-credential decision avoids granting an agent service roles, account scope or credential recovery; Task 1's continuation dies as a mutation capability when the one operation is reserved. The five Review Focus cases have named owning tests. Shared operation/flow/seed identities and signatures match across tasks. No production function bodies or full test suite were run or written during planning. The supported-placement boundary is explicit: ordinary placement is checked first, existing seed restrictions are retained, and an unsupported result refuses before stopping the demo. |
| + |
| +## Open questions |
| + |
| +None for Paul. Builder choices above are marked “my call”; copy approval and any scoped infrastructure rollout approval are execution gates, not unresolved product decisions. |
diff --git a/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md b/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md| new file mode 100644 |
| index 000000000..706306f6e |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md |
| @@ -0,0 +1,237 @@ |
| +# /start and the homepage Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** A person pastes one line into their coding agent, describes a small app, gets a working demo, claims it, and learns the normal development path. |
| + |
| +**Architecture:** The website builds Markdown and HTML from one agent-instruction source and ships a versioned source starter beside them. 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. |
| + |
| +**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. |
| + |
| +**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. |
| + |
| +## 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. |
| +- 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 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. |
| + |
| +## 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`. |
| +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`. |
| +5. A claim with several accounts, unavailable claiming or an asynchronous data transfer must not be presented as permanent success: Tasks 2 and 5, claim-contract fixtures and the real cloud-agent witness. |
| + |
| +--- |
| + |
| +## Evidence and boundaries |
| + |
| +Read against platform `2914921ceabd4218b0363a9780f8e4db890aab4c` and website `ef3def7d546504dab3e2b35e2cdfc10f6c880808`. These are discovery anchors, not permission to ignore later merged producer interfaces. New file/function names below are decisions, not existing APIs. |
| + |
| +| Evidence | Consequence | |
| +|---|---| |
| +| W `AGENTS.md:26`, `:63`, `:126`, `:176`; W `README.md:17`; W `eleventy.config.js:49`, `:62`, `:206` | Homepage and `/start` are hand-authored passthrough files today. Eleventy builds `_site/`; footer and disclosure are added after rendering. Never edit vendored `src/docs/`, `src/_data/docs*.json` or `src/well-known/`. | |
| +| W `PRODUCT.md:51`, `:61`, `:72`; W `DESIGN.md:130`, `:207`, `:267`, `:281`; W `AGENTS.md:65`, `:74` | Keep the website's house style, system fonts, light/dark modes and approved clipboard exception. The newly approved journey supersedes the older developer-only primary action in `PRODUCT.md:23`. | |
| +| W `src/index.html:27`; W `src/start/index.html:29`; W `src/start/start-tabs.js:1` | The hero contains numeric multipliers inside a human-marked block. The existing start flow asks for tools before deploying. Replace only the authorised hero/start journey after Paul's copy review; preserve unrelated human-certified sections. Reuse clipboard attributes and fallback selection. | |
| +| W `src/llms.njk:9`; W `AGENTS.md:160` | Point new-app agents to `/start` before the older install-first skill path; keep skills and account reference links. Do not rewrite the vendored skills. | |
| +| `internal/edge/static.go:585`, `:599`, `:632`, `:668` | Static serving 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/console/apidemo.go:264`, `:293`, `:310`, `:371`, `:437`, `:496`, `:553`, `:580` | Actual create/update endpoint, gzip content type, bearer selects update, returned fields, Retry-After/status states and live URL. Claim availability is currently false. | |
| +| `internal/demo/config.go:13`, `:31`; `internal/console/demo_store.go:238`, `:329`; `internal/console/demo_jobs.go:45` | Exact source cap, 60 update attempts, off-by-default admission, fixed 24-hour expiry and at most one active job per demo. Do not promise concurrent updates or unlimited repair attempts. | |
| +| `internal/demobuild/source.go:24`, `:51`, `:190`, `:207`, `:227`, `:273`; `internal/demobuild/lock.go:18`, `:127`, `:170`; `internal/demobuild/probe.go:42` | Exact archive grammar and module closure; local imports under `demo.local/app` are allowed, direct transitive imports are not. The probe demonstrates ordinary USTAR packaging without leading `./`. | |
| +| `internal/demobuild/runner.go:36`; `internal/console/testdata/demo/go.mod:1`; `internal/console/testdata/demo/main.go:16`; `internal/activator/backend_exec.go:2530`, `:2733` | Copy the lock files, not the fixture's environment-based entrypoint. Real runtime launches pass flags. Offline builds use a prewarmed closure and no toolchain download. | |
| +| `internal/activator/demo_durability.go:18`, `:94`, `:105`; `internal/provision/demo_policy.go:15`; `internal/edge/demo.go:18`, `:27`, `:72`; Plan 1 rulings `:19`, `:27`, `:33`, `:34` | Local-only data, fixed assignment, root-owned demo-box isolation, never-reused hosts and the corrected wire fields are binding. R23b forbids a substitute fake starter as acceptance evidence. | |
| +| Rastrillo module-cache `amadan.net/rastrillo/rastrillo@v0.30.2/serve.go:70`, `:133`, `:145`, `:385`, `:823` | `rastrillo.Options` accepts `Router func(*sql.DB) (*http.ServeMux, error)`, `DBPath`, `Migrations` and `Socket`; `rastrillo.Serve(Options) error` opens SQLite and serves the socket. Set flags explicitly so its TCP fallback is unreachable. | |
| +| `internal/console/static/fiesta/VERSION:2`; Fiesta commit `4ee76b5e651ff4fb5a4bae12d7508f55a2531eff`, `README.md:11`, `:63`, `:75`, `releases/1.1.0/SHA256SUMS:1`, `:9` | Pin Fiesta 1.1.0 assets from that commit. Day, Plain and Signal exist; preserve MPL-2.0 notice. No Fiesta Go dependency is needed. | |
| +| W `AGENTS.md:195`; W `hack/cache-bust.mjs:14`; `docs/site/cli.md:54`, `:316`, `:348`, `:1362`; W `src/start/index.html:33` | 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. | |
| + |
| +**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. |
| + |
| +**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. |
| + |
| +| Plan 3 declared interface, not shipped yet | Website instruction contract | |
| +|---|---| |
| +| Plan 3 `:72`: `POST /api/demo/claims`, JSON `{claimToken,email,flowToken?}` | Initial call omits `flowToken`; resends retain it. `202 {state:"email_required",flowToken,expiresAt}` means ask for the emailed code, not that delivery is guaranteed. `200 {state:"browser_required",claimUrl}` means open the returned link; no fabricated flow token. | |
| +| Plan 3 `:74`: `POST /api/demo/claims/verify`, JSON `{flowToken,code}`; `POST /api/demo/claims/select`, JSON `{flowToken,accountId}` | `account_required` returns `accounts:[{id,name,role}]`. Ask the person, submit the exact selected ID, never the display name or MRU account. Zero/one membership is resolved by the server. | |
| +| Plan 3 `:76`: `GET /api/demo/claims/status`, `Authorization: Bearer <flowToken>` | `202 {state:"claiming",phase,retryAfter:2}` remains pending. `200 {state:"claimed",accountId,app,url,next:"cli_login"}` alone authorises the success explanation and normal CLI path. Wait at least the returned `retryAfter` seconds between polls, respecting a longer HTTP Retry-After. | |
| +| Plan 3 `:78`, `:100`, `:102` | Proof/selection expires at the earlier of 15 minutes and demo expiry; resend does not extend it. Transfer has a five-minute bound before commitment; recovery after commitment can continue. Stop automatic waiting after five minutes and explain pending recovery without creating another app. Result reads use the flow token until original expiry plus 24 hours. | |
| + |
| +The flow token is distinct from the demo update token and from a CLI credential. Never send either secret to the app origin, install it as an account credential, or discard the flow token before recording successful completion. Plan 3 grants no post-claim deploy credential. Browser completion may require normal sign-in to discover the permanent app if no flow token was returned; never guess its address. |
| + |
| +## Agent content contract |
| + |
| +One source, `W/src/start/agent.md`, contains the following ordered directives. `W/hack/build-start.mjs` substitutes only validated deployment values and release metadata, producing both the Markdown response and the complete visible HTML agent section. The HTML introduction is separate reviewed copy. Do not hide the directives in comments, a collapsed disclosure or JavaScript. |
| + |
| +1. **Ask first.** Ask what the person wants to make and wait. Offer a booking page, shop, tracker or team tool only if they are stuck. Infer experience from their language; ask one light clarifying question if needed. Ask how the UI should feel. Confirm the small first version before generating or uploading anything. |
| +2. **Adapt the explanation.** Experienced developers get the Go/Rastrillo/Fiesta/SQLite stack, remote build, 24-hour expiry, claim and later CLI workflow. Newcomers get plain language without product/framework names unless they ask. Everyone is told the app is public, temporary and has no backup; use invented data, no real passwords or sensitive information. Do not describe demo storage as replicated or durable across box loss. |
| +3. **Choose scope and style.** One binary and one local SQLite database; no outbound calls or restricted capabilities. Existing-app migrations take the account path with an honest rootfs/managed-fleet explanation at the user's level, not an automatic rewrite. Map calm/everyday to `day`, minimal to `plain`, bold to `signal`, and playful to `day` with small local presentation changes (my call). Explain that the three themes are starting points, not four invented theme packages. Keep the initial app to one useful screen and one persisted entity. |
| +4. **Fetch the pinned starter.** Use its same-origin immutable archive and checksum or the complete source listing beside it. Keep `go.mod` and `go.sum` unchanged. No CLI, Go installation, package manager or local compilation is required of the demo user. Use an already available archive/HTTP tool in the agent's environment. A cloud agent without Go must complete the flow. A chat application unable to make outbound requests is out of scope. |
| +5. **Pack the source.** Regular USTAR entries rooted at `go.mod`, `go.sum`, `main.go`, `templates/`, `static/` and `LICENSE.fiesta`, with relative clean names and no enclosing directory or leading `./`. Include new application files explicitly; exclude tests, `.git`, credentials, SQLite files and the output archive. A GNU tar example uses `tar --format=ustar -czf <outside-source>/source.tar.gz go.mod go.sum main.go templates static LICENSE.fiesta`; a Python standard-library alternative specifies `tarfile.USTAR_FORMAT`, enumerates only regular allowlisted files, and assigns the same relative names. Never use an unqualified `tar ... .`. Do not execute generators or change dependency versions to repair an error. |
| +6. **Publish through the console origin.** Send raw archive bytes to `POST <consoleOrigin>/api/demo/apps`, `Content-Type: application/gzip`, `X-Carlos-Client: <actual harness>`, without Authorization on the first create. No multipart, base64 or JSON wrapper. On 202 retain `jobId`, `name`, `statusUrl`, Unix-seconds `expiresAt`, `claimToken`, `claimUrl`, and `claimAvailable` in private agent state; never in the app, repository, public transcript or screenshots. Give the user the returned secret claim link once, privately, as recovery information. Do not claim it works if `claimAvailable` is false. |
| +7. **Wait and repair.** GET the returned `statusUrl` without a bearer token. Poll no faster than its `Retry-After` (2 seconds on main); use 5 seconds if absent, respect longer retry values and allow at most five minutes of automatic waiting (my call). `building`/`starting` are pending; only `live` plus `url` is success. `failed` carries `diagnostics`, `diagnosticsTruncated` and `message`; fix source and resubmit with `Authorization: Bearer <claimToken>` to the same publish endpoint. Retain the original claim fields because update replies omit them. Make at most two automatic repair submissions before explaining the problem; do not consume the lifetime's 60 attempts in a loop. Do not promise rollback unless the response says it occurred. |
| +8. **Handle refusals without creating a second app.** 400/413/415 require source correction; 409 means wait for the active update; 429 can mean a request budget or the lifetime update limit, so follow its response rather than retry indefinitely; 503 means unavailable, not permission to rotate identity. 401/404/410 or unavailable claims never fall back to anonymous create. A lost create response is an unknown outcome with a potentially lost one-time token: stop automatic submission and explain, since main has no create idempotency/recovery endpoint. A transport-level host block is distinct from an API error. Explain one exact console hostname to allow under the agent's internet/network permissions, why it is needed and that settings differ by product; then retry once authorised. Never suggest disabling the sandbox or allowing wildcard domains. |
| +9. **Share the result.** Hand over the returned live URL unchanged, formatted as a full Markdown link, and explain the actual `expiresAt`, fixed 24-hour lifetime and claim availability. Updates use the same bearer and do not extend expiry. Do not synthesize URLs from `name`, shorten a claim link, lose its fragment, or send a token to the live app. HTTP tooling must not follow a credential-bearing request to another origin; validate HTTPS console origin before using returned status/claim endpoints, while preserving valid returned URLs byte-for-byte. |
| +10. **Claim through Plan 3 (declared dependency).** When claiming is available, ask whether they want to keep it; then ask for email, start the declared challenge and ask for the emailed code. Keymail uses the returned browser link. If multiple accounts are returned, ask the person to choose explicitly; do not choose the most recently used account. Plan-limit/permission refusals leave the demo on its original expiry. Follow Plan 3's completion/status contract through data transfer; verification or account choice alone is not success. Share the returned permanent URL only after successful completion, verify a previously saved row there, and discard the consumed demo credential. Do not manufacture a scoped account credential. |
| +11. **The right way after claim.** Offer, rather than silently start, the permanent workflow. Download the matching CLI binary and published checksums from the public `carlosframework/releases` release page; never `go install` the private platform module. Sign in with `carlos auth login --console <consoleOrigin>` and browser code approval, inspect `carlos auth whoami`, select the claimed account/app, put source in the user's chosen repository, and keep tokens/databases/build output out of it. Build the app for the deployment's supported architecture in a development environment, then `carlos deploy --console <consoleOrigin> --account <claimedAccount> --app <claimedApp> ./shop-linux-arm64`. Preserve the database and verify both the new UI and saved row. Do not run `apps create` for an already claimed app. For newcomers explain each step and defer setup until they choose it; the no-install promise applies to the demo, not all future development. |
| + |
| +## Task 1: Publish a locked, flag-based Rastrillo and Fiesta starter |
| + |
| +**Risk/review:** storage, security gate (the archive/dependency boundary and public writable example), and the form's same-origin redirect. Independent task review required. No root, termination or billing change. |
| + |
| +**Files:** |
| + |
| +- Create W `src/start/starter/v1/{main.go,go.mod,go.sum,templates/index.html,static/fiesta.css,static/fiesta-plain.css,static/fiesta-signal.css,LICENSE.fiesta,manifest.json}`. |
| +- Create W `hack/pack-starter.py`, `hack/check-starter.mjs`, `test/starter/main_test.go.txt`, `test/starter/website_starter_contract_test.go.txt`, `test/starter-pack.test.mjs`. |
| +- Modify W `package.json` to expose `check:starter`; change passthrough wiring with Task 3. No source Go test files enter the submitted archive. |
| + |
| +**Interfaces:** |
| + |
| +- Consumes the exact Plan 1 lock and fixture `go.mod`/`go.sum`. Lock-file SHA-256 is `a858eb184a5255068a4a56470e3549a2a7d4718635a90fe69f40e9faff3948c5`; fixture mod/sum hashes are `78a1f3d56026dc3efa3a9456dc7a39c63672bafcf0bb04944c075eac6e601180` and `688bf53e93ba1ba280fc924446986ab2cf32fba7c4f16efaf80a8c6e36848b49`. |
| +- Produces `parseFlags(args []string) (socket, dbPath string, err error)` and `newRouter(db *sql.DB) (*http.ServeMux, error)` in the starter. Both flags are required absolute paths; missing flags fail before listening, regardless of `CARLOS_SOCKET`/`CARLOS_DB`. Call `rastrillo.Serve` with the parsed socket/database and additive `items(id INTEGER PRIMARY KEY, name TEXT NOT NULL)` migration. |
| +- Routes: `GET /` renders escaped rows, `POST /items` accepts one `name` (1-120 Unicode characters, body at most 4096 bytes), then returns 303 to `/`; `GET /static/{file}` serves only the three embedded CSS files. Use same-origin POST checking with nonempty Origin required; no destructive or credential features. Store at most 100 rows for the starter (my call). All UI strings use the copy-table IDs. |
| +- `pack_starter(source: Path, output: Path) -> None` writes sorted USTAR entries with fixed modes, zero mtime/uid/gid, empty owner names and deterministic gzip metadata; output must be outside source. Its input inventory excludes `manifest.json`, which describes the archive rather than being included in it. Reject links, unsafe paths and cap breaches. Publish `/start/starter/v1/source.tar.gz` plus `manifest.json` with `schema:1`, `archiveSHA256:string`, `files:[{path:string,sha256:string}]`, `platformCommit:string`, `lockSHA256:string`, and `fiesta:{version:string,commit:string}` (the `StarterManifest` shape). Never replace v1 bytes after publication; fixes get v2. |
| +- Fiesta combined CSS hashes from the pinned release: Day `141597a63cdc616bc33c7bec0ee6bcda47bd5d279726ed9f44fa6ddf3671b68a`; Plain `47f6911af8efc962d268cb4f1bedeaf6ac921c2fef6a29cfa57be0ab0ce01b43`; Signal `b8d5337117166c9156271762e39e0dec1f44bb8459ce98f9632dff31322a999a`. Embed and serve locally; no CDN requests, inline scripts or JavaScript dependency. Choose one stylesheet in the template. |
| + |
| +- [ ] **Step 1: Write failing tests.** `TestStarterFlagsAndPersistence`: environment variables absent; launch with both flags; GET succeeds; POST saves a row; restart and rebuild/update preserve it; missing flags never listen on TCP; hostile markup renders escaped; cross-origin POST is refused; unknown asset is 404. `starter-pack.test.mjs`: deterministic hash, no directory wrapper/`./`, no links/PAX records, explicit source inventory, each cap boundary, unchanged lock files and all three Fiesta hashes. `TestWebsiteStarterContract`: the generated archive passes real `demobuild.ValidateSource` with `DefaultLock`; deliberately altered dependency, removed checksum and PAX fixture fail. |
| +- [ ] **Step 2: Run and observe failure.** `node --test test/starter-pack.test.mjs` and `node hack/check-starter.mjs --platform <read-only-platform-checkout>` fail on missing packer/starter. The latter uses a Go `-overlay` mapping to supply `website_starter_contract_test.go` to the existing `internal/demobuild` package without editing that checkout, and runs only `TestWebsiteStarterContract`. It copies the starter and its runtime test into disk scratch, never the live demo box. |
| +- [ ] **Step 3: Implement the declared starter and packer.** Before writing the template, review the starter UI entries from the copy table with Paul using the copy-review skill; Task 4 does not reopen this approved copy. Use `html/template`, parameterised SQL and Rastrillo's database lifecycle; no source generation or direct SQLite-driver import. Copy verified module/asset bytes from the cited sources. Generate the archive, checksum and browsable source listing from the same inventory. |
| +- [ ] **Step 4: Verify.** Repeat Step 2; download the locked closure once on the author/CI machine with normal checksum verification, then build the scratch starter offline using Go 1.26.10, `GOWORK=off GOTOOLCHAIN=local GOENV=off GOFLAGS= GOPROXY=off GOSUMDB=off CGO_ENABLED=0`, using `go build -mod=readonly -trimpath -buildvcs=false -o <scratch-binary> .` (the worker command at `internal/host/units/carlos-demo-build@.service:11`), for both local runtime testing and `GOOS=linux GOARCH=arm64`. Assert `go.mod`/`go.sum` stayed byte-identical and binary size is within cap. Actual remote build remains Task 5's evidence, with no fake substitute. |
| +- [ ] **Step 5: Commit.** Stage only Task 1 files after its independent review; subject `feat: add pinned anonymous demo starter`. |
| + |
| +## Task 2: Write and test the agent journey against producer contracts |
| + |
| +**Risk/review:** security-sensitive credential instructions, covered by whole-branch review; this task grants no new API authority. No new security gate, root, termination, storage, billing or redirect implementation; no separate task review. |
| + |
| +**Files:** |
| + |
| +- Create W `src/start/agent.md`, `src/_data/start-config.mjs`, `src/_data/start-claim-contract.json`, `hack/start-content.mjs`, `test/start-protocol.test.mjs`, `test/fixtures/start-protocol.json`. |
| +- Modify W `src/llms.njk:9` to distinguish the anonymous new-app path from account development. |
| + |
| +**Interfaces:** |
| + |
| +- `loadStartConfig(env: Record<string,string|undefined>) -> StartConfig`; fields `enabled:boolean`, `siteOrigin:string`, `consoleOrigin:string`, `accountUrl:string`, `starterVersion:string`, `claimContractRevision:string`. `CARLOS_START_DEMO` is unset or `1`; enabled builds require `CARLOS_START_SITE_ORIGIN`, `CARLOS_START_CONSOLE_ORIGIN`, `CARLOS_START_ACCOUNT_URL`. Origins must be HTTPS, without credentials/query/fragment/path; account URL must be same-console-origin HTTPS. No origin from a request Host, query parameter or model guess. Starter version is `v1`. |
| +- Production site origin is [https://carlosframework.com](https://carlosframework.com); its console origin is [https://console.carloku.com](https://console.carloku.com). Dev values come from the active dev destination, recorded during Task 5. Public copy still contains the single canonical paste line; dev acceptance uses the equivalent deployed dev `/start` URL and verifies the public line separately. |
| +- Produces `renderAgent(template: string, config: StartConfig, claimContract: ClaimContract, starter: StarterManifest) -> string` in `hack/start-content.mjs`; replace named deployment/contract placeholders only, reject unresolved placeholders, and preserve all other Markdown bytes. Task 3 consumes this renderer. |
| +- Create/update/status consume the actual fields in the Agent content contract. `start-claim-contract.json` has the `ClaimContract` shape and is a website-side documentation fixture, **not a new console endpoint or wire format**. Its keys are `producerCommit`, `producerPlan`, `start`, `verify`, `chooseAccount`, `status`, `browser`, `complete`; each operation records Plan 3's exact method/path/auth/request/response fixture. It contains synthetic secrets only. The build refuses enabled claim instructions without a pinned merged producer revision and complete fixtures. |
| + |
| +- [ ] **Step 1: Bind the declared Plan 3 dependency.** Once Plan 3 is merged, encode the declared interface table above in `start-claim-contract.json`, cite producer handler file:line and merged SHA, and compare every field to the handlers. Carry account selection, Keymail browser completion, retry/expiry and asynchronous data transfer exactly. If the producer has changed, update this consumer contract before implementing it; if absent, keep this task pending. Do not review against an unmerged producer. Paul need not design the wire protocol. |
| +- [ ] **Step 2: Write failing transcript tests.** Fixtures cover novice, experienced developer, playful/minimal UI, existing-app migration, external API request, blocked host, failed build then bearer update, 429, lost 202 response, expired token and `claimAvailable:false`. Assertions pin ask-before-build, no demo install, bounded polling/repair, unchanged URLs, secret-free public output, no second create and explicit account path. Claim fixtures cover zero/one/multiple accounts, wrong code, Keymail, plan refusal, pending copy, successful permanent URL and consumed token. A canned transcript is contract coverage, not proof of LLM behaviour. |
| +- [ ] **Step 3: Run to verify failure.** `node --test test/start-protocol.test.mjs`; expect missing directives/config/fixtures to fail. Assertions must inspect parsed request transcripts and rendered instructions, not only keyword presence. |
| +- [ ] **Step 4: Write the Agent content contract into the single source.** Include complete request/response examples, GNU tar and Python packaging recipes, link to the pinned starter and all required fields. Render the exact merged claim examples from the fixture. Add the public releases link, verified CLI sequence and source-preservation guidance after claim. `llms.txt` gets an anonymous-demo exception to its general replicated-storage description. |
| +- [ ] **Step 5: Verify and commit.** Repeat the transcript tests; compare each rendered wire example to its producer fixture. Commit subject `docs: add the agent demo and claim journey`. |
| + |
| +## Task 3: Serve one /start URL as Markdown or HTML |
| + |
| +**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. |
| + |
| +**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. |
| + |
| +**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. |
| + |
| +- [ ] **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`. |
| + |
| +## Task 4: Review and build the human introduction and homepage hero |
| + |
| +**Risk/review:** presentation only; none of security gate, root, termination, storage, billing or redirect. Whole-branch review only. Paul's copy review is required independently of technical review. |
| + |
| +**Files:** |
| + |
| +- Create W `test/start-pages.test.mjs`; use W `copy-review/strings.json`, `copy-review/preview/` and archived approved results according to the website workflow. |
| +- Modify W `src/_data/start-copy.json`, `src/index.html:27`, `src/_includes/start.njk`, `src/start/start-tabs.js:1`, `src/start/start.css`, `src/home.css`, `hack/build-start.mjs`, `PRODUCT.md:23`, `AGENTS.md:26`, `:195`, `README.md:10`, `:62`. |
| + |
| +**Interfaces:** |
| + |
| +- `start-copy.json` uses the exact IDs in the copy table. Build-time placeholders map each ID to every HTML occurrence. Homepage and `/start` reuse one paste-line value: “Follow the directions on [https://carlosframework.com/start](https://carlosframework.com/start)”; the copied value is plain text, not Markdown syntax. |
| +- Homepage replaces the numeric hero promise with Paul's reviewed modest claim and makes the paste line plus copy control its primary action. Keep architecture/reference links secondary. The authorised hero change supersedes its existing human-marker protection only after Paul approves its replacement; do not edit unrelated certified text. |
| +- `/start` has a short human explanation, copy line, temporary/no-backup notice, claim explanation, account-path link and an always-visible `#for-your-agent` section containing Task 2's complete instructions. Use visible AI attribution for agent-authored prose per W `AGENTS.md:40`; retain approved attribution rules for human-certified copy. |
| +- Reuse `data-copy-target`, `data-original`, `data-copied`. Hide the copy control until enhanced; native text selection remains available without scripts. Clipboard rejection selects the entire line and exposes a reviewed, polite live-region instruction. No network calls from the copy button. |
| + |
| +- [ ] **Step 1: Prepare Paul's copy review.** Draft the remaining homepage and documentation table entries into the website string index with context and previews before writing copy into source. Tasks 1 and 3 already obtained approval for the starter and start page; carry those approved bytes forward. Use `/home/paulca/.agents/skills/copy-review/SKILL.md`, run its preview check, submit to Paul and apply his result verbatim. Keep one review per logical surface. The instruction Markdown is exempt; its visible section heading is not. No delegated model approval substitutes for Paul. |
| +- [ ] **Step 2: Write failing page tests.** `start-pages.test.mjs` checks exact copied plain-text line, one primary action, no numeric multiplier in the hero, unique copy targets, visible complete agent section, approved copy IDs/bytes, no unreviewed aria/meta/error strings, and no client-side API fetch. Browser checks at 390px and 1280px cover light/dark, keyboard focus, reduced motion, script-disabled reading and denied clipboard permission. |
| +- [ ] **Step 3: Run to verify failure.** `node --test test/start-pages.test.mjs`; expect the old hero and install-first start page to fail these assertions. |
| +- [ ] **Step 4: Implement the approved surfaces.** Preserve existing layout/styles where practical; add the readable prompt and agent section without a redesign. Update the website's product/deploy documentation to describe the build-time content and binary serving exception 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. |
| + |
| +**Files:** |
| + |
| +- Create W `test/start-live.test.mjs`, `docs/start-demo-acceptance.md`, `hack/release-start.mjs`. |
| +- Modify W `package.json` to include the focused checks in the website gate. Keep live checks explicitly opt-in and out of normal CI. |
| + |
| +**Interfaces:** |
| + |
| +- `verifyStartOrigin(origin: URL) -> Promise<Verification>`, where `Verification={origin:string,version:string,markdownSHA256:string,starterSHA256:string,checks:Record<string,boolean>}`, in the live test checks real negotiated responses, TLS, content hash, release header and starter checksum. It never creates apps by being imported or through the default test command. |
| +- Acceptance record holds website/platform/Plan 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. |
| + |
| +- [ ] **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 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`. |
| + |
| +## Human-facing strings: copy review required |
| + |
| +This is an inventory of meanings and fixed literals, not approved shipping copy. Each row becomes individual strings where several surfaces need different wording. Draft and submit via the website copy-review workflow before implementation; Paul reviews the human surfaces. The agent directives, protocol identifiers and synthetic fixture fields are LLM-facing and exempt. Any additional human-facing string discovered during implementation joins this same table/index before use. |
| + |
| +| IDs | Surface and content to review | |
| +|---|---| |
| +| `home.hero.promise`, `home.hero.intro`, `home.hero.action`, `home.meta.description`, `home.og.description` | Modest hero promise such as Paul's “better, faster, more secure apps”, short invitation and accessible action. No numeric multipliers. Meta/social descriptions match the journey. | |
| +| `start.prompt` | Exact shared paste line: Follow the directions on [https://carlosframework.com/start](https://carlosframework.com/start). Copied as plain text with the complete URL. | |
| +| `start.title`, `start.meta.description`, `start.intro`, `start.steps`, `start.lifetime`, `start.data`, `start.claim`, `start.account`, `start.agent.heading`, `start.authorship` | Page title/metadata, what happens, temporary/public app and no-backup explanation, keeping it by email, account/migration link, visible “for your agent” heading and AI attribution. | |
| +| `copy.label`, `copy.done`, `copy.fallback`, `copy.aria` | Button label, success status, selection/manual-copy fallback and accessible names. Shared across homepage and start page. | |
| +| `start.disabled.title`, `start.disabled.body`, `start.disabled.account` | Account-only path when the website journey is disabled; no promise of a working demo or claim. | |
| +| `starter.title`, `starter.empty`, `starter.name`, `starter.add`, `starter.invalid`, `starter.full`, `starter.error`, `starter.aria` | One-screen shop-list starter: title, empty state, field and submit labels, input/row-limit errors, generic database failure and accessible names. No live credentials, personal information or framework jargon. | |
| +| `start.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. | |
| + |
| +## 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. |
| + |
| +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. |
| + |
| +## 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. |