# SandboxV1 scaffold (registered, not routed)

> Status: **foundation slice — registered in Wrangler and wired to the real
> `DirectoryBackup`, but NOT the completed Sandbox 1.0 migration and NOT a
> durability guarantee.** 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.

## 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 is registered in `wrangler.jsonc`:

- **Bootstrap migration `v7`** declares `new_sqlite_classes: ["SandboxV1"]`.
- A dedicated **container application** per environment (`fouria-sandbox-v1`
  for local/production, `fouria-sandbox-v1-staging` for staging) uses
  `scheduling_policy: "durable_object"` and builds
  `containers[].images.sandbox.dockerfile = "./Dockerfile.v1"`. The DO reads the
  image from `ctx.container.images.sandbox` (`CONTAINER_IMAGE_KEY = 'sandbox'`).
- The `SandboxV1` binding is declared under `durable_objects.bindings`.

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'`)
gets **no inactivity timeout** — the container stays awake and is stopped only by an
explicit lerma freeze (`POST /control` → `sandbox.destroy()`). 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** — no migration of existing
   0.12 `.sqsh` archives into the v1 record format. The F4E1 helper is a
   _different_ on-disk shape from the legacy `.sqsh.enc` line; the two do not
   interoperate and no conversion exists yet.
3. **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).
4. **Restore-before-Gateway integration** — `start-openclaw.sh setup` does not yet
   restore a v1 `DirectoryBackup` before gateway launch for this line.
5. **End-to-end data migration + cutover** — no routing/tenant cutover, and no
   verified migration of live tenant data.

Until all five land, the v1 line is a **foundation only** and carries no
durability claim.

## 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.
