Skip to content

An open-source, faster Devin alternative

TypeScript

Automate D1 migrations (#488)

Mohamed Habib20155859fc38
diff --git a/.github/workflows/apply-d1-migrations.yml b/.github/workflows/apply-d1-migrations.yml
new file mode 100644
index 00000000..cd14e609
--- /dev/null
+++ b/.github/workflows/apply-d1-migrations.yml
@@ -0,0 +1,89 @@
+name: Apply D1 Migrations
+
+on:
+ workflow_dispatch:
+ inputs:
+ action:
+ description: 'Migration action'
+ required: true
+ default: 'list'
+ type: choice
+ options:
+ - list
+ - apply
+
+concurrency:
+ group: apply-d1-migrations-prod
+ cancel-in-progress: false
+
+jobs:
+ migrations:
+ name: D1 migrations
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '22'
+
+ - name: Resolve prod target
+ id: target
+ run: |
+ echo "config=wrangler.prod.toml" >> "$GITHUB_OUTPUT"
+ echo "database=OPENCOMPUTER_DB" >> "$GITHUB_OUTPUT"
+
+ - name: Install api-edge dependencies
+ working-directory: cloudflare-workers/api-edge
+ run: npm ci
+
+ - name: Prepare CI Wrangler config
+ working-directory: cloudflare-workers/api-edge
+ run: |
+ python3 - <<'PY'
+ from pathlib import Path
+
+ src = Path("${{ steps.target.outputs.config }}")
+ dst = Path("wrangler.ci.toml")
+ lines = src.read_text().splitlines()
+
+ out = []
+ skipping_routes = False
+ for line in lines:
+ if line.startswith("routes = ["):
+ skipping_routes = True
+ continue
+ if skipping_routes:
+ if line.strip() == "]":
+ skipping_routes = False
+ continue
+ out.append(line)
+
+ dst.write_text("\n".join(out).rstrip() + "\n")
+ PY
+
+ - name: List pending D1 migrations
+ if: inputs.action == 'list'
+ working-directory: cloudflare-workers/api-edge
+ env:
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ run: |
+ if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
+ echo "CLOUDFLARE_API_TOKEN GitHub secret is required for Wrangler D1 migrations" >&2
+ exit 1
+ fi
+ npx wrangler d1 migrations list "${{ steps.target.outputs.database }}" --remote -c wrangler.ci.toml
+
+ - name: Apply pending D1 migrations
+ if: inputs.action == 'apply'
+ working-directory: cloudflare-workers/api-edge
+ env:
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ run: |
+ if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
+ echo "CLOUDFLARE_API_TOKEN GitHub secret is required for Wrangler D1 migrations" >&2
+ exit 1
+ fi
+ npx wrangler d1 migrations apply "${{ steps.target.outputs.database }}" --remote -c wrangler.ci.toml
diff --git a/.github/workflows/deploy-api-edge.yml b/.github/workflows/deploy-api-edge.yml
index 7859cb75..3864da27 100644
--- a/.github/workflows/deploy-api-edge.yml
+++ b/.github/workflows/deploy-api-edge.yml
@@ -9,15 +9,6 @@ on:
- 'web/**'
- '.github/workflows/deploy-api-edge.yml'
workflow_dispatch:
- inputs:
- target:
- description: 'Cloudflare Worker target'
- required: true
- default: 'prod'
- type: choice
- options:
- - prod
- - dev
concurrency:
group: deploy-api-edge
@@ -39,26 +30,9 @@ jobs:
- name: Resolve target
id: target
run: |
- if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
- TARGET="${{ inputs.target }}"
- else
- TARGET="prod"
- fi
-
- case "$TARGET" in
- prod)
- echo "config=wrangler.prod.toml" >> "$GITHUB_OUTPUT"
- echo "name=opencomputer-edge-prod" >> "$GITHUB_OUTPUT"
- ;;
- dev)
- echo "config=wrangler.toml" >> "$GITHUB_OUTPUT"
- echo "name=opensandbox-edge-dev" >> "$GITHUB_OUTPUT"
- ;;
- *)
- echo "unknown target: $TARGET" >&2
- exit 1
- ;;
- esac
+ echo "config=wrangler.prod.toml" >> "$GITHUB_OUTPUT"
+ echo "database=OPENCOMPUTER_DB" >> "$GITHUB_OUTPUT"
+ echo "name=opencomputer-edge-prod" >> "$GITHUB_OUTPUT"
- name: Build dashboard assets
working-directory: web
@@ -110,6 +84,17 @@ jobs:
dst.write_text("\n".join(out).rstrip() + "\n")
PY
+ - name: Apply D1 migrations
+ working-directory: cloudflare-workers/api-edge
+ env:
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ run: |
+ if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
+ echo "CLOUDFLARE_API_TOKEN GitHub secret is required for Wrangler D1 migrations" >&2
+ exit 1
+ fi
+ npx wrangler d1 migrations apply "${{ steps.target.outputs.database }}" --remote -c wrangler.ci.toml
+
- name: Deploy ${{ steps.target.outputs.name }}
working-directory: cloudflare-workers/api-edge
env:
diff --git a/AGENTS.md b/AGENTS.md
index 33b0dd7c..358f0695 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -61,9 +61,10 @@ the quirks that bite, are documented in **`.agents/reference/dev-edge-setup.md`*
never `grep|cut` (the literal `${...}` string breaks WorkOS as `invalid_client`).
- `cloudflare-workers/api-edge/wrangler.toml` points at **prod** — always pass
`--config wrangler.igor-dev.toml` for personal-dev `wrangler` commands.
-- D1: apply only `cloudflare-workers/schema.sql` (it is the full current
- snapshot; the `schema_phase*.sql` files are baked in and error with
- `duplicate column` on a fresh DB).
+- D1: for a fresh API edge database, bootstrap from
+ `cloudflare-workers/api-edge/schema-snapshots/current_schema.sql`, then use
+ Wrangler migrations from `cloudflare-workers/api-edge/migrations/`.
+ Existing dev/prod databases must not receive the snapshot.
## Hard rules
diff --git a/cloudflare-workers/api-edge/migrations/README.md b/cloudflare-workers/api-edge/migrations/README.md
new file mode 100644
index 00000000..e83cffdf
--- /dev/null
+++ b/cloudflare-workers/api-edge/migrations/README.md
@@ -0,0 +1,44 @@
+# D1 migrations
+
+Wrangler applies SQL files in this directory and records them in the D1
+`d1_migrations` table.
+
+Schema snapshots live outside this directory in `../schema-snapshots/`, so they
+are never applied by Wrangler migrations.
+
+## Existing databases
+
+Do not apply `../schema-snapshots/current_schema.sql` to the existing prod database.
+For prod, use the Wrangler migration ledger:
+
+```bash
+cd cloudflare-workers/api-edge
+npx wrangler d1 migrations list opencomputer-prod --remote -c wrangler.prod.toml
+npx wrangler d1 migrations apply opencomputer-prod --remote -c wrangler.prod.toml
+```
+
+The API edge deploy workflow applies pending prod migrations before deploying
+the prod Worker.
+
+## Fresh databases
+
+For a brand-new D1 database, apply the snapshot once before running Wrangler
+migrations:
+
+```bash
+cd cloudflare-workers/api-edge
+npx wrangler d1 execute <database-name> --remote -c <wrangler-config> --file schema-snapshots/current_schema.sql
+npx wrangler d1 migrations apply <database-name> --remote -c <wrangler-config>
+```
+
+## Future schema changes
+
+Create one numbered migration per schema change:
+
+```bash
+cd cloudflare-workers/api-edge
+npx wrangler d1 migrations create opencomputer-prod add_example_column
+```
+
+Review the generated SQL before merging. Migrations should be safe to run before
+the matching Worker deploy because CI applies migrations first.
diff --git a/cloudflare-workers/api-edge/schema-snapshots/current_schema.sql b/cloudflare-workers/api-edge/schema-snapshots/current_schema.sql
new file mode 100644
index 00000000..c9929120
--- /dev/null
+++ b/cloudflare-workers/api-edge/schema-snapshots/current_schema.sql
@@ -0,0 +1,341 @@
+-- Current OpenComputer D1 schema snapshot.
+--
+-- This file is intentionally NOT a Wrangler migration. It lives outside
+-- migrations_dir, so Wrangler ignores it during CI and production deploys.
+--
+-- Use only when bootstrapping a brand-new D1 database, then run:
+-- npx wrangler d1 migrations apply <database-name> --remote -c <wrangler-config>
+--
+-- Do not apply this file to an existing prod/dev database.
+
+CREATE TABLE agent_subscriptions (
+ id TEXT PRIMARY KEY, -- D1-local UUID
+ org_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ feature TEXT NOT NULL, -- "telegram", "premium-tools", etc.
+ status TEXT NOT NULL DEFAULT 'active', -- active | cancelled
+ stripe_item_id TEXT, -- Stripe Subscription Item ID
+ created_at INTEGER NOT NULL,
+ cancelled_at INTEGER
+);
+
+CREATE TABLE api_keys (
+ id TEXT PRIMARY KEY,
+ org_id TEXT NOT NULL,
+ created_by TEXT,
+ key_hash TEXT NOT NULL UNIQUE,
+ key_prefix TEXT NOT NULL,
+ name TEXT NOT NULL,
+ scopes TEXT NOT NULL DEFAULT 'sandbox:*',
+ last_used INTEGER,
+ expires_at INTEGER,
+ created_at INTEGER NOT NULL
+);
+
+CREATE TABLE billing_prices (key TEXT PRIMARY KEY, price_id TEXT NOT NULL, updated_at INTEGER NOT NULL);
+
+CREATE TABLE cells (
+ cell_id TEXT PRIMARY KEY, -- "{cloud}-{region}-cell-{slot}"
+ cloud TEXT NOT NULL, -- "azure" | "aws" | "gcp"
+ region TEXT NOT NULL,
+ base_url TEXT NOT NULL, -- regional CP base URL (scheme+host[:port])
+ status TEXT NOT NULL DEFAULT 'active', -- active | draining | down
+ -- Capacity-aware placement (updated by cell_capacity events; see
+ -- internal/controlplane/capacity_reporter.go + events-ingest worker).
+ -- The CP aggregates per-worker memory pressure from WorkerEntry. A cell is
+ -- placement-eligible iff available_workers > 0 AND capacity_updated_at is
+ -- within the freshness window (~120s). NULL/stale capacity_updated_at ⇒ the
+ -- reporting CP is dead, treat the cell as unhealthy regardless of `status`.
+ --
+ -- "available" = worker where committed_memory_mb/total_memory_mb < 85%.
+ -- Single-worker-below-threshold is the right gate because a sandbox lands
+ -- on one worker, not striped across workers — aggregating across the cell
+ -- would wrongly skip a cell with 1 free worker and 9 loaded ones.
+ healthy_workers INTEGER NOT NULL DEFAULT 0, -- alive workers in this cell
+ available_workers INTEGER NOT NULL DEFAULT 0, -- workers under the mem threshold
+ running_sandboxes INTEGER NOT NULL DEFAULT 0, -- observability only, not in placement
+ capacity_updated_at INTEGER,
+ created_at INTEGER NOT NULL
+, accepts_new_orgs INTEGER NOT NULL DEFAULT 0);
+
+CREATE TABLE checkpoints_index (
+ id TEXT PRIMARY KEY,
+ sandbox_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ owner_cell_id TEXT NOT NULL,
+ s3_url TEXT NOT NULL,
+ size_bytes INTEGER,
+ golden_hash TEXT NOT NULL,
+ workspace_size INTEGER,
+ created_at INTEGER NOT NULL,
+ expires_at INTEGER,
+ replicated_to TEXT NOT NULL DEFAULT '[]'
+, name TEXT, status TEXT NOT NULL DEFAULT 'ready', error_msg TEXT, failed_at INTEGER, kind TEXT NOT NULL DEFAULT 'full');
+
+CREATE TABLE events (
+ id TEXT PRIMARY KEY, -- event UUID from worker
+ cell_id TEXT NOT NULL,
+ type TEXT NOT NULL,
+ org_id TEXT,
+ sandbox_id TEXT,
+ user_id TEXT,
+ worker_id TEXT,
+ ts INTEGER NOT NULL, -- unix ms
+ payload TEXT NOT NULL -- JSON
+);
+
+CREATE TABLE golden_versions (
+ hash TEXT PRIMARY KEY,
+ canonical_url TEXT NOT NULL,
+ size_bytes INTEGER,
+ cells_available TEXT NOT NULL DEFAULT '[]',
+ ami_version TEXT,
+ created_at INTEGER NOT NULL,
+ retired_at INTEGER
+);
+
+CREATE TABLE images_index (id TEXT PRIMARY KEY, org_id TEXT NOT NULL, owner_cell_id TEXT NOT NULL, content_hash TEXT NOT NULL, checkpoint_id TEXT, name TEXT, manifest TEXT NOT NULL, status TEXT NOT NULL, created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL);
+
+CREATE TABLE invitations (
+ id TEXT PRIMARY KEY, -- D1-local UUID
+ org_id TEXT NOT NULL,
+ email TEXT NOT NULL,
+ role TEXT NOT NULL DEFAULT 'member', -- "owner" | "admin" | "member"
+ invited_by TEXT, -- user_id of the inviter
+ workos_invitation_id TEXT, -- WorkOS Invitation.id (null until WorkOS call succeeds)
+ status TEXT NOT NULL DEFAULT 'pending', -- pending | accepted | revoked | expired
+ token TEXT UNIQUE, -- short opaque accept token (not currently used; WorkOS owns the flow)
+ expires_at INTEGER, -- unix s; null = no expiry
+ created_at INTEGER NOT NULL,
+ accepted_at INTEGER,
+ revoked_at INTEGER
+);
+
+CREATE TABLE managed_model_keys (
+ id TEXT PRIMARY KEY,
+ org_id TEXT NOT NULL,
+ or_key_hash TEXT, -- OpenRouter key hash (non-secret); null between insert + create
+ managed_credential_id TEXT, -- sessions-api credential row id (the sealed key); null until bound
+ operation_id TEXT, -- idempotency id for the edge→sessions-api bind hand-off (§5.1/§6.7.5)
+ status TEXT NOT NULL CHECK (status IN ('active', 'superseded', 'deleting')),
+ committed_micro INTEGER NOT NULL DEFAULT 0, -- OR usage already debited to Autumn (micro-USD watermark)
+ pending_from_micro INTEGER, -- the single in-flight debit interval [from,to), immutable until committed
+ pending_to_micro INTEGER,
+ pending_idem TEXT, -- "model_spend:<org>:<from>:<to>" — stable across retries
+ attempts INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT,
+ created_at INTEGER NOT NULL, -- unix seconds
+ superseded_at INTEGER
+);
+
+CREATE TABLE org_memberships (
+ org_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ role TEXT NOT NULL, -- "owner" | "admin" | "member"
+ created_at INTEGER NOT NULL,
+ PRIMARY KEY (org_id, user_id)
+);
+
+CREATE TABLE org_subscription_items (
+ org_id TEXT NOT NULL,
+ tier TEXT NOT NULL, -- e.g. "memory" | "cpu"
+ stripe_item_id TEXT NOT NULL,
+ price_id TEXT NOT NULL,
+ PRIMARY KEY (org_id, tier)
+);
+
+CREATE TABLE orgs (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ slug TEXT NOT NULL UNIQUE,
+ plan TEXT NOT NULL, -- "free" | "pro"
+ home_cell TEXT NOT NULL,
+ stripe_customer_id TEXT,
+ stripe_subscription_id TEXT,
+ workos_org_id TEXT UNIQUE,
+ is_personal INTEGER NOT NULL DEFAULT 0,
+ owner_user_id TEXT,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+, is_halted INTEGER NOT NULL DEFAULT 0, halted_at INTEGER, custom_domain TEXT, cf_hostname_id TEXT, domain_verification_status TEXT NOT NULL DEFAULT 'none', domain_ssl_status TEXT NOT NULL DEFAULT 'none', verification_txt_name TEXT, verification_txt_value TEXT, ssl_txt_name TEXT, ssl_txt_value TEXT, free_credits_remaining_cents INTEGER NOT NULL DEFAULT 500, credit_balance_cents INTEGER NOT NULL DEFAULT 0, max_concurrent_sandboxes INTEGER NOT NULL DEFAULT 5, max_sandbox_timeout_sec INTEGER NOT NULL DEFAULT 3600, max_disk_mb INTEGER NOT NULL DEFAULT 0, max_memory_gb INTEGER NOT NULL DEFAULT 0, billing_mode TEXT NOT NULL DEFAULT 'unified', last_usage_reported_at INTEGER NOT NULL DEFAULT 0, billing_provider TEXT NOT NULL DEFAULT 'legacy', autumn_usage_watermark INTEGER NOT NULL DEFAULT 0, has_webhooks INTEGER NOT NULL DEFAULT 0, model_billing_status TEXT NOT NULL DEFAULT 'off', model_markup_bps INTEGER NOT NULL DEFAULT 0, autumn_concurrency_override INTEGER);
+
+CREATE TABLE sandboxes_index (
+ id TEXT PRIMARY KEY, -- sandbox_id
+ org_id TEXT NOT NULL,
+ user_id TEXT,
+ cell_id TEXT NOT NULL,
+ worker_id TEXT,
+ status TEXT NOT NULL, -- running | hibernated | stopped | error
+ template_id TEXT,
+ created_at INTEGER NOT NULL,
+ last_event_at INTEGER,
+ stopped_at INTEGER
+, cpu_count INTEGER, memory_mb INTEGER);
+
+CREATE TABLE secret_store_entries (
+ id TEXT PRIMARY KEY,
+ store_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ encrypted_value BLOB NOT NULL, -- AES-GCM, key in CF secret
+ allowed_hosts TEXT NOT NULL DEFAULT '[]', -- JSON array
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+
+CREATE TABLE secret_stores (
+ id TEXT PRIMARY KEY,
+ org_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ egress_allowlist TEXT NOT NULL DEFAULT '[]', -- JSON array
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+
+CREATE TABLE templates (
+ id TEXT PRIMARY KEY,
+ org_id TEXT, -- NULL = public template
+ name TEXT NOT NULL,
+ tag TEXT NOT NULL DEFAULT 'latest',
+ template_type TEXT NOT NULL DEFAULT 'dockerfile',
+ image_ref TEXT,
+ rootfs_s3_key TEXT,
+ workspace_s3_key TEXT,
+ dockerfile TEXT,
+ is_public INTEGER NOT NULL DEFAULT 0,
+ status TEXT NOT NULL DEFAULT 'ready',
+ cells_available TEXT NOT NULL DEFAULT '[]', -- JSON array
+ created_at INTEGER NOT NULL
+, canonical_rootfs_url TEXT, canonical_workspace_url TEXT);
+
+CREATE TABLE usage_meter_events (
+ id TEXT PRIMARY KEY, org_id TEXT NOT NULL, meter_event_name TEXT NOT NULL, value REAL NOT NULL,
+ billing_mode TEXT NOT NULL, bucket_start INTEGER NOT NULL, bucket_end INTEGER NOT NULL,
+ state TEXT NOT NULL DEFAULT 'pending', stripe_identifier TEXT, created_at INTEGER NOT NULL, sent_at INTEGER);
+
+CREATE TABLE usage_samples (
+ id TEXT PRIMARY KEY, org_id TEXT NOT NULL, sandbox_id TEXT NOT NULL,
+ memory_mb INTEGER NOT NULL, cpu_count INTEGER NOT NULL, interval_s INTEGER NOT NULL,
+ ts INTEGER NOT NULL, cell_id TEXT NOT NULL, rolled_up INTEGER NOT NULL DEFAULT 0);
+
+CREATE TABLE usage_snapshots (
+ org_id TEXT NOT NULL,
+ snapshot_ts INTEGER NOT NULL, -- hourly bucket (unix s)
+ cpu_seconds INTEGER NOT NULL,
+ wall_seconds INTEGER NOT NULL,
+ memory_gb_seconds REAL NOT NULL,
+ sandbox_count INTEGER NOT NULL,
+ cost_cents INTEGER NOT NULL,
+ reported_to_stripe INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (org_id, snapshot_ts)
+);
+
+CREATE TABLE users (
+ id TEXT PRIMARY KEY,
+ email TEXT NOT NULL UNIQUE,
+ workos_user_id TEXT UNIQUE,
+ name TEXT,
+ created_at INTEGER NOT NULL
+);
+
+CREATE TABLE webhook_destinations (
+ id TEXT PRIMARY KEY, -- 'whk_' + random hex
+ org_id TEXT NOT NULL,
+ svix_app_id TEXT NOT NULL, -- Svix app id (uid = org_id)
+ svix_endpoint_id TEXT NOT NULL, -- Svix endpoint id
+ url TEXT NOT NULL,
+ event_types TEXT NOT NULL DEFAULT '[]', -- JSON array; [] = all types
+ sandbox_id TEXT, -- NULL = org-wide; else Svix channel scope
+ name TEXT,
+ disabled INTEGER NOT NULL DEFAULT 0, -- mirrors the Svix endpoint disabled flag
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ deleted_at INTEGER -- soft-delete; history stays in Svix
+);
+
+CREATE TABLE webhook_idempotency (
+ org_id TEXT NOT NULL,
+ idempotency_key TEXT NOT NULL,
+ destination_id TEXT NOT NULL,
+ created_at INTEGER NOT NULL, request_hash TEXT,
+ PRIMARY KEY (org_id, idempotency_key)
+);
+
+CREATE INDEX idx_agent_subs_org ON agent_subscriptions(org_id);
+
+CREATE UNIQUE INDEX idx_agent_subs_unique ON agent_subscriptions(org_id, agent_id, feature);
+
+CREATE INDEX idx_api_keys_hash ON api_keys(key_hash);
+
+CREATE INDEX idx_api_keys_org ON api_keys(org_id);
+
+CREATE INDEX idx_checkpoints_expires ON checkpoints_index(expires_at)
+ WHERE expires_at IS NOT NULL;
+
+CREATE INDEX idx_checkpoints_org ON checkpoints_index(org_id);
+
+CREATE INDEX idx_checkpoints_owner ON checkpoints_index(owner_cell_id);
+
+CREATE INDEX idx_checkpoints_sandbox ON checkpoints_index(sandbox_id);
+
+CREATE INDEX idx_events_cell_ts ON events(cell_id, ts DESC);
+
+CREATE INDEX idx_events_org_ts ON events(org_id, ts DESC);
+
+CREATE INDEX idx_events_sandbox_ts ON events(sandbox_id, ts DESC);
+
+CREATE INDEX idx_events_type_ts ON events(type, ts DESC);
+
+CREATE INDEX idx_golden_versions_active
+ ON golden_versions(created_at) WHERE retired_at IS NULL;
+
+CREATE INDEX idx_images_org_created ON images_index(org_id, created_at DESC);
+
+CREATE INDEX idx_invitations_email ON invitations(email);
+
+CREATE INDEX idx_invitations_org_status ON invitations(org_id, status);
+
+CREATE UNIQUE INDEX idx_managed_model_keys_one_active ON managed_model_keys(org_id) WHERE status='active';
+
+CREATE INDEX idx_managed_model_keys_org_status
+ ON managed_model_keys(org_id, status);
+
+CREATE INDEX idx_memberships_user ON org_memberships(user_id);
+
+CREATE INDEX idx_meter_events_org_bucket ON usage_meter_events(org_id, bucket_start);
+
+CREATE INDEX idx_meter_events_pending ON usage_meter_events(state, bucket_start) WHERE state = 'pending';
+
+CREATE INDEX idx_orgs_billing_provider ON orgs(billing_provider) WHERE billing_provider = 'autumn';
+
+CREATE INDEX idx_orgs_halted ON orgs(is_halted) WHERE is_halted = 1;
+
+CREATE INDEX idx_orgs_model_billing_active
+ ON orgs(model_billing_status) WHERE model_billing_status = 'active';
+
+CREATE INDEX idx_sandboxes_active ON sandboxes_index(org_id) WHERE status = 'running';
+
+CREATE INDEX idx_sandboxes_cell ON sandboxes_index(cell_id, status);
+
+CREATE INDEX idx_sandboxes_org_status ON sandboxes_index(org_id, status);
+
+CREATE INDEX idx_secret_entries_store ON secret_store_entries(store_id);
+
+CREATE UNIQUE INDEX idx_secret_entries_unique ON secret_store_entries(store_id, name);
+
+CREATE INDEX idx_secret_stores_org ON secret_stores(org_id);
+
+CREATE UNIQUE INDEX idx_secret_stores_unique ON secret_stores(org_id, name);
+
+CREATE INDEX idx_templates_public ON templates(is_public) WHERE is_public = 1;
+
+CREATE UNIQUE INDEX idx_templates_unique ON templates(org_id, name, tag);
+
+CREATE INDEX idx_usage_samples_unrolled ON usage_samples(org_id, ts) WHERE rolled_up = 0;
+
+CREATE INDEX idx_usage_unreported ON usage_snapshots(reported_to_stripe, org_id) WHERE reported_to_stripe = 0;
+
+CREATE INDEX webhook_dest_org_idx
+ ON webhook_destinations (org_id) WHERE deleted_at IS NULL;
+
+CREATE UNIQUE INDEX webhook_dest_svix_ep_idx
+ ON webhook_destinations (svix_endpoint_id);
diff --git a/cloudflare-workers/api-edge/src/model_billing.ts b/cloudflare-workers/api-edge/src/model_billing.ts
index 8109f12d..b9c37f04 100644
--- a/cloudflare-workers/api-edge/src/model_billing.ts
+++ b/cloudflare-workers/api-edge/src/model_billing.ts
@@ -326,7 +326,7 @@ export async function enableManagedBilling(env: ModelBillingEnv, orgId: string):
});
} catch (e) {
// Lost a concurrent enable race — the unique "one active key per org" index
- // (schema_phase9) rejected this insert. Adopt the row the winner created.
+ // unique partial index rejected this insert. Adopt the row the winner created.
row = await getResumableRow(env, orgId);
if (!row) throw e;
}
diff --git a/cloudflare-workers/api-edge/wrangler.igor-dev.toml b/cloudflare-workers/api-edge/wrangler.igor-dev.toml
index cfd7d338..10857698 100644
--- a/cloudflare-workers/api-edge/wrangler.igor-dev.toml
+++ b/cloudflare-workers/api-edge/wrangler.igor-dev.toml
@@ -42,6 +42,7 @@ run_worker_first = true
binding = "OPENCOMPUTER_DB"
database_name = "opencomputer-igor-dev"
database_id = "d5bbb12a-0491-4a95-9d7d-32ed8c3ce15d"
+migrations_dir = "migrations"
# CreditAccount DO is self-hosted by this worker (script_name defaults to self).
[[durable_objects.bindings]]
diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.toml
index c86d8e47..61b62cd9 100644
--- a/cloudflare-workers/api-edge/wrangler.prod.toml
+++ b/cloudflare-workers/api-edge/wrangler.prod.toml
@@ -31,6 +31,7 @@ run_worker_first = true
binding = "OPENCOMPUTER_DB"
database_name = "opencomputer-prod"
database_id = "8329e0f0-100d-445a-bf89-95c065f15dbb"
+migrations_dir = "migrations"
[[kv_namespaces]]
binding = "SESSIONS_KV"
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index 8ac8d6e6..36338f49 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -59,6 +59,7 @@ run_worker_first = true
binding = "OPENCOMPUTER_DB"
database_name = "opencomputer-dev"
database_id = "f9e534bf-a9f3-4b30-81cd-f9eb9087e96d"
+migrations_dir = "migrations"
[[kv_namespaces]]
binding = "SESSIONS_KV"
diff --git a/cloudflare-workers/schema.sql b/cloudflare-workers/schema.sql
deleted file mode 100644
index d2a93958..00000000
--- a/cloudflare-workers/schema.sql
+++ /dev/null
@@ -1,267 +0,0 @@
--- D1 schema for OpenSandbox global layer.
--- Apply with: wrangler d1 execute opencomputer-dev --file cloudflare-workers/schema.sql
-
--- Identity ----------------------------------------------------------------
-
-CREATE TABLE IF NOT EXISTS orgs (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- slug TEXT NOT NULL UNIQUE,
- plan TEXT NOT NULL, -- "free" | "pro"
- home_cell TEXT NOT NULL,
- stripe_customer_id TEXT,
- stripe_subscription_id TEXT,
- workos_org_id TEXT UNIQUE,
- is_personal INTEGER NOT NULL DEFAULT 0,
- owner_user_id TEXT,
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
-);
-
-CREATE TABLE IF NOT EXISTS users (
- id TEXT PRIMARY KEY,
- email TEXT NOT NULL UNIQUE,
- workos_user_id TEXT UNIQUE,
- name TEXT,
- created_at INTEGER NOT NULL
-);
-
-CREATE TABLE IF NOT EXISTS org_memberships (
- org_id TEXT NOT NULL,
- user_id TEXT NOT NULL,
- role TEXT NOT NULL, -- "owner" | "admin" | "member"
- created_at INTEGER NOT NULL,
- PRIMARY KEY (org_id, user_id)
-);
-CREATE INDEX IF NOT EXISTS idx_memberships_user ON org_memberships(user_id);
-
-CREATE TABLE IF NOT EXISTS api_keys (
- id TEXT PRIMARY KEY,
- org_id TEXT NOT NULL,
- created_by TEXT,
- key_hash TEXT NOT NULL UNIQUE,
- key_prefix TEXT NOT NULL,
- name TEXT NOT NULL,
- scopes TEXT NOT NULL DEFAULT 'sandbox:*',
- last_used INTEGER,
- expires_at INTEGER,
- created_at INTEGER NOT NULL
-);
-CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash);
-CREATE INDEX IF NOT EXISTS idx_api_keys_org ON api_keys(org_id);
-
--- Global catalog ---------------------------------------------------------
-
-CREATE TABLE IF NOT EXISTS templates (
- id TEXT PRIMARY KEY,
- org_id TEXT, -- NULL = public template
- name TEXT NOT NULL,
- tag TEXT NOT NULL DEFAULT 'latest',
- template_type TEXT NOT NULL DEFAULT 'dockerfile',
- image_ref TEXT,
- rootfs_s3_key TEXT,
- workspace_s3_key TEXT,
- dockerfile TEXT,
- is_public INTEGER NOT NULL DEFAULT 0,
- status TEXT NOT NULL DEFAULT 'ready',
- cells_available TEXT NOT NULL DEFAULT '[]', -- JSON array
- created_at INTEGER NOT NULL
-);
-CREATE UNIQUE INDEX IF NOT EXISTS idx_templates_unique ON templates(org_id, name, tag);
-CREATE INDEX IF NOT EXISTS idx_templates_public ON templates(is_public) WHERE is_public = 1;
-
--- Global secret stores (CPs fetch via HMAC at sandbox-create time;
--- regional CP never persists a copy).
-CREATE TABLE IF NOT EXISTS secret_stores (
- id TEXT PRIMARY KEY,
- org_id TEXT NOT NULL,
- name TEXT NOT NULL,
- egress_allowlist TEXT NOT NULL DEFAULT '[]', -- JSON array
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
-);
-CREATE UNIQUE INDEX IF NOT EXISTS idx_secret_stores_unique ON secret_stores(org_id, name);
-CREATE INDEX IF NOT EXISTS idx_secret_stores_org ON secret_stores(org_id);
-
-CREATE TABLE IF NOT EXISTS secret_store_entries (
- id TEXT PRIMARY KEY,
- store_id TEXT NOT NULL,
- name TEXT NOT NULL,
- encrypted_value BLOB NOT NULL, -- AES-GCM, key in CF secret
- allowed_hosts TEXT NOT NULL DEFAULT '[]', -- JSON array
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
-);
-CREATE UNIQUE INDEX IF NOT EXISTS idx_secret_entries_unique ON secret_store_entries(store_id, name);
-CREATE INDEX IF NOT EXISTS idx_secret_entries_store ON secret_store_entries(store_id);
-
--- Cell registry ----------------------------------------------------------
--- One row per regional control plane. The edge Worker uses base_url to:
--- - proxy POST /api/sandboxes → {base_url}/internal/sandboxes/create
--- - dispatch admin callbacks → {base_url}/admin/halt-org, /admin/resume-org
--- - 307-redirect dumb clients → {base_url}/api/sandboxes/{id}/...
--- (In production the public 307 target and the internal edge→CP URL may
--- diverge — e.g. an internal-only hostname for /internal/*. Split into two
--- columns then; one URL is enough while every cell exposes both on one host.)
--- orgs.home_cell, sandboxes_index.cell_id, and events.cell_id all reference
--- cell_id here, but D1 has no cross-table FKs so it's by convention.
-CREATE TABLE IF NOT EXISTS cells (
- cell_id TEXT PRIMARY KEY, -- "{cloud}-{region}-cell-{slot}"
- cloud TEXT NOT NULL, -- "azure" | "aws" | "gcp"
- region TEXT NOT NULL,
- base_url TEXT NOT NULL, -- regional CP base URL (scheme+host[:port])
- status TEXT NOT NULL DEFAULT 'active', -- active | draining | down
- -- New-org onboarding gate: pickHomeCell only assigns brand-new orgs to cells
- -- with accepts_new_orgs=1. Distinct from `status` (which governs routing of
- -- existing orgs / pins / failover) so a cell can be active+routable without
- -- yet adopting new signups. Default 0 = a freshly-registered cell does NOT
- -- onboard new orgs until explicitly opened (a D1 row toggle, no deploy).
- accepts_new_orgs INTEGER NOT NULL DEFAULT 0,
- -- Capacity-aware placement (updated by cell_capacity events; see
- -- internal/controlplane/capacity_reporter.go + events-ingest worker).
- -- The CP aggregates per-worker memory pressure from WorkerEntry. A cell is
- -- placement-eligible iff available_workers > 0 AND capacity_updated_at is
- -- within the freshness window (~120s). NULL/stale capacity_updated_at ⇒ the
- -- reporting CP is dead, treat the cell as unhealthy regardless of `status`.
- --
- -- "available" = worker where committed_memory_mb/total_memory_mb < 85%.
- -- Single-worker-below-threshold is the right gate because a sandbox lands
- -- on one worker, not striped across workers — aggregating across the cell
- -- would wrongly skip a cell with 1 free worker and 9 loaded ones.
- healthy_workers INTEGER NOT NULL DEFAULT 0, -- alive workers in this cell
- available_workers INTEGER NOT NULL DEFAULT 0, -- workers under the mem threshold
- running_sandboxes INTEGER NOT NULL DEFAULT 0, -- observability only, not in placement
- capacity_updated_at INTEGER,
- created_at INTEGER NOT NULL
-);
-
--- Global sandbox index (cross-region routing and listing) -----------------
-
-CREATE TABLE IF NOT EXISTS sandboxes_index (
- id TEXT PRIMARY KEY, -- sandbox_id
- org_id TEXT NOT NULL,
- user_id TEXT,
- cell_id TEXT NOT NULL,
- worker_id TEXT,
- status TEXT NOT NULL, -- running | hibernated | stopped | error
- template_id TEXT,
- -- Requested resources, projected by api-edge's POST /api/sandboxes (SSE) path
- -- and surfaced by GET /api/sandboxes. Nullable: not every create path sets them.
- cpu_count INTEGER,
- memory_mb INTEGER,
- created_at INTEGER NOT NULL,
- last_event_at INTEGER,
- stopped_at INTEGER
-);
-CREATE INDEX IF NOT EXISTS idx_sandboxes_org_status ON sandboxes_index(org_id, status);
-CREATE INDEX IF NOT EXISTS idx_sandboxes_cell ON sandboxes_index(cell_id, status);
-CREATE INDEX IF NOT EXISTS idx_sandboxes_active ON sandboxes_index(org_id) WHERE status = 'running';
-
--- Events (audit + query) -------------------------------------------------
-
-CREATE TABLE IF NOT EXISTS events (
- id TEXT PRIMARY KEY, -- event UUID from worker
- cell_id TEXT NOT NULL,
- type TEXT NOT NULL,
- org_id TEXT,
- sandbox_id TEXT,
- user_id TEXT,
- worker_id TEXT,
- ts INTEGER NOT NULL, -- unix ms
- payload TEXT NOT NULL -- JSON
-);
-CREATE INDEX IF NOT EXISTS idx_events_org_ts ON events(org_id, ts DESC);
-CREATE INDEX IF NOT EXISTS idx_events_sandbox_ts ON events(sandbox_id, ts DESC);
-CREATE INDEX IF NOT EXISTS idx_events_cell_ts ON events(cell_id, ts DESC);
-CREATE INDEX IF NOT EXISTS idx_events_type_ts ON events(type, ts DESC);
-
--- Billing (pro tier) ------------------------------------------------------
-
--- Raw per-tick resource samples for pro orgs — the edge analog of the cell's
--- `sandbox_scale_events`. events-ingest writes one row per pro `usage_tick`;
--- the rollup cron aggregates these into `usage_snapshots` (memory_gb_seconds
--- per hourly bucket) and meters them to Stripe.
---
--- `id` is the originating event UUID, so the INSERT can use ON CONFLICT(id)
--- DO NOTHING for the same at-least-once dedup the `events` table relies on —
--- the CP forwarder retries batches, and additive billing must not double-count.
--- Rows are disposable once rolled up (see rolled_up flag); kept short-lived,
--- independent of the `events` audit log's retention.
-CREATE TABLE IF NOT EXISTS usage_samples (
- id TEXT PRIMARY KEY, -- originating event UUID
- org_id TEXT NOT NULL,
- sandbox_id TEXT NOT NULL,
- memory_mb INTEGER NOT NULL,
- cpu_count INTEGER NOT NULL,
- interval_s INTEGER NOT NULL, -- seconds this sample covers
- ts INTEGER NOT NULL, -- unix ms (tick emit time)
- cell_id TEXT NOT NULL,
- rolled_up INTEGER NOT NULL DEFAULT 0
-);
--- Rollup cron scans unrolled samples ordered by time; partial index keeps it
--- tight as rolled-up rows accumulate before cleanup.
-CREATE INDEX IF NOT EXISTS idx_usage_samples_unrolled ON usage_samples(org_id, ts) WHERE rolled_up = 0;
-
-CREATE TABLE IF NOT EXISTS usage_snapshots (
- org_id TEXT NOT NULL,
- snapshot_ts INTEGER NOT NULL, -- hourly bucket (unix s)
- cpu_seconds INTEGER NOT NULL,
- wall_seconds INTEGER NOT NULL,
- memory_gb_seconds REAL NOT NULL,
- sandbox_count INTEGER NOT NULL,
- cost_cents INTEGER NOT NULL,
- reported_to_stripe INTEGER NOT NULL DEFAULT 0,
- PRIMARY KEY (org_id, snapshot_ts)
-);
-CREATE INDEX IF NOT EXISTS idx_usage_unreported ON usage_snapshots(reported_to_stripe, org_id) WHERE reported_to_stripe = 0;
-
--- Billing outbox — one row per Stripe meter event the rollup cron will ship.
--- The edge analog of the cell's `billable_events`. Meter-grained (not one row
--- per org/hour like usage_snapshots) because legacy orgs bill one meter event
--- PER memory tier, while unified orgs bill a single flat overage meter — a
--- per-org/hour row can't hold the legacy per-tier breakdown.
---
--- `id` is deterministic: "{org}:{bucket_start}:{meter_event_name}". That makes
--- the whole rollup idempotent — re-running a bucket recomputes identical ids,
--- so ON CONFLICT(id) DO NOTHING drops the dup, and it doubles as the Stripe
--- meter-event Identifier (Stripe dedups the same identifier within 24h). So a
--- crash anywhere in roll→send→mark is safe to replay.
---
--- `value` units depend on billing_mode: unified=GB-seconds (float), legacy=
--- seconds at that tier (integer, the unit the cell's per-tier meter expects).
-CREATE TABLE IF NOT EXISTS usage_meter_events (
- id TEXT PRIMARY KEY, -- {org}:{bucket_start}:{meter_event_name}
- org_id TEXT NOT NULL,
- meter_event_name TEXT NOT NULL, -- Stripe meter event_name
- value REAL NOT NULL, -- GB-seconds (unified) | seconds (legacy tier)
- billing_mode TEXT NOT NULL, -- 'legacy' | 'unified' (for the parity diff)
- bucket_start INTEGER NOT NULL, -- unix s (inclusive)
- bucket_end INTEGER NOT NULL, -- unix s (exclusive); meter event timestamp
- state TEXT NOT NULL DEFAULT 'pending', -- 'pending' | 'sent' | 'shadow'
- stripe_identifier TEXT, -- echoed back by Stripe on send
- created_at INTEGER NOT NULL,
- sent_at INTEGER
-);
-CREATE INDEX IF NOT EXISTS idx_meter_events_pending ON usage_meter_events(state, bucket_start) WHERE state = 'pending';
-CREATE INDEX IF NOT EXISTS idx_meter_events_org_bucket ON usage_meter_events(org_id, bucket_start);
-
--- Stripe price catalog — the resolved metered Price IDs the edge attaches when
--- it provisions a pro subscription. The catalog is GLOBAL (one Stripe account,
--- same prices for every cell), so it's written by a single deploy-time step
--- (cmd/ensure-products), NOT by per-cell publishing — 40 cells must not each
--- race to write it. The edge reads every row and attaches each price_id as a
--- subscription item (mirrors the CP's CreateSubscription).
--- key: "tier_1024".."tier_65536" | "overage" | "reserved" | "disk_overage"
-CREATE TABLE IF NOT EXISTS billing_prices (
- key TEXT PRIMARY KEY,
- price_id TEXT NOT NULL,
- updated_at INTEGER NOT NULL
-);
-
-CREATE TABLE IF NOT EXISTS org_subscription_items (
- org_id TEXT NOT NULL,
- tier TEXT NOT NULL, -- e.g. "memory" | "cpu"
- stripe_item_id TEXT NOT NULL,
- price_id TEXT NOT NULL,
- PRIMARY KEY (org_id, tier)
-);
diff --git a/cloudflare-workers/schema_phase10_autumn_concurrency_override.sql b/cloudflare-workers/schema_phase10_autumn_concurrency_override.sql
deleted file mode 100644
index 69bbb42f..00000000
--- a/cloudflare-workers/schema_phase10_autumn_concurrency_override.sql
+++ /dev/null
@@ -1,18 +0,0 @@
--- Phase 10: Autumn per-org concurrency override.
---
--- Autumn normally projects orgs.max_concurrent_sandboxes from the customer's
--- active Autumn concurrency product:
--- base=5, concurrency_pro=100, concurrency_pro_plus=600,
--- concurrency_pro_plus_plus=1000.
---
--- Some migrated customers need a bespoke limit that should survive Autumn
--- balance/concurrency projection. NULL means "follow Autumn plan"; a positive
--- integer pins orgs.max_concurrent_sandboxes to that value whenever projection
--- runs.
---
--- Apply with:
--- wrangler d1 execute opencomputer-prod --remote --file cloudflare-workers/schema_phase10_autumn_concurrency_override.sql
---
--- SQLite/D1 has no ADD COLUMN IF NOT EXISTS, so this is one-shot.
-ALTER TABLE orgs ADD COLUMN autumn_concurrency_override INTEGER;
-
diff --git a/cloudflare-workers/schema_phase2.sql b/cloudflare-workers/schema_phase2.sql
deleted file mode 100644
index e2047ef4..00000000
--- a/cloudflare-workers/schema_phase2.sql
+++ /dev/null
@@ -1,102 +0,0 @@
--- Phase 2: multi-region resource layer
---
--- Adds the global registries that let cells share canonical resources
--- (golden rootfs blobs, templates, checkpoints) via Tigris and D1.
---
--- Apply with:
--- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase2.sql
---
--- The original schema.sql remains the bootstrap; this layers on top.
--- All statements are idempotent (`IF NOT EXISTS` for tables/indexes).
--- The ALTER TABLE statements use a CASE pattern that no-ops if the
--- column already exists (D1/SQLite doesn't support `ADD COLUMN IF NOT
--- EXISTS` directly, so we use the `pragma_table_info` workaround).
-
--- Golden versions registry ----------------------------------------------
---
--- One row per distinct golden hash that exists anywhere in the fleet.
--- canonical_url points at Tigris (s3://opencomputer-goldens-dev/bases/{hash}/default.ext4).
--- cells_available tracks which cells have pulled + cached the blob locally.
--- A worker's PrepareGoldenSnapshot path:
--- 1. Look up golden_versions WHERE hash=$1
--- 2. If not in cells_available[this_cell]: pull blob from canonical_url
--- 3. Build local snapshot, update cells_available
---
--- retired_at is a soft-retire — set when no sandboxes depend on this
--- golden. Lifecycle GC can purge canonical bytes after a TTL.
-
-CREATE TABLE IF NOT EXISTS golden_versions (
- hash TEXT PRIMARY KEY, -- sha256 of default.ext4 content
- canonical_url TEXT NOT NULL, -- s3://opencomputer-goldens-dev/bases/{hash}/default.ext4
- size_bytes INTEGER,
- cells_available TEXT NOT NULL DEFAULT '[]', -- JSON array of cell_ids
- ami_version TEXT, -- AMI/image version that produced this golden (e.g. git SHA)
- created_at INTEGER NOT NULL, -- unix s
- retired_at INTEGER -- unix s, NULL = active
-);
-
-CREATE INDEX IF NOT EXISTS idx_golden_versions_active
- ON golden_versions(created_at) WHERE retired_at IS NULL;
-
--- Checkpoint global index ----------------------------------------------
---
--- One row per checkpoint, regardless of which cell stores the bytes.
--- The bytes themselves stay in the owning cell's S3 (Azure Blob / AWS S3 /
--- per-cell store) — Tigris is for canonical *globally-shared* blobs, not
--- per-sandbox checkpoints (write-heavy, mostly local-read pattern).
---
--- replicated_to lets us track cross-cell wakes that triggered a copy.
--- Wake flow:
--- 1. Look up checkpoints_index WHERE id=$1 → owner_cell_id
--- 2. If owner_cell_id == this_cell: wake locally (fast path)
--- 3. If different: copy bytes from owner cell's S3 to local, update replicated_to
--- OR: redirect user to owner cell via X-Owner-Cell header (avoid the copy)
-
-CREATE TABLE IF NOT EXISTS checkpoints_index (
- id TEXT PRIMARY KEY, -- checkpoint UUID
- sandbox_id TEXT NOT NULL,
- org_id TEXT NOT NULL,
- owner_cell_id TEXT NOT NULL, -- cell whose S3 holds the canonical bytes
- s3_url TEXT NOT NULL, -- e.g. azure-blob://bucket/checkpoints/sb-X/ckpt-Y/...
- size_bytes INTEGER,
- golden_hash TEXT NOT NULL, -- which golden version this checkpoint depends on
- workspace_size INTEGER,
- created_at INTEGER NOT NULL,
- expires_at INTEGER, -- nullable, optional TTL
- replicated_to TEXT NOT NULL DEFAULT '[]' -- JSON array of cell_ids that have a local cached copy
-);
-
-CREATE INDEX IF NOT EXISTS idx_checkpoints_org ON checkpoints_index(org_id);
-CREATE INDEX IF NOT EXISTS idx_checkpoints_sandbox ON checkpoints_index(sandbox_id);
-CREATE INDEX IF NOT EXISTS idx_checkpoints_owner ON checkpoints_index(owner_cell_id);
-CREATE INDEX IF NOT EXISTS idx_checkpoints_expires ON checkpoints_index(expires_at)
- WHERE expires_at IS NOT NULL;
-
--- Templates: extend existing table with canonical Tigris URLs ----------
---
--- The original schema.sql has `templates(rootfs_s3_key, workspace_s3_key)`
--- which were per-cell paths. Phase 2 adds canonical_*_url pointing at
--- Tigris (s3://opencomputer-templates-dev/{template_id}/...) so any cell
--- can fetch the template on first use.
---
--- cells_available was already in the schema (JSON array). Per-cell paths
--- become caches; canonical_*_url is the source of truth.
---
--- D1/SQLite doesn't support `ALTER TABLE ADD COLUMN IF NOT EXISTS`, so
--- we use a guard query that only ADDs the column if it's missing. If you
--- run this twice, the second run silently no-ops (we're idempotent).
-
--- canonical_rootfs_url
-SELECT CASE
- WHEN (SELECT COUNT(*) FROM pragma_table_info('templates') WHERE name='canonical_rootfs_url') = 0
- THEN RAISE(IGNORE)
-END
-WHERE 0; -- never executes; the actual ALTER follows
-
--- The above is a no-op SELECT that documents intent. SQLite's pragma trick
--- doesn't actually ADD COLUMN conditionally. The cleanest path is to
--- accept that re-running this file fails on the ALTERs after first run,
--- which is fine — Phase 2 schema is applied once.
-
-ALTER TABLE templates ADD COLUMN canonical_rootfs_url TEXT;
-ALTER TABLE templates ADD COLUMN canonical_workspace_url TEXT;
diff --git a/cloudflare-workers/schema_phase2_d1.sql b/cloudflare-workers/schema_phase2_d1.sql
deleted file mode 100644
index aec17db4..00000000
--- a/cloudflare-workers/schema_phase2_d1.sql
+++ /dev/null
@@ -1,45 +0,0 @@
--- Phase 2 schema for D1 (no RAISE clauses — D1 rejects them outside triggers).
--- Strips the no-op pragma_table_info guard from schema_phase2.sql; only the
--- table creates + the ALTER TABLE calls remain. ALTER is one-shot; re-running
--- this file fails (idempotent re-run isn't supported by D1).
-
-CREATE TABLE IF NOT EXISTS golden_versions (
- hash TEXT PRIMARY KEY,
- canonical_url TEXT NOT NULL,
- size_bytes INTEGER,
- cells_available TEXT NOT NULL DEFAULT '[]',
- ami_version TEXT,
- created_at INTEGER NOT NULL,
- retired_at INTEGER
-);
-
-CREATE INDEX IF NOT EXISTS idx_golden_versions_active
- ON golden_versions(created_at) WHERE retired_at IS NULL;
-
-CREATE TABLE IF NOT EXISTS checkpoints_index (
- id TEXT PRIMARY KEY,
- sandbox_id TEXT NOT NULL,
- org_id TEXT NOT NULL,
- owner_cell_id TEXT NOT NULL,
- s3_url TEXT NOT NULL,
- size_bytes INTEGER,
- golden_hash TEXT NOT NULL,
- workspace_size INTEGER,
- created_at INTEGER NOT NULL,
- expires_at INTEGER,
- replicated_to TEXT NOT NULL DEFAULT '[]',
- name TEXT,
- status TEXT NOT NULL DEFAULT 'ready',
- error_msg TEXT,
- failed_at INTEGER
-);
-
-CREATE INDEX IF NOT EXISTS idx_checkpoints_org ON checkpoints_index(org_id);
-CREATE INDEX IF NOT EXISTS idx_checkpoints_sandbox ON checkpoints_index(sandbox_id);
-CREATE INDEX IF NOT EXISTS idx_checkpoints_owner ON checkpoints_index(owner_cell_id);
-CREATE INDEX IF NOT EXISTS idx_checkpoints_expires ON checkpoints_index(expires_at)
- WHERE expires_at IS NOT NULL;
-
--- templates: extend with canonical Tigris URLs. ALTERs run once; re-runs fail.
-ALTER TABLE templates ADD COLUMN canonical_rootfs_url TEXT;
-ALTER TABLE templates ADD COLUMN canonical_workspace_url TEXT;
diff --git a/cloudflare-workers/schema_phase3.sql b/cloudflare-workers/schema_phase3.sql
deleted file mode 100644
index d2e7fb99..00000000
--- a/cloudflare-workers/schema_phase3.sql
+++ /dev/null
@@ -1,16 +0,0 @@
--- Phase 3: free-tier halt tracking
---
--- The CreditAccount DO is the source of truth for an org's free-tier balance
--- and halt status (lives in DO storage, lazy-loaded on first /check). The
--- mirror column below exists for one reason: the api-edge /internal/halt-list
--- endpoint needs to enumerate halted orgs without round-tripping every org's
--- DO. The DO writes back to this column on dispatchHalt success and clears it
--- on dispatchResume. D1 is the projection; DO is authoritative.
---
--- Apply with:
--- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase3.sql
-
-ALTER TABLE orgs ADD COLUMN is_halted INTEGER NOT NULL DEFAULT 0;
-ALTER TABLE orgs ADD COLUMN halted_at INTEGER;
-
-CREATE INDEX IF NOT EXISTS idx_orgs_halted ON orgs(is_halted) WHERE is_halted = 1;
diff --git a/cloudflare-workers/schema_phase4.sql b/cloudflare-workers/schema_phase4.sql
deleted file mode 100644
index 251c94a8..00000000
--- a/cloudflare-workers/schema_phase4.sql
+++ /dev/null
@@ -1,93 +0,0 @@
--- Phase 4: dashboard-on-edge data model.
---
--- The CF edge becomes the source of truth for identity, billing, and the
--- sandbox routing index (per the new architecture diagram). This migration
--- adds the missing columns and tables to D1 so api-edge dashboard handlers
--- can read/write directly instead of proxying to cell PG.
---
--- Apply with:
--- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase4.sql
---
--- SQLite/D1 has no `ALTER TABLE ADD COLUMN IF NOT EXISTS`, so these ALTERs
--- fail on re-run. Phase 4 is one-shot. If you need to re-apply, drop the
--- affected columns first or skip the ALTERs.
-
--- ── orgs: full feature parity with cell PG ───────────────────────────────
---
--- These mirror columns the cell PG `orgs` table has had since migrations
--- 005 / 016 / 029. Carrying them in D1 means dashboard can manage them
--- without touching any cell. The CF custom-domain handlers live on the
--- edge (it calls the CF API directly anyway), so this is the natural
--- place for the data.
-
-ALTER TABLE orgs ADD COLUMN custom_domain TEXT;
-ALTER TABLE orgs ADD COLUMN cf_hostname_id TEXT;
-ALTER TABLE orgs ADD COLUMN domain_verification_status TEXT NOT NULL DEFAULT 'none';
-ALTER TABLE orgs ADD COLUMN domain_ssl_status TEXT NOT NULL DEFAULT 'none';
-ALTER TABLE orgs ADD COLUMN verification_txt_name TEXT;
-ALTER TABLE orgs ADD COLUMN verification_txt_value TEXT;
-ALTER TABLE orgs ADD COLUMN ssl_txt_name TEXT;
-ALTER TABLE orgs ADD COLUMN ssl_txt_value TEXT;
-
--- Billing balances mirrored from CreditAccount DO. The DO is the live
--- authority; these columns let dashboard render balances without a DO
--- round-trip per page load. Updated on /debit, /credit, /mark-pro.
-ALTER TABLE orgs ADD COLUMN free_credits_remaining_cents INTEGER NOT NULL DEFAULT 500;
-ALTER TABLE orgs ADD COLUMN credit_balance_cents INTEGER NOT NULL DEFAULT 0;
-
--- Org quota controls (matches PG migration 029).
-ALTER TABLE orgs ADD COLUMN max_concurrent_sandboxes INTEGER NOT NULL DEFAULT 5;
-ALTER TABLE orgs ADD COLUMN max_sandbox_timeout_sec INTEGER NOT NULL DEFAULT 3600;
-ALTER TABLE orgs ADD COLUMN max_disk_mb INTEGER NOT NULL DEFAULT 0;
-ALTER TABLE orgs ADD COLUMN max_memory_gb INTEGER NOT NULL DEFAULT 0;
-
--- Billing mode (matches PG migration 031): "legacy" = UsageReporter → Stripe;
--- "unified" = phase-3 billable_events sender. New orgs default to unified
--- in the dashboard create flow.
-ALTER TABLE orgs ADD COLUMN billing_mode TEXT NOT NULL DEFAULT 'unified';
-
--- Last Stripe usage report timestamp (matches PG migration 016 area).
-ALTER TABLE orgs ADD COLUMN last_usage_reported_at INTEGER NOT NULL DEFAULT 0;
-
--- ── invitations ─────────────────────────────────────────────────────────
---
--- Pending invitations to an org. WorkOS handles the email send and acceptance
--- handshake; we mirror state here so dashboard can list outstanding invites
--- and revoke them. Acceptance flow (WorkOS callback) updates D1 directly.
-
-CREATE TABLE IF NOT EXISTS invitations (
- id TEXT PRIMARY KEY, -- D1-local UUID
- org_id TEXT NOT NULL,
- email TEXT NOT NULL,
- role TEXT NOT NULL DEFAULT 'member', -- "owner" | "admin" | "member"
- invited_by TEXT, -- user_id of the inviter
- workos_invitation_id TEXT, -- WorkOS Invitation.id (null until WorkOS call succeeds)
- status TEXT NOT NULL DEFAULT 'pending', -- pending | accepted | revoked | expired
- token TEXT UNIQUE, -- short opaque accept token (not currently used; WorkOS owns the flow)
- expires_at INTEGER, -- unix s; null = no expiry
- created_at INTEGER NOT NULL,
- accepted_at INTEGER,
- revoked_at INTEGER
-);
-CREATE INDEX IF NOT EXISTS idx_invitations_org_status ON invitations(org_id, status);
-CREATE INDEX IF NOT EXISTS idx_invitations_email ON invitations(email);
-
--- ── agent_subscriptions ─────────────────────────────────────────────────
---
--- Per-(org, agent, feature) subscription rows. Pro-tier orgs subscribe to
--- specific agent features (e.g., Telegram bot premium tools) and we ship
--- those events to Stripe via meters. Dashboard reads this to render
--- subscription state; mutations dispatch to Stripe + record here.
-
-CREATE TABLE IF NOT EXISTS agent_subscriptions (
- id TEXT PRIMARY KEY, -- D1-local UUID
- org_id TEXT NOT NULL,
- agent_id TEXT NOT NULL,
- feature TEXT NOT NULL, -- "telegram", "premium-tools", etc.
- status TEXT NOT NULL DEFAULT 'active', -- active | cancelled
- stripe_item_id TEXT, -- Stripe Subscription Item ID
- created_at INTEGER NOT NULL,
- cancelled_at INTEGER
-);
-CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_subs_unique ON agent_subscriptions(org_id, agent_id, feature);
-CREATE INDEX IF NOT EXISTS idx_agent_subs_org ON agent_subscriptions(org_id);
diff --git a/cloudflare-workers/schema_phase5.sql b/cloudflare-workers/schema_phase5.sql
deleted file mode 100644
index 6e19e75b..00000000
--- a/cloudflare-workers/schema_phase5.sql
+++ /dev/null
@@ -1,37 +0,0 @@
--- Phase 5: home-cell onboarding gate moves from the edge `CELLS` env var to a
--- column on the D1 `cells` table.
---
--- Why: `pickHomeCell` used a hardcoded, deploy-time `CELLS` allowlist that had
--- to be kept in sync with the `cells` table by hand. It drifted — prod shipped
--- `CELLS = ""`, so every new org since ~2026-05-27 got an empty `home_cell`.
--- Making onboarding-eligibility a property of the cell row removes the second
--- source of truth: it can't drift from `cells` because it IS `cells`, and
--- opening a cell to new signups becomes a row toggle instead of a deploy.
---
--- Apply with:
--- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase5.sql
---
--- SQLite/D1 has no `ADD COLUMN IF NOT EXISTS`, so this ALTER fails on re-run —
--- one-shot, like the earlier phases.
---
--- ROLLOUT ORDER MATTERS. Run this migration AND open the onboarding cell(s)
--- (step 2 below) BEFORE deploying the new api-edge code. The new pickHomeCell
--- reads `accepts_new_orgs`; if you deploy code while every cell still has the
--- default 0, new orgs get an empty home_cell during the gap.
-
--- 1. Schema: the onboarding gate. Default 0 = a cell does NOT adopt new orgs
--- until explicitly opened. Distinct from `status` (routing of existing
--- orgs / pins / failover), so a cell can be active+routable without
--- onboarding new signups (e.g. a brand-new cell still under validation).
-ALTER TABLE cells ADD COLUMN accepts_new_orgs INTEGER NOT NULL DEFAULT 0;
-
--- 2. Open the cell(s) that SHOULD onboard new orgs. Run the line for your env;
--- the other is a harmless no-op (cell_id won't match).
--- prod: UPDATE cells SET accepts_new_orgs = 1 WHERE cell_id = 'azure-us-east-2-a';
--- dev: UPDATE cells SET accepts_new_orgs = 1 WHERE cell_id = 'azure-westus2-cell-a';
-
--- 3. Backfill orgs that were created with an empty home_cell during the drift
--- window, pointing them at the de-facto cell (prod: azure-us-east-2-a).
--- Run per env:
--- UPDATE orgs SET home_cell = 'azure-us-east-2-a'
--- WHERE home_cell IS NULL OR home_cell = '';
diff --git a/cloudflare-workers/schema_phase6.sql b/cloudflare-workers/schema_phase6.sql
deleted file mode 100644
index 4c03db87..00000000
--- a/cloudflare-workers/schema_phase6.sql
+++ /dev/null
@@ -1,18 +0,0 @@
--- Phase 6: checkpoint failure details in the global D1 checkpoint index.
---
--- The edge dashboard reads /checkpoints from checkpoints_index, not from each
--- cell's local Postgres. Before this phase, failed async checkpoints stayed in
--- cell PG only, so the dashboard could show "No checkpoints yet" while
--- `oc checkpoint list` showed a failed checkpoint with an error reason.
---
--- Apply before deploying api-edge/events-ingest/control-plane code that reads
--- or writes these columns:
--- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase6.sql
---
--- SQLite/D1 has no `ADD COLUMN IF NOT EXISTS`, so this ALTER fails on re-run —
--- one-shot, like earlier phase files.
-
-ALTER TABLE checkpoints_index ADD COLUMN name TEXT;
-ALTER TABLE checkpoints_index ADD COLUMN status TEXT NOT NULL DEFAULT 'ready';
-ALTER TABLE checkpoints_index ADD COLUMN error_msg TEXT;
-ALTER TABLE checkpoints_index ADD COLUMN failed_at INTEGER;
diff --git a/cloudflare-workers/schema_phase7.sql b/cloudflare-workers/schema_phase7.sql
deleted file mode 100644
index 12cd67d1..00000000
--- a/cloudflare-workers/schema_phase7.sql
+++ /dev/null
@@ -1,37 +0,0 @@
--- Phase 7: Autumn billing — per-org billing_provider selector on D1.
---
--- The edge is authoritative for billing_provider: signup sets it, the cutover
--- backfill flips existing orgs, and the cap-token carries it to each cell's
--- Postgres mirror (like `plan`). The create/wake gates + the dashboard billing
--- read it directly from D1, so this column MUST exist before the new api-edge
--- code is deployed.
---
--- Apply with:
--- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase7.sql
---
--- SQLite/D1 has no `ADD COLUMN IF NOT EXISTS`, so this is one-shot like the
--- earlier phases.
---
--- ROLLOUT ORDER MATTERS. Run this migration BEFORE deploying the new api-edge
--- code: loadOrgPolicy + GET /api/dashboard/billing now SELECT billing_provider
--- for every org, and a missing column makes those reads error for ALL orgs
--- (not just Autumn ones).
---
--- 'legacy' — in-house pipeline (CreditAccount DO / usage_reporter).
--- 'autumn' — Autumn owns the credit ledger, metering, top-ups, concurrency.
---
--- Defaults to 'legacy' so every existing org is unaffected until explicitly
--- flipped. Mirrors internal/db/migrations/047 on the cell.
-ALTER TABLE orgs ADD COLUMN billing_provider TEXT NOT NULL DEFAULT 'legacy';
-
--- Cutover backfill / dashboard reads filter on it; partial index keeps the
--- "which orgs are on Autumn" sweep tight while almost everyone is still legacy.
-CREATE INDEX IF NOT EXISTS idx_orgs_billing_provider ON orgs(billing_provider) WHERE billing_provider = 'autumn';
-
--- Per-org watermark (unix seconds) for the edge autumn meter loop: the end of
--- the last fully-tracked 5-minute bucket. 0 = unseeded; the first cron sight
--- seeds it to "now" and bills forward only (never retroactively charges usage
--- accrued before the org moved to Autumn). This is the edge-native replacement
--- for the cell's orgs.last_usage_synced_at — billing is one place (the edge),
--- off usage_samples, not per-cell.
-ALTER TABLE orgs ADD COLUMN autumn_usage_watermark INTEGER NOT NULL DEFAULT 0;
diff --git a/cloudflare-workers/schema_phase8.sql b/cloudflare-workers/schema_phase8.sql
deleted file mode 100644
index 50c1e4d3..00000000
--- a/cloudflare-workers/schema_phase8.sql
+++ /dev/null
@@ -1,15 +0,0 @@
--- Phase 8: checkpoint kind in the global D1 checkpoint index.
---
--- The dashboard reads /checkpoints from checkpoints_index, not directly from
--- each cell's Postgres sandbox_checkpoints table. Disk-only checkpoints need
--- their kind mirrored here so the dashboard can distinguish them from full
--- checkpoints.
---
--- Apply before deploying api-edge/events-ingest code that reads or writes this
--- column:
--- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase8.sql
---
--- SQLite/D1 has no `ADD COLUMN IF NOT EXISTS`, so this is one-shot like the
--- earlier phase files.
-
-ALTER TABLE checkpoints_index ADD COLUMN kind TEXT NOT NULL DEFAULT 'full';
diff --git a/cloudflare-workers/schema_phase8_webhooks.sql b/cloudflare-workers/schema_phase8_webhooks.sql
deleted file mode 100644
index 73632fea..00000000
--- a/cloudflare-workers/schema_phase8_webhooks.sql
+++ /dev/null
@@ -1,42 +0,0 @@
--- Phase 8: sandbox lifecycle webhooks (all-Svix-at-edge).
--- api-edge owns /api/webhooks management; the index below maps OC destination
--- ids ↔ Svix endpoints. events-ingest reads orgs.has_webhooks as the dormancy
--- gate (skip the Svix call entirely for orgs with no webhooks).
--- See .agents/work/sandbox-webhooks-rearchitecture.md §8.
-
--- Coarse dormancy flag: true once an org has ≥1 live destination.
-ALTER TABLE orgs ADD COLUMN has_webhooks INTEGER NOT NULL DEFAULT 0;
-
--- Webhook destinations (the OC↔Svix mapping; secrets live in Svix, not here).
-CREATE TABLE IF NOT EXISTS webhook_destinations (
- id TEXT PRIMARY KEY, -- 'whk_' + random hex
- org_id TEXT NOT NULL,
- svix_app_id TEXT NOT NULL, -- Svix app id (uid = org_id)
- svix_endpoint_id TEXT NOT NULL, -- Svix endpoint id
- url TEXT NOT NULL,
- event_types TEXT NOT NULL DEFAULT '[]', -- JSON array; [] = all types
- sandbox_id TEXT, -- NULL = org-wide; else Svix channel scope
- name TEXT,
- disabled INTEGER NOT NULL DEFAULT 0, -- mirrors the Svix endpoint disabled flag
- created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL,
- deleted_at INTEGER -- soft-delete; history stays in Svix
-);
-
-CREATE INDEX IF NOT EXISTS webhook_dest_org_idx
- ON webhook_destinations (org_id) WHERE deleted_at IS NULL;
-CREATE UNIQUE INDEX IF NOT EXISTS webhook_dest_svix_ep_idx
- ON webhook_destinations (svix_endpoint_id);
-
--- Create idempotency: a (org, Idempotency-Key) → destination map so a retried
--- POST /api/webhooks returns the SAME destination instead of a duplicate. The
--- PK makes the claim atomic; a concurrent loser deletes its just-created dup and
--- returns the winner's row (see api-edge createWebhook).
-CREATE TABLE IF NOT EXISTS webhook_idempotency (
- org_id TEXT NOT NULL,
- idempotency_key TEXT NOT NULL,
- destination_id TEXT NOT NULL,
- request_hash TEXT, -- sha256 of the create body; reuse with a different body → 409
- created_at INTEGER NOT NULL,
- PRIMARY KEY (org_id, idempotency_key)
-);
diff --git a/cloudflare-workers/schema_phase9_model_billing.sql b/cloudflare-workers/schema_phase9_model_billing.sql
deleted file mode 100644
index 7d2ebf9a..00000000
--- a/cloudflare-workers/schema_phase9_model_billing.sql
+++ /dev/null
@@ -1,74 +0,0 @@
--- Phase 9: Token / model-usage billing — managed OpenRouter keys + per-org state.
---
--- Adds the edge-native state for billing an org's LLM token usage out of the same
--- Autumn `credits` pool as compute (design: .agents/work/token-billing.md). The
--- edge provisions one OpenRouter key per managed org, meters its spend, and pushes
--- the cap to mirror the shared balance; this schema holds the per-key ledger + the
--- per-org provisioning state.
---
--- EDGE-ONLY (D1), unlike billing_provider (phase 7 / migration 047, which mirrors
--- to each cell's Postgres via the cap-token). The Go cell holds no OpenRouter or
--- Autumn client and never gates on model-billing state, so there is deliberately
--- NO cell-PG mirror migration for these.
---
--- Apply with:
--- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase9_model_billing.sql
--- wrangler d1 execute opencomputer-prod --remote --file cloudflare-workers/schema_phase9_model_billing.sql
---
--- SQLite/D1 has no `ADD COLUMN IF NOT EXISTS`, so the ALTERs are one-shot like the
--- earlier phases. Run BEFORE deploying api-edge code that reads these columns.
-
--- Per-org provisioning state machine (token-billing §5.1). Drives off→provisioning
--- →active (or error). `active` ⇒ Managed is offered + resolvable for the org.
--- 'off' — not enabled (default; all existing orgs unaffected).
--- 'provisioning' — OR key being minted + bound to a sessions-api credential.
--- 'active' — a managed credential is bound; Managed available.
--- 'error' — provisioning failed after bounded retries (alert; stays off).
-ALTER TABLE orgs ADD COLUMN model_billing_status TEXT NOT NULL DEFAULT 'off';
-
--- Markup applied to OpenRouter cost before debiting Autumn, in basis points
--- (0 = at-cost; 2000 = +20%). Per-org override of an env default. BOTH the debit
--- and the cap-push math depend on it (token-billing §7). See §9.2 for why
--- at-cost (0) loses ~5% to OR's credit-purchase fee.
-ALTER TABLE orgs ADD COLUMN model_markup_bps INTEGER NOT NULL DEFAULT 0;
-
--- Partial index: the "which orgs run Managed" sweep stays tight while almost
--- everyone is still 'off'.
-CREATE INDEX IF NOT EXISTS idx_orgs_model_billing_active
- ON orgs(model_billing_status) WHERE model_billing_status = 'active';
-
--- One row per provisioned OpenRouter key (token-billing §4). Normally one 'active'
--- per org; ≥1 transiently during a rotation. Per-key watermark so each key's spend
--- is debited independently until it quiesces, and so the in-flight debit interval
--- is durable across cron crashes (persist-before-track, §5.4/§7).
---
--- The plaintext OR key is NEVER stored here — only the non-secret hash + the
--- sessions-api credential id that points at the sealed secret (Infisical).
-CREATE TABLE IF NOT EXISTS managed_model_keys (
- id TEXT PRIMARY KEY,
- org_id TEXT NOT NULL,
- or_key_hash TEXT, -- OpenRouter key hash (non-secret); null between insert + create
- managed_credential_id TEXT, -- sessions-api credential row id (the sealed key); null until bound
- operation_id TEXT, -- idempotency id for the edge→sessions-api bind hand-off (§5.1/§6.7.5)
- status TEXT NOT NULL CHECK (status IN ('active', 'superseded', 'deleting')),
- committed_micro INTEGER NOT NULL DEFAULT 0, -- OR usage already debited to Autumn (micro-USD watermark)
- pending_from_micro INTEGER, -- the single in-flight debit interval [from,to), immutable until committed
- pending_to_micro INTEGER,
- pending_idem TEXT, -- "model_spend:<org>:<from>:<to>" — stable across retries
- attempts INTEGER NOT NULL DEFAULT 0,
- last_error TEXT,
- created_at INTEGER NOT NULL, -- unix seconds
- superseded_at INTEGER
-);
-
--- The hot lookups: an org's active key (resolve/cap) and its still-draining
--- superseded/deleting keys (poll until quiesced).
-CREATE INDEX IF NOT EXISTS idx_managed_model_keys_org_status
- ON managed_model_keys(org_id, status);
-
--- AT MOST ONE active key per org. Without this, two concurrent enable calls/retries
--- (getResumableRow → insertRow with no txn) could mint two active OR keys + two
--- managed credentials. The unique partial index makes the losing insert fail; the
--- provisioning driver catches it and adopts the winner.
-CREATE UNIQUE INDEX IF NOT EXISTS idx_managed_model_keys_one_active
- ON managed_model_keys(org_id) WHERE status = 'active';
diff --git a/docs/dev-cutover-runbook.md b/docs/dev-cutover-runbook.md
index 2d624687..4b6fa9d0 100644
--- a/docs/dev-cutover-runbook.md
+++ b/docs/dev-cutover-runbook.md
@@ -66,7 +66,8 @@ parity has been clean for 24h+.
- [ ] CF infra provisioned:
- [ ] D1 database `opencomputer-dev` (`wrangler d1 create opencomputer-dev`)
- - [ ] D1 schema applied (`wrangler d1 execute opencomputer-dev --file cloudflare-workers/schema.sql`)
+ - [ ] D1 schema applied from the API edge snapshot for fresh databases only
+ (`cd cloudflare-workers/api-edge && wrangler d1 execute opencomputer-dev --file schema-snapshots/current_schema.sql`)
- [ ] KV namespace `SESSIONS_KV` (`wrangler kv:namespace create sessions_kv`)
- [ ] R2 bucket `events-archive-dev` (`wrangler r2 bucket create events-archive-dev`)
- [ ] DNS: GoDaddy NS flipped to `fred.ns.cloudflare.com` / `lovisa.ns.cloudflare.com`