> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bastani.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Store snapshots in the cloud

> Configure Azure Blob Storage, Amazon S3, S3-compatible stores, Google Cloud Storage, or a local directory for Atomic worktree snapshots.

Use this guide if you're a developer or host operator configuring external storage for Atomic worktree snapshots. By the end of this page, you can configure snapshot storage on any supported provider, optionally separate shared read-only prepared bases from per-session snapshots, rotate short-lived host credentials, configure encryption, and diagnose storage errors.

This page covers snapshot storage configuration and troubleshooting. For how disk-image snapshots work, platform support, and rollback or fork workflows, see [Save and restore worktree snapshots](https://docs.bastani.ai/worktree-snapshots.md). For session conversation databases (SQLite, JSONL, or PostgreSQL), see [Storage](https://docs.bastani.ai/storage.md).

## How snapshot storage separates from session storage

Session storage (SQLite or PostgreSQL) stores your conversations and a small pointer to each snapshot. Snapshot storage (`snapshots.storage`) stores prepared repository bases, chunked diffs, manifests, and chain heads. Snapshot data never goes into SQLite or PostgreSQL.

Worktree snapshots are off by default on fresh installs and after upgrading from Atomic 0.10.x, and there is no implicit storage location. Snapshots are effectively on only when both of the following conditions hold:

* You request snapshots on in `settings.json`, a CLI flag, an environment variable, the SDK, or RPC.
* You configure a valid, supported snapshot storage URL with resolvable credentials.

If you request snapshots on without valid storage, Atomic writes no snapshot data anywhere (no local fallback, no temporary blobs, and nothing in the session database), prints one plain message naming how to configure storage on your surface (or turn snapshots off), and continues the session normally. If configured storage becomes unreachable or refuses access at save time, Atomic skips that save with one message, never falls back locally, and tries again on the next save.

Supported snapshot storage locations include the following standard stores:

* **Azure Blob Storage**, including Azure Data Lake Storage Gen2 (ADLS Gen2) accounts with a hierarchical namespace.
* **Amazon S3** and S3-compatible stores (MinIO, Cloudflare R2, and Backblaze B2).
* **Google Cloud Storage**.
* An **explicit local directory** (`file://`) for single-machine use.

Credentials never go in `settings.json` or in `snapshots.storage` or `snapshots.baseStorage` URLs. Atomic authenticates through each cloud's standard credential chain or through a short-lived, prefix-scoped credential file rotated by a host.

> [!NOTE]
>
> Host-rotated credential files (Azure user-delegation Shared Access Signature (SAS), AWS session or presigned credentials, and Google Cloud downscoped tokens) and environment-key credentials work over plain HTTP with zero extra packages installed; ambient cloud sign-in chains install one optional package in the steps that follow.

## Before you begin

Confirm the following prerequisites before configuring a provider:

* Atomic 0.11.0 or later installed on every machine that saves or restores snapshots.
* Permission to create a bucket, container, or local directory and assign a least-privilege role or policy.
* Your cloud CLI installed (`az`, `aws`, or `gcloud`) if you plan to use the cloud's ambient credential chain.

## Configure a storage provider

Pick your provider, grant the least-privilege role or policy, sign in with your cloud identity, and turn snapshots on.

### Configure Azure Blob Storage and ADLS Gen2

Atomic works with flat-namespace Azure Blob accounts and ADLS Gen2 accounts, including accounts with shared-key access disabled (`--allow-shared-key-access false`).

1. Look up your subscription ID and the Microsoft Entra object ID for your user or VM managed identity:

   ```bash theme={null}
   SUBSCRIPTION_ID="$(az account show --query id -o tsv)"
   # For your signed-in user:
   ASSIGNEE_OBJECT_ID="$(az ad signed-in-user show --query id -o tsv)"
   # Or, for a VM's system-assigned managed identity:
   # ASSIGNEE_OBJECT_ID="$(az vm show -g RESOURCE_GROUP -n VM_NAME \
   #   --query identity.principalId -o tsv)"
   ```

   Replace `RESOURCE_GROUP` with your Azure resource group name and `VM_NAME` with your Azure VM name (only if assigning a VM's managed identity).

2. Create the storage account with shared-key access disabled:

   ```bash theme={null}
   az storage account create \
     --name ACCOUNT_NAME \
     --resource-group RESOURCE_GROUP \
     --location REGION \
     --sku Standard_LRS \
     --allow-shared-key-access false
   ```

   Replace `ACCOUNT_NAME` with a globally unique storage account name (3–24 lowercase letters and digits), `RESOURCE_GROUP` with your resource group name, and `REGION` with an Azure region close to your machines (such as `eastus2`).

   Optional: If your organization's policy requires a storage firewall, add `--default-action Deny` to `az storage account create`, then allow your machine's IP address or VM subnet with `az storage account network-rule add --account-name ACCOUNT_NAME --resource-group RESOURCE_GROUP --ip-address CLIENT_IP` (replacing `CLIENT_IP` with your outbound IP address, or pass `--subnet SUBNET_ID`).

3. Create the `atomic-snapshots` container through Azure Resource Manager (`container-rm` requires no data-plane roles beforehand):

   ```bash theme={null}
   az storage container-rm create \
     --storage-account ACCOUNT_NAME \
     --resource-group RESOURCE_GROUP \
     --name atomic-snapshots
   ```

4. Grant **Storage Blob Data Contributor** scoped to that container:

   ```bash theme={null}
   STORAGE_ACCOUNT_SCOPE="/subscriptions/${SUBSCRIPTION_ID}"
   STORAGE_ACCOUNT_SCOPE+="/resourceGroups/RESOURCE_GROUP"
   STORAGE_ACCOUNT_SCOPE+="/providers/Microsoft.Storage/storageAccounts/ACCOUNT_NAME"
   CONTAINER_SCOPE="${STORAGE_ACCOUNT_SCOPE}/blobServices/default/containers/atomic-snapshots"

   az role assignment create \
     --assignee "$ASSIGNEE_OBJECT_ID" \
     --role "Storage Blob Data Contributor" \
     --scope "$CONTAINER_SCOPE"
   ```

5. Install Azure sign-in support (not needed when you use a host-rotated SAS credential file):

   ```bash theme={null}
   atomic install npm:@azure/identity@4.14.1
   ```

6. Optional: If you aren't running on a VM or container with Managed Identity, AKS Workload Identity, or `AZURE_TENANT_ID` / `AZURE_CLIENT_ID` / `AZURE_CLIENT_SECRET`, sign in with your Azure account:

   ```bash theme={null}
   az login
   ```

   If `HTTPS_PROXY` is set on an Azure VM using Managed Identity, add the Instance Metadata Service address to `NO_PROXY` (`NO_PROXY=169.254.169.254`, plus any private identity endpoint) so Managed Identity token requests bypass the proxy.

7. Turn snapshots on and verify read and write access:

   ```bash theme={null}
   # Flat-namespace Blob Storage:
   atomic snapshots on --storage az://ACCOUNT_NAME/atomic-snapshots/team-a
   # Alternative HTTPS URL:
   # atomic snapshots on \
   #   --storage https://ACCOUNT_NAME.blob.core.windows.net/atomic-snapshots/team-a

   # ADLS Gen2 (hierarchical namespace):
   # atomic snapshots on \
   #   --storage abfss://atomic-snapshots@ACCOUNT_NAME.dfs.core.windows.net/team-a
   # atomic snapshots on \
   #   --storage https://ACCOUNT_NAME.dfs.core.windows.net/atomic-snapshots/team-a

   atomic snapshots status --check
   ```

   Confirm that `atomic snapshots status --check` prints `Check: ok` and exits `0`.

### Configure Amazon S3

Amazon S3 turns on AES-256 server-side encryption (SSE-S3) by default for every bucket.

1. Create a bucket and attach the following minimal Identity and Access Management (IAM) policy scoped to your prefix (`atomic-snapshots/*`). `s3:AbortMultipartUpload` and `s3:ListMultipartUploadParts` let Atomic clean up interrupted multipart uploads:

   ```json theme={null}
   {
     "Version": "2012-10-17",
     "Statement": [
       {
         "Sid": "AtomicSnapshotsCaptureAndResume",
         "Effect": "Allow",
         "Action": [
           "s3:GetObject",
           "s3:PutObject",
           "s3:AbortMultipartUpload",
           "s3:ListMultipartUploadParts"
         ],
         "Resource": "arn:aws:s3:::BUCKET_NAME/atomic-snapshots/*"
       }
     ]
   }
   ```

   Replace `BUCKET_NAME` with your S3 bucket name.

   Optional: For an operator identity that runs `atomic snapshots collect`, attach a policy that adds `s3:DeleteObject` on the prefix and `s3:ListBucket` restricted to the prefix:

   ```json theme={null}
   {
     "Version": "2012-10-17",
     "Statement": [
       {
         "Sid": "AtomicSnapshotsCollectObjects",
         "Effect": "Allow",
         "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
         "Resource": "arn:aws:s3:::BUCKET_NAME/atomic-snapshots/*"
       },
       {
         "Sid": "AtomicSnapshotsCollectList",
         "Effect": "Allow",
         "Action": ["s3:ListBucket"],
         "Resource": "arn:aws:s3:::BUCKET_NAME",
         "Condition": {
           "StringLike": {
             "s3:prefix": ["atomic-snapshots/*"]
           }
         }
       }
     ]
   }
   ```

2. Install AWS sign-in support (not needed when you use a host-rotated credential file or `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` directly):

   ```bash theme={null}
   atomic install npm:@aws-sdk/credential-providers@3.1184.0
   ```

3. Optional: If you aren't using an attached IAM role, IRSA, ECS task role, or EC2 IMDSv2, select your AWS profile and region (or sign in with `aws sso login`):

   ```bash theme={null}
   export AWS_PROFILE=PROFILE_NAME
   export AWS_REGION=AWS_REGION_CODE
   ```

   Replace `PROFILE_NAME` with your AWS CLI profile name and `AWS_REGION_CODE` with your bucket's region, such as `us-east-1`.

4. Turn snapshots on and verify connectivity:

   ```bash theme={null}
   atomic snapshots on --storage s3://BUCKET_NAME/atomic-snapshots
   atomic snapshots status --check
   ```

   Confirm that `atomic snapshots status --check` prints `Check: ok` and exits `0`.

### Configure S3-compatible stores

Use an `s3://BUCKET_NAME/PREFIX` URL together with `snapshots.s3` endpoint settings in `~/.atomic/agent/settings.json` (or `AWS_ENDPOINT_URL_S3`).

> [tab] Cloudflare R2
>
> 1. Set the endpoint and `"region": "auto"` in `~/.atomic/agent/settings.json`:
>
>    ```json theme={null}
>    {
>      "snapshots": {
>        "on": true,
>        "storage": "s3://BUCKET_NAME/atomic-snapshots",
>        "s3": {
>          "endpoint": "https://ACCOUNT_ID.r2.cloudflarestorage.com",
>          "region": "auto"
>        }
>      }
>    }
>    ```
>
>    Replace `BUCKET_NAME` with your R2 bucket name and `ACCOUNT_ID` with your Cloudflare account ID.
>
> 2. Export your R2 S3 API token with `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` (or configure a named profile in `~/.aws/credentials`), then verify access:
>
>    ```bash theme={null}
>    atomic snapshots status --check
>    ```

> [tab] Backblaze B2
>
> 1. Set your bucket's S3-compatible endpoint and region in `~/.atomic/agent/settings.json`:
>
>    ```json theme={null}
>    {
>      "snapshots": {
>        "on": true,
>        "storage": "s3://BUCKET_NAME/atomic-snapshots",
>        "s3": {
>          "endpoint": "https://s3.B2_REGION.backblazeb2.com",
>          "region": "B2_REGION"
>        }
>      }
>    }
>    ```
>
>    Replace `BUCKET_NAME` with your B2 bucket name and `B2_REGION` with your bucket region, such as `us-west-004`.
>
> 2. Provide your B2 Application Key ID and Application Key in `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` (or `~/.aws/credentials`), then verify access:
>
>    ```bash theme={null}
>    atomic snapshots status --check
>    ```

> [tab] MinIO
>
> 1. Set `"forcePathStyle": true` for MinIO in `~/.atomic/agent/settings.json`:
>
>    ```json theme={null}
>    {
>      "snapshots": {
>        "on": true,
>        "storage": "s3://BUCKET_NAME/atomic-snapshots",
>        "s3": {
>          "endpoint": "https://MINIO_HOST:9000",
>          "region": "us-east-1",
>          "forcePathStyle": true
>        }
>      }
>    }
>    ```
>
>    Replace `BUCKET_NAME` with your MinIO bucket name and `MINIO_HOST` with your MinIO server hostname.
>
> 2. Export `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, then verify access:
>
>    ```bash theme={null}
>    atomic snapshots status --check
>    ```

### Configure Google Cloud Storage

Google Cloud Storage turns on Google-managed AES-256 server-side encryption on every bucket by default.

1. Create the bucket with uniform bucket-level access:

   ```bash theme={null}
   gcloud storage buckets create gs://BUCKET_NAME \
     --location=US \
     --uniform-bucket-level-access
   ```

   Replace `BUCKET_NAME` with your Google Cloud Storage bucket name.

2. Grant `roles/storage.objectUser` (or `roles/storage.objectAdmin` for machines that run `atomic snapshots collect`) scoped with an IAM condition to your prefix:

   ```bash theme={null}
   PREFIX_EXPR="resource.name.startsWith("
   PREFIX_EXPR+="'projects/_/buckets/BUCKET_NAME/objects/atomic-snapshots/')"
   gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
     --member="serviceAccount:SERVICE_ACCOUNT_EMAIL" \
     --role="roles/storage.objectUser" \
     --condition="expression=${PREFIX_EXPR},title=atomic-snapshots-prefix"
   ```

   Replace `SERVICE_ACCOUNT_EMAIL` with the service account email address.

3. Install Google Cloud sign-in support (not needed when you use a host-rotated downscoped token file):

   ```bash theme={null}
   atomic install npm:google-auth-library@11.3.4
   ```

4. Optional: If you aren't using Workload Identity Federation, an attached service account, or `GOOGLE_APPLICATION_CREDENTIALS`, sign in with Application Default Credentials (ADC):

   ```bash theme={null}
   gcloud auth application-default login
   ```

5. Turn snapshots on and verify connectivity:

   ```bash theme={null}
   atomic snapshots on --storage gs://BUCKET_NAME/atomic-snapshots
   atomic snapshots status --check
   ```

   Confirm that `atomic snapshots status --check` prints `Check: ok` and exits `0`.

### Configure a local directory (`file://`)

If you work on one machine and want snapshots stored locally without a cloud account, configure an explicit absolute directory path writable by your user:

```bash theme={null}
atomic snapshots on --storage "file://$HOME/atomic-snapshots"
atomic snapshots status --check
```

On Windows, use `file:///C:/Users/USERNAME/atomic-snapshots` (replace `USERNAME` with your Windows user name). Avoid placing a local snapshot directory inside a cloud-synced folder or on a slow network share when an object store is available. Snapshot storage may live on a network share (an NFS or SMB mount used through `file://`); only `snapshots.imageDir`, where the active worktree images and their markers live, must be on a local disk.

## Configure snapshot storage across every surface

Every surface reads the same settings using one precedence order (highest first):

1. **RPC** (`set_snapshots`)
2. **SDK** (`createAgentSession({ snapshots })`)
3. **CLI flag** (`--snapshots` or `--no-snapshots`, `--snapshots-storage URL`, `--snapshots-base-storage URL`, `--snapshots-credential-file PATH`, `--snapshots-base-credential-file PATH`, `--snapshots-chain CHAIN_ID`, `--snapshots-engine MODE`)
4. **Environment variable** (`ATOMIC_SNAPSHOTS`, `ATOMIC_SNAPSHOTS_STORAGE`, `ATOMIC_SNAPSHOTS_BASE_STORAGE`, `ATOMIC_SNAPSHOTS_CREDENTIAL_FILE`, `ATOMIC_SNAPSHOTS_BASE_CREDENTIAL_FILE`, `ATOMIC_SNAPSHOTS_CHAIN`, `ATOMIC_SNAPSHOTS_ENGINE`)
5. **Project settings** (`.atomic/settings.json`, only in a trusted project)
6. **Global settings** (`~/.atomic/agent/settings.json`)
7. **Default** (snapshots off, no storage set)

Run `atomic snapshots status` at any time to see the requested state, the effective state (`on` or `off`), and which configuration layer set each value. In the following examples, replace `ACCOUNT_NAME` with your Azure storage account name and `BUCKET_NAME` with your S3 bucket name.

> [tab] settings.json
>
> Add `snapshots.on` and `snapshots.storage` to `~/.atomic/agent/settings.json` (or `.atomic/settings.json` in a trusted project):
>
> ```json theme={null}
> {
>   "snapshots": {
>     "on": true,
>     "storage": "az://ACCOUNT_NAME/atomic-snapshots/team-a"
>   }
> }
> ```

> [tab] CLI
>
> Persist snapshot settings or override them for one run:
>
> ```bash theme={null}
> # Persist globally (add --project for .atomic/settings.json)
> atomic snapshots on --storage az://ACCOUNT_NAME/atomic-snapshots/team-a
> atomic snapshots status --check
> atomic snapshots off
>
> # Override for one run without editing settings.json
> atomic --snapshots --snapshots-storage s3://BUCKET_NAME/atomic-snapshots
> atomic --no-snapshots
> ```

> [tab] Environment
>
> Export the snapshot variables before starting Atomic:
>
> ```bash theme={null}
> export ATOMIC_SNAPSHOTS=1
> export ATOMIC_SNAPSHOTS_STORAGE="az://ACCOUNT_NAME/atomic-snapshots/team-a"
> ```

> [tab] TypeScript SDK
>
> Pass `snapshots` to `createAgentSession`, or inspect effective snapshot status directly with `snapshotStatus`:
>
> ```typescript theme={null}
> import { createAgentSession, snapshotStatus } from "@bastani/atomic";
>
> const { session, snapshotRestore } = await createAgentSession({
>   snapshots: {
>     on: true,
>     storage: "az://ACCOUNT_NAME/atomic-snapshots/team-a",
>   },
> });
>
> const status = await snapshotStatus({
>   cwd: "/work/repo",
>   snapshots: {
>     on: true,
>     storage: "az://ACCOUNT_NAME/atomic-snapshots/team-a",
>   },
> });
> ```
>
> A program finds the cloud sign-in package (`@azure/identity`, `@aws-sdk/credential-providers` or `google-auth-library`) in its own `node_modules` first, then in `AGENT_DIR/npm`, where `atomic install` puts it. `AGENT_DIR` is the `agentDir` option you pass to `createAgentSession` or to a snapshot function; without it, Atomic uses `ATOMIC_CODING_AGENT_DIR`, then `~/.atomic/agent`.

> [tab] RPC
>
> Send `set_snapshots` and inspect the effective state with `get_state`:
>
> ```json theme={null}
> {
>   "id": "1",
>   "type": "set_snapshots",
>   "on": true,
>   "storage": "az://ACCOUNT_NAME/atomic-snapshots/team-a"
> }
> { "id": "2", "type": "get_state" }
> ```
>
> `set_snapshots` is session-scoped by default (reporting `source: "rpc"` without editing `settings.json`); pass `"persist": true` and optional `"scope": "global"` or `"project"` to save it. When snapshots are active afterward, `set_snapshots` also runs a storage write/read check (up to 15 seconds) and returns `check` (`{ ok, code?, message, latencyMs? }`) and `lastCheck` without changing `active` on a failed check. `get_state` includes `data.snapshots` with `on` (requested), `active` (effective: `true` only when `on` is `true` and valid storage is configured), `source`, `storage`, `storageType`, `storageSource`, `chain`, `engine`, non-secret `credential` metadata (`type`, `expiresAt`, `source`), `lastCheck` (`{ ok, code?, message, at }`, the session's last storage check or save), and `configError` when misconfigured. Secrets are never returned. See [RPC protocol](https://docs.bastani.ai/rpc/protocol.md#set_snapshots).

## Isolate settings and issue per-prefix credentials on a host

A host that sleeps sessions and wakes them on fresh machines shouldn't give a worker VM broad access to an entire bucket or container, and shouldn't let untrusted files in a workspace redirect snapshot storage.

### Restrict configuration sources

Set `ATOMIC_SNAPSHOTS_SETTINGS_SOURCES=env,flags` on host-launched processes so Atomic ignores project `.atomic/settings.json` and user `~/.atomic/agent/settings.json` completely and reads only environment variables and CLI flags. Accepted comma-separated tokens are `env`, `flags` (or `cli`), `sdk`, `rpc`, `project`, and `user` (or `global`).

### Share read-only prepared bases separately (`snapshots.baseStorage`)

Prepared repository bases are shared across sessions for the same repository and OS, while per-session diffs belong to one tenant or workspace prefix. To avoid duplicating prepared bases into every per-session prefix, configure a separate read-only base store:

* **URL:** `snapshots.baseStorage`, `ATOMIC_SNAPSHOTS_BASE_STORAGE`, `--base-storage URL` / `--snapshots-base-storage URL`, or SDK `snapshots.baseStorage`.
* **Optional separate credential (host-only, forbidden in `settings.json`):** `ATOMIC_SNAPSHOTS_BASE_CREDENTIAL_FILE`, `--base-credential-file PATH` / `--snapshots-base-credential-file PATH`, or SDK `snapshots.baseCredentialFile` / `snapshots.baseCredential`.

When `snapshots.baseStorage` is set, Atomic downloads and verifies prepared bases from `baseStorage` while writing session chunks, manifests, and chain heads to `snapshots.storage`. With client-side encryption enabled (`snapshots.encryption.mode: "aes-256-gcm"`), `snapshots.baseStorage` is read using the same encryption key as the snapshots—prepare its bases with that key, because sessions with different keys can't share one base store (see [What stays visible with client-side encryption](#what-stays-visible-with-client-side-encryption)).

### Trust model for storage write access

Like other object-store snapshot tools (such as restic and kopia), snapshot storage has no separate trusted monotonic counter: anyone with write access to a snapshot storage location has full control of its snapshots, including rewriting a chain head to roll a fresh machine back to an earlier generation. A machine that already saved on that chain still detects the divergence and refuses its next save with `head-advanced`, but a fresh machine with no local history trusts the head stored in the prefix unless an external coordinator pins the expected generation or verifies signed expectations through `--expect` and `snapshots.mountHelper`.

Follow these access boundaries:

* Grant write access only to machines that save snapshots to that prefix.
* Scope each machine's write credential strictly to its own tenant or workspace prefix.
* Use read-only credentials for shared prepared-base stores (`snapshots.baseStorage`).

### What stays visible with client-side encryption

When `snapshots.encryption.mode` is `"aes-256-gcm"`, Atomic encrypts snapshot data chunks, manifests, and prepared base descriptors (`bases/BASE_ID.json`) before uploading—and rejects plaintext base descriptors with no fallback.

Chain heads (`heads/CHAIN_ID.json`) stay plaintext so cloud conditional compare-and-swap fencing works directly without a separate coordinator. As other encrypted object-store snapshot tools (such as restic and kopia) document, anyone who can read the storage location can still see:

* **Head metadata:** Each chain head's `generation`, opaque `writerId` (contains no hostname or username), snapshot and manifest IDs, SHA-256 hashes, base fingerprint, and timestamps.
* **Object keys:** Prefix paths and object names under `bases/`, `data/sha256/...`, `manifests/`, `heads/`, and `locks/`.
* **Object sizes and timestamps:** Byte lengths and last-modified times of stored objects.
* **Chain and generation structure:** Which chains exist, how many generations each chain has, and when saves occur.

Client-side encryption applies only to objects stored in snapshot storage—not the local mounted worktree, active disk images (`snapshots.imageDir`), cached prepared base images (`snapshots.baseCacheDir`), or the local read-through object cache (`snapshots.cacheDir`, which stores plaintext verified objects). Protect the machine's local storage with full-disk encryption and OS permissions (and set `snapshots.cacheMaxBytes` to `0` if you want to disable the local object cache).

A separate base store (`snapshots.baseStorage`) is read with the same client-side encryption key as the snapshots, so prepare its bases with that key. Sessions with different keys can't share one base store: a base prepared without client-side encryption, or with another key, is refused with a message directing you to re-prepare it with `atomic snapshots base create` (or use a base store prepared with that key), and is never read as plaintext.

### Rotate prefix-scoped credential files

Pass the credential file path with `ATOMIC_SNAPSHOTS_CREDENTIAL_FILE` or `--snapshots-credential-file PATH` (never in `settings.json`). The host writes one JSON object atomically (`write`, `fsync`, `rename`) with an ISO-8601 UTC `expiresAt`.

Azure SAS credential file:

```json theme={null}
{
  "type": "azure-sas",
  "sas": "sv=2025-01-05&sr=d&sdd=2&sp=rcw&se=2026-12-05T13:00:00Z&sig=SIGNATURE",
  "expiresAt": "2026-12-05T13:00:00Z"
}
```

AWS session credential file:

```json theme={null}
{
  "type": "aws-session",
  "accessKeyId": "ACCESS_KEY_ID",
  "secretAccessKey": "SECRET_ACCESS_KEY",
  "sessionToken": "SESSION_TOKEN",
  "expiresAt": "2026-12-05T13:00:00Z"
}
```

Google Cloud downscoped OAuth token file:

```json theme={null}
{
  "type": "gcs-token",
  "accessToken": "OAUTH_ACCESS_TOKEN",
  "expiresAt": "2026-12-05T13:00:00Z"
}
```

Replace `ACCESS_KEY_ID`, `SECRET_ACCESS_KEY`, `SESSION_TOKEN`, `SIGNATURE`, and `OAUTH_ACCESS_TOKEN` with the short-lived prefix-scoped values issued by your host.

Atomic handles host-supplied credentials with these rules:

* **No silent widening:** When a host credential is configured, Atomic disables the machine's ambient cloud credential chain completely. Isolation between tenants comes from the cloud credential's prefix scope.
* **Proactive rotation:** Atomic rereads the file when within five minutes of `expiresAt`. If the cloud returns an expired-credential `401` or `403`, Atomic rereads once and retries the request once.
* **Immediate withdrawal:** If the host deletes the credential file, Atomic fails immediately with `credentials-missing` and doesn't retry.
* **Least privilege on the hot path:** Saving and restoring need only read, create, and write on keys under the prefix (for example, an Azure user-delegation SAS with `sp=rcw`). Atomic never calls `list`, `delete`, container creation, or account APIs on the hot path.
* **Minimal health check:** `atomic snapshots status --check` writes and reads back one fixed `.atomic-probe` object under the prefix (no `list`, no `delete`) and reports which permission is missing if it fails.
* **Shared-worktree chains:** Set `snapshots.chain`, `ATOMIC_SNAPSHOTS_CHAIN`, or `--snapshots-chain` when multiple sessions share one workspace. Atomic enforces single-writer fencing with conditional writes so two VMs waking the same chain can't overwrite each other; the second writer receives `chain-conflict`.

Hosts embedding the SDK can also pass a `credential: () => Promise<SnapshotCredential>` callback (and `baseCredential` for `baseStorage`), or push a rotated credential over RPC with `set_snapshots`.

## Configure encryption

Server-side encryption (SSE) is on by default on every cloud provider:

* **Azure Blob and ADLS Gen2:** AES-256 Storage Service Encryption (optional custom scope with `snapshots.azure.encryptionScope`).
* **Amazon S3:** SSE-S3 AES-256 (optional Key Management Service (KMS) key with `snapshots.s3.kmsKeyId`).
* **Google Cloud Storage:** Google-managed AES-256 (optional Customer-Managed Encryption Key (CMEK) with `snapshots.gcs.kmsKeyName`).

### Opt in to client-side encryption

To encrypt snapshot data chunks, manifests, and prepared base descriptors (`bases/BASE_ID.json`) before they leave the machine, opt in to AES-256-GCM client-side encryption (when enabled, Atomic rejects plaintext base descriptors with no fallback; chain heads remain plaintext—see [What stays visible with client-side encryption](#what-stays-visible-with-client-side-encryption)):

1. Generate a 256-bit key and save it with owner-only permissions. On Linux and macOS, Atomic reads the key file only when it's a regular file you own with mode `0600`, not a link. It checks the mode and owner, not ACLs: on macOS, an ACL can still let others read a `0600` file, so check with `ls -le` that the file has none, and remove any with `chmod -N`:

   ```bash theme={null}
   openssl rand -base64 32 > ~/.atomic/agent/snapshot.key
   chmod 600 ~/.atomic/agent/snapshot.key
   ```

2. Point `snapshots.encryption` at the key file in `~/.atomic/agent/settings.json` (or pass the base64 or hex 32-byte key in `ATOMIC_SNAPSHOTS_ENCRYPTION_KEY`):

   ```json theme={null}
   {
     "snapshots": {
       "on": true,
       "storage": "s3://BUCKET_NAME/atomic-snapshots",
       "encryption": {
         "mode": "aes-256-gcm",
         "keyFile": "/home/USERNAME/.atomic/agent/snapshot.key"
       }
     }
   }
   ```

   Replace `BUCKET_NAME` with your bucket name and `USERNAME` with your local username. Setting `ATOMIC_SNAPSHOTS_ENCRYPTION_KEY` on its own turns client-side encryption on (`aes-256-gcm`), even with no `snapshots.encryption` setting.

Hosts embedding the SDK pass the key's 32 bytes directly instead of a file:

```ts theme={null}
import { createAgentSession } from "@bastani/atomic";

const { session } = await createAgentSession({
  cwd: "/home/USERNAME/work/REPO_NAME",
  snapshots: {
    on: true,
    storage: "s3://BUCKET_NAME/atomic-snapshots",
    encryption: { mode: "aes-256-gcm", key: KEY_BYTES },
  },
});
```

Replace the following:

* `USERNAME`: your local username.
* `REPO_NAME`: your worktree folder name.
* `BUCKET_NAME`: your S3 bucket name.
* `KEY_BYTES`: a `Uint8Array` holding the 32-byte key read from your secret manager.

RPC clients can't send an encryption key: `set_snapshots` refuses an `encryption` field instead of ignoring it. Configure encryption with `ATOMIC_SNAPSHOTS_ENCRYPTION_KEY`, `snapshots.encryption` in `settings.json`, or the SDK before the session starts.

#### Encryption that can't be applied stops the save

When client-side encryption is requested and Atomic can't apply it, Atomic stores nothing and reports `invalid-setting` naming the setting. It never falls back to unencrypted storage. Each of these stops the save before anything is mounted or written:

* `snapshots.encryption.mode` is missing or isn't `"aes-256-gcm"` or `"sse"`.
* `"aes-256-gcm"` is set with no key from the SDK, `ATOMIC_SNAPSHOTS_ENCRYPTION_KEY`, or `snapshots.encryption.keyFile`.
* The key doesn't decode to exactly 32 bytes, or the key file can't be read.
* On Linux and macOS, the key file is a symbolic link, isn't a regular file, has a mode other than `0600`, or is owned by another user. The message names the file and the `chmod` or `chown` that fixes it.
* A key is set while the mode is `"sse"`, so the key would go unused.

A store whose base descriptors or snapshots were written without client-side encryption can't be read with it: Atomic refuses those plaintext objects with no fallback. Use a new storage prefix when you turn client-side encryption on. See [What stays visible with client-side encryption](#what-stays-visible-with-client-side-encryption) for what remains readable in storage and on local disk.

> [!WARNING]
>
> If you lose the client-side encryption key, existing encrypted snapshots can't be decrypted. Back up the key in a secret manager before enabling `aes-256-gcm`.

## Manage the local cache and run garbage collection

For cloud snapshot storage, Atomic maintains two local caches:

* **Prepared base cache (`snapshots.baseCacheDir`, default `~/.atomic/agent/snapshot-bases`):** Stores verified read-only (`0444`) sparse base images and stat stamps so wakes skip redownloading base images. Place `baseCacheDir` on the same reflink-capable filesystem as `snapshots.imageDir`.
* **Object read-through cache (`snapshots.cacheDir`, default `~/.atomic/agent/snapshot-cache`, cap `snapshots.cacheMaxBytes`, default `512 MiB`):** Caches downloaded chunk objects per storage location (isolated by storage type, canonical URL, endpoint, and encryption key) after verifying their SHA-256 checksums. Objects larger than `snapshots.cacheMaxBytes` download through a temporary staging file without evicting cached entries. Set `snapshots.cacheMaxBytes` to `0` to disable disk caching.

To remove unreferenced data objects and superseded manifests from your bucket or container, run garbage collection from an operator identity with list and delete permissions on the prefix:

```bash theme={null}
# Preview what would be deleted without modifying storage
atomic snapshots collect --dry-run

# Delete unreferenced objects and superseded manifests older than 1 hour (default 3600 s)
atomic snapshots collect

# Use a shorter grace window (values under 1800 s require --no-active-writers)
atomic snapshots collect --grace 600 --no-active-writers
```

Garbage collection follows these safety rules:

* **Marks all live references:** Collection scans all chain heads, every retained generation in each chain's history, and every published prepared base (`bases/BASE_ID.json`), keeping every referenced chunk and compact base object alive.
* **Prunes superseded manifests:** Collection removes superseded version-3 manifests past the grace window when their chain's live head is newer, while preserving every active generation's manifest.
* **Respects server clocks and the grace window:** Object ages, re-stamps, and collection locks use the storage service's clock, not the local machine's clock. Passing `--grace` under `1800` seconds (including `0`, half the 3600-second default) requires `--no-active-writers` (SDK `noActiveWriters: true`), an assertion by the caller that no snapshot save runs against this storage during collection (`--dry-run` doesn't require `--no-active-writers`).
* **Retiring unused prepared bases:** Because published bases in `bases/` are kept live even before any snapshot uses them, retire an old prepared base by deleting its `bases/BASE_ID.json` metadata object (replace `BASE_ID` with the base identifier). The next `collect` run removes its compact data object after no manifest references it.

### Stores that can't refuse a stale delete

Garbage collection deletes snapshot data only when the storage can refuse to delete an object that a running save just reused. Where it can't, `atomic snapshots collect` deletes nothing, prints `Nothing was deleted.` with the reason and the exact `atomic snapshots collect ... --no-active-writers` command repeating your options, and exits `3` so a scheduled job can tell this safe refusal from a failure (exit `1`). When `--grace` is below `1800` seconds without `--dry-run`, it also deletes nothing and exits `1`, naming `--grace 1800` and the same command. Pass `--no-active-writers` (SDK `noActiveWriters: true`) only after stopping every writer saving snapshots to that storage.

The following table shows which stores support collecting while sessions save:

| Store | Collects while sessions save | What to do |
| - | - | - |
| Azure Blob Storage and ADLS Gen2 (all tiers) | Yes | Nothing. |
| Local folder (`file://`) | Yes | Nothing. |
| Amazon S3 directory buckets | Yes | Nothing. |
| Amazon S3 general-purpose buckets | No (S3 doesn't support the delete condition) | Run `atomic snapshots collect --no-active-writers` while nothing saves. |
| MinIO | No | Run `atomic snapshots collect --no-active-writers` while nothing saves. |
| Google Cloud Storage | Yes when Atomic's check passes | If `collect` refuses, run `atomic snapshots collect --no-active-writers` while nothing saves. |
| `fake-gcs-server` (testing) | No | Run `atomic snapshots collect --no-active-writers` while nothing saves. |

A host that sleeps sessions and wakes them on fresh machines runs collection while no machine is saving to that storage, and passes `--no-active-writers` only then. No setting or environment variable turns it on.

## Test locally with an emulator

You can test cloud snapshot storage locally without a cloud account by running Azurite, MinIO, or `fake-gcs-server`.

> [tab] Azurite (Azure Blob)
>
> Start Azurite, create the container, and verify access:
>
> ```bash theme={null}
> docker run -d --name azurite -p 127.0.0.1:10000:10000 \
>   mcr.microsoft.com/azure-storage/azurite \
>   azurite-blob --blobHost 0.0.0.0 --loose
>
> export AZURE_STORAGE_CONNECTION_STRING="DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;"
> az storage container create --name atomic-snapshots \
>   --connection-string "$AZURE_STORAGE_CONNECTION_STRING"
> atomic snapshots on --storage az://devstoreaccount1/atomic-snapshots/dev
> atomic snapshots status --check
> ```

> [tab] MinIO (S3-compatible)
>
> Start MinIO, create the bucket, and verify access:
>
> ```bash theme={null}
> docker run -d --name minio -p 127.0.0.1:9000:9000 \
>   -e MINIO_ROOT_USER=minioadmin -e MINIO_ROOT_PASSWORD=minioadmin \
>   cgr.dev/chainguard/minio server /data
>
> export AWS_ACCESS_KEY_ID=minioadmin AWS_SECRET_ACCESS_KEY=minioadmin
> export AWS_REGION=us-east-1
> export AWS_ENDPOINT_URL_S3=http://127.0.0.1:9000
> aws s3 mb s3://atomic-snapshots --endpoint-url "$AWS_ENDPOINT_URL_S3"
> atomic snapshots on --storage s3://atomic-snapshots/dev
> atomic snapshots status --check
> ```

> [tab] fake-gcs-server (GCS)
>
> Start `fake-gcs-server`, create the bucket, and verify access:
>
> ```bash theme={null}
> docker run -d --name fake-gcs -p 127.0.0.1:4443:4443 \
>   fsouza/fake-gcs-server \
>   -scheme http -port 4443 -external-url http://127.0.0.1:4443
> curl -s -X POST "http://127.0.0.1:4443/storage/v1/b?project=local-emulator" \
>   -H "content-type: application/json" -d '{"name":"atomic-snapshots"}'
>
> export STORAGE_EMULATOR_HOST=http://127.0.0.1:4443
> atomic snapshots on --storage gs://atomic-snapshots/dev
> atomic snapshots status --check
> ```

## Cost estimates

Because snapshots store only changed 8 MiB chunks compressed with zstd and deduplicate identical content by SHA-256, storage usage stays proportional to changed blocks rather than full virtual disk sizes. The following table gives approximate monthly cloud storage footprints:

| Workload | Typical stored size | Approximate cloud storage cost per month |
| - | - | - |
| Individual developer (10–30 active sessions) | 100 MiB–2 GiB | Under \$0.05 |
| Small team (10 developers, shared bucket) | 5–25 GiB | $0.15–$0.60 |
| Hosted fleet (100 active workspaces with build artifacts) | 100–500 GiB | $2–$12 |

Follow these practices to keep storage and transfer costs low:

* **Put snapshot storage in the same cloud region as your machines.** Same-region transfers between VMs and object storage are free on Azure, AWS, and Google Cloud; cross-region or internet egress incurs per-GB transfer charges.
* **Run `atomic snapshots collect` periodically** (for example, daily or weekly) and set `snapshots.keepGenerations` if you want a cap on retained generations per chain.
* **Keep `snapshots.baseCacheDir` and `snapshots.cacheDir` enabled** so repeated wakes reuse verified local copies instead of redownloading objects.

## Troubleshoot storage errors

Every snapshot storage failure returns a stable error code, describes what happened, and names the fix (with all credentials redacted). The following table lists every snapshot storage error code:

| Error code | Retryable | What happened | How to fix (and host action) |
| - | - | - | - |
| `no-storage` | No | Snapshots are requested on, but `snapshots.storage` is unset on every layer. | Set `snapshots.storage` to an `az://`, `s3://`, `gs://`, or `file://` URL, or run `atomic snapshots off` (setting `snapshots.on` to `false`). Hosts: treat as a launch configuration error. |
| `bad-storage-url` | No | `snapshots.storage` or `snapshots.baseStorage` is malformed, uses an unsupported scheme (such as `postgres://` or `sqlite://`), or contains `..` segments. | Use a supported URL format; see [Configure a storage provider](#quick-setup-by-provider). |
| `credential-in-config` | No | A secret, SAS query string (`?sig=`), URL password, or credential file key was placed in `settings.json` or a storage URL. | Remove the secret from `settings.json` or the URL and use your cloud credential chain or `ATOMIC_SNAPSHOTS_CREDENTIAL_FILE`. |
| `invalid-setting` | No | A `snapshots.*` setting, environment variable, encryption key, or runtime option (`concurrency`, `graceSeconds`, `AZURE_STORAGE_CONNECTION_STRING` account mismatch) has an invalid value. | Fix the named setting or option to match the accepted type and bounds in [Settings](https://docs.bastani.ai/settings.md#snapshots). |
| `size-limit-exceeded` | No | A single object upload exceeded a backend or credential-mode size limit (for example, S3 `aws-presigned`'s 5 GiB single-PUT limit). | Use `aws-session` credentials (which support multipart upload), lower `snapshots.maxDiffBytes`, or reduce large generated files inside the image. |
| `credentials-missing` | No | No cloud credentials were found, an optional cloud auth SDK isn't installed, or the host credential file doesn't exist (`ENOENT`). | Sign in (`az login`, AWS credentials, or `gcloud auth application-default login`) or install the optional auth package named in the error. Hosts: a missing file means access was withdrawn; stop the session. |
| `credentials-invalid` | No | The host credential file is empty, unreadable, invalid JSON, wrong `type` for the storage URL, or has a non-ISO-8601 `expiresAt`. | Fix the host's credential writer to emit the exact JSON shape atomically. Hosts: treat as a host bug. |
| `credentials-expired` | Yes | The host credential remained expired after one reread and retry. | Rotate the credential file and retry. |
| `access-denied` | No | The cloud returned HTTP `403` for the operation on this prefix. | Grant the least-privilege role in [Configure a storage provider](#quick-setup-by-provider) and run `atomic snapshots status --check` to see whether read or write failed. |
| `throttled` | Yes | The cloud returned HTTP `429` (`SlowDown` or throttling) after automatic jittered retries, or the identity endpoint (Azure managed identity, AWS instance metadata, or the Google metadata server) throttled the request for a token. | Retry later or reduce concurrent snapshot traffic. |
| `unreachable` | Yes | Network error, DNS failure, timeout, proxy refusal, or persistent HTTP `5xx` (other than `507`) after retries, or the request for a cloud identity token timed out or failed on the identity endpoint's side (the message names the token request). | Check connectivity, firewall rules, and `HTTPS_PROXY` / `NO_PROXY`. On a cloud VM with `HTTPS_PROXY` set, add `169.254.169.254` to `NO_PROXY` so token requests reach the instance metadata endpoint directly. Hosts: keep the session running and retry save at the next idle point. |
| `chain-conflict` | No | Another machine already advanced this snapshot chain's generation, or the expected head is missing from storage. | Run `atomic snapshots status` to compare generations, pull from outside the worktree with `atomic snapshots restore --into WORKTREE_DIR`, or branch local work with `atomic snapshots fork --new-chain`. |
| `corrupt` | No | A downloaded object, uploaded payload, manifest, base record, or client-side decryption check failed SHA-256 or AES-GCM verification. | Check storage integrity and (if using client-side encryption) verify that every machine uses the same 32-byte key. |
| `invalid-key` | No | An object key or identifier contained `..`, a leading `/`, a backslash, a NUL byte, or a symlink escaping local storage. | Keep keys and chain or base IDs strictly within allowed identifier characters and the configured prefix. |
| `storage-not-found` | No | The configured bucket or container doesn't exist in the storage service. | Create the bucket or container named in `snapshots.storage` before turning snapshots on. |
| `no-space` | No | The disk that holds `file://` snapshot storage is full, or a cloud store answered that it's full or over its quota: HTTP `507` (Insufficient Storage) from any provider, or an S3-compatible server's `XMinioStorageFull`, `XMinioAdminBucketQuotaExceeded` (MinIO), `InsufficientCapacity` or `QuotaExceeded` (Ceph). The message names the storage. Nothing was saved, but a save that stopped partway leaves the chunks it already stored. | Free space on that disk or in that storage, or raise its quota, then save again; Atomic doesn't retry, because the same request fails until then. `atomic snapshots collect` deletes a stopped save's chunks after they are older than the grace period (1 hour by default), or right away with `atomic snapshots collect --grace 0 --no-active-writers` while nothing else saves to this storage. |
| `request-rejected` | No | The storage service rejected the request as malformed or disallowed by bucket or container configuration (HTTP `501` or another `4xx` not covered by a more specific code). | Check bucket configuration, custom endpoint settings, and request parameters, then run `atomic snapshots status --check`. |
| `not-found` | No | The requested snapshot object doesn't exist in storage. | Verify the chain ID, base ID, and storage prefix; if a base was retired or deleted, recreate it with `atomic snapshots base create`. |
| `precondition-failed` | No | A conditional write or delete encountered a concurrent modification (`HTTP 412`). | Handled internally by deduplication and garbage collection; retry if invoked directly through the SDK. |
| `conditional-delete-unsupported` | No | The storage backend can't refuse a stale-precondition delete (such as Amazon S3 general-purpose buckets, MinIO, or `fake-gcs-server`), so `collect` deleted nothing. | Stop all active writers saving to this storage, then run `atomic snapshots collect --no-active-writers` (SDK `noActiveWriters: true`); see [Stores that can't refuse a stale delete](#stores-that-cant-refuse-a-stale-delete). |
| `gc-active` | Yes | Another collector holds a non-expired garbage collection lock on this prefix. | Wait for the active `atomic snapshots collect` run to finish before starting another. |
| `writer-expired` | No | A writer lease expired before commit. | Refresh the writer session and retry the save. |
| `aborted` | No | The operation was canceled through an `AbortSignal`. | Retry when ready. |

## What's next

* [Save and restore worktree snapshots](https://docs.bastani.ai/worktree-snapshots.md) — how disk-image snapshots work, platform support, rollback, and fork workflows.
* [Worktree snapshots reference](https://docs.bastani.ai/worktree-snapshots/reference.md) — SDK functions, mount-helper protocol, RPC commands, and `SnapshotError` codes.
* [Settings](https://docs.bastani.ai/settings.md#snapshots) — complete `snapshots.*` reference.
* [CLI reference](https://docs.bastani.ai/reference/cli.md#snapshots-commands) — `--snapshots*` flags and `atomic snapshots` subcommands.
* [Environment variables](https://docs.bastani.ai/environment-variables.md) — `ATOMIC_SNAPSHOTS*` and cloud credential variables.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.