# Nucleic Cloud — Cloud Runtime Service Plan

> **Status (2026-07-02): plan, nothing built.** Synthesized from a multi-agent research pass:
> five codebase readers, three platform/market researchers with 12 load-bearing claims
> adversarially re-verified against current docs, three competing architectures scored by a
> three-judge panel (Ported Host 246 · Edge-Native 235 · Nucleus Hybrid 231 /300), best ideas
> grafted from the non-winners, then a completeness critique folded in. Platform facts below
> are as of July 2026 and marked where they must be re-verified at spike time.

## 0. Thesis

**Nucleic Cloud** is a paid subscription that runs Nucleic Control sandboxes in the cloud, so a
user can create and run projects from any device — especially iPhone, which can never run agents
locally — with projects and sessions syncing across all devices. The core bet:

**Port the existing Swift host runtime (NucleicCore, headless) to Linux as one binary —
`nucleicd` — and run it inside one Cloudflare Container per user. The container is
simultaneously the host-of-record and the sandbox.** Devices speak the exact same Noise/CBOR
sync protocol to the cloud host that they speak to a Mac today; the already-written (not yet
deployed) `nucleic-edge` Worker + Room Durable Object relays ciphertext and sends content-free
APNs wakes, and never sees plaintext.

Fidelity is the point: one `SessionController`, one `TranscriptWriter` seq authority, one
`ApprovalCoordinator` with first-responder-wins — identical code locally (free) and in the
cloud (paid), so semantics cannot drift and nothing local is ever paywalled.

Three findings make this the *right* bet rather than the romantic one:

1. **The codebase was accidentally built for it.** `RunSpec.container` is `Optional` — `nil`
   means "spawn the agent on the host via `Foundation.Process`" (`Sources/NucleicCore/Backend.swift:203`),
   which is *exactly* the code path a cloud Linux container wants (the container **is** the
   sandbox; Apple containerization becomes irrelevant there). The Apple-only surface of
   NucleicCore is small and enumerated (§3.1). The sandbox OCI image
   (`containers/nucleic-sandbox/Dockerfile`) already carries `claude`/`codex`/`grok`, git, `gh`,
   the interceptor shims, and env-configurable control-plane URLs. Credential seeding into Linux
   containers already exists (`ClaudeLoginKeychain`, Codex `auth.json`, `GITHUB_TOKEN`).
2. **Workers for Platforms is the wrong primitive** (§1) — the user-facing suggestion was
   checked and fails hard. Cloudflare **Containers + Durable Objects** (GA April 2026) is the
   right one, and it is a near-conceptual match for what Nucleic Control already does locally.
3. **The sync protocol is host-count-agnostic by design.** A cloud host is just another host
   with its own X25519 static key and room. The wire protocol needs near-zero change; the work
   is at the edges (multi-host iOS, pairing without a QR, one new `createProject` verb).

## 1. Primitive selection: why not Workers for Platforms

Workers for Platforms runs **V8 isolates**: 128 MB memory per isolate, CPU capped at 30 s
default / 5 min hard max per invocation, `node:child_process` is a non-functional stub, and
`node:fs` is an ephemeral per-request virtual filesystem. `claude` (Node), `codex` (Rust), and
`grok` literally cannot execute there — no subprocesses, no real filesystem, no hours-long
session. WfP's actual job is multi-tenant deployment of *customer Workers scripts*.

**Where WfP (or the simpler Dynamic Workers beta) could still fit later:** hosting per-user
preview deployments of web projects users build in their sandboxes, and per-tenant
webhook/automation snippets. Both are optional premium conveniences, not the runtime.

**The right primitive — Cloudflare Containers + Sandbox SDK + Durable Objects** (all verified
against current docs, July 2026):

| Fact | Verified detail |
|---|---|
| GA | Containers + Sandbox SDK GA on Workers Paid, **2026-04-13**; active-CPU pricing, credential injection, PTY terminals |
| Largest instance | `standard-4`: **4 vCPU / 12 GiB / 20 GB disk** (custom types GA 2026-01-05, capped at standard-4 equivalents; ≥3 GiB per vCPU, ≤2 GB disk per GiB memory) |
| Account limits | **1,500 concurrent vCPU / 6 TiB memory / 30 TB disk** (raised 15× on 2026-02-25), 50 GB image storage; raiseable on request |
| Pricing | CPU **$0.000020/vCPU-s billed on *active* CPU only**; memory $0.0000025/GiB-s + disk $0.00000007/GB-s on provisioned resources while running; **$0 while asleep**. Realistic agent session ≈ **$0.06–0.10/hr**; idle-but-awake (1 vCPU/4 GiB) ≈ $0.04/hr |
| Disk | **Fully ephemeral** — sleep/restart = fresh disk from image. Native snapshots "coming soon"; R2 FUSE mounts and Sandbox backup/restore exist today. This is the single design-forcing constraint (§3.5) |
| Integration | Containers are addressed by Durable Objects (hibernatable WebSockets, SQLite, alarms); WebSockets into containers work; preview URLs via `sandbox.tunnels`/`exposePort` (custom domain + wildcard DNS needed in prod) |
| No | GPU, true persistent volumes, >20 GB disk per instance. Monorepos beyond 20 GB are out of scope — say so |

Ephemeral disk actually *aligns* with Nucleic's model: worktrees are disposable clones,
transcripts are append-only JSONL, git remotes are the durable store. Wake = clone + restore +
resume (§3.5).

## 2. Decisions

| Decision | Choice |
|---|---|
| Runtime primitive | **Cloudflare Containers** (one per user), addressed by a Container DO; **not** Workers for Platforms |
| Cloud host | **`nucleicd`** — headless Linux build of NucleicCore; container = host-of-record **and** sandbox (`RunSpec.container = nil`) |
| Relay | Reuse `cloud/nucleic-edge` Room DO as ciphertext router for cloud hosts too — but note it's *written and unit-tested*, not deployed; Phase 1 is build-and-harden, not reuse-of-running-system |
| Free/paid line | **"Paid = Nucleic computes or durably stores on your behalf."** Relay + APNs push ship **free forever** (promised as core roadmap, PLAN.md M5). Entire local product stays free. No current functionality paywalled |
| Agent accounts | **BYO** (Claude setup-token/API key, Codex device-auth, xAI keys). Never proxy, pool, meter, or resell model tokens. "Where vendor terms permit" copy; API-key/Console fallback first-class (§7.3) |
| Pricing | **Nucleic Cloud $19/mo** (1 vCPU/4 GiB/8 GB host, 60 active hrs, 20 GB R2, $0.20–0.25/hr overage); later **Cloud Pro $39/mo** (standard-4, 200 hrs, 3 hosts) |
| Billing | Stripe (web-primary) + US-only external purchase link on iOS; **Stripe Tax + refund policy + EU decision before first payment** |
| Privacy claim | Three published trust tiers (§5). **Never** claim E2EE for cloud *execution* |
| Go/no-go | A 2–3 week Linux-port spike (§10 Phase 2) proves or kills the whole tier **before any billing exists** |

## 3. Architecture

```
 iPhone ─┐  Noise/CBOR (E2EE)         ┌──────────── Cloudflare ────────────────┐
 Mac ────┼──── WebSocket ─────────────►│ nucleic-edge Worker + Room DO          │
         │   (ciphertext only)        │   (routes frames, presence, APNs wake) │
         │                            │        │ ciphertext frames             │
         │                            │        ▼                               │
         │                            │ Container DO (per user) ── lifecycle,  │
         │                            │        │   metering, fencing, alarms   │
         │                            │        ▼                               │
         │                            │ ┌─ Cloudflare Container (per user) ──┐ │
         │                            │ │ nucleicd (headless NucleicCore)    │ │
         │                            │ │  SessionController · Transcript    │ │
         │                            │ │  ApprovalCoordinator · Worktrees   │ │
         │                            │ │  ← Noise terminates HERE           │ │
         │                            │ │ claude / codex / grok + shims      │ │
         │                            │ └──────┬─────────────────┬───────────┘ │
         │                            │        ▼                 ▼             │
         │                            │  user's git remote     R2 (encrypted   │
         │                            │  (clones, branches)     checkpoints)   │
         │                            └────────────────────────────────────────┘
         │                            ┌────────────────────────────────────────┐
         └── HTTPS (accounts/billing)►│ nucleic-cloud Worker + D1/KV (control) │
                                      └────────────────────────────────────────┘
```

### 3.1 `nucleicd` — the ported host

The container runs the ported Swift runtime as supervisor: `SessionController` (actor, single
writer), `TranscriptWriter` (canonical seq, JSONL source of truth), `ApprovalCoordinator`,
`WorktreeManager`/`GitRunner`, `GRDBMetadataStore`, all three adapters, and
`SyncHost`/`ConnectionHandler` — existing code. The Apple-only seams, enumerated:

| Seam | Port |
|---|---|
| `Sources/NucleicCore/Container/*` (Apple containerization, 4 files) | **Excluded** — platform-conditional in Package.swift. The cloud container is the sandbox; `RunSpec.container` stays `nil` |
| `Claude/MCPApprovalServer.swift` (Network.framework) | Rehost on SwiftNIO, loopback:9099. Shims' env-URL contract + per-session bearer tokens carry over verbatim; `control-bridge.js` unnecessary (host and agents share one kernel) |
| `Sync/LANTransport.swift` (Network.framework) | Replace with outbound NIO WebSocket `FrameChannel` dialing the Room DO as host-role (`SyncListener` is an explicit transport seam, `Sync/SyncTransport.swift:9`) |
| 6 Keychain call sites | 0600-file secret store (container credential-file pattern already exists) |
| `os.Logger` (3 files) | swift-log |
| CryptoKit (NucleicProtocol Noise) | swift-crypto — API drop-in, **but Noise interop must be proven byte-for-byte against Darwin peers in CI** (iOS-proven ≠ Linux-proven) |
| GRDB on Linux | Verify week one; bounded fallback: raw-SQLite `SessionMetadataStore` reimplementation (it's a protocol, metadata-only) |
| `IntelligenceProviding` (FoundationModels is app-side only) | Cloud implementation backed by the user's agent credentials or a small metered model; `HeuristicIntelligence` fallback exists in Core |

`AppStore` (orchestration root, 5,383 lines, `@MainActor @Observable`) runs headless with no-op
UI hooks — it *appears* to import only Foundation+Observation, but **verifying its actual
transitive import graph on Linux is a named spike check, not a premise**. Accepting the
headless drag is deliberate: a slim supervisor would fork the runtime and invite local/cloud
semantic drift, which is the one unacceptable cost. A **golden-transcript conformance suite**
(replay recorded Mac sessions against Linux `nucleicd` in CI) pins platform parity — the port
removes TS-twin drift risk but not platform drift (FileManager paths, Process signals, strict
concurrency).

### 3.2 Image

Extend `containers/nucleic-sandbox/Dockerfile` (node:22-bookworm-slim + three CLIs + git/gh +
build tools, ~1.2 GB) with the `nucleicd` binary + Swift runtime libs (~250 MB) → ~1.5–2 GB.
CI adds **linux/amd64** (Cloudflare requirement) alongside arm64 and smoke-tests each CLI
per-arch. Push via wrangler to the Cloudflare registry.

**Image maintenance contract** (the CLIs update weekly): CLI versions pinned per image tag;
weekly rebuild CI with per-arch smoke tests; staged rollout aligned to the existing
dev/canary/beta/rc/stable channels; documented rollback. Decide and test what happens to
*sleeping* containers when a new image deploys (wake into new image — does it invalidate
checkpoints?). Validate realistic cold start with the full image (expect **5–15 s**, not the
1–3 s marketing number); if it's 10–20 s, message it honestly.

### 3.3 Durable Objects: routing + lifecycle

- **Room DO (`nucleic-edge`, reused):** relays binary Noise frames byte-for-byte between device
  sockets and the cloud host's outbound socket; presence; APNs wake. Phase-1 hardening (free
  relay *and* cloud prerequisite): per-account token minting replacing the global
  `RELAY_ADMIN_SECRET`; **server-side `roomID = hash(host static public key)` derivation and
  verification at token minting** (closes room-squatting structurally); push-token keyed by
  `(roomId, deviceId)`; KV revocation paired with DO force-close; **per-peer frame routing from
  day one** (the broadcast-to-all AEAD-drop fan-out is a known defect; Phase 1 is the cheapest
  time to fix it).
- **Container DO (per user, new):** owns container lifecycle (start/sleep/alarms), meters
  awake-seconds itself (no polling; flushed hourly to Stripe Billing Meters), issues a
  **monotonic fencing epoch on each wake** — R2 checkpoint writes and git pushes carry it and
  stale epochs are rejected (closes the zombie-writer/split-brain hole). When a device connects
  and no host socket exists, the Room DO signals the Container DO to wake `nucleicd`.

### 3.4 Control-plane Worker (`cloud/nucleic-cloud`)

Nucleic's first-ever accounts — firewalled from the anonymous local product (a Nucleus account
is never required for local use). Responsibilities: auth (**passkeys + email magic-link** —
lowest solo-dev surface; decide how account recovery interacts with the device-held root key,
§5 — a recoverable account with unrecoverable data must be explicit, not accidental), Stripe
webhooks → entitlements in D1 + KV cache, sandbox provisioning, pairing bootstrap (§4), per-
account relay-token minting, data-lifecycle endpoints (§9.3).

### 3.5 Persistence across restarts (disk is fully ephemeral)

- **Repos:** fresh-cloned on wake from the user's git remote. On SIGTERM, `nucleicd` pushes
  every session branch to a `nucleic/` ref namespace on the user's remote and tars
  uncommitted/untracked state to R2. **`nucleic/` ref pushing is opt-in/opt-out per project**
  (it needs write scope, can trigger org CI/webhooks, may violate org policy) with R2-only
  persistence fallback. **GitHub App vs deploy-key decision lands in Phase 3, not 4** — the
  beta needs private-repo clones.
- **Transcripts + `nucleic.sqlite`:** on local disk (no SQLite-over-FUSE); append-only JSONL
  incrementally uploaded to a per-user R2 prefix every N seconds; sqlite checkpointed on
  interval + shutdown.
- **CLI-internal state — critical and easy to miss:** `resume(backendSessionID)` after wake
  requires the CLIs' *own* session stores (`~/.claude/projects` JSONL, `~/.codex` state, xAI
  equivalent) to survive restart. **CLI home dirs are part of the R2 checkpoint set**, and
  "kill container mid-turn → wake → resume → verify transcript continuity" is a named Phase-2
  spike test. Without this, wake = clone + restore + resume collapses.
- **Don't trust SIGTERM.** The 15-min grace is not guaranteed (host maintenance/failure can
  deliver far less). **Periodic checkpoint cadence** while a session is dirty: auto-WIP-commit
  or working-tree snapshot to R2 every N minutes. Publish the resulting RPO in the beta copy.
- All R2 state encrypted with a per-account key — see §5 for the device-held-key upgrade.

### 3.6 Lifecycle economics

A running turn or pending approval holds the container awake (CLIs can't checkpoint a suspended
MCP call): send APNs, stay hot up to a configurable cap (default 2 h), then gracefully abort
the turn, checkpoint, sleep. No active turns → checkpoint + sleep after 10 min. Sleeping = $0.

Two grafted refinements: **park-and-rerun** (opt-in) — for idempotent/read-only gated tools,
checkpoint + sleep during a long approval wait and re-execute the tool on wake, recovering most
approval-wait cost without breaking semantics; and an **empirical spike question that gates the
whole cost model**: *does an idle proxied/outbound WebSocket hold the container activity
timer?* No design had a documented answer; measure it before pricing is promised.

## 4. Sync protocol integration

The wire protocol needs near-zero change — `ClientMsg`/`HostMsg` over Noise over a
`FrameChannel` is transport-agnostic, and the cloud host is just another host key + room.
The work, all at the edges:

1. **WebSocket `FrameChannel`** client on iOS (`URLSessionWebSocketTask`) and in `nucleicd`
   (NIO) + LAN-first/relay-fallback transport selection — the already-named CLOUD_INFRA gap.
2. **Multi-host iOS:** replace the single `loadPairedHost()` slot with a host table (per-host
   key pins, per-host `SyncClient`), key sessions/projects by `(hostID, sessionID)`, host
   switcher UI, per-host Settings/privacy copy.
3. **One new verb: `createProject(repoURL, branch)`** so a phone can create projects on a cloud
   host — gated by `HostMsg` capability advertisement so old Macs bounce it cleanly. (ClientMsg
   decoding throws on unknown tags, so capability gating must land with the first cloud
   release.)
4. **Pairing without a Mac screen**, trust anchor shifts from physical possession to account
   auth: (a) *Mac-mediated introduction* — the paired Mac ships the cloud host's static key +
   fresh PSK to the phone over the existing E2EE channel; (b) *phone-first* — after account
   login, the control Worker returns the same `PairingPayload` CBOR (with the
   documented-but-missing `roomID` + membership-token fields) over authenticated TLS, and the
   phone completes Noise XXpsk0 through the relay. Cloud-paired devices get explicit per-device
   scope management rather than automatic control scope.
5. **`adoptProject` / handoff (Phase 5):** start on phone in cloud → adopt on Mac via git pull
   *with transcript continuity* (and the reverse). The most Nucleic-native premium feature in
   the field — cross-device state is git-mediated (both push to the same remote; cloud
   worktrees are fresh clones, never synced worktrees), which matches how the system already
   thinks.

Approvals, seq catch-up, snapshots, first-responder-wins: unchanged code.

## 5. Privacy posture — the three-tier trust table

Publish this table verbatim (website + per-host Settings copy); it is the §13 honesty guardrail
applied, and a marketable differentiator against competitors who gloss it.

| Tier | What Nucleic can see |
|---|---|
| **Local (default, free)** | Nothing. No account, nothing uploaded. All existing copy stays literally true |
| **Relay + push (free)** | Ciphertext, frame sizes, timing, room presence. E2EE device↔host; the Worker/DO can never read code, transcripts, or approvals |
| **Nucleic Cloud (paid, opt-in)** | The control channel from your devices terminates *inside your rented container* — E2EE past every Worker and past Nucleic's edge code. **But the container necessarily holds plaintext code, transcripts, and your agent credentials, because it runs the agents.** Honest frame: "your cloud sandbox is a trusted endpoint like your Mac, except it runs on infrastructure we operate — encrypted at rest, isolated per user, no service-side plaintext path in the data plane; the operator could technically access a running container, and we design so we never need to" |

**Never say "we can't read your code" for cloud execution.** One sloppy sentence damages the
core differentiator more than the tier earns.

Hardening grafts:
- **Sealed credential injection:** at provisioning, the container generates an ephemeral X25519
  key; the user's device encrypts agent/GitHub credentials directly *to the container* — no
  intermediary (Worker, DO, R2 vault path) ever holds plaintext creds; R2 checkpoint key
  derivation anchors to it.
- **Device-held account root key for R2 archives:** client-side key that exists only on user
  devices (exchanged over the existing Noise channel at pairing), with a clearly-labeled
  optional recovery-phrase escrow — makes the transcript archive verifiably
  Nucleic-cannot-decrypt, and must be reconciled with account recovery (§3.4).
- **Fix the incorrect Secure-Enclave claim before any cloud security marketing ships.** The
  claims live at `docs/SYNC_PROTOCOL.md:79`, `docs/RUNTIME_ARCHITECTURE.md:195`,
  `docs/UX_IOS.md:187`, and the comment at `Sources/NucleicProtocol/Noise/SecureChannel.swift:5`
  — Curve25519 keys cannot live in the Secure Enclave (it holds P-256 only). Fold into the
  Phase 1 relay-hardening PR, when relay security copy first ships.

## 6. Tenancy & abuse

- One container per paying user (VM-grade isolation), Container DO id = account id; roomID
  cryptographically bound to the host key (§3.3). Default instance: custom **1 vCPU / 4 GiB /
  8 GB** (~$0.06/active-hr at 30% CPU; ~$0.04/hr idle-awake). Pro: standard-4. Defaults fit
  ~1,000+ subscribers within the 1,500-vCPU account ceiling before a limit-raise request.
- **Metering:** Container DO accumulates awake-seconds, flushes hourly to Stripe Billing
  Meters (the legacy usage-records API is gone).
- **Quota-exhaustion semantics (user-protecting):** finish the current turn, refuse new turns,
  never mid-turn kill; usage alerts at 50/80/100%; **default hard monthly spend cap** on
  overage, user-adjustable — a runaway agent loop must not become bill shock.
- **Abuse:** payment-before-provisioning helps but **don't lean on Stripe Radar** — stolen-card
  + crypto-mining is the canonical pattern Radar misses until chargeback; budget real fraud-ops
  time. Mining heuristic `nucleicd` can attest (it knows when a turn is genuinely active):
  sustained high CPU with zero active sessions → Container DO kills the instance. **Verify
  whether Containers/Sandbox-SDK network-level egress allowlisting exists** before asserting
  shim-level-only enforcement — if it exists it's the cheapest abuse control available; spam/
  port-scanning from Nucleic's IP reputation is an AUP liability beyond mining.
- **Escape hatch:** keep the container-side interface plain (outbound WS + loopback HTTP) so a
  Fly/Hetzner-class VM runtime can slot behind the same Container-DO control plane if the
  4 vCPU/12 GiB/20 GB ceiling pinches or pricing shifts — no client or wire-protocol changes.

## 7. Billing & packaging

### 7.1 The free/paid line

**Free forever:** the entire local product, plus relay + APNs push for Mac hosts. Relay/push
was promised as core roadmap (PLAN.md M5); drawing the paid line there would breach the ethos
in spirit. (Honesty note: "costs ~nothing" isn't zero — long-lived WebSocket DO duration across
a free user base is an unpriced commitment; hibernation makes it small, but track it.)

**Paid = Nucleic computes or durably stores on your behalf.**

### 7.2 Tiers

| Tier | Price | Includes |
|---|---|---|
| **Nucleic Cloud** (launch) | **$19/mo** | 1 always-available cloud host (1 vCPU/4 GiB/8 GB), 60 active hrs/mo, 20 GB R2 state, overage **$0.20–0.25/active-hr** (unit cost ~$0.06–0.10/hr + Stripe fees; $0.10 overage would be nearly margin-free) |
| **Cloud Pro** (later) | $39/mo | standard-4 instance, 200 hrs, 3 concurrent hosts, larger archive |
| *(Optional, decision point)* **Nucleic Plus** | ~$8/mo | Account/sync plane only: E2EE project-registry + idea-inbox sync, encrypted transcript backup, multi-host directory. **Could ship before the port lands** (the economics judge's case: first revenue in weeks, exercises accounts→entitlements→metering→revocation on low-stakes features; marginal cost ≈ cents). Counterpoint: it front-loads billing/support ops before the flagship exists. Recommendation: build the account plane in Phase 3 regardless; decide on selling Plus separately *after* the Phase 2 go/no-go — if the port is green, skip Plus and launch Cloud directly; if the port slips, Plus is the revenue bridge |

Never meter or resell model tokens.

### 7.3 BYO agent accounts — the load-bearing external risk

The defensible position: Nucleic-hosted sandboxes run only **unmodified official vendor CLIs**
with credentials the user injects E2EE from their own device; Nucleic never proxies, pools, or
resells tokens, and never touches plaintext credentials server-side. That mirrors Anthropic's
sanctioned CI pattern (setup-token + `claude-code-action` on GitHub runners) while staying
clear of the banned pattern (third-party harness/service routing requests through consumer
credentials). But Anthropic blocked third-party harnesses in April 2026 and has a *suspended*
plan to bill non-interactive/SDK usage at API rates — so: ask Anthropic directly, keep sessions
interactive-shaped, make **Console API keys / Bedrock / Vertex first-class fallbacks**, and
write marketing as "where vendor terms permit." OpenAI and xAI pose no comparable obstacle.

**Credential lifecycle:** tokens expire and Codex device-auth is interactive. `nucleicd`
detects auth failure, parks the session, sends a content-free "cloud host needs re-auth" push;
sealed re-injection from the phone is the recovery path. Design this in Phase 3, not as a
support ticket at 3am.

### 7.4 Purchase mechanics

- **Web-primary:** Stripe Checkout + Customer Portal; webhooks (`checkout.session.completed`,
  `subscription.updated/deleted`) verified in the control Worker; entitlements in D1, KV cache.
  **Add Stripe Tax, a written refund/dispute policy, and proration rules before the first
  payment.**
- **EU:** decide up front — geo-gate the beta, or place container/R2 jurisdiction (Cloudflare
  supports `eu`) and publish a DPA/subprocessor statement. EU beta users arrive in Phase 3 with
  a D1 account store; "EU is a Phase 6 word" doesn't survive contact.
- **iOS:** companion app with a **US-storefront external purchase link** (0% commission today;
  SCOTUS review of Epic v. Apple heard Oct 2026 — revisit then), login-only with zero purchase
  references on other storefronts. App Review risk is low (GitHub Mobile, ChatGPT/Codex, Claude
  iOS precedents).

## 8. Premium features (all optional conveniences; nothing local paywalled)

1. **Cloud sandboxes** — create and run Nucleic Control sessions from iPhone with no Mac awake
   (the headline; Claude-first, Codex next, Grok when its container support lands —
   already a tracked coordinated change).
2. **Phone-initiated project creation** — `createProject` + GitHub App for repo browsing/access.
3. **Project handoff (`adoptProject`)** — start on phone in cloud, adopt on Mac with transcript
   continuity; and the reverse.
4. **Scheduled/queued sessions** — dispatch an idea-inbox item to a cloud host at 9am
   (Container DO alarms make this nearly free to build; the inbox is the natural front door).
5. **Preview URLs** — cloudflared tunnels to dev servers in the sandbox, shareable from the
   phone (later: WfP/Dynamic Workers for persistent per-user preview deployments).
6. **Encrypted cloud transcript archive** — R2-backed, device-held key, cross-device search,
   long retention.
7. **Cloud intelligence provider** — server-side turn classification/naming/summaries at full
   quality (replaces the FoundationModels gap headless; changes nothing locally, where
   FoundationModels already works free).
8. **Bigger/multiple hosts** — Cloud Pro.
9. **Full diff fetch on iPhone** — built cloud-first for review-before-integrate from the
   phone, **then enabled free for LAN Mac hosts too** — each release turns the no-paywall rule
   into a visible goodwill gesture.

## 9. Operations

### 9.1 Observability without breaking the posture
A content-free telemetry schema from `nucleicd` (turn state, seq lag, checkpoint
success/fail, OOM/crash) — structural metadata only, same discipline as the existing
OSLog-privacy design; plus an explicit **user-initiated diagnostic-bundle consent flow**. State
in the trust table what the operator can and cannot see. This is how a solo operator debugs
"my cloud session hung" without violating "we design so we never need container access."

### 9.2 Version skew
Local Macs update via Sparkle on the user's schedule; cloud hosts update on deploy. Same
NucleicCore + the existing five-channel discipline + capability advertisement (§4.3) keep the
fleet coherent.

### 9.3 Data lifecycle (build before beta, not under a GDPR request)
Account deletion endpoint; R2 retention schedule; **cancellation flow:** subscription ends →
host stops accepting new sessions → 30-day export grace window (R2 state + un-pushed
`nucleic/` branches downloadable; transcript/state export API) → purge, with documented
`nucleic/*` ref cleanup; the phone's host table shows the dead host with an export CTA, not a
silent disappearance.

### 9.4 Offline/degraded states (define in iOS UX, Phase 4)
Relay/regional outage; device offline while an approval pins the container (APNs undeliverable
— the 2 h cap must still protect the user's hours); clone-on-wake failure (remote down,
credentials revoked) → parked session + content-free push, never a silent burn.

## 10. Phasing

Commitment stated up front: **the Linux port is product-invisible — slippage delays only the
paid tier, never the free relay/M5 deliverables.**

- **Phase 1 — Ship the free relay (fulfills M5).** Deploy `nucleic-edge` with the §3.3
  hardening (per-account token minting, server-side roomID derivation, per-peer frame routing,
  push-token keying, revocation force-close); Mac host relay client + iOS WebSocket
  `FrameChannel` + APNs capability; Secure-Enclave doc corrections (§5). Real traffic on the
  exact infrastructure the cloud host will use; zero cloud-compute risk.
- **Phase 2 — Linux port spike (2–3 weeks, go/no-go, can start in parallel).** Compile
  NucleicProtocol + a `nucleicd` target on Linux CI; **checklist:** GRDB-on-Linux (fallback:
  raw-SQLite store); NIO MCPApprovalServer + file secret store; AppStore's actual transitive
  import graph; swift-crypto↔CryptoKit Noise interop byte-for-byte; kill-mid-turn →
  wake → resume with CLI home dirs in the checkpoint set; empirical SIGTERM grace; idle
  proxied WebSocket vs. the container activity timer; cold start with the full ~2 GB image;
  image-redeploy effect on sleeping containers; network-level egress controls existence;
  golden-transcript conformance suite. Exit: an iPhone driving a full claude session headless
  in a local amd64 Docker container through the deployed relay. **This proves or kills the
  tier before any money is taken.**
- **Phase 3 — Cloud control plane + persistence.** `cloud/nucleic-cloud` Worker (passkey/
  magic-link accounts, Stripe + Tax + refund policy, entitlements, provisioning, pairing
  bootstrap, data-lifecycle endpoints); Container DO (fencing epochs, metering, alarms);
  checkpoint/restore choreography (periodic WIP snapshots, R2, git-push-on-SIGTERM,
  clone-on-wake); sealed credential injection + re-auth flow; GitHub App vs deploy-key
  decision; EU decision. Private beta: Claude-only, invite-gated, labeled Beta, §13-honest copy.
- **Phase 4 — Multi-host iOS + phone-first workflows.** Host table with per-host pins and
  per-host privacy copy; host switcher; `createProject` + GitHub App; full diff fetch;
  per-device scope management; offline/degraded states. **Public launch of the $19 tier.**
- **Phase 5 — Premium conveniences.** `adoptProject` handoff, scheduled sessions from the idea
  inbox, preview tunnels, cloud intelligence provider, transcript archive/search; Cloud Pro.
- **Phase 6 — Breadth + hardening.** Codex in-container verification, Grok container support,
  jurisdiction placement, limit-raise negotiation, WfP/Dynamic Workers preview hosting.

## 11. Top risks

1. **Swift-on-Linux tail risk** — ~100+ NucleicCore files never compiled on Linux; the six
   seams are enumerated but FileManager/Process/strict-concurrency surprises are expected.
   Bounded by the Phase-2 go/no-go before any billing.
2. **Anthropic ToS flux** — the BYO-subscription question sits between the sanctioned CI
   pattern and the banned harness pattern; suspended SDK-billing plan could change economics.
   Mitigation: ask directly, API-key fallback first-class, "where vendor terms permit."
3. **Checkpoint/restore is the new reliability surface** — ephemeral disk means every
   sleep/wake is a rebuild; bugs lose user work. Periodic WIP snapshots + fencing + the named
   spike tests bound it; this needs the most testing of anything here.
4. **Approval-wait economics** — a pending approval pins the container awake; inverted from
   the local free-suspend model. APNs nudges + 2 h cap + park-and-rerun + spend caps; watch in
   beta.
5. **AppStore headless drag** — carrying UI-adjacent state into a server preserves fidelity
   but could age badly; the alternative (fork) is worse. Revisit only with conformance-suite
   evidence.
6. **Solo-dev ops load** — accounts, fraud, abuse, secrets custody are new standing burdens;
   everything sleeps and DOs hibernate, but on-call is real now.
7. **Brand risk** — one E2EE overclaim for cloud execution costs more than the tier earns;
   per-host privacy copy + §13 review of every page is mandatory.
8. **SCOTUS Oct 2026** — external-purchase-link economics may change mid-flight; web-primary
   billing insulates most of it.

## 12. Alternatives considered

- **Edge-Native Host** (TypeScript host-of-record in a per-project DO + per-session containers;
  235/300): best platform fit and idle economics, but converts a one-time bounded port risk
  into two permanent ones — a TS twin of the host semantics conformance-tested against the Mac
  forever, and hand-rolled Noise in a second language — and moves plaintext event logs into
  Nucleic-operated DO SQLite (structurally softer privacy). Its best ideas are grafted:
  sealed credentials, golden-transcript suite, per-peer routing, park-and-rerun, the empirical
  spike checklist.
- **Nucleus Hybrid** (account plane first, cloud hosts second; 231/300): won the economics/GTM
  lens — first revenue in weeks, billing pipes exercised on low-stakes features. Grafted: the
  optional Plus tier decision (§7.2), server-side roomID derivation, `adoptProject`,
  device-held root key, three-tier trust table, VM-provider fallback, product-invisible port
  framing.
- **Workers for Platforms as runtime:** rejected on verified platform facts (§1); retained as
  optional preview-hosting substrate.

## 13. Open questions

1. Anthropic's written position on BYO-subscription tokens in hosted interactive sandboxes.
2. Does an idle proxied WebSocket hold the container activity timer? (Gates the cost model.)
3. Network-level egress allowlisting for Containers — exists or not?
4. GRDB 7 on Linux; AppStore's real import graph. (Both have bounded fallbacks.)
5. Sell Plus separately, or account-plane-only-then-Cloud? (Decide after the Phase-2 spike.)
6. EU: geo-gate the beta vs. `eu` jurisdiction + DPA from day one.
7. Account recovery vs. device-held root key: escrow UX or accept unrecoverable archives.
