Skip to content

feat: add open-agents schema port (Phase 0)#20

Merged
sweetmantech merged 2 commits into
mainfrom
feat/open-agents-phase-0-schema-port
May 1, 2026
Merged

feat: add open-agents schema port (Phase 0)#20
sweetmantech merged 2 commits into
mainfrom
feat/open-agents-phase-0-schema-port

Conversation

@sweetmantech
Copy link
Copy Markdown
Contributor

@sweetmantech sweetmantech commented May 1, 2026

Summary

Phase 0 of the open-agents → main app migration. Ports the core agent/chat schema from open-agents' Drizzle definitions into Supabase migrations so api can absorb the open-agents backend in subsequent phases.

Tables added

Table Purpose
`sessions` Agent runs bound to a sandbox + repo state
`chats` Per-session chat threads
`chat_messages` Message parts (JSONB)
`chat_reads` Per-(account, chat) last-read marker
`shares` Public share-link records for chat threads
`workflow_runs` Each Vercel Workflow execution
`workflow_run_steps` Per-step timings inside a workflow run

Decisions baked into the schema

Open-agents table Migration treatment
`users` Dropped. Privy identity maps to existing `accounts.id`. `user_id` renamed to `account_id` (uuid FK) on every ported table.
`accounts` (GitHub OAuth tokens) Dropped. Env-authenticated hard-coded GH account replaces per-user tokens.
`user_preferences` Dropped. Preferences move to session cookies. `auto_commit_push_override`, `auto_create_pr_override`, `global_skill_refs` (per-session column) preserved on `sessions` where still needed; PR-related columns dropped.
`installations` / `linked_accounts` / `last_repo` Dropped. Not needed for production flow.
`public_usage_profile` Dropped. Public dashboards out of scope.
`usage` / `usage_domain_leaderboard` / `usage_insights` Deferred to Phase 0b (low-priority observability).
`pr_number`, `pr_status`, `auto_create_pr_override` columns on `sessions` Dropped. Auto-commit-and-push to default branch is the sole flow.

Type choices

  • Text PKs preserved. Open-agents uses nanoid (`text`); the migration keeps `text` PKs to minimize port surface. Unifying `sessions` ↔ existing `rooms` (uuid) is a separate post-migration project.
  • `account_id` is uuid (FK to existing `accounts.id`).
  • Status enums modeled as `TEXT` + `CHECK` constraints (matches Drizzle's `text({enum:[...]})` runtime semantics; Postgres-native enums avoided to dodge `ALTER TYPE` pain later).

Schema additions beyond the open-agents source

  • Added `chat_messages_chat_id_idx`. Open-agents' Drizzle schema doesn't explicitly index this column, but Postgres doesn't auto-index FK child columns and "get all messages for chat" is a hot path. Production scale needs the index.

Security

  • RLS enabled on every new table per repo convention.
  • No policies added — api consumes these tables via `service_role`, which bypasses RLS. Policies can land in a follow-up if anon/authenticated access surfaces become needed.

Data migration

None. Per the plan, open-agents data starts fresh in Supabase (the live POC instance is being deprecated, not migrated).

Test plan

  • CI applies migrations cleanly on a preview branch
  • Local `supabase db reset` succeeds with these migrations
  • No conflicts with existing tables (sessions / chats / shares / workflow_runs do not exist in current production schema — verified by grep over migrations/)

Up next

  • Phase 0b: usage / leaderboard / insights tables (separate PR)
  • Phase 0.5: Turborepo conversion of api repo
  • Phase 1: Supabase lib helpers in api repo (`lib/supabase/sessions/*`, `lib/supabase/chats/*`, etc.)

🤖 Generated with Claude Code


Summary by cubic

Phase 0 ports the core open-agents agent/chat schema into Supabase so the main app can absorb the open-agents backend. Adds sessions, chats, chat_messages, chat_reads, workflow_runs, and workflow_run_steps.

  • Migration
    • Keep text PKs; account_id is a UUID FK to existing accounts.id. Identity unified on accounts; open-agents users, token accounts, preferences, and PR-related columns are not ported.
    • workflow_runs only keeps chat_id; removed session_id/account_id to avoid cross-ownership bugs.
    • Excludes the shares public-link table (out of scope for production chat).
    • Use TEXT + CHECK for statuses (no Postgres enums).
    • Index hot joins (e.g., chat_messages_chat_id_idx); cascade deletes on FKs; add updated_at triggers on sessions, chats, and chat_reads.
    • Enable RLS on all tables; no policies (API uses service_role). No data migration; data starts fresh in Supabase.

Written for commit d80b81c. Summary will update on new commits.

Ports 7 tables from the open-agents POC's Drizzle schema
(apps/web/lib/db/schema.ts) into recoupable production Supabase as the
first phase of the broader migration to absorb the open-agents
architecture into the main app.

Tables:
- sessions: agent runs bound to a sandbox + repo state
- chats / chat_messages / chat_reads / shares: per-session chat threads
- workflow_runs / workflow_run_steps: Vercel Workflow observability

Decisions baked in (per migration plan):
- text PKs (nanoid) preserved — type unification deferred to a later
  cleanup pass
- user_id renamed to account_id and re-FK'd to existing accounts(id)
  (uuid). Open-agents' separate users + accounts tables are not ported;
  Privy identity already lives in accounts.
- user_preferences NOT ported (preferences move to session cookies)
- PR-related columns (auto_create_pr_override, pr_number, pr_status)
  dropped — auto-commit/push to default branch is the sole flow
- GitHub-OAuth-token "accounts" table dropped — env-authenticated
  hard-coded GH account replaces per-user tokens
- installations / linked_accounts / last_repo / public_usage_profile
  dropped — not needed in production
- usage / usage_domain_leaderboard / usage_insights deferred to Phase 0b
- Added chat_messages_chat_id_idx (open-agents schema didn't index it;
  production scale needs it for "get messages for chat" queries)

RLS enabled on every new table per repo convention; no policies added,
api consumes via service_role.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 1, 2026

📝 Walkthrough

Walkthrough

Two database migrations introduce the core persistence layer for an "open agents" system. The first migration creates tables for user sessions, chats, chat messages, read tracking, and share links. The second migration creates tables for workflow run tracking and per-step timing data. All tables include proper indexing and Row Level Security enablement.

Changes

Cohort / File(s) Summary
Open Agents Core Sessions & Chats
supabase/migrations/20260501000000_open_agents_sessions_and_chats.sql
Creates sessions table for agent run metadata with status and lifecycle state enums, chats and chat_messages linked to sessions with JSONB message parts, chat_reads for per-account read tracking, and shares for share-link records. Includes indexes on foreign keys and RLS enablement across all tables.
Workflow Runs Tracking
supabase/migrations/20260501000001_open_agents_workflow_runs.sql
Creates workflow_runs table linking to chats/sessions with status constraints and timing metadata, and workflow_run_steps table with per-step timing and uniqueness constraint on (workflow_run_id, step_number). Adds supporting indexes and RLS enablement.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 Hops with glee through databases new,
Sessions and chats, all shiny and true,
Workflows that run with steps so neat,
Row-level security makes it complete!
Open agents bloom in the schema tonight,
Migration magic, everything right!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: add open-agents schema port (Phase 0)' clearly and concisely summarizes the main change: porting the open-agents schema as Phase 0 migrations.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/open-agents-phase-0-schema-port

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@supabase
Copy link
Copy Markdown

supabase Bot commented May 1, 2026

Updates to Preview Branch (feat/open-agents-phase-0-schema-port) ↗︎

Deployments Status Updated
Database Fri, 01 May 2026 17:15:09 UTC
Services Fri, 01 May 2026 17:15:09 UTC
APIs Fri, 01 May 2026 17:15:09 UTC

Tasks are run on every commit but only new migration files are pushed.
Close and reopen this PR if you want to apply changes from existing seed or migration files.

Tasks Status Updated
Configurations Fri, 01 May 2026 17:15:09 UTC
Migrations Fri, 01 May 2026 17:15:09 UTC
Seeding Fri, 01 May 2026 17:15:09 UTC
Edge Functions Fri, 01 May 2026 17:15:09 UTC

View logs for this Workflow Run ↗︎.
Learn more about Supabase for Git ↗︎.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@supabase/migrations/20260501000001_open_agents_workflow_runs.sql`:
- Around line 5-17: The workflow_runs table currently has independent FKs
(chat_id, session_id, account_id) which allow mismatched ownership; add
uniqueness on the parent pairs and replace the single-column FKs with composite
FKs to enforce the chain: create UNIQUE (id, session_id) on chats and UNIQUE
(id, account_id) on sessions, then change workflow_runs to drop the separate
REFERENCES on chat_id/session_id/account_id and add FOREIGN KEY (chat_id,
session_id) REFERENCES chats(id, session_id) and FOREIGN KEY (session_id,
account_id) REFERENCES sessions(id, account_id) (keeping columns non-null as
appropriate). Ensure the status/check, timestamps and defaults remain unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b394f4ca-bec5-4ea9-a3bd-d2a81c3637d2

📥 Commits

Reviewing files that changed from the base of the PR and between a952927 and ddfe7a3.

📒 Files selected for processing (2)
  • supabase/migrations/20260501000000_open_agents_sessions_and_chats.sql
  • supabase/migrations/20260501000001_open_agents_workflow_runs.sql

Comment thread supabase/migrations/20260501000001_open_agents_workflow_runs.sql
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 2 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="supabase/migrations/20260501000000_open_agents_sessions_and_chats.sql">

<violation number="1" location="supabase/migrations/20260501000000_open_agents_sessions_and_chats.sql:45">
P2: `updated_at` columns are added without an auto-update trigger, so timestamps will become stale on row updates.</violation>

<violation number="2" location="supabase/migrations/20260501000000_open_agents_sessions_and_chats.sql:71">
P2: Independent foreign keys on `chat_id`, `session_id`, and `account_id` don't enforce the ownership chain. The database will accept a `workflow_runs` row where `chat_id` points to a chat belonging to session A, while `session_id` is set to session B — a cross-ownership inconsistency.

Since `chats` already has a `session_id` column and `sessions` already has `account_id`, you can use composite foreign keys to enforce consistency. This requires adding unique indexes on the parent tables (`chats(id, session_id)` and `sessions(id, account_id)`) and replacing the independent FKs here with composite constraints:

```sql
CONSTRAINT workflow_runs_chat_session_fk
    FOREIGN KEY (chat_id, session_id)
    REFERENCES chats(id, session_id) ON DELETE CASCADE,
CONSTRAINT workflow_runs_session_account_fk
    FOREIGN KEY (session_id, account_id)
    REFERENCES sessions(id, account_id) ON DELETE CASCADE
```</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

-- Chat messages: full message parts as JSON
CREATE TABLE IF NOT EXISTS chat_messages (
id TEXT PRIMARY KEY,
chat_id TEXT NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Independent foreign keys on chat_id, session_id, and account_id don't enforce the ownership chain. The database will accept a workflow_runs row where chat_id points to a chat belonging to session A, while session_id is set to session B — a cross-ownership inconsistency.

Since chats already has a session_id column and sessions already has account_id, you can use composite foreign keys to enforce consistency. This requires adding unique indexes on the parent tables (chats(id, session_id) and sessions(id, account_id)) and replacing the independent FKs here with composite constraints:

CONSTRAINT workflow_runs_chat_session_fk
    FOREIGN KEY (chat_id, session_id)
    REFERENCES chats(id, session_id) ON DELETE CASCADE,
CONSTRAINT workflow_runs_session_account_fk
    FOREIGN KEY (session_id, account_id)
    REFERENCES sessions(id, account_id) ON DELETE CASCADE
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At supabase/migrations/20260501000000_open_agents_sessions_and_chats.sql, line 71:

<comment>Independent foreign keys on `chat_id`, `session_id`, and `account_id` don't enforce the ownership chain. The database will accept a `workflow_runs` row where `chat_id` points to a chat belonging to session A, while `session_id` is set to session B — a cross-ownership inconsistency.

Since `chats` already has a `session_id` column and `sessions` already has `account_id`, you can use composite foreign keys to enforce consistency. This requires adding unique indexes on the parent tables (`chats(id, session_id)` and `sessions(id, account_id)`) and replacing the independent FKs here with composite constraints:

```sql
CONSTRAINT workflow_runs_chat_session_fk
    FOREIGN KEY (chat_id, session_id)
    REFERENCES chats(id, session_id) ON DELETE CASCADE,
CONSTRAINT workflow_runs_session_account_fk
    FOREIGN KEY (session_id, account_id)
    REFERENCES sessions(id, account_id) ON DELETE CASCADE
```</comment>

<file context>
@@ -0,0 +1,106 @@
+-- Chat messages: full message parts as JSON
+CREATE TABLE IF NOT EXISTS chat_messages (
+    id TEXT PRIMARY KEY,
+    chat_id TEXT NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
+    role TEXT NOT NULL
+        CHECK (role IN ('user', 'assistant')),
</file context>

…ow_runs, add updated_at triggers

Three fixes from PR #20 bot review:

1. Drop the shares table. The /shared/[shareId] public-link UX is not
   in scope for production chat. Reversible if the feature is wanted
   later.

2. Drop session_id and account_id from workflow_runs. Both were
   redundant FKs derivable via chat -> session -> account joins, and
   independent FKs allowed cross-ownership inconsistency (workflow_run
   row could reference chat A while pointing session_id at session B).
   Keeping only chat_id makes the inconsistency impossible.

3. Add set_updated_at triggers on sessions, chats, and chat_reads.
   The existing convention is trigger_set_updated_at() (see
   20250130200000_create_social_fans_table.sql); my first pass
   wrongly used trigger_set_timestamp() which targets accounts.timestamp,
   not generic updated_at columns. Without these triggers, updated_at
   would hold creation time forever.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@sweetmantech sweetmantech merged commit f687835 into main May 1, 2026
3 checks passed
@sweetmantech sweetmantech deleted the feat/open-agents-phase-0-schema-port branch May 1, 2026 18:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant