# v1 Migrations

Fresh-schema migrations for the v1 hard reset (`docs/design/v1-backend-spec.md`). Apply in numeric order against an **empty** Postgres database (or a fresh schema in an existing one). The legacy migrations in the parent directory (`007_*` through `036_*`) are preserved for historical reference but are NOT applied to v1 databases.

Application order:

1. `001_users_orgs.sql` — users, orgs, org_memberships, platform_admin_audit, api_keys.
2. `002_members.sql` — members (with partial unique indexes), invites.
3. `003_member_content.sql` — member_connections, member_skills, member_activity.
4. `004_chats_messages.sql` — chats, chat_members, messages, file_references, plus triggers.
5. `005_openclaw_runtime.sql` — openclaw_runtimes (with file-service columns), openclaw_agent_bindings.
6. `006_skill_source_github.sql` — extend member_skills.source CHECK to include 'github'.
7. `007_org_profile_member_role.sql` — orgs.profile jsonb + members.role with backfill.
8. `008_approvals.sql` — centralized approvals record (mirrors OpenClaw's per-channel approvals; magic-link decision token).
9. `009_approvals_log_shape.sql` — reshape approvals from gating queue to log of social acts (nullable token/expiry, message FKs, scope).
10. `010_agent_bindings_created_by_member.sql` — repoint openclaw_agent_bindings.creator_id from users(id) to members(id) for actor-agnostic audit (humans and agents alike).

All migrations are idempotent (`CREATE TABLE IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`, etc.) so re-running is safe during development.

No Row-Level Security policies are declared. Per backend spec §3.3, clients never hold Postgres credentials; all DB access goes through Dialetica's gateway, which enforces permissions in `apps/gateway/src/lib/permissions.ts`.

## Applying

Local dev (plain `psql`):

```bash
for f in 001 002 003 004 005 006 007 008 009 010; do
  psql "$DATABASE_URL" -f apps/gateway/migrations/v1/${f}*.sql
done
```

## Not applied to v1 databases

- Any file under `packages/services/migrations/007_*.sql` through `036_*.sql`.
- `ALL_MIGRATIONS.sql` and `migrate-users.mjs` in the parent directory — legacy tooling for the old schema.

Those files will be deleted at cutover (see `docs/design/v1-implementation-plan.md`).
