carlos / platform Public

plan: agent-start-demo plan 1, anonymous demo apps on dev

Written by Astra from the approved design; controller fixes: abuse
logs keep the creating IP and client header, generous per-IP budget,
60 updates per demo, open questions settled.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev c2a25331c458183f633d1584cbc290b698636033 parent df476c3
1 file changed, +387 −0
  • docs/superpowers/plans/2026-11-02-agent-start-demo-1-anonymous-apps.md +387 −0
diff --git a/docs/superpowers/plans/2026-11-02-agent-start-demo-1-anonymous-apps.md b/docs/superpowers/plans/2026-11-02-agent-start-demo-1-anonymous-apps.md
new file mode 100644
index 000000000..c74c6da81
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-02-agent-start-demo-1-anonymous-apps.md
@@ -0,0 +1,387 @@
+# Anonymous demo apps on dev 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:** An unauthenticated agent submits a small Go source archive and receives a working, updatable, SQLite-backed demo URL on the operator's demo fleet for 24 hours.
+
+**Architecture:** The console owns admission, claim-token hashes, jobs, publication and temporary-app expiry; a dedicated fleet builds source in disposable offline systemd units. Completed binaries enter the existing ship, signed promotion, adoption and fleet-routing paths. An explicit demo identity carries restrictive instance policy and local-only database durability without changing ordinary apps.
+
+**Tech Stack:** Go, SQLite, systemd 257 nested isolation, Ed25519, existing release.Store and change-index interfaces; linux-arm64 output, Rastrillo and Fiesta dependency lock (open question 1).
+
+**Spec:** `docs/superpowers/specs/2026-11-02-agent-start-demo-design.md`, approved 2026-11-02, especially §§4.1–4.4, 5 and 6. Also read `2026-09-25-temporary-static-sites-design.md` §§1–6, `2026-10-28-managed-fleets-design.md` §4 phase 1 and §6, `2026-10-21-instance-sizes-and-egress-design.md` §§0, 3a, 4.3 and 5, and `2026-10-24-rootfs-apps-design.md` §§3, 5.3, 5.7 and 7, all under `docs/superpowers/specs/`.
+
+## Global Constraints
+
+- Plan 1 of 4 only: anonymous publish, build, placement, routing and lifecycle on dev. No claim-by-email implementation, website, banner, CSP, cookie rewrite, traffic caps, cap page, kill switch, takedown verb or report link.
+- Fixed design requirements: “24 hours, no extension without claiming”; “nothing is backed up”; “the smallest instance size; low CPU weight”; “no outbound network at all”; “no email, object storage, schedules, sidecars or custom domains”.
+- Source cap is 5 MB compressed, defined here as 5,000,000 bytes; output is linux-arm64; `CGO_ENABLED=0`; no `go:generate`, toolchain directive, unapproved imports or network-dependent build.
+- Provider-neutral core: use release.Store, fleet APIs and systemd, never an AWS SDK in new core packages. No new per-box polling; build dispatch rides the console's existing change index and durable outbox, with a pushed worker stream.
+- Deployment switches default off. With no demo settings, API routing, app creation, units, budgets, replication, domains and bucket request counts remain as today.
+- Additive wire fields with zero-value compatibility. A fleet box that cannot enforce the demo contract must refuse demos, never run them as ordinary apps.
+- Examples use `shop` and `example.com`; `trycarlos.com` is the approved Carloku configuration value, not a core default. No tenant names in examples.
+- User-facing strings remain **copy review required**, collected in the one table at the end. Do not treat protocol identifiers or test assertions as approved prose. No em dashes in user-facing copy.
+- This document authoring session changes only this plan, in `design-agent-start-demo`; no product code, commit, push, other worktree or full test suite. Commit and verification steps below are for subsequent implementation.
+- Implementation scratch goes on disk; keep the agent's default Go caches. Build-service cache mounts described below are product isolation requirements, not instructions to relocate the implementer's cache into `/tmp`.
+- Paul receives the visible first slice: all tasks land together, with a source-to-live-URL dev witness. Dev switches on when Plan 1 lands; Carloku switches on when `/start` ships after Plans 2 and 3. Do not merge scaffolding separately.
+- No production or shared-account infrastructure changes are authorized by this plan. Dev activation requires an explicitly designated sandbox or scoped approval for the exact DNS, certificates, fleet and configuration changes; local mocks proceed independently.
+
+## Review Focus
+
+1. Concurrent creates, a restarted console and forged forwarded IPs must not reset budgets or overfill the live ceiling: Task 1, `TestDemoAdmissionDurableAndAtomic`.
+2. A small archive containing expansion bombs, alternate dependency inputs or hidden build files must be refused before compilation: Task 2, `TestDemoSourceCannotEscapeLock`.
+3. Missing policy or an inherited DNS allow must never give a demo internet access or a larger fallback size: Task 3, `TestDemoPolicyFailClosed` and `TestDemoDenyAllKernel`.
+4. Duplicate, stale or cross-box build results arriving after update, expiry or restart must not publish: Task 5, `TestDemoJobAttemptFencing`; Task 7, `TestDemoPublishRechecksLifetime`.
+5. An expired app with a running build or an interrupted purge must disappear without resurrection, unrelated deletion or a replica upload: Tasks 4 and 8, `TestDemoLeaseWithoutReplication` and `TestDemoExpiryRaces`.
+
+---
+
+## Discovery and implementation boundaries
+
+Read against checkout `df476c3b6178877ec65930a57fa037cf46842732`. Citations are current checkout line anchors, not the older line numbers inside the designs. New names below are proposed interfaces, not claims about existing code.
+
+| Existing mechanism | Evidence and consequence |
+|---|---|
+| Temporary create | `internal/console/authcli.go:577`, `internal/console/apitemporary.go:105`, `:133`, `:198`: authenticated `/api/cli/apps/{account}/new-temporary`, strict body, fresh `tmp-` name, no placement. Do not expose that handler without authentication. |
+| Fresh-name claim | `internal/console/server.go:5305` `claimAppWith(ctx, acct, name, addr, placement, ownerClaim, rq, expiresAt)` checks namespace and prefix occupancy. Share its fresh-claim checks, never use owner adoption for demos. |
+| Lifecycle storage | `internal/console/store.go:569`, `:765`; `internal/console/tempstore.go:25`, `:51`, `:87`: apps expiry, restoring, purge timestamps, lifetime and cap predicates. Console rows remain the sole expiry authority. |
+| Existing retention | `internal/console/expirypass.go:20`, `:154`, `:203`; `internal/console/store.go:2022`; `internal/console/lifetimes_purge.go:40`; `internal/release/trash.go:196`, `:350`: five-minute expiry pass, tombstone-bound purge, three-day temporary grace, policy cleanup. Demo prompt purge requires a separate rule. |
+| Existing restrictions | `internal/console/apicli.go:2154` rejects temporary binary/rootfs ship; `internal/console/fleets.go:798` refuses placing temporary apps. The temporary design §4 lists all capability mutation doors. Only the internal demo workflow may create a demo binary instance. |
+| Budgets and IPs | `internal/console/authcli.go:114` has 10 create attempts/address/24h and `:124` has 50 temporary attempts/principal/24h; `internal/console/svcprincipal.go:610` shares the temporary limiter; `internal/console/authcli.go:1182` `clientIP` uses the edge proof (`internal/console/edgeproof.go:66`). The existing map reset caveat at `internal/console/authcli.go:115` is unsuitable for anonymous global admission. |
+| Fleet creation and assignment | `internal/console/apicli.go:454` validates `place`; `internal/registry/fleets.go:714` parses `fleet/<f>`; `internal/console/fleets.go:728` `placeAppTarget`; `internal/console/apiinstances.go:1778` inherits placement. `internal/console/fleetbox.go:249`, `:128` load the fleet view and choose a destination. |
+| Fleet record ownership | `internal/provision/provision.go:68` has FleetBox/FleetBoxAt; `internal/provision/reconcile.go:513`, `:538` scope and own records. Demo records must name their box even on a single-box fleet. |
+| Actual deploy path | `deploy.go:502`, `:508`: ship then promote; `apimode.go:4925` uploads artifacts; `internal/console/apicli.go:2027` handles ship. `internal/release/claim_app_writes.go:26`, `:40` expose `ShipSpooled` and `Signer.PromoteOnLadder`. |
+| Artifact representation | `internal/release/release.go:81`, `:319`, `:322`, `:325`: platform artifact map, manifest/artifact/channel keys under the account/app. `internal/release/adopt.go:29` selects the box architecture; `internal/release/versions.go:109` checks staged digests. Do not install output straight into a live link. |
+| Change-driven work | `internal/release/changeindex.go:40`, `:54` excludes data prefixes and maps app keys; `internal/host/changeindex.go:48`, `:180`, `:261` arms one watcher and runs scoped passes; `internal/host/agent.go:3186` acts on changed generations. However `internal/host/changeindex.go:48` explicitly disables the reader on fleet boxes. Use the console watch at `cmd/console/main.go:675`, `:1799` and its existing backstop at `:1817`; add a pushed build stream, not a fleet poll. Include jobs for apps with no route yet. |
+| Box transport | `internal/edge/storedoor.go:1`, `:530`, `:644` lets a fleet read its account's app objects, but not publish releases. `internal/host/runrelay.go:3`, `internal/console/apirunsbox.go:1` provide a per-instance run relay, not a general build queue. Add a dedicated build protocol; do not turn `carlos run` into arbitrary host execution. |
+| Unit installation | `internal/host/bootstrap.go:36`, `:512`, `:642` embeds and enumerates service/slice files; extend this installation path for the builder. |
+| Box authentication | `internal/console/apiinteractivebox.go:117` `fleetIdentityOK(reg, name, token, wantFleet, wantAccount)` verifies the active fleet box and account ownership. Build completion must additionally match the assigned box label and attempt. |
+| Signed instance policy | `internal/apppolicy/apppolicy.go:52`, `:141`, `internal/apppolicy/signed.go:136`; `internal/console/apipolicy.go:181` and `internal/console/policylease.go:1`: signed policy, revision checks, console writer lease. `internal/provision/apppolicy_cache.go:149`, `internal/provision/apppolicy_reconcile.go:114`, `internal/provision/reconcile.go:1039` deliver it to routes. |
+| Policy enforcement | `internal/host/egress_source.go:143`, `:244`, `:432`; `internal/instancectl/egress.go:201`; `internal/activator/size.go:38`. Current policy adds private-address allows, not deny-all. Claims mode deliberately defers egress; Plan 1 refuses activation with claims mode enabled. |
+| Smallest size | `internal/cgroup/sizes.go:18`: small = 256 MiB, CPUWeight 50, CPUQuotaPercent 50, IOWeight 50. Use this table, not a parallel tier definition. |
+| Nested isolation | `internal/host/units/carlos-instance@.service:28`, `:53`, `:71`, `:150`, `:174`: carlos UID, own writable directories, namespace fences, public-internet-permitting IP filter, W^X. Root entry is `internal/instancectl/server.go:319`, `:397`, `:715`; socket path is `internal/controlsock/controlsock.go:15`. |
+| Database lease and backups | `internal/activator/activator.go:382`, `:3149`; `internal/activator/backend_exec.go:802`, `:850`; `internal/lease/lease.go:132`, `:405`, `:560`: stateful wake currently trades the lease for a replicator. `internal/registry/registry.go:550` has no replication-off class. Empty replication means stream, not off. |
+| Hostname routing and TLS | `cmd/console/main.go:528`, `:964` configure `PLATFORM_APPS_DOMAIN`; `internal/provision/provision.go:352` has manifest Domain. `internal/edge/edge.go:824`, `:1604`, `:1855` reload, look up and serve routes. `internal/provision/forward.go:28`, `:51` and `internal/registry/forward.go:87` enumerate forward-row fields and their writers; add demo metadata there too. `internal/edge/pending.go:161` and `internal/edge/wildcard.go:203` support explicit `CARLOS_WILDCARD_DOMAINS` parents. |
+| Regional domains #447 | `internal/edge/regional.go:3`, `:65`, `:111`: regional claims bind to regional targets and prohibit backhaul. They do not supply an additional platform apps-domain setting. Use direct demo hosts and the existing fleet forward path, not regional claims. |
+| Dependency evidence | `go.mod:3` specifies Go 1.26.0; installed `go version` reports go1.26.10. `internal/console/static/rastrillo/VERSION:4` pins frontend assets v0.29.0; `internal/console/static/fiesta/VERSION:2` pins CSS 1.1.0. Neither proves the build's Go dependency closure. |
+
+## Decisions and file map
+
+Nine tasks, one implementation branch and one visible merge. Tasks 1–2 define admission and source boundaries; 3–4 define runtime guarantees; 5–6 deliver bounded build work; 7 connects publication and routing; 8 completes deletion; 9 proves the whole slice. Files created by a task are owned there; later tasks consume its interfaces. Existing files in Files blocks refer to the anchors above or the explicit anchors in the block.
+
+Choose an operator-provisioned, non-ops **holding account** with no human memberships or service credentials, owning only the demo fleet. Require an empty fleet at first enablement and reject normal apps on that fleet thereafter. Anonymous callers never acquire that account's credentials or select an account, host, fleet, box, channel, policy or TTL. Ordinary temporary apps keep every existing rule.
+
+Use public names `adjective-noun-NN`, cryptographically sampled from two checked-in lists of 128 benign words of at most eight letters and a two-digit suffix. Internal app names are `tmp-demo-<public-name>`; public hosts are `<public-name>.<DemoDomain>`. Reserve the internal namespace from ordinary creation and keep a unique public-host reservation until purge finishes. Retry a collision at most 16 times; do not infer authority from a name. Job IDs and demo IDs are independent random identifiers (32 and 16 bytes respectively, base64url without padding).
+
+New operator settings, all parsed into `demo.Config`:
+
+| Setting | Value/validation |
+|---|---|
+| `CARLOS_DEMO_APPS` | Only `1` enables console admission; unset disables. |
+| `CARLOS_DEMO_ACCOUNT`, `CARLOS_DEMO_FLEET`, `CARLOS_DEMO_DOMAIN` | Required when enabled; holding-account sqid, owned fleet name, bare separate registrable domain. Refuse overlap with the console, primary apps zone, or a customer domain claim. |
+| `CARLOS_DEMO_CREATE_PER_IP_DAY`, `CARLOS_DEMO_CREATE_GLOBAL_DAY`, `CARLOS_DEMO_MAX_LIVE` | Defaults 30, 100, 20 (per-IP is deliberately generous: many cloud agents share a few egress addresses, design §4.6; the global budget is the real bound); positive integers. Durable rolling 24h attempt windows; ceiling counts reserved, building, failed-but-retained and live demos. Refuse, never evict. |
+| `CARLOS_DEMO_BUILD_WORKER` | `1` only on designated nested linux-arm64 demo boxes. Root and agent both require fleet/account/domain configuration matching the console. |
+| `CARLOS_DEMO_BUILD_CONCURRENCY` | Default 1, allowed 1–4; lower to 1 if provisioning cannot reserve the per-build memory. |
+| `CARLOS_DEMO_TOOLCHAIN_DIR` | Absolute root-owned immutable toolchain/cache bundle directory; required by worker. Verified manifest pins Go 1.26.10, module graph and file digests. No remote fetch fallback. |
+
+The console uses its configured origin for all API and claim links. Enabling console admission requires worker readiness, a verified dependency bundle, policy writer lease, compatible hub/box demo capability `anonymous-demo-v1`, working TLS/DNS and change-index delivery. Add the capability to existing box status, not a heartbeat loop. A disabled admission switch still permits cleanup of existing demos; it is not Plan 2's serving kill switch.
+
+## Interfaces for later plans
+
+- Console identity: add `apps.demo_id TEXT NOT NULL DEFAULT ''`; add `demo_apps` keyed by `demo_id`, unique `(account_id, app)` and `host`, with `name`, `claim_token_hash BLOB`, `created_at`, `generation`, `state`, `assigned_box`. Expiry and lifetime stay on `apps`, never in a second lifecycle clock. `state` is `anonymous`, `retiring` or `retired`; Plan 3 may add its claim states.
+- Tokens: 32 random bytes, base64url; store SHA-256 of decoded bytes only and compare in constant time. Return `claimToken` only on accepted create. Neither jobs, logs, audit, bucket objects nor status contain it or its hash. No recovery or rotation endpoint in Plan 1.
+- Wire identity: add optional `demo` (`*demo.Descriptor`) to the provision record and signed app policy; add `DemoID`, `DemoHost`, `DemoExpiresAt`, `DemoLifetime` to the registry row. Descriptor fields are `ID`, `Host`, `Lifetime` (strings), `ExpiresAt` (int64 Unix seconds). Every ordinary writer preserves it; every placement/adoption path validates account, app, host, lifetime and fleet binding. Root requires the signed policy for a demo start.
+- Plan 2 consumes `registry.Route.IsDemo() bool` and `edge.demoHost(host string) bool`. The latter checks a single direct label under the configured demo domain, independently of a live route, so pending, cached and expired-host responses can receive Plan 2 controls. Descriptor survives hub forwarding and edge reload; it contains no token. Unknown hosts receive no route merely because their suffix matches.
+- Plan 3 consumes `(*Store).LookupDemoToken(ctx context.Context, token string) (DemoRow, error)` and `(*Server).withDemoLocked(ctx context.Context, id string, fn func(DemoRow, AppLife) error) error`. The callback runs under the same app mutex as expiry; it must reread lifecycle/generation. Plan 1 does not implement a transfer, email, challenge, TTL extension or claim state transition.
+- Create returns `claimUrl = <console-origin>/demo/claim#<claimToken>`, with `claimAvailable:false` until Plan 3. Reserve this path; its handler and UI belong to Plan 3. Do not promise a working claim flow on the dev slice or put the token in query parameters.
+- Local SQLite persists through sleep, update and process restart on its assigned box. There is no replica to copy during Plan 3: its claim plan must arrange a quiesced local-data transfer before retirement. Plan 1 refuses moving a demo to another box with a fresh empty database.
+
+### Task 1: Durable anonymous admission and identity
+
+**Risk/review:** security gate, storage and billing admission. Independent task review required.
+
+**Files:**
+- Create: `internal/demo/config.go`, `internal/demo/identity.go`, `internal/demo/names.go`, `internal/console/demo_store.go`, `internal/console/apidemo.go`.
+- Modify: `cmd/console/main.go:528`, `internal/console/server.go:5305`, `internal/console/store.go:569`, `internal/console/tempstore.go:25`, `internal/console/authcli.go:577`.
+- Test: `internal/demo/config_test.go`, `internal/console/apidemo_test.go`, `internal/console/demo_store_test.go`.
+
+**Interfaces:**
+- Consumes: existing `clientIP(*http.Request) string`, fresh-name checks and app lifecycle storage from discovery.
+- Produces: `demo.LoadConfig(getenv func(string) string) (Config, error)`, `demo.NewIdentity(r io.Reader) (Identity, error)`; Identity carries demo ID, public name, internal app name, plaintext token and hash.
+- Produces: `DemoRow` with the columns above; `(*Store).ReserveDemo(ctx context.Context, in DemoAdmission) (DemoRow, error)`. DemoAdmission contains Identity, account ID/sqid, host, fleet, canonical IP, now and Config; transaction writes app/lifetime, hash, host reservation, counters and first job together.
+- Produces: `LookupDemoToken` and `withDemoLocked` above; handlers `handleDemoPublish(w http.ResponseWriter, r *http.Request)` and `handleDemoStatus(w http.ResponseWriter, r *http.Request)`.
+- HTTP: `POST /api/demo/apps` accepts a raw gzip tarball (`application/gzip`), no credential for create; `Authorization: Bearer <claimToken>` means update of exactly its app. A supplied invalid credential never falls back to create. `GET /api/demo/jobs/{jobID}` is a read-only bearer-by-unguessable-ID status URL.
+- Replies: create/update 202 with `jobId`, `name`, `statusUrl`, `expiresAt`; create alone adds token/claim URL/availability. Status has `state` = `building|starting|live|failed`, `url` only after readiness, and `diagnostics` on failure. Internal queued/running states map to building. All responses are `Cache-Control: no-store`.
+
+- [ ] **Step 1: Write failing admission tests.** Add these executable assertions to the named tests:
+
+```text
+TestDemoAdmissionDurableAndAtomic: acceptedConcurrentCreates <= 20; createsAtIP31 == 429; globalAttempt101 == 429; restartRemainingBudget == previousRemainingBudget; spoofedXFFBudgetKey == peerIP; ceilingEvictions == 0
+TestDemoIdentity: rawTokenBytes == 32; persistedToken == SHA256(rawToken); statusContainsToken == false; ordinaryTemporaryCap == 20; ordinaryTemporaryBudget == 50
+TestDemoUpdateAuthority: invalidBearerCreates == 0; validUpdateDemoID == originalDemoID; expiryAfterUpdate == expiryBeforeUpdate; activeJobsPerDemo <= 1
+TestDemoConfigOff: demoPOST == 404; newBackgroundLoops == 0; ordinaryResponses == baseline; partialEnabledConfig == error
+```
+
+- [ ] **Step 2: Run tests to verify failure.** `go test ./internal/demo ./internal/console -run 'TestDemo(Admission|Identity|UpdateAuthority|ConfigOff)' -count=1`; expect missing interfaces or failed assertions.
+- [ ] **Step 3: Implement the Task 1 interfaces in its files.** Use durable attempt rows `demo_admissions(ip_hash, attempted_at)` and a transaction to spend per-IP/global budgets before parsing archive contents; use `clientIP`, normalize IPv4-mapped IPv6, and prune rows older than 24h without wholesale reset. Refusals for exhausted IP/global budgets spend no additional row. The request byte cap applies before spooling; body reading has a 30s deadline. Reserve only after validation in Task 2; until wired, the handler refuses rather than accepting unusable jobs. Cap updates at 60 attempts per demo lifetime (agents iterate on build errors; running out mid-demo is the "scary first run" anti-goal), separate from create budgets; one active job per demo, 409 otherwise. Status uses console DB only, with a bounded 60/minute/IP limiter and a 2s suggested retry. Budget rows key on a salted IP hash, but the demo row also keeps the raw creating IP, the source archive SHA-256 and the `X-Carlos-Client` header value (trimmed to 100 bytes) for the app's life plus 7 days after purge, then wipes them (design §4.6 abuse logs; §4.1 client header). Store errors fail admission closed.
+- [ ] **Step 4: Run the Step 2 command.** Expect PASS, including original temporary-create regression tests via `-run 'Test.*Temporary|TestDemo'` in `./internal/console`.
+- [ ] **Step 5: Commit.** Stage only this task's files; subject `feat: add bounded anonymous demo admission`.
+
+### Task 2: Validate source against an offline dependency lock
+
+**Risk/review:** security gate and cache. Independent task review required. Dependency lock completion is blocked by open question 1; do not guess module versions.
+
+**Files:**
+- Create: `internal/demobuild/source.go`, `internal/demobuild/lock.go`, `internal/demobuild/diagnostics.go`, `internal/demobuild/toolchain.lock.json`, `internal/demobuild/testdata/` fixtures.
+- Test: `internal/demobuild/source_test.go`, `internal/demobuild/diagnostics_test.go`.
+
+**Interfaces:**
+- Consumes: Task 1 source cap and identity; `release.Store` later stores only the accepted original bytes plus their digest.
+- Produces: `demobuild.ValidateSource(r io.Reader, lock Lock) (Source, []Diagnostic, error)`; Source is bounded archive bytes, SHA256 and normalized file inventory, not a caller-supplied filesystem path.
+- Produces: `demobuild.ReadLock(r io.Reader) (Lock, error)`; Lock contains exact toolchain, direct-import package prefixes, module versions/sums and transitive closure, bundle digest and entry package `.`.
+- Produces: `Diagnostic{File string, Line int, Message string}` and `demobuild.TrimDiagnostics(raw []byte) []Diagnostic`.
+
+- [ ] **Step 1: Write failing source tests.**
+
+```text
+TestDemoSourceLimits: compressedBytes(5000001) == refused; expandedBytes(20000001) == refused; fileCount(257) == refused; binaryCap == 33554432
+TestDemoSourceCannotEscapeLock: traversal/symlink/hardlink/device/sparse/duplicatePath/archiveTrailingData == refused; go.work/vendor/nestedGoMod/replace/toolchain/goGenerate/importC/syso/assembly/linkname == refused; wrongVersion == refused
+TestDemoImports: stdlibAndLockedFrameworkAndLocalPackages == accepted; userImportOfTransitiveOnlyModule == refused; ignoredBuildTagFileWithBadImport == refused
+TestDemoDiagnostics: maxEntries == 50; totalUTF8Bytes <= 16384; noAbsoluteHostPathsOrANSIOrTokens; fileLineMessagePreserved == true
+```
+
+- [ ] **Step 2: Run tests to verify failure.** `go test ./internal/demobuild -run 'TestDemo(Source|Imports|Diagnostics)' -count=1`; expect missing interfaces/assertion failure.
+- [ ] **Step 3: Implement the Task 2 interfaces.** Accept one gzip member containing a tar archive with regular files and directories only; 20,000,000 bytes expanded, 256 files, 2,000,000 bytes/file. Reject absolute paths, backslashes, NULs, dot segments and normalized duplicates. Parse every `.go` file, including excluded build tags and tests, without executing tools. Allow one root module `demo.local/app`, its internal imports, stdlib except `C`, and the locked Rastrillo/Fiesta import prefixes. Module files may only match the lock's requirements and sums; no replace, exclude, toolchain, tool, workspace or vendor inputs. Reject `go:generate` and `go:linkname`; confine embed inputs to validated regular files. Dependency transitive imports come from the operator lock, never from archive-selected versions. Return only normalized relative file/line/message diagnostics; truncate compiler output at 64 KiB before parsing. Approved copy IDs represent platform validation failures; do not forward raw tool banners, environment or paths.
+- [ ] **Step 4: Run the Step 2 command.** Expect PASS with both boundary values and one byte/file beyond each bound.
+- [ ] **Step 5: Commit.** Stage only Task 2 files; subject `feat: validate demo source against an offline module lock`.
+
+### Task 3: Enforce demo identity, smallest size and deny-all networking
+
+**Risk/review:** security gate, root and cache. Independent task review and root-read census required.
+
+**Files:**
+- Create: `internal/demo/descriptor.go`, `internal/console/demo_policy.go`, `internal/instancectl/demo_policy.go`, `internal/host/demo_policy.go`.
+- Modify: `internal/apppolicy/apppolicy.go:52`, `internal/provision/provision.go:68`, `internal/provision/apppolicy_reconcile.go:114`, `internal/provision/reconcile.go:1039`, `internal/registry/registry.go:550`, `internal/host/egress_source.go:244`, `internal/instancectl/server.go:715`, `internal/instancectl/egress.go:201`, `internal/activator/size.go:38`.
+- Test: `internal/apppolicy/demo_test.go`, `internal/provision/demo_policy_test.go`, `internal/instancectl/demo_policy_test.go`, `internal/host/demo_policy_linux_test.go`.
+
+**Interfaces:**
+- Consumes: Task 1 identity/lifetime; existing signed policy writer, reader and smallest-size table.
+- Produces: `demo.Descriptor`, `registry.Route.IsDemo() bool`; `apppolicy.Policy.EgressMode string` (`""` = existing behavior, `"deny-all"` = demo) and `Policy.Demo *demo.Descriptor`.
+- Produces: `(*Server).writeDemoPolicy(ctx context.Context, d DemoRow, life AppLife) error` and `(*instancectl.Server).assertDemoPolicy(ctx context.Context, host string) error`; signature verification, policy revision and lifetime binding are mandatory before start.
+- Root fixed policy: small, no allows, no replica, demo descriptor required. `demo.ValidateBinding(d Descriptor, account, app, host, lifetime, fleet string) error` validates identity, generated name, lifetime, host and configured placement. Existing records without Demo remain byte-compatible.
+
+- [ ] **Step 1: Write failing policy tests.**
+
+```text
+TestDemoPolicyFailClosed: absent/expired/badSignature/wrongLifetime/wrongFleet/missingMarker/flat/claimsMode == noStart; size == small; ordinaryNoPolicyUnits == baseline
+TestDemoDenyAllKernel: connect(publicIPv4/publicIPv6/loopback/IMDS/resolver/inheritedAllowedIP) == denied; unixAppSocketHTTP == success; spawnedChildConnect == denied
+TestDemoPolicyRoundTrip: descriptorSurvivesOrdinaryRecordWriters == true; downgradeToOrdinary == refused; nonDemoDefaults == baseline
+```
+
+- [ ] **Step 2: Run tests to verify failure.** `go test ./internal/apppolicy ./internal/provision ./internal/instancectl ./internal/host -run 'TestDemoPolicy|TestDemoDenyAll' -count=1`; expect assertions to fail. Kernel witness runs only on an explicitly designated systemd dev sandbox.
+- [ ] **Step 3: Implement the Task 3 interfaces.** Write through the existing policy lease/revision/audit machinery, including its writer census. Extend its changed-app cache and route delivery, without another watcher. For demo service starts, set and verify `PrivateNetwork=yes`, `RestrictAddressFamilies=AF_UNIX`, `IPAddressDeny=any` and empty unit allows; the network namespace and address-family restriction close inherited slice DNS allows. Apply to every generation and command/seed variant a demo could reach, or refuse that variant; rootfs and sidecars are refused. Root reads the signed descriptor through the existing policy read gate and refuses malformed/missing state on a configured demo fleet. Do not convert a demo to ordinary behavior on policy failure. Enforce small from the size table and prove effective cgroup values before exec. Keep this additive extension separate from deferred claims-mode egress.
+- [ ] **Step 4: Run the Step 2 command and the dev kernel witness.** Expect PASS; a skipped kernel witness is not evidence of isolation. Recheck policy writer inventory and ordinary no-policy tests.
+- [ ] **Step 5: Commit.** Stage this task's files and approved census additions; subject `feat: enforce demo instance size and deny-all networking`.
+
+### Task 4: Keep local SQLite and its lease without backups
+
+**Risk/review:** storage, termination and billing. Independent task review and census required.
+
+**Files:**
+- Create: `internal/activator/demo_durability.go`.
+- Modify: `internal/activator/activator.go:382`, `:3149`, `internal/activator/backend_exec.go:802`, `:850`, `:916`, `internal/activator/escrow.go:377`; `internal/console/fleetrelabel.go:143`, `:405`.
+- Test: `internal/activator/demo_durability_test.go`, `internal/console/demo_move_test.go`.
+
+**Interfaces:**
+- Consumes: verified Task 3 descriptor; existing `Lease`, `Rep`, `execLease` and renewing `lease.Held` from discovery.
+- Produces: optional `localDemoLease` interface `KeepLocal(ctx context.Context) (Rep, error)`, implemented by `execLease`. The returned Rep's Err observes lease loss; Close releases the lease without checkpointing/uploading a replica.
+- Produces: `(*ExecBackend).restoreDemoLocal(ctx context.Context, rt registry.Route) (bool, error)`; only a newly created instance may initialize absent data. Existing-instance missing data is a reported failure, not silent reseeding.
+
+- [ ] **Step 1: Write failing durability tests.**
+
+```text
+TestDemoLeaseWithoutReplication: concurrentWriters == 1; leaseRenewals > 0; replicaGETs == 0; replicaPUTs == 0; snapshotCalls == 0; lostLeaseStopsApp == true
+TestDemoDatabaseSurvivesLocalRestart: sleepWakeAndUpdateRead == previousSQLiteValue; newInstanceMissingDB == fresh; establishedInstanceMissingDB == failed
+TestDemoCannotMoveWithoutData: fleetRelabel/drain/moveDemoToAnotherBox == refused; regularFleetRelabel == baseline
+```
+
+- [ ] **Step 2: Run tests to verify failure.** `go test ./internal/activator ./internal/console -run 'TestDemo(Lease|Database|CannotMove)' -count=1`; expect failures at current replication/restore behavior.
+- [ ] **Step 3: Implement the Task 4 interfaces.** Select KeepLocal only for a verified demo route; a backend without it refuses that route. Preserve lease acquisition, renewal, fencing and stop-before-release ordering. Retain `CARLOS_DB` and ordinary nested DB paths. Skip backup restore, Litestream creation, seed snapshots, escrow and HA file publication for demos; refuse seed/import/move/HA APIs for them. Fence the assigned box rather than using fleet failover to an empty database. Ordinary replication classes and their defaults remain untouched. Cover all service wake and adoption restart paths with the same predicate.
+- [ ] **Step 4: Run the Step 2 command.** Expect PASS, with spy stores proving absence of replica reads/writes rather than relying on an omitted configuration string.
+- [ ] **Step 5: Commit.** Stage Task 4 files and approved census additions; subject `feat: retain demo database leases without replication`.
+
+### Task 5: Deliver fenced build jobs over existing app changes
+
+**Risk/review:** security gate, storage and cache. Independent task review and census required.
+
+**Files:**
+- Create: `internal/demobuild/job.go`, `internal/console/demo_jobs.go`, `internal/console/apidemobox.go`, `internal/host/demo_jobs.go`.
+- Modify: `internal/release/changeindex.go:40`, `cmd/console/main.go:675`, `:1817`, `internal/host/agent.go:3186` (worker startup alongside existing passes), `internal/console/server.go:1444` (server-owned synchronization/state).
+- Test: `internal/demobuild/job_test.go`, `internal/console/demo_jobs_test.go`, `internal/host/demo_jobs_test.go`.
+
+**Interfaces:**
+- Consumes: Source/Lock/Diagnostic (Task 2), DemoRow and locked lifecycle (Task 1), fleet identity authentication from discovery.
+- Produces: `demobuild.Job` with ID, DemoID, Account, App, Host, Lifetime, Fleet, Box, SourceSHA256 and BundleSHA256 (strings), Generation (uint64), Attempt (uint32), Deadline (time.Time); no executable path, shell, environment or compiler flags.
+- Produces: `demobuild.SignJob(priv ed25519.PrivateKey, j Job) ([]byte, error)` and `VerifyJob(pub ed25519.PublicKey, wire []byte, now time.Time) (Job, error)` using separator `carlos demo-build v1\n`.
+- Produces: `(*Server).enqueueDemo(ctx context.Context, d DemoRow, src demobuild.Source) (demobuild.Job, error)`; `(*Server).DispatchDemoChanges(ctx context.Context, scopes []string) error`; `(*demoWorker).Accept(ctx context.Context, signedJob []byte) error`; `(*Server).acceptDemoResult(ctx context.Context, j demobuild.Job, result demobuild.Result) error`.
+- `demobuild.Result` contains job/attempt, source/bundle digests, binary spool path (console-local only), binary digest/size, and diagnostics. HTTP never accepts a spool path; it receives bytes.
+- Objects: `apps/<account>/<app>/demo-build/current.json` holds the signed job; `demo-build-data/<jobID>/source.tar.gz` beneath that app holds source. Add only `demo-build-data` to ChangeScope's data-prefix exclusions. Jobs have a SQL outbox: accepted admission plus desired job in one transaction; retry the same object after a failed write.
+- New worker stream: `GET /api/box/demo-builds` upgrades to a WebSocket authenticated with the existing fleet-box identity. Console sends fixed-schema signed job envelopes for that exact box; reconnect replays outstanding queued jobs from SQL. `(*Server).handleDemoBuildStream(w http.ResponseWriter, r *http.Request)` and `(*demoWorker).Connect(ctx context.Context) error` own it. Use the run-relay transport precedent, without sharing its app-instance admission.
+- New box doors on the console: `POST /api/box/demo-builds/{jobID}/pickup` and `POST /api/box/demo-builds/{jobID}/result`. They require existing fleet-box bearer authentication, exact assigned label, matching attempt and live demo generation. Pickup is an atomic state transition; results are bounded multipart bytes plus fixed-schema metadata.
+
+- [ ] **Step 1: Write failing job tests.**
+
+```text
+TestDemoJobAttemptFencing: duplicatePickupRuns == 1; wrongBox/wrongFleet/staleAttempt/expiredDemo == refused; duplicateMatchingResultPublishes <= 1; changedDuplicateResult == refused
+TestDemoJobsUseChangeIndex: unchangedTicksExtraStoreRequests == 0; changedAppJobReads <= 1; appWithoutRouteJobDiscovered == true; fleetIndexRemainsDisarmed == true; idleWorkerStorePolls == 0; sourceAndOutputWritesBumpScope == false
+TestDemoJobCrashRecovery: outboxReplayJobID == original; pickedJobAfterConsoleRestart == failedUnlessMatchingDurableResult; lateResultAfterFailure == refused
+```
+
+- [ ] **Step 2: Run tests to verify failure.** `go test ./internal/demobuild ./internal/console ./internal/host -run 'TestDemoJob' -count=1`; expect missing interfaces/assertion failures.
+- [ ] **Step 3: Implement Task 5's protocol.** Keep a SQL `demo_jobs` row keyed by ID with unique active `(demo_id)`, attempt, generation, assigned label, deadlines, state and result digest, plus durable outbox. Pick eligible ready arm64 boxes from the configured fleet only, counting pending builds as well as assigned instances. Maximum queue is 16 globally; queue pickup deadline 30s, build deadline 180s after pickup, result upload grace 15s. Expired queue entries fail instead of silently extending deadlines. Console dispatch observes its existing changed-app generations before route filtering and wakes immediately after its own successful outbox write. Share the already-armed watch; do not call Poll from a new loop. Existing console startup/backstop work reconciles pending SQL/outbox jobs. Push their signed envelopes over the new authenticated worker stream; reconnection is bounded network retry, not object-store polling. A worker with no free slot retains bounded local pending work and drains it on completion. Root's per-box semaphore is authoritative across agent restart. Read source through the existing read-only fleet store door; upload outputs to the console over the new authenticated door. Do not broaden fleet release/policy write ACLs. Console restart fails picked work safely; queued work is resumable. Peer identity is revalidated on reconnect and on pickup/result, and revoke/detach closes its stream. Retirement and publication notifications use this same stream to trigger the worker's existing scoped/full pass, so fleet boxes need no index reader or extra polling. No retry silently creates a second build.
+- [ ] **Step 4: Run the Step 2 command.** Expect PASS, including counting-store tests with no hosted route and with repeated unchanged ticks.
+- [ ] **Step 5: Commit.** Stage Task 5 files and approved census additions; subject `feat: queue demo builds through app change indexes`.
+
+### Task 6: Run offline builds in bounded disposable units
+
+**Risk/review:** root, security gate, termination and cache. Independent task review and census required.
+
+**Files:**
+- Create: `internal/instancectl/demo_build.go`, `internal/demobuild/runner.go`, `internal/host/demo_toolchain.go`, `internal/host/units/carlos-demo-build@.service`, `internal/host/units/carlos-demo-builds.slice`.
+- Modify: `internal/instancectl/server.go:397`, `internal/host/bootstrap.go:36`, `:512`, `:642`, `internal/host/units_isolation_test.go:250`; no new CLI verb. Tests also pin the off-switch installation/arming behavior so the added unit files never start a worker by themselves.
+- Test: `internal/instancectl/demo_build_test.go`, `internal/demobuild/runner_test.go`, `internal/host/demo_build_linux_test.go`.
+
+**Interfaces:**
+- Consumes: signed Job and bounded source (Task 5), Lock/validation/diagnostics (Task 2), nested readiness (Task 3).
+- Produces: `(*instancectl.Client).BuildDemo(ctx context.Context, signedJob []byte, source io.Reader) (demobuild.BuildOutput, error)` on the existing peer-vetted control socket; server handler `handleDemoBuild(w http.ResponseWriter, r *http.Request)`.
+- Produces: `demobuild.Run(ctx context.Context, workDir string, lock Lock) (BuildOutput, error)`; BuildOutput contains validated linux-arm64 ELF bytes/digest and diagnostics. Fixed root-selected paths only; workDir never comes from HTTP.
+- Produces: `host.CheckDemoToolchain(dir string, lock demobuild.Lock) error`; worker readiness includes exact toolchain/bundle digest, nested proof, free build slot budget and capability `anonymous-demo-v1`.
+
+- [ ] **Step 1: Write failing sandbox tests.**
+
+```text
+TestDemoBuildIsolation: siblingData/hostCredentials/controlSocket/sharedWritableCache == inaccessible; networkAndDNS == denied; descendantAfterTimeout == absent
+TestDemoBuildLimits: liveUnits <= configuredConcurrency; elapsed <= 185s; memoryMax == 1073741824; outputBytes(33554433) == refused; workBytes <= 536870912
+TestDemoOfflineBuild: CGO_ENABLED == 0; GOOS == linux; GOARCH == arm64; proxyRequests == 0; toolchainDownloads == 0; sharedSeedMutation == impossible; outputMachine == ELF_EM_AARCH64
+TestDemoBuildCleanup: cancel/failure/success/rebootRecovery => noJobScratchOrRunningUnit; wrongGrantOrSymlinkSource => noRootOpenOutsideJob
+```
+
+- [ ] **Step 2: Run tests to verify failure.** `go test ./internal/instancectl ./internal/demobuild ./internal/host -run 'TestDemo(Build|Offline)' -count=1`; expect missing interfaces/assertion failures. Reserve actual unit proof for the designated dev sandbox.
+- [ ] **Step 3: Implement the Task 6 interfaces and units.** Root verifies the signed job, account/fleet/box/lifetime/deadline, local worker switch and bundle digest. It accepts bounded source bytes, revalidates/hash-checks them, and creates root-owned paths under `/var/lib/carlos-demo-builds/<jobID>/<attempt>` with no-follow directory-relative operations. No caller-chosen unit name, argv or mount source. Run as an unprivileged dynamic UID, without the agent's credentials; copy the existing nested namespace protections and test every changed bind. Add PrivateNetwork, AF_UNIX-only, no capabilities, W^X, TasksMax 128, MemoryMax 1 GiB, MemorySwapMax 0, CPUQuota 50%, CPUWeight 10, RuntimeMaxSec 180, TimeoutStopSec 5 and KillMode control-group. Bound the entire writable work filesystem at 512 MiB and the builder slice to concurrency times its per-job limits. The compiler and approved module/cache seed are root-owned, read-only mounts; each build has a private writable build-cache overlay removed afterward, never a shared untrusted cache.
+
+ Use Go 1.26.10 with clean environment, `GOTOOLCHAIN=local`, `GOPROXY=off`, `GOSUMDB=off`, `GOWORK=off`, `GOENV=off`, `CGO_ENABLED=0`, `GOOS=linux`, `GOARCH=arm64`; fixed unit ExecStart `/opt/carlos/demo-toolchain/bin/go build -mod=readonly -trimpath -buildvcs=false -o /work/out/app .`, with the validated source at `/work/src` as WorkingDirectory. The configured toolchain is bound to that fixed read-only unit path; `demobuild.Run` prepares and supervises this invocation, never runs the compiler outside the unit. No inherited GOFLAGS, PATH tools, toolexec, generate, tests or execution of the resulting binary. A deterministic cache bundle is prebuilt from the resolved lock during operator provisioning; refresh only by installing a new verified digest and draining old jobs. Missing cache is a readiness refusal. Return bytes through a bounded pipe after proving a regular arm64 ELF with no interpreter; stop/reap the entire unit before collecting output or deleting scratch. Root recovers abandoned job directories/units at worker startup by validated IDs, never glob-deleting unrelated files.
+- [ ] **Step 4: Run the Step 2 command and the real sandbox witness.** Expect PASS and effective systemd properties read back; test a malicious fixture attempting network and sibling reads. Missing kernel/systemd support is a readiness failure, never a weaker build mode.
+- [ ] **Step 5: Commit.** Stage Task 6 files and approved census additions; subject `feat: build demo source in isolated offline units`.
+
+### Task 7: Publish the binary, place its instance and serve the demo host
+
+**Risk/review:** security gate, production storage, routing and billing. Independent task review and census required.
+
+**Files:**
+- Create: `internal/console/demo_publish.go`, `internal/console/demo_domains.go`, `internal/edge/demo.go`.
+- Modify: `internal/console/apidemo.go` (Task 1), `internal/console/demo_jobs.go` (Task 5), `internal/console/fleets.go:728`, `internal/console/apiinstances.go:1778`, `internal/console/apicli.go:2154`, `internal/console/apitemporary.go:280`, `:297`, `internal/provision/reconcile.go:565`, `internal/provision/forward.go:28`, `internal/registry/forward.go:87`, `internal/edge/edge.go:824`, `internal/edge/pending.go:161`, `internal/edge/wildcard.go:203`, `internal/console/domainpolicy.go:1`.
+- Test: `internal/console/demo_publish_test.go`, `internal/provision/demo_routing_test.go`, `internal/edge/demo_test.go`.
+
+**Interfaces:**
+- Consumes: accepted result (Task 5), policy/descriptor (Task 3), lease-only durability (Task 4), locked demo lifetime (Task 1).
+- Produces: `(*Server).publishDemo(ctx context.Context, d DemoRow, j demobuild.Job, output demobuild.Result) error`; `(*Server).demoReady(ctx context.Context, d DemoRow, version string) (bool, error)`; `(*Edge).demoHost(host string) bool`.
+- Publish contract: immutable version `v0.0.0-demo.<generation>`; one `linux-arm64` artifact, binary kind, small memory tier, hold/stop-before-start swap, no declared capabilities. Use `release.ShipSpooled(ctx, store, account, manifest, paths)` then `Signer.PromoteOnLadder(ctx, store, account, app, "edge", version, options)` from discovery. Console constructs and signs everything; user source and box results cannot supply a manifest.
+- Placement contract: provision Manifest Domain is the configured demo domain; one Record Host is the exact public host, Region is `fleet/<configured>`, FleetBox is the explicit selected label, Hibernate true, runtime binary, descriptor present. No extra canonical host under the ordinary apps zone and no automatic canary alias.
+
+- [ ] **Step 1: Write failing publication/routing tests.**
+
+```text
+TestDemoPublishRechecksLifetime: expired/deleted/replaced/olderGenerationResult == noPromotion; failedBuildUpdateCurrentVersion == previousVersion; DBValueAfterUpdate == previousValue
+TestDemoUsesRealReleasePath: artifactKey == ArtifactKey(account,app,version,"linux-arm64"); stagedDigest == shippedDigest; liveVersionHeader == version
+TestDemoFleetOnly: chosenFleet == configured; wrongAccount/ordinaryFleet/flat/staleWorker == refused; recordFleetBox != empty; noOrdinaryAppOnDemoFleet
+TestDemoDomainRouting: exactDemoHostServesApp == true; customerAliasToDemo == refused; unknownDemoSuffixHostHasRoute == false; ordinaryAppsDomainUnchanged == true
+TestDemoCapabilities: email/store/schedules/sidecars/customDomain/keep/ttl/rename/move/seed/run/interactive/controlPlane => refused
+```
+
+- [ ] **Step 2: Run tests to verify failure.** `go test ./internal/console ./internal/provision ./internal/edge -run 'TestDemo(Publish|UsesReal|FleetOnly|Domain|Capabilities)' -count=1`; expect current temporary restrictions or missing interfaces to fail.
+- [ ] **Step 3: Implement Task 7's publication and routing.** Recheck current demo generation and lifecycle under the app lock at each publish boundary; persist progress so crash recovery can replay immutable ship and promotion safely. Use the existing app-lifetime write guards when enabled. Write restrictive policy before any startable record. Share the create/ship/instance validation internals through a private demo operation, not an HTTP-auth bypass or broad exemption for all temporary apps. The anonymous request contains no placement/capability knobs. Refuse all ordinary mutation doors for holding-account demos, including ops keep/TTL and migration paths; Plan 3 gets a specific future transition rather than reusing keep. Reuse named fleet ownership, readiness and assignment checks; no fallback to a shared region or alternate fleet.
+
+ Preserve descriptor on the hub's fleet forward row and the fleet's local row, including reload and adoption. Add the configured demo domain to the explicit wildcard-parent and pending-host inputs without replacing PLATFORM_APPS_DOMAIN. Reserve its suffix against customer attach/alias/catch-all and routing overrides, including attempts from other accounts. Issue/use the existing wildcard certificate mechanism; DNS/wildcard provisioning is an operator deployment step in Task 9. Start with a real GET to the configured exact host through the normal edge, no redirects or arbitrary callback URL; report live only for 2xx plus the expected `X-Carlos-Version`. Bound starting at 60s; failed readiness reports failure with the attempted version. Build/validation failures before promotion leave the previous version running. Reuse the existing adoption rollback behavior on start failure; do not promise database rollback after new application code has written to SQLite, because demos have no backups. The agent can then submit another update with its unchanged token. Record-only static scanning remains the existing scan mechanism's responsibility and cannot become an admission gate; this plan adds no scanner service.
+- [ ] **Step 4: Run the Step 2 command.** Expect PASS through console, fleet forward, local route, staging and actual GET, not a direct call to a fake publisher alone.
+- [ ] **Step 5: Commit.** Stage Task 7 files and approved census additions; subject `feat: publish anonymous demos on their dedicated fleet domain`.
+
+### Task 8: Expire and purge demos without resurrection
+
+**Risk/review:** termination and storage. Independent task review and census required.
+
+**Files:**
+- Create: `internal/console/demo_expiry.go`, `internal/host/demo_cleanup.go`, `internal/instancectl/demo_cleanup.go`.
+- Modify: `internal/console/expirypass.go:154`, `:203`, `internal/console/tempstore.go:25`, `internal/console/store.go:2022`, `internal/console/lifetimes_purge.go:40`, `internal/release/trash.go:196`, `internal/provision/reconcile.go:2277`, `internal/host/versionsweep.go:52`.
+- Test: `internal/console/demo_expiry_test.go`, `internal/host/demo_cleanup_test.go`, `internal/instancectl/demo_cleanup_test.go`.
+
+**Interfaces:**
+- Consumes: app lifetime/expiry, fenced jobs, local-only DB, route descriptor and existing tombstone-bound purge.
+- Produces: `(*Server).expireDemoLocked(ctx context.Context, d DemoRow, now time.Time) error`; `(*instancectl.Server).purgeDemoLocal(ctx context.Context, d demo.Descriptor) error`.
+- Cleanup record: signed retirement receipt under `apps/<account>/<app>/demo-retire.json`, binding demo ID, host, lifetime, assigned box and tombstone time; root handles it only after observing the matching retirement through the normal pass. Receipt grants removal only of that demo's derived local paths. Console owns expiry; the box does not independently shorten TTL from a bucket field.
+
+- [ ] **Step 1: Write failing expiry tests.**
+
+```text
+TestDemoExpiryRaces: expiry == creation+86400; updateAtExpiry == refused; lateBuildResult == noShip; promptPurgeGrace == 0; ordinaryTemporaryGrace == 3days
+TestDemoPurgeRecovery: interruptedMarkerOrRowWrite => retrySameLifetime; wrongTombstone/emptyBucket/readError => noUnprovedDeletion; restoreOrKeepDemo == refused
+TestDemoLocalPurge: stopBeforeDelete == true; cgroupEmptyBeforeRemove == true; DB/WAL/SHM/source/output/privateCache == absent; siblingAndSharedToolchain == preserved
+TestDemoOfflineRetirement: offlineBoxReconnect => cleanupBeforeServe; slotHeldUntilPurgeComplete == true; ordinaryVersionSweepGraceUnchanged == true
+```
+
+- [ ] **Step 2: Run tests to verify failure.** `go test ./internal/console ./internal/host ./internal/instancectl -run 'TestDemo(Expiry|Purge|LocalPurge|OfflineRetirement)' -count=1`; expect current three-day grace and local retention to fail.
+- [ ] **Step 3: Implement the Task 8 interfaces.** Reuse the existing five-minute console expiry pass, lock, settle, tripwire, lifetime retirement and matching-tombstone checks. For a demo only, store purge_after equal to tombstone time, and process due demo purges in that pass; normal temporary apps retain three days. The existing `StartExpiryPass` runs even with temporary creation off (`internal/console/expirypass.go:26`), so retain that cleanup behavior when demo admission is disabled. Mark retiring and increment generation before stopping job acceptance, invalidating token use and issuing retirement. Persist retirement until the assigned box has acknowledged stopped units and local cleanup; a disconnected box cannot resurrect or start before catching up. No file removal while its cgroup or build unit is live. Retain a bounded SQL retirement row and host reservation until acknowledged purge; refuse new work if incomplete cleanup exhausts the ceiling. Retry failed cleanup without resetting TTL or selecting another lifetime. Remove source/job objects, releases, policy, local database and unreferenced staged demo builds; leave shared toolchains and versions referenced by other routes. Wipe token hashes at retirement, retaining only IDs needed for cleanup. Existing version-sweep grace is bypassed only for proven-retired demo versions. API status returns 410 after retirement; no Plan 2 cap/claim page.
+- [ ] **Step 4: Run the Step 2 command.** Expect PASS with crashes injected between bucket and row writes and with build completion racing each transition. Add the current temporary expiry/restore regression tests to the targeted run.
+- [ ] **Step 5: Commit.** Stage Task 8 files and approved census additions; subject `feat: expire and promptly purge anonymous demos`.
+
+### Task 9: Prove the dev slice and finish the branch gate
+
+**Risk/review:** whole-branch review; the sandbox witness validates root, storage and termination behavior. Do not buy another per-task review for a test-only integration change.
+
+**Files:**
+- Create: `internal/console/demo_e2e_test.go`, `internal/host/demo_dev_linux_test.go`, `internal/console/testdata/demo/` (locked SQLite starter fixture).
+- Modify: `README.md:585` (existing operator-policy rollout guidance): add an adjacent anonymous-demo configuration/rollout section. All prose waits for the copy-review table below.
+- Generated during implementation: `internal/provision/testdata/plan14-root-reads-agent-start-demo-1.tsv`, census chain registration and `docs/superpowers/notes/census-proposal-agent-start-demo-1.md`, through the repo's proposal tool, never hand-approved hashes.
+
+**Interfaces:**
+- Consumes: public create/status/update, exact-host readiness GET, authenticated box jobs and existing expiry pass; no private fixture shortcuts for the source-to-live witness.
+- Produces: `TestDemoSourceToLiveAndUpdate`, `TestDemoDevKernelAndPurge`, `TestDemoDisabledCompatibility` and a recorded dev acceptance result against the built binaries.
+
+- [ ] **Step 1: Write the failing integration tests.**
+
+```text
+TestDemoSourceToLiveAndUpdate: noLogin; compressedSource <= 5000000; SQLiteWriteThenRead == savedValue; submittedUpdateChangesVersion == true; updateKeepsDB == true; liveElapsed < 5min
+TestDemoDevKernelAndPurge: actualUnitIsolation == proven; noOutboundFromAppOrBuilder; TTL == 24h; localAndBucketCleanupAfterExpiry == complete; noReplicaObjectsEverWritten
+TestDemoDisabledCompatibility: noSettings => existingRoutesAndUnitsAndBudgetsAndStoreRequestCounts == baseline
+```
+
+- [ ] **Step 2: Run tests to verify failure.** `go test ./internal/console ./internal/host -run 'TestDemo(SourceToLive|DevKernel|DisabledCompatibility)' -count=1`; demonstrate failure with the demo publish connection disabled, then restore it. Kernel/dev tests must not silently pass via skips.
+- [ ] **Step 3: Complete only the integration wiring needed by those tests.** Provision the locked toolchain bundle and dedicated arm64 nested demo fleet in the explicitly approved dev scope; use the console/CLI for ordinary administration. Configure a dedicated dev demo domain with wildcard DNS to the existing ingress, wildcard TLS and all demo switches. Verify both a new demo and an ordinary app through their actual hostnames and the newly built binaries. Use an injected clock in automated tests for the 24h boundary; do not expose a TTL override in the public API. Record DNS, TLS, worker readiness and cleanup evidence. Disable admission and clean up only this witness's resources afterward unless dev switch-on was explicitly authorized to persist.
+- [ ] **Step 4: Run the final implementation gate once.** Run the targeted commands above, then repository-required build/vet/full test and cross-compilation gates once before landing, using the default Go cache. This is a future implementation requirement, not an instruction to run them in this document-only session. Prepare the census card and claims; require independent other-family reviewer dispositions for every affected root unit/envelope. Review the final branch against amadan main, verify tip CI before merge, and inspect main CI afterward. No merge with an unresolved prerequisite or skipped kernel witness.
+- [ ] **Step 5: Commit.** Stage only integration tests, reviewed docs and approved census artifacts; subject `test: prove anonymous demo publish and cleanup on dev`. Land all task commits as one reviewed squash through amadan, only in the later implementation session.
+
+## Review budget and self-review
+
+Implementation task reviews apply only where marked. Opus reviews authority/root/production work by a Codex author, with an other-family census verdict using `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`. One whole-branch review follows. Stop at the first round with no P1; apply that round's P2s without reopening, list P3s as follow-ups, retain census and newly changed security/root/termination/storage checks. A fourth round needs Paul's go; two rounds against the same invariant require the repository's stop-and-choose rule. Do not review against unmerged dependencies.
+
+Plan review history: zero independent review rounds in this authoring session. Two read-only discovery delegates supplied code anchors; they did not review the design or approve security changes. Self-review completed against the approved scope: Tasks 1/7 cover API and token ownership, 2/5/6 cover build restrictions and execution, 3/4 cover runtime restrictions and database durability, 7 covers domain/placement/artifacts, 8 covers expiry, 9 proves the visible slice. The five Review Focus cases each have owning tests. Interfaces use one descriptor, lifetime, generation and job attempt throughout. No production function bodies are included. Open prerequisites below deliberately prevent claiming the plan is ready for unconditional implementation.
+
+## User-facing strings: copy review required
+
+| Copy ID/surface | Meaning to draft and review before implementation |
+|---|---|
+| DEMO-CONFIG | Missing/inconsistent settings, holding account/fleet/domain, unsupported box, policy writer or cache readiness; operator-facing startup/status explanation. |
+| DEMO-CREATE-LIMIT | Per-IP or deployment create budget exhausted; retry time; do not suggest creating another identity. |
+| DEMO-LIVE-LIMIT | Ceiling reached; existing demos are retained; refusal and retry guidance. |
+| DEMO-SOURCE | Archive format/size/path/import/module/directive refusal; expected pinned starter contract. |
+| DEMO-TOKEN | Invalid, unavailable or expired demo credential; consistent non-enumerating response. |
+| DEMO-UPDATE | Build already active or lifetime update budget exhausted; an update does not extend expiry. |
+| DEMO-BUILD | Queued, building, starting, live, failed, timeout, unavailable worker, output too large; compiler file/line/message formatting and truncation notice. |
+| DEMO-CLAIM-LATER | Claim link is reserved on the dev slice; claiming becomes available in Plan 3. |
+| DEMO-POLICY | Restricted capability or placement refused; absent policy and deny-all enforcement failure; no fallback. |
+| DEMO-DATA | Demo database is local only, missing after box loss, or cannot move; no recovery/backups promise. |
+| DEMO-EXPIRED | Expiry/purge status, audit wording and operator cleanup failures, including offline boxes. |
+| DEMO-OPERATOR-DOCS | Switches, limits, DNS/TLS, verified toolchain bundle, activation, smoke check and cleanup instructions. |
+
+## Open questions (settled by the controller, 2026-11-02)
+
+1. **The dependency lock.** Fiesta is CSS/JS, not a Go module: the starter vendors Fiesta's assets as embedded files, and the import allowlist holds only the pinned Rastrillo module. The lock is Rastrillo's module at a pinned tag plus its full transitive closure (including its pure-Go SQLite driver), generated in Task 2 from the Rastrillo starter by `go mod download` on the operator side and reviewed as data. User code may import Rastrillo packages and the standard library only; transitive modules are reachable only through Rastrillo. Coordinate the tag with the Fiesta lightness work (Rastrillo #158). Not Paul's call.
+2. **Prompt purge latency.** The next healthy five-minute expiry pass is enough: a demo stops serving within 10 minutes of its 24 hours and its local data is removed once the assigned box acknowledges. An outage that delays the pass delays purge; it never extends serving beyond the console's retirement. No extra delivery mechanism.