Skip to content

Feature/issue 57/add database functions migration#61

Merged
urjitc merged 5 commits into
mainfrom
feature/issue-57/add-database-functions-migration
Jan 19, 2026
Merged

Feature/issue 57/add database functions migration#61
urjitc merged 5 commits into
mainfrom
feature/issue-57/add-database-functions-migration

Conversation

@urjitc

@urjitc urjitc commented Jan 19, 2026

Copy link
Copy Markdown
Member

Fixes #57


Important

This PR adds a new database migration, updates AI model integration to use Google, reorganizes the database schema, and enhances the README for better setup instructions.

  • Database Migration:
    • Adds 0000_sad_wallflower.sql for new database functions and tables, including account, session, user, user_profiles, verification, workspace_events, workspace_snapshots, and workspaces.
    • Removes old migration files 0000_military_jigsaw.sql to 0007_white_gambit.sql.
    • Updates drizzle/meta/0000_snapshot.json and drizzle/meta/_journal.json to reflect new migration.
  • AI Model Integration:
    • Replaces vertex with google in route.ts and workers.ts for AI model usage.
    • Updates AI model provider integration for improved compatibility.
  • Schema and Indexing:
    • Updates indexes in schema.ts for workspaces, workspace_snapshots, and workspace_events.
    • Adjusts index operations for better performance.
  • Documentation:
    • Enhances README.md with detailed environment configuration and database setup instructions.
    • Adds db:setup script in package.json for convenient database setup.

This description was created by Ellipsis for 01f9a13. You can customize this summary. It will automatically update as commits are pushed.


Summary by CodeRabbit

  • Documentation

    • Expanded README with step-by-step self-host environment setup, clearer required/optional variables, and improved database setup/run instructions.
  • Refactor

    • Switched AI model provider integration for improved compatibility.
    • Reorganized database schema and indexing strategy to improve performance and maintainability.
  • Chores

    • Added a convenient database setup script.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel

vercel Bot commented Jan 19, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
thinkexv2 Ready Ready Preview, Comment Jan 19, 2026 6:24am

@coderabbitai

coderabbitai Bot commented Jan 19, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Consolidates and replaces legacy migrations with a new baseline schema and DB functions for workspace events/snapshots, removes many snapshot files and migrations, switches AI client usage from the Vertex SDK to the standard Google SDK, updates README with explicit env and DB setup instructions, and adjusts several index opclasses/types.

Changes

Cohort / File(s) Summary
Documentation
README.md
Reworked Self-Host section: explicit .env.local Required/Optional variables, Database Setup with pnpm db:setup (migrate) and pnpm db:push options, and updated dev server/run instructions.
Baseline migration (new)
drizzle/0000_sad_wallflower.sql
Adds comprehensive PostgreSQL baseline: tables (account, session, user, user_profiles, verification, workspace_events, workspace_snapshots, workspaces), RLS policies, indexes, and functions for versioned event append, snapshot creation/lookup, fast event reads, and snapshot necessity checks.
Removed/cleanup migrations & snapshots
drizzle/0000_military_jigsaw.sql, drizzle/0001_*.sqldrizzle/0007_*.sql, drizzle/meta/*_snapshot.json, drizzle/meta/_journal.json
Deletes legacy migration statements and many meta snapshot files; consolidates journal to a single baseline entry and removes older migration artifacts (columns, indexes, workspace_shares, policies, etc.).
Index/type corrections
src/lib/db/schema.ts
Adjusted composite index opclasses/types (e.g., workspaceId → uuid_ops, userId → text_ops, timestamp → int8_ops, snapshotVersion/version operand types).
Package scripts & deps
package.json
Added db:setup script → drizzle-kit migrate; removed dependency @ai-sdk/google-vertex.
AI provider migration
src/app/api/cards/from-message/route.ts, src/lib/ai/workers.ts
Replaced Vertex SDK usage with standard Google SDK (@ai-sdk/google), updated model calls (vertex(...) → google(...)), tool references, and providerMetadata keys.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client
  participant API as Server/API
  participant DB as Postgres

  Client->>API: POST /workspace/:id/events (event payload, expected_version)
  API->>DB: SELECT get_workspace_version(p_workspace_id)
  DB-->>API: current_version
  API->>DB: SELECT append_workspace_event(..., p_expected_version)
  DB-->>API: (version, conflict)
  alt conflict = true
    API->>Client: 409 Conflict (version mismatch)
  else
    API->>DB: SELECT needs_snapshot(p_workspace_id, threshold)
    DB-->>API: (needs_snapshot, current_version, last_snapshot_version, events_since_snapshot)
    alt needs_snapshot = true
      API->>DB: SELECT create_workspace_snapshot(...)
      DB-->>API: snapshot_id
    end
    API->>Client: 200 OK (new version, optional snapshot_id)
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

🐰🌿 I hopped through snapshots, old and gray,
Cleared the burrow, made a brand new way.
From Vertex to Google my carrots gleam,
Events and snapshots hum like a dream.
Cheers — a tidy schema, and code agleam! 🥕✨

🚥 Pre-merge checks | ✅ 2 | ❌ 3
❌ Failed checks (2 warnings, 1 inconclusive)
Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning Issue #57 requires fixing duplicate store registration and HMR crashes during local development, but the PR changes (database migrations, AI SDK replacements, schema updates, documentation) do not address the root cause of store registration crashes. The PR lacks code changes to fix HMR-related duplicate store registration. Add store initialization checks, HMR cleanup handlers, or state management fixes to prevent duplicate store creation on hot reload.
Out of Scope Changes check ⚠️ Warning The PR includes AI SDK migration (vertex to google), README documentation updates, and package.json script changes that appear unrelated to fixing the HMR/store registration issue in #57. Separate the AI SDK migration and documentation updates into a distinct PR. Focus this PR solely on resolving the duplicate store registration crash to maintain clear issue-to-PR traceability.
Title check ❓ Inconclusive The PR title 'Feature/issue 57/add database functions migration' relates to the primary changes (database migration, functions, and schema updates) but does not address the actual issue objective of fixing HMR/duplicate store registration crashes. The title describes the implementation approach (adding DB functions) rather than the problem being solved (fixing local dev crashes). Consider clarifying whether this PR truly addresses issue #57's HMR crash or if it's preparatory work.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 markdownlint-cli2 (0.18.1)
README.md

markdownlint-cli2 v0.18.1 (markdownlint v0.38.0)
Finding: README.md
Linting: 1 file(s)
Summary: 20 error(s)
Error: EACCES: permission denied, open '/markdownlint-cli2-results.json'
at async open (node:internal/fs/promises:640:25)
at async Object.writeFile (node:internal/fs/promises:1214:14)
at async Promise.all (index 0)
at async outputSummary (file:///usr/local/lib/node_modules/markdownlint-cli2/markdownlint-cli2.mjs:877:5)
at async main (file:///usr/local/lib/node_modules/markdownlint-cli2/markdownlint-cli2.mjs:1053:25)
at async file:///usr/local/lib/node_modules/markdownlint-cli2/markdownlint-cli2-bin.mjs:12:22 {
errno: -13,
code: 'EACCES',
syscall: 'open',
path: '/markdownlint-cli2-results.json'
}


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

@urjitc
urjitc force-pushed the feature/issue-57/add-database-functions-migration branch from b1724e2 to 07e4ab3 Compare January 19, 2026 06:16

@ellipsis-dev ellipsis-dev Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed everything up to b1724e2 in 1 minute and 58 seconds. Click for details.
  • Reviewed 8883 lines of code in 23 files
  • Skipped 0 files when reviewing.
  • Skipped posting 7 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. drizzle/0000_sad_wallflower.sql:1
  • Draft comment:
    The baseline migration script correctly creates all the required tables and indexes with proper defaults and constraints. Ensure that these definitions match those in the ORM schema to avoid runtime mismatches.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
2. drizzle/meta/0000_snapshot.json:1
  • Draft comment:
    The snapshot JSON now reflects a single baseline migration (0000_sad_wallflower) which helps prevent duplicate registration of the schema on a fresh clone. This cleanup should mitigate the duplicate store issue.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative, explaining what the snapshot JSON now reflects and the purpose of the change. It does not provide a suggestion, ask for confirmation, or point out a potential issue.
3. drizzle/meta/_journal.json:5
  • Draft comment:
    The journal file now contains only one entry tagged '0000_sad_wallflower', indicating that old, possibly duplicate, migration entries have been removed. This is a good step toward preventing duplicate store initialization.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative and does not provide any actionable feedback or suggestions for improvement. It simply states an observation about the changes made in the PR.
4. package.json:16
  • Draft comment:
    The addition of the 'db:setup' script (set to run 'drizzle-kit migrate') helps ensure that database migrations run in a controlled and predictable manner on a fresh clone. Verify that this script aligns with your deployment and local development practices.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% The comment is asking the PR author to verify alignment with deployment and development practices, which is against the rules. It doesn't provide a specific suggestion or point out a clear issue.
5. src/app/api/cards/from-message/route.ts:7
  • Draft comment:
    The refactor to import and use the 'google' provider (instead of 'vertex') and calling google('gemini-2.5-flash') is consistent. Ensure that all downstream calls relying on this AI model are compatible with the new library interface.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is asking the PR author to ensure compatibility with downstream calls, which is a form of asking them to double-check their work. This violates the rule against asking the author to ensure behavior is intended or tested. The comment does not provide a specific suggestion or point out a specific issue, making it not useful according to the guidelines.
6. src/lib/ai/workers.ts:6
  • Draft comment:
    The AI workers now consistently use the 'google' API for different operations. Note the change in extracting provider metadata (using providerMetadata?.google). This ensures that grounding information and tool executions are correctly handled.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative, as it is simply noting a change and explaining what it does without providing any actionable feedback or suggestions. It does not align with the rules for good comments, which should provide specific suggestions or ask for confirmation on potentially unintended changes.
7. src/lib/db/schema.ts:101
  • Draft comment:
    Index operator corrections in the schema (e.g. using 'text_ops' for userId and 'int4_ops' for integer columns) now better reflect the underlying data types. Also, the workspace events index now uses int4_ops for version, matching its type. This improves query performance and consistency.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative, as it describes the changes made in the code without suggesting any improvements or asking for clarifications. It doesn't align with the rules for useful comments, which should provide actionable feedback or raise specific concerns.

Workflow ID: wflow_0OTig3Hn1ehvRive

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

@ellipsis-dev ellipsis-dev Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed 07e4ab3 in 1 minute and 22 seconds. Click for details.
  • Reviewed 80 lines of code in 3 files
  • Skipped 0 files when reviewing.
  • Skipped posting 7 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. README.md:135
  • Draft comment:
    The update to use 'your database's SQL editor' instead of 'Supabase SQL Editor' improves generality. This wording is clear.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
2. src/app/api/cards/from-message/route.ts:7
  • Draft comment:
    The import change from '@ai-sdk/google-vertex/edge' to '@ai-sdk/google' is correctly applied. Ensure the new google module supports the same API interface as before.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
3. src/app/api/cards/from-message/route.ts:80
  • Draft comment:
    The generateText call now uses google("gemini-2.5-flash"). Verify that the model string and configuration remain valid with the new integration.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
4. src/lib/ai/workers.ts:46
  • Draft comment:
    Updating provider metadata extraction from 'providerMetadata?.vertex' to 'providerMetadata?.google' is appropriate. Confirm that the underlying metadata now uses the 'google' key.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
5. src/lib/ai/workers.ts:92
  • Draft comment:
    In the code execution worker, the call to google.tools.codeExecution() is correctly replacing the vertex equivalent. Ensure that all tool-specific methods work as expected with the new module.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
6. src/lib/ai/workers.ts:740
  • Draft comment:
    The textSelectionWorker now uses google("gemini-2.5-flash") for generating text. This update is consistent; just double-check that prompt merging with additionalContext behaves as expected.
  • Reason this comment was not posted:
    Confidence changes required: 0% <= threshold 50% None
7. General:0
  • Draft comment:
    The PR title mentions resolving a duplicate store registration issue (#57) related to local development crashes, but none of the visible diffs address store registration or HMR behavior. Please confirm that the database functions migration or any additional changes addressing store duplication are included or that this diff fully resolves the issue.
  • Reason this comment was not posted:
    Comment was not on a location in the diff, so it can't be submitted as a review comment.

Workflow ID: wflow_OodDaRd1mOMbNjyC

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

@greptile-apps

greptile-apps Bot commented Jan 19, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR consolidates database migrations and simplifies the AI provider setup to resolve the fresh clone local development issue.

Key Changes:

  • Consolidated 8 separate migration files into a single comprehensive initial migration (0000_sad_wallflower.sql) that includes all tables, indexes, row-level security policies, and critical database functions
  • Replaced Google Vertex AI SDK with Google Generative AI SDK throughout the codebase, simplifying authentication from service account credentials to a single API key
  • Fixed operator class mismatches in database indexes where column types didn't match the specified operators (e.g., uuid_ops on integer columns)
  • Added db:setup npm script as the recommended approach for fresh database initialization
  • Improved README documentation with detailed environment variable requirements and clear distinction between db:setup (with migrations) and db:push (schema sync only)

Database Functions Included:
The migration now properly creates essential database functions required for workspace operations:

  • get_workspace_version() - retrieve current version
  • append_workspace_event() - append events with optimistic locking
  • create_workspace_snapshot() - create and manage snapshots
  • get_latest_snapshot() / get_latest_snapshot_fast() - retrieve snapshots
  • get_workspace_events_fast() - fetch events efficiently
  • needs_snapshot() - determine snapshot requirements

This addresses the root cause from issue #57 where fresh clones would fail because the database functions weren't being created by db:push.

Confidence Score: 5/5

  • This PR is safe to merge with minimal risk
  • The changes are well-structured and address a critical issue. The migration consolidation is clean, the Google AI SDK migration is straightforward (vertex to generative AI is a supported path), and the database index fixes correct actual schema mismatches. The README improvements add clarity for new contributors. All database functions are properly defined and are already being used in the existing codebase.
  • No files require special attention

Important Files Changed

Filename Overview
drizzle/0000_sad_wallflower.sql New consolidated initial migration with all tables, indexes, policies, and database functions
README.md Improved environment variable documentation and added db:setup instructions
src/lib/ai/workers.ts Replaced Google Vertex AI with Google Generative AI SDK throughout workers
package.json Added db:setup script for running migrations on fresh database
src/lib/db/schema.ts Fixed operator classes on database indexes to match correct column types

Sequence Diagram

sequenceDiagram
    participant Dev as Developer
    participant CLI as pnpm CLI
    participant Drizzle as Drizzle Kit
    participant DB as PostgreSQL DB
    participant App as Next.js App
    participant Google as Google AI

    Note over Dev,Google: Fresh Database Setup Flow (New)
    
    Dev->>CLI: pnpm db:setup
    CLI->>Drizzle: drizzle-kit migrate
    Drizzle->>DB: Run 0000_sad_wallflower.sql
    DB->>DB: Create tables, indexes, policies
    DB->>DB: Create database functions:<br/>- get_workspace_version()<br/>- append_workspace_event()<br/>- create_workspace_snapshot()<br/>- get_latest_snapshot()<br/>- needs_snapshot()
    Drizzle-->>Dev: ✅ Database initialized
    
    Note over Dev,Google: Application Runtime (Updated)
    
    Dev->>App: Start application
    App->>App: Load environment variables
    Note over App: Uses GOOGLE_GENERATIVE_AI_API_KEY
    
    App->>Google: Initialize @ai-sdk/google
    Note over Google: Replaced @ai-sdk/google-vertex
    
    App->>DB: Query workspace data
    DB->>DB: Execute custom functions
    DB-->>App: Return workspace state
    
    App->>Google: Generate AI responses<br/>(searchWorker, codeExecutionWorker)
    Google-->>App: AI results
    App-->>Dev: Application ready
Loading

@urjitc
urjitc force-pushed the feature/issue-57/add-database-functions-migration branch from 07e4ab3 to 01f9a13 Compare January 19, 2026 06:19
@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@drizzle/0000_sad_wallflower.sql`:
- Around line 132-134: The SELECT policies named "Users can read workspace
events they have access to" (on workspace_events) and "Users can read workspace
snapshots they have access to" (on workspace_snapshots) currently grant SELECT
TO public with no USING clause; replace that with a restrictive policy that does
not target public and adds a USING expression which enforces
membership/ownership or public-visibility checks (e.g., compare workspace owner
or membership/user id from auth with event/snapshot.workspace_id, or check a
workspace.is_public flag via a subquery/join). Update the two policy definitions
to remove TO public and add appropriate USING (...) conditions that reference
workspace_id, owner_id, membership tables or is_public so only authorized users
can read the rows.
- Around line 136-138: The workspace policies for INSERT, UPDATE, and SELECT on
"workspaces" are too permissive; change them to restrict actions to the
workspace owner by comparing the record's user_id to the current authenticated
user's id (auth.uid()). Specifically, update the policy named "Users can insert
their own workspaces" to include a WITH CHECK clause that enforces
new.row.user_id = auth.uid(), update "Users can update their own workspaces" to
include a USING clause (and/or WITH CHECK for updates) enforcing
existing.user_id = auth.uid() (and new.row.user_id = auth.uid() for updates),
and update "Users can view their own workspaces" to include a USING clause
enforcing user_id = auth.uid(); keep the existing DELETE owner-only policy
as-is.
- Around line 127-128: The policies "Users can update their own profile" and
"Users can view their own profile" on the table "user_profiles" are missing
USING clauses so authenticated users can access any profile; update those
policies to include a USING expression that restricts rows to the current user's
own profile (e.g., compare the authenticated principal id to the profile owner
id column such as auth.uid() = user_profiles.user_id or
current_setting('jwt.claims.user_id') = user_profiles.user_id depending on your
auth context) so both the UPDATE and SELECT policies only permit operations when
the row belongs to the requesting authenticated user.
🧹 Nitpick comments (1)
package.json (1)

16-18: Consider removing duplicate script or adding differentiation.

db:setup (Line 18) is identical to db:migrate (Line 16) - both run drizzle-kit migrate. While using db:setup for semantic clarity in the README is reasonable, having two identical scripts may cause confusion. Consider either:

  1. Aliasing: "db:setup": "pnpm db:migrate" to make the relationship explicit
  2. Removing the duplicate if db:migrate is sufficient

Comment on lines +127 to +128
CREATE POLICY "Users can update their own profile" ON "user_profiles" AS PERMISSIVE FOR UPDATE TO "authenticated";--> statement-breakpoint
CREATE POLICY "Users can view their own profile" ON "user_profiles" AS PERMISSIVE FOR SELECT TO "authenticated";--> statement-breakpoint

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Missing USING clauses allow users to access any profile.

The UPDATE and SELECT policies for user_profiles lack USING clauses. Authenticated users can currently view and update any user's profile, not just their own.

🔒 Proposed fix to restrict access to own profile
-CREATE POLICY "Users can update their own profile" ON "user_profiles" AS PERMISSIVE FOR UPDATE TO "authenticated";--> statement-breakpoint
-CREATE POLICY "Users can view their own profile" ON "user_profiles" AS PERMISSIVE FOR SELECT TO "authenticated";--> statement-breakpoint
+CREATE POLICY "Users can update their own profile" ON "user_profiles" AS PERMISSIVE FOR UPDATE TO "authenticated" USING ((( SELECT (auth.jwt() ->> 'sub'::text)) = user_id));--> statement-breakpoint
+CREATE POLICY "Users can view their own profile" ON "user_profiles" AS PERMISSIVE FOR SELECT TO "authenticated" USING ((( SELECT (auth.jwt() ->> 'sub'::text)) = user_id));--> statement-breakpoint
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
CREATE POLICY "Users can update their own profile" ON "user_profiles" AS PERMISSIVE FOR UPDATE TO "authenticated";--> statement-breakpoint
CREATE POLICY "Users can view their own profile" ON "user_profiles" AS PERMISSIVE FOR SELECT TO "authenticated";--> statement-breakpoint
CREATE POLICY "Users can update their own profile" ON "user_profiles" AS PERMISSIVE FOR UPDATE TO "authenticated" USING ((( SELECT (auth.jwt() ->> 'sub'::text)) = user_id));--> statement-breakpoint
CREATE POLICY "Users can view their own profile" ON "user_profiles" AS PERMISSIVE FOR SELECT TO "authenticated" USING ((( SELECT (auth.jwt() ->> 'sub'::text)) = user_id));--> statement-breakpoint
🤖 Prompt for AI Agents
In `@drizzle/0000_sad_wallflower.sql` around lines 127 - 128, The policies "Users
can update their own profile" and "Users can view their own profile" on the
table "user_profiles" are missing USING clauses so authenticated users can
access any profile; update those policies to include a USING expression that
restricts rows to the current user's own profile (e.g., compare the
authenticated principal id to the profile owner id column such as auth.uid() =
user_profiles.user_id or current_setting('jwt.claims.user_id') =
user_profiles.user_id depending on your auth context) so both the UPDATE and
SELECT policies only permit operations when the row belongs to the requesting
authenticated user.

Comment on lines +132 to +134
CREATE POLICY "Users can read workspace events they have access to" ON "workspace_events" AS PERMISSIVE FOR SELECT TO public;--> statement-breakpoint
CREATE POLICY "Service role can insert workspace snapshots" ON "workspace_snapshots" AS PERMISSIVE FOR INSERT TO public WITH CHECK (true);--> statement-breakpoint
CREATE POLICY "Users can read workspace snapshots they have access to" ON "workspace_snapshots" AS PERMISSIVE FOR SELECT TO public;--> statement-breakpoint

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Open SELECT policies expose workspace data to everyone.

The SELECT policies for workspace_events and workspace_snapshots are granted to public with no USING clause, allowing anyone (including unauthenticated users) to read all events and snapshots. Consider restricting access based on workspace ownership or public workspace status.

🤖 Prompt for AI Agents
In `@drizzle/0000_sad_wallflower.sql` around lines 132 - 134, The SELECT policies
named "Users can read workspace events they have access to" (on
workspace_events) and "Users can read workspace snapshots they have access to"
(on workspace_snapshots) currently grant SELECT TO public with no USING clause;
replace that with a restrictive policy that does not target public and adds a
USING expression which enforces membership/ownership or public-visibility checks
(e.g., compare workspace owner or membership/user id from auth with
event/snapshot.workspace_id, or check a workspace.is_public flag via a
subquery/join). Update the two policy definitions to remove TO public and add
appropriate USING (...) conditions that reference workspace_id, owner_id,
membership tables or is_public so only authorized users can read the rows.

Comment on lines +136 to +138
CREATE POLICY "Users can insert their own workspaces" ON "workspaces" AS PERMISSIVE FOR INSERT TO "authenticated";--> statement-breakpoint
CREATE POLICY "Users can update their own workspaces" ON "workspaces" AS PERMISSIVE FOR UPDATE TO "authenticated";--> statement-breakpoint
CREATE POLICY "Users can view their own workspaces" ON "workspaces" AS PERMISSIVE FOR SELECT TO "authenticated";--> statement-breakpoint

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Workspace policies allow unauthorized access.

The INSERT, UPDATE, and SELECT policies for workspaces lack proper restrictions. Only the DELETE policy (line 135) correctly restricts access to the owner. This allows authenticated users to:

  • Insert workspaces with any user_id
  • Update any workspace
  • View any workspace
🔒 Proposed fix to restrict workspace access to owners
-CREATE POLICY "Users can insert their own workspaces" ON "workspaces" AS PERMISSIVE FOR INSERT TO "authenticated";--> statement-breakpoint
-CREATE POLICY "Users can update their own workspaces" ON "workspaces" AS PERMISSIVE FOR UPDATE TO "authenticated";--> statement-breakpoint
-CREATE POLICY "Users can view their own workspaces" ON "workspaces" AS PERMISSIVE FOR SELECT TO "authenticated";--> statement-breakpoint
+CREATE POLICY "Users can insert their own workspaces" ON "workspaces" AS PERMISSIVE FOR INSERT TO "authenticated" WITH CHECK ((( SELECT (auth.jwt() ->> 'sub'::text)) = user_id));--> statement-breakpoint
+CREATE POLICY "Users can update their own workspaces" ON "workspaces" AS PERMISSIVE FOR UPDATE TO "authenticated" USING ((( SELECT (auth.jwt() ->> 'sub'::text)) = user_id));--> statement-breakpoint
+CREATE POLICY "Users can view their own workspaces" ON "workspaces" AS PERMISSIVE FOR SELECT TO "authenticated" USING ((( SELECT (auth.jwt() ->> 'sub'::text)) = user_id));--> statement-breakpoint
🤖 Prompt for AI Agents
In `@drizzle/0000_sad_wallflower.sql` around lines 136 - 138, The workspace
policies for INSERT, UPDATE, and SELECT on "workspaces" are too permissive;
change them to restrict actions to the workspace owner by comparing the record's
user_id to the current authenticated user's id (auth.uid()). Specifically,
update the policy named "Users can insert their own workspaces" to include a
WITH CHECK clause that enforces new.row.user_id = auth.uid(), update "Users can
update their own workspaces" to include a USING clause (and/or WITH CHECK for
updates) enforcing existing.user_id = auth.uid() (and new.row.user_id =
auth.uid() for updates), and update "Users can view their own workspaces" to
include a USING clause enforcing user_id = auth.uid(); keep the existing DELETE
owner-only policy as-is.

@ellipsis-dev ellipsis-dev Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed 01f9a13 in 1 minute and 54 seconds. Click for details.
  • Reviewed 92 lines of code in 4 files
  • Skipped 0 files when reviewing.
  • Skipped posting 7 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. README.md:132
  • Draft comment:
    Clarified the note to use 'your database's SQL editor' instead of a specific tool for greater generality.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
2. package.json:31
  • Draft comment:
    Removed the '@ai-sdk/google-vertex' dependency. Confirm that no components still rely on it, especially regarding store registration issues.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% The comment is asking the PR author to confirm that no components rely on a removed dependency. This is a request for confirmation, which violates the rule against asking the author to confirm their intention or to double-check things.
3. src/app/api/cards/from-message/route.ts:7
  • Draft comment:
    Updated the import to use 'google' from '@ai-sdk/google' instead of 'vertex' to ensure consistency with the new provider integration.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative, explaining a change that was made without asking for confirmation or suggesting improvements. It doesn't align with the rules for good comments.
4. src/app/api/cards/from-message/route.ts:80
  • Draft comment:
    Changed the model invocation from vertex('gemini-2.5-flash') to google('gemini-2.5-flash').
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative, as it only states what was changed without providing any suggestion, question, or potential issue related to the change. It doesn't ask for confirmation or suggest any improvements.
5. src/lib/ai/workers.ts:46
  • Draft comment:
    Updated metadata extraction to use the 'google' property instead of 'vertex' to correctly access the grounding metadata.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative, explaining a change that was made. It doesn't provide a suggestion, ask for confirmation, or point out a potential issue. According to the rules, purely informative comments should be removed.
6. src/lib/ai/workers.ts:92
  • Draft comment:
    Replaced the model invocation and tool usage in codeExecutionWorker to use google('gemini-2.5-flash') and google.tools.codeExecution, ensuring consistency.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative, describing what was changed without providing any actionable feedback or suggestions. It does not ask for confirmation or suggest improvements.
7. src/lib/ai/workers.ts:740
  • Draft comment:
    Updated textSelectionWorker to use google('gemini-2.5-flash') for AI operations, aligning it with the other workers.
  • Reason this comment was not posted:
    Comment did not seem useful. Confidence is useful = 0% <= threshold 50% This comment is purely informative, as it only describes what was done without providing any suggestions, questions, or issues to address. It doesn't align with the rules for useful comments.

Workflow ID: wflow_IqqQi2REe6EJkihW

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

@urjitc
urjitc merged commit aefd46c into main Jan 19, 2026
7 checks passed
@github-project-automation github-project-automation Bot moved this from Backlog to Done in Dev Board Jan 19, 2026
@urjitc
urjitc deleted the feature/issue-57/add-database-functions-migration branch January 19, 2026 06:24

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

2 issues found across 23 files

Prompt for AI agents (all issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="drizzle/meta/0000_snapshot.json">

<violation number="1" location="drizzle/meta/0000_snapshot.json:201">
P3: `idx_session_token` is redundant because the existing `session_token_unique` constraint already creates an index on `token`. Consider removing this extra index to avoid duplicate index maintenance.</violation>

<violation number="2" location="drizzle/meta/0000_snapshot.json:305">
P3: `idx_user_email` duplicates the unique index created by `user_email_unique`. Removing the redundant index will reduce storage and write overhead.</violation>
</file>

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

},
"indexes": {},
"indexes": {
"idx_user_email": {

@cubic-dev-ai cubic-dev-ai Bot Jan 19, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3: idx_user_email duplicates the unique index created by user_email_unique. Removing the redundant index will reduce storage and write overhead.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At drizzle/meta/0000_snapshot.json, line 305:

<comment>`idx_user_email` duplicates the unique index created by `user_email_unique`. Removing the redundant index will reduce storage and write overhead.</comment>

<file context>
@@ -244,7 +301,24 @@
       },
-      "indexes": {},
+      "indexes": {
+        "idx_user_email": {
+          "name": "idx_user_email",
+          "columns": [
</file context>
Fix with Cubic

"method": "btree",
"with": {}
},
"idx_session_token": {

@cubic-dev-ai cubic-dev-ai Bot Jan 19, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P3: idx_session_token is redundant because the existing session_token_unique constraint already creates an index on token. Consider removing this extra index to avoid duplicate index maintenance.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At drizzle/meta/0000_snapshot.json, line 201:

<comment>`idx_session_token` is redundant because the existing `session_token_unique` constraint already creates an index on `token`. Consider removing this extra index to avoid duplicate index maintenance.</comment>

<file context>
@@ -164,7 +181,40 @@
+          "method": "btree",
+          "with": {}
+        },
+        "idx_session_token": {
+          "name": "idx_session_token",
+          "columns": [
</file context>
Fix with Cubic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Local dev crashes on fresh clone (duplicate store registration)

1 participant