# SandboxV1 scaffold (class + deploy surface restored on the v1-sandbox track)

> Status: **foundation slice — the class, `Dockerfile.v1`, migration `v7` and the
> `durable_object` container application + `SandboxV1` DO binding are restored on
> the independent `v1-sandbox` migration track, and the class is wired to the real
> `DirectoryBackup`. This is NOT the completed Sandbox 1.0 migration and NOT a
> durability guarantee.** No tenant is routed to `SandboxV1` yet; the legacy
> `Sandbox` class still serves every tenant until an explicit, staging-only
> conversion. This note documents the additive `SandboxV1` slice
> (`apps/fouria/src/sandbox-v1.ts`) and its inactivity-policy behavior so the
> remaining wiring prerequisites are explicit.
>
> **Execution plan:** every implemented V1 capability is mapped to a milestone and a
> v1 disposition in [`sandbox-v1-evaluation-plan.json`](/staging/assets/docs/plans/sandbox-v1-evaluation-plan.json)
> (human summary: [`sandbox-v1-evaluation-plan.md`](/staging/llms/platform/reference/plans/sandbox-v1-evaluation-plan/index.md)).

## What this is

`SandboxV1` is an **additive** user-owned Durable Object class for the Sandbox
SDK 1.0 model (where the developer writes the DO and drives the container
through `this.ctx.container`). It is exported from `src/index.ts` alongside
`DirectoryBackupGateway` (the DO passes `ctx.exports.DirectoryBackupGateway` to
`DirectoryBackup`) and registered in `wrangler.jsonc`:

- **Bootstrap migration `v7`** declares `new_sqlite_classes: ["SandboxV1"]`.
  Migrations are append-only, so this entry stays.
- **Deploy surface restored on `v1-sandbox` (2026-11-04).** The `SandboxV1` DO
  binding and its `scheduling_policy: "durable_object"` container application
  (`fouria-sandbox-v1` local/production, `fouria-sandbox-v1-staging` staging,
  built from `./Dockerfile.v1`) are restored in `wrangler.jsonc`. This is a
  deliberate reversal of durable-agents audit finding F9 **for the migration
  track only**: the v1 image must be built and published so the staging lane can
  promote `unstable-<sha>` artifacts. The legacy `Sandbox` class still serves
  every tenant; no route selects `SandboxV1` and no tenant is converted.
- **Cutover prerequisite.** The restored entry uses
  `containers[].images.sandbox.dockerfile = "./Dockerfile.v1"`, which the DO
  reads via `ctx.container.images.sandbox` / `CONTAINER_IMAGE_KEY = 'sandbox'`.
  `SANDBOX_RUNTIME=v1` remains `pending` until the conversion intent (S2) and
  serving path (S3) land; the deploy surface alone does not route traffic.

The real `DirectoryBackup` (from `@cloudflare/sandbox@1.x`) is instantiated in
the DO against `ctx.container` + `ctx.exports.DirectoryBackupGateway`, scoped to
the tenant via a `sandbox-v1/<encoded-do-name>/` R2 prefix in `BACKUP_BUCKET`.

## What this is not (explicitly)

- **No default routing change.** The legacy `Sandbox` class plus `getSandbox()`
  still serve every tenant; no route or request path selects `SandboxV1`, and no
  customer has been cut over.
- **Not a durability guarantee.** `DirectoryBackup` is wired to R2 and the F4E1
  post-encryption/decrypt path is **implemented in the v1 backup surface** (see
  below), but the legacy `.sqsh` → DirectoryBackup conversion, Worker-owned
  periodic snapshots/retention, and restore-before-Gateway integration for the
  v1 line are still **not implemented**. Do not read the backup surface as a
  data-safety guarantee yet.

### F4E1 encryption policy (v1 backup surface)

`SandboxV1` resolves its backup-encryption policy from the same bindings as the
legacy path (`BACKUP_ENCRYPTION_REQUIRED`, `BACKUP_ENCRYPTION_KEY`):

- **`BACKUP_ENCRYPTION_REQUIRED='true'`** — the master key must be present. If it
  is missing (or invalid), `backupDirectory` throws **before** the SDK upload and
  `restoreDirectory` throws for any record with no encrypted sidecar (fail
  closed). Never silently falls back to plaintext.
- **Key present, `REQUIRED` unset** — every new backup is encrypted in place;
  encrypted records are decrypted transiently on restore.
- **Optional and no key** — plaintext mode, explicitly. `restoreDirectory`
  accepts a v1 record with no encrypted sidecar (documented legacy/plaintext
  mode). This is the only allowed unencrypted path.

The master key never leaves the Worker: it is read from `env`, used for the
in-Worker F4E1 transform, and is never placed in a container environment
variable or any container request. `deleteDirectoryBackup` removes the canonical
plaintext key, the `.enc` ciphertext, and the `.meta.json` sidecar (the SDK
delete alone removes only the canonical key).

## Inactivity / TTL policy behavior

`resolveInactivityPolicy()` derives the 1.0 container TTL from the instance's own
`WORKER_URL` (reusing `resolveSleepAfter()` so the legacy and 1.0 lines cannot
drift). There is **no** `SANDBOX_SLEEP_AFTER` binding.

**Billable production** (`platform === 'production' && environment === 'production'`)
sets the **6h platform maximum** and renews it from a recurring keep-alive alarm on
the `SandboxV1` DO; it is stopped only by an explicit lerma freeze (`POST /control` →
`sandbox.destroy()`). SDK 1.0 has no "never stop" timeout: an absent timeout stops
the container shortly after the DO becomes inactive, so a `null` policy would mean
the opposite of keep-alive. This avoids a cold-start / downtime window after an idle
period on the billable production environment.

Non-billable instances get a finite, capped timeout, and the `ActivityScheduler`
DO alarm wakes a sleeping container:

- **Staging platform** (`staging-*` hostname) — 15m.
- **Dev environment** (`*-dev` hostname) — 2h.
- Any derived value is clamped to the 6h platform maximum.

### Deployed idle timeout by instance

| Environment                 | Idle timeout          |
| --------------------------- | --------------------- |
| `env.production` (billable) | **none** (keep-alive) |
| deployed non-staging dev    | 2h                    |
| `env.staging`               | 15m                   |

The value is derived in the Worker from the instance hostname; the provisioner
does not deploy a per-instance idle binding.

## Image / package pairing

The v1 line is pinned by the root `package.json` catalog and must be bumped
together:

| Surface        | Value                                               |
| -------------- | --------------------------------------------------- |
| Worker package | `@cloudflare/sandbox@1.0.0` (`catalog`)             |
| Legacy package | `@cloudflare/sandbox-legacy@0.13.0-next.776.1`      |
| Legacy import  | aliased to `@cloudflare/sandbox` (`npm:` alias)     |
| Shim source    | `COPY --from=cloudflare/sandbox:1.0.0 sandbox-shim` |
| Image          | `apps/fouria/Dockerfile.v1` (`containers[].images`) |

`Dockerfile.v1` does **not** inherit the `cloudflare/sandbox` base: 1.0 removes
the in-image SDK server, so it uses `node:24-trixie-slim` and COPYs the
`sandbox-shim` helper from the matching `1.0.0` image. The shim tag must track
the installed `@cloudflare/sandbox` version.

## Remaining blockers (before cutover / durability)

1. ~~**F4E1 for DirectoryBackup records**~~ — **implemented in the v1 surface.**
   `SandboxV1.backupDirectory` / `restoreDirectory` / `deleteDirectoryBackup` now
   use the F4E1 helper `src/crypto/directory-backup-encryption.ts`:
   a new backup is post-encrypted in place (`<id>.tar.zst` → `<id>.tar.zst.enc`
   - `<id>.meta.json`, plaintext deleted), restore transiently decrypts for the
     SDK and always removes the transient plaintext, and delete removes canonical,
     ciphertext and metadata. This remains **not wired end-to-end** (no scheduler,
     no routing cutover), see blockers below.
2. ~~**Legacy `.sqsh` → DirectoryBackup conversion**~~ — **implemented in S2.**
   `SandboxV1.convertToV1()` writes the intent, acquires the per-tenant lease,
   opens the legacy recovery point (`stable-backup.json`, decrypting
   `data.sqsh.enc` when needed), streams the squashfs into the v1 container,
   extracts it with `unsquashfs -f -d /home/openclaw`, takes a v1
   `DirectoryBackup` (`tar+zstd/1`), and writes the conversion record + stable
   pointer. `Dockerfile.v1` installs `squashfs-tools`.
3. ~~**Serving parity (proxy, health, admin RPC)**~~ — **implemented in S3.** The
   Worker acquires the `SandboxV1` DO for a converted tenant (`V1SandboxClient`)
   and serves through the DO: `fetch()` forwards HTTP/WS to the container port
   (never waking a stopped container), `ensureGateway` delegates to the DO-owned
   owner start, and `getHealthSnapshot` keeps `sleeping` / 503-until-ready
   semantics. Restoring the committed v1 `DirectoryBackup` before the launch is
   part of the DO start. See `WORKER-DEVELOPMENT.md` §"Sandbox v1 serving (S3)".
4. **Worker-owned periodic snapshots + retention** — no interval-gated v1
   snapshot scheduler or retention pruning (the legacy path in `persistence.ts`
   is unchanged and still the only wired scheduler). `SandboxV1Client` fails
   closed on `createBackup` / `restoreBackup` / file tools / eviction hooks.
5. **Durable jobs, control actions and scheduling on v1** — the boot/backup
   jobs, `ActivityScheduler`, `/control` actions, and the eviction hooks still
   acquire the legacy stub; a converted tenant answers
   `503 SANDBOX_V1_CONTROL_UNSUPPORTED` for control actions until S4/S5.
6. **Tenant provisioning of the v1 runtime (OCM-4)** — code landed and **verified
   live on staging** (2026-11-05): both tenants carry `WORKER_PLATFORM`,
   `SANDBOX_V1_CUTOVER` and a `SandboxV1` DO binding, and each has a
   `…-sandbox-v1-<platform>` container application with
   `scheduling_policy: "durable_object"` and a digest-pinned named image. The
   staging Lerma was temporarily the branch image during the validation and is
   back on `:latest-pre`; a later promotion from `develop` Lerma would drop the
   v1 bindings, so the branch Lerma must drive upgrades until this lands. See
   [`sandbox-v1-staging-observations.md`](/staging/llms/platform/reference/plans/sandbox-v1-staging-observations/index.md).
7. **End-to-end data migration + cutover** — the conversion is orchestrated
   (`/control migrate` → `SandboxV1` DO alarm → `convertToV1`), but no tenant
   has been converted yet, so there is no verified live migration and no
   routing/tenant cutover. `PER-3`/`S5` owns the first live conversion; it needs
   a committed legacy recovery point (`stable-backup.json`).

Until the remaining blockers land, the v1 line is a **foundation + serving
parity** slice: a converted staging tenant can serve, but durability, billing,
and fleet operations are not yet claimed.

## Tests

`apps/fouria/src/sandbox-v1.test.ts` covers duration parsing, the TTL/keep-alive
policy matrix, constructor re-apply/retry, keep-alive retry/headroom behavior,
`exec` delegation, and the wired `DirectoryBackup` surface.
