Skip to content

Conversation

maparent
Copy link
Collaborator

@maparent maparent commented Jun 9, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new "PlatformAccount" model to represent accounts across different platforms, supporting additional metadata, agent types, and permissions.
    • Added support for "AgentIdentifier" entities, allowing multiple identifiers (such as email or ORCID) to be linked to a platform account.
    • Enhanced API endpoints for managing platform accounts and agent identifiers.
  • Improvements

    • Updated all references from legacy agent and account models to the new platform account structure.
    • Standardized platform representation using enums (e.g., "Roam", "Obsidian") instead of separate tables.
    • Improved validation and error handling for account and identifier-related API endpoints.
  • Removals

    • Removed legacy "Agent", "Person", "AutomatedAgent", "Account", and "Platform" models and related API endpoints.
    • Deprecated old API routes for managing persons, accounts, and platforms.
  • Database

    • Migrated and refactored database schema to support the new account-centric model.
    • Updated foreign key relationships and enums to align with new platform account and identifier structures.

Copy link

vercel bot commented Jun 9, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
discourse-graph ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 9, 2025 6:04pm

Copy link
Contributor

coderabbitai bot commented Jun 9, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

This change implements a major schema and API refactor, replacing the previous agent-centric model with a platform account-centric model. It introduces new database entities and enums, updates API endpoints to align with the new structure, removes legacy agent and person logic, and migrates all relevant foreign keys and validation logic to use platform accounts and identifiers.

Changes

File(s) / Path(s) Change Summary
apps/website/app/api/supabase/account/route.ts, apps/website/app/api/supabase/person/[id].ts, apps/website/app/api/supabase/person/route.ts, apps/website/app/api/supabase/platform/route.ts Removed API routes and handlers for legacy Account, Person, and Platform entities, including POST, GET, DELETE, and OPTIONS handlers.
apps/website/app/api/supabase/agent_identifier/[id].ts, apps/website/app/api/supabase/platform_account/[id].ts Updated GET and DELETE handlers to target AgentIdentifier and PlatformAccount entities instead of legacy Account, Person, or Platform entities.
apps/website/app/api/supabase/agent_identifier/route.ts Added POST and OPTIONS handlers for AgentIdentifier entity, including input validation and upsert logic.
apps/website/app/api/supabase/platform_account/route.ts Added POST and OPTIONS handlers for PlatformAccount entity with strict validation and upsert logic.
apps/website/app/api/supabase/space/route.ts Changed validation and processing to use string platform field ("Roam" or "Obsidian") instead of numeric platform_id.
packages/database/schema.puml, packages/database/schema.yaml Refactored schema: removed Agent, Person, AutomatedAgent, and Account; introduced PlatformAccount, AgentIdentifier, Users, and new enums. Updated all associations and references to use PlatformAccount.
packages/database/supabase/schemas/account.sql, packages/database/supabase/schemas/agent.sql Removed agent-related tables and constraints; added PlatformAccount and AgentIdentifier tables and enums; updated foreign keys.
packages/database/supabase/schemas/base.sql, packages/database/supabase/schemas/concept.sql, packages/database/supabase/schemas/content.sql, packages/database/supabase/schemas/contributor.sql, packages/database/supabase/schemas/space.sql Updated enum values, foreign key references, and table definitions to use PlatformAccount and platform enums. Removed Platform table, replaced with enum.
packages/database/supabase/config.toml Removed agent.sql schema from migration list.
packages/database/supabase/migrations/20250603144146_account_centric.sql Major migration: renames, drops, and creates tables and enums to implement the account-centric model. Migrates data, updates foreign keys, and cleans up obsolete structures.
packages/database/supabase/migrations/20250605083319_alpha_upload.sql, packages/database/supabase/migrations/20250605133006_update_alpha_functions.sql Added and updated PL/pgSQL functions for discourse node upsert and synchronization, adapted to new schema.
packages/database/types.gen.ts Regenerated types: removed legacy agent/account/platform types, added PlatformAccount and AgentIdentifier, updated all relationships and enums.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant SupabaseDB

    Client->>API: POST /api/supabase/platform_account {name, platform, ...}
    API->>API: Validate input (name, platform, account_local_id, etc.)
    API->>SupabaseDB: Upsert PlatformAccount (by account_local_id + platform)
    SupabaseDB-->>API: PlatformAccount record
    API-->>Client: JSON response (success or error)
Loading
sequenceDiagram
    participant Client
    participant API
    participant SupabaseDB

    Client->>API: POST /api/supabase/agent_identifier {identifier_type, account_id, value, ...}
    API->>API: Validate input (identifier_type, account_id, value, trusted)
    API->>SupabaseDB: Upsert AgentIdentifier (by value + identifier_type + account_id)
    SupabaseDB-->>API: AgentIdentifier record
    API-->>Client: JSON response (success or error)
Loading

Suggested reviewers

  • mdroidian

Poem

In fields of code where schemas grow,
The agents hopped, but now must go.
Platform accounts, with names anew,
Bring structure crisp and tables true.
Identifiers linked with care,
The database breathes fresher air!
🐇✨


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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

linear bot commented Jun 9, 2025

@maparent
Copy link
Collaborator Author

maparent commented Jun 9, 2025

@CodeRabbit review

Copy link
Contributor

coderabbitai bot commented Jun 9, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@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: 18

🔭 Outside diff range comments (2)
packages/database/supabase/schemas/account.sql (1)

97-99: ⚠️ Potential issue

Critical: Access control table should have restricted permissions.

The SpaceAccess table controls authorization, yet grants ALL permissions to anonymous users. This could allow unauthorized users to grant themselves access to spaces.

Implement strict access controls:

-GRANT ALL ON TABLE public."SpaceAccess" TO anon;
+-- Anonymous users should not have any access to the access control table
 GRANT ALL ON TABLE public."SpaceAccess" TO authenticated;
 GRANT ALL ON TABLE public."SpaceAccess" TO service_role;
packages/database/schema.yaml (1)

448-452: ⚠️ Potential issue

Invalid default syntax for validation & epistemic_status
ifabsent: Validation(suggested) and ifabsent: EpistemicStatus(unknown) should use literal enum values (e.g. ifabsent: 'suggested', ifabsent: 'unknown').

🧹 Nitpick comments (11)
apps/website/app/api/supabase/agent_identifier/route.ts (1)

29-30: Specify radix parameter for parseInt.

When using parseInt, always specify the radix parameter to avoid unexpected behavior with strings starting with "0".

-  if (!account_id || Number.isNaN(Number.parseInt(account_id)))
+  if (!account_id || Number.isNaN(Number.parseInt(account_id, 10)))
apps/website/app/api/supabase/platform_account/route.ts (2)

34-38: Improve metadata validation error handling.

The current error message doesn't specify what went wrong with JSON parsing.

     else try {
       JSON.parse(metadata)
     } catch (error) {
-      return "metadata should be a JSON string";
+      return `metadata should be a valid JSON string: ${error instanceof Error ? error.message : 'Invalid JSON'}`;
     }

45-47: Extract UUID regex to a constant.

The UUID regex pattern should be extracted to a reusable constant for better maintainability.

+const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
 const accountValidator: ItemValidator<PlatformAccountDataInput> = (account: any) => {
   // ... existing code ...
   if (dg_account != undefined) {
     if (typeof dg_account != "string")
       return "dg_account should be a UUID string";
-    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-    if (!uuidRegex.test(dg_account))
+    if (!UUID_REGEX.test(dg_account))
       return "dg_account must be a valid UUID";
   }
packages/database/supabase/schemas/account.sql (1)

11-14: Consider future extensibility of identifier types.

The AgentIdentifierType enum currently only supports email and orcid. Consider whether additional identifier types might be needed in the future (e.g., github, linkedin, twitter, phone, etc.). Adding new enum values later requires a migration.

packages/database/schema.yaml (6)

167-173: Use boolean literals for trusted default
ifabsent: "false" should be an unquoted boolean (false).


301-301: Boolean default for obsolete
Change ifabsent: 'false' to the boolean literal false.


318-318: Arity default as string
Use numeric 0 for ifabsent instead of the string '0'.


329-329: is_schema default value
Switch ifabsent: 'false' to the boolean literal false.


438-440: Position default as string
Convert ifabsent: '0' for position into numeric 0.


444-445: Character position default
Replace ifabsent: '0' with numeric 0 for char_position.

packages/database/supabase/migrations/20250603144146_account_centric.sql (1)

92-99: Create AgentIdentifier table
Consider adding an index on account_id to improve lookup performance by account.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 901e473 and cbac1e4.

⛔ Files ignored due to path filters (1)
  • packages/database/schema.svg is excluded by !**/*.svg
📒 Files selected for processing (23)
  • apps/website/app/api/supabase/account/route.ts (0 hunks)
  • apps/website/app/api/supabase/agent_identifier/[id].ts (1 hunks)
  • apps/website/app/api/supabase/agent_identifier/route.ts (1 hunks)
  • apps/website/app/api/supabase/person/[id].ts (0 hunks)
  • apps/website/app/api/supabase/person/route.ts (0 hunks)
  • apps/website/app/api/supabase/platform/route.ts (0 hunks)
  • apps/website/app/api/supabase/platform_account/[id].ts (1 hunks)
  • apps/website/app/api/supabase/platform_account/route.ts (1 hunks)
  • apps/website/app/api/supabase/space/route.ts (2 hunks)
  • packages/database/schema.puml (3 hunks)
  • packages/database/schema.yaml (11 hunks)
  • packages/database/supabase/config.toml (0 hunks)
  • packages/database/supabase/migrations/20250603144146_account_centric.sql (1 hunks)
  • packages/database/supabase/migrations/20250605083319_alpha_upload.sql (1 hunks)
  • packages/database/supabase/migrations/20250605133006_update_alpha_functions.sql (1 hunks)
  • packages/database/supabase/schemas/account.sql (2 hunks)
  • packages/database/supabase/schemas/agent.sql (0 hunks)
  • packages/database/supabase/schemas/base.sql (2 hunks)
  • packages/database/supabase/schemas/concept.sql (1 hunks)
  • packages/database/supabase/schemas/content.sql (2 hunks)
  • packages/database/supabase/schemas/contributor.sql (2 hunks)
  • packages/database/supabase/schemas/space.sql (1 hunks)
  • packages/database/types.gen.ts (14 hunks)
💤 Files with no reviewable changes (6)
  • packages/database/supabase/config.toml
  • apps/website/app/api/supabase/platform/route.ts
  • apps/website/app/api/supabase/person/[id].ts
  • apps/website/app/api/supabase/person/route.ts
  • apps/website/app/api/supabase/account/route.ts
  • packages/database/supabase/schemas/agent.sql
🧰 Additional context used
🧬 Code Graph Analysis (3)
apps/website/app/api/supabase/agent_identifier/[id].ts (2)
apps/website/app/utils/supabase/apiUtils.ts (3)
  • makeDefaultGetHandler (92-113)
  • defaultOptionsHandler (79-84)
  • makeDefaultDeleteHandler (118-136)
apps/website/app/api/supabase/agent_identifier/route.ts (1)
  • OPTIONS (65-65)
apps/website/app/api/supabase/platform_account/[id].ts (2)
apps/website/app/api/supabase/agent_identifier/[id].ts (3)
  • GET (7-7)
  • OPTIONS (9-9)
  • DELETE (11-11)
apps/website/app/utils/supabase/apiUtils.ts (3)
  • makeDefaultGetHandler (92-113)
  • defaultOptionsHandler (79-84)
  • makeDefaultDeleteHandler (118-136)
apps/website/app/api/supabase/agent_identifier/route.ts (3)
apps/website/app/utils/supabase/server.ts (1)
  • createClient (5-47)
apps/website/app/api/supabase/agent_identifier/[id].ts (1)
  • OPTIONS (9-9)
apps/website/app/utils/supabase/apiUtils.ts (1)
  • defaultOptionsHandler (79-84)
🔇 Additional comments (49)
packages/database/supabase/schemas/base.sql (2)

27-27: LGTM! Enum value updated correctly for schema migration.

The change from 'Account' to 'PlatformAccount' aligns with the broader schema refactor described in the AI summary.


40-40: Good documentation improvement.

Adding a descriptive comment to the EntityType enum enhances code documentation and clarity.

packages/database/supabase/schemas/concept.sql (1)

73-73: LGTM! Foreign key correctly updated for schema migration.

The change from referencing Agent to PlatformAccount is consistent with the broader schema refactor. The cascade behaviors are appropriately preserved.

apps/website/app/api/supabase/agent_identifier/[id].ts (1)

7-7:

✅ Verification successful

Verify AgentIdentifier table exists in database schema.

The API endpoint changes from "Account" to "AgentIdentifier" align with the schema migration. However, ensure that the AgentIdentifier table is properly defined in the database schema.

Also applies to: 11-11


🏁 Script executed:

#!/bin/bash
# Description: Verify that AgentIdentifier table exists in the database schema
# Expected: Find AgentIdentifier table definition

rg -A 10 'CREATE TABLE.*AgentIdentifier' packages/database/supabase/schemas/

Length of output: 972


AgentIdentifier table confirmed in database schema

The public."AgentIdentifier" table is defined in packages/database/supabase/schemas/account.sql, so the updated GET and DELETE handlers using "AgentIdentifier" are valid and aligned with the schema.

packages/database/supabase/schemas/contributor.sql (1)

19-19: LGTM! Foreign keys correctly updated for schema migration.

Both contributor tables now properly reference PlatformAccount instead of Agent, maintaining consistency with the broader schema refactor. The cascade behaviors are appropriately preserved.

Also applies to: 39-39

apps/website/app/api/supabase/platform_account/[id].ts (1)

7-7: LGTM! Correct table name update for the new schema.

The changes correctly update the API handlers to use "PlatformAccount" instead of "Platform", aligning with the new account-centric data model. The utility functions will handle this table name appropriately.

Also applies to: 11-11

apps/website/app/api/supabase/space/route.ts (2)

20-32: LGTM! Correct migration from foreign key to enum approach.

The validation logic correctly updates from numeric platform_id to string platform enum, with proper validation for the "Roam" and "Obsidian" values that match the SQL schema definition.


38-38: LGTM! Consistent payload updates.

The destructuring and insertion payload correctly use the new platform enum field instead of platform_id, maintaining consistency with the validation changes.

Also applies to: 52-52

packages/database/supabase/schemas/space.sql (2)

1-6: LGTM! Good design pattern using enum for fixed values.

Creating a Platform enum with 'Roam' and 'Obsidian' values is an excellent design choice for fixed platform types, eliminating the need for a separate lookup table and foreign key constraints.


14-14: LGTM! Consistent schema update.

The Space table correctly uses the Platform enum type directly, which aligns perfectly with the API validation logic and simplifies the overall data model.

packages/database/supabase/schemas/content.sql (2)

34-36: LGTM! Correct foreign key migration for Document.author_id.

The foreign key constraint correctly updates to reference PlatformAccount instead of Agent, maintaining the CASCADE behavior for referential integrity.


86-88: LGTM! Consistent foreign key updates for Content table.

Both author_id and creator_id foreign key constraints correctly reference PlatformAccount instead of Agent, maintaining the appropriate SET NULL cascade behavior for optional relationships.

Also applies to: 91-93

packages/database/schema.puml (1)

5-95: Schema changes align with the platform-account-centric refactor.

The PlantUML schema correctly reflects the migration from the agent-centric model to the platform-account-centric model, with proper relationships and field definitions.

packages/database/types.gen.ts (1)

1-731: Generated types correctly reflect the schema changes.

The TypeScript type definitions properly represent the new PlatformAccount and AgentIdentifier tables, updated foreign key relationships, and new enum types. The migration from agent-centric to platform-account-centric model is accurately reflected.

packages/database/supabase/migrations/20250605083319_alpha_upload.sql (2)

3-137: Well-implemented deletion function with proper cascade handling.

The alpha_delete_by_source_local_ids function correctly handles cascading deletions across related tables and provides comprehensive error handling and progress reporting.


139-155: Simple and effective sync time retrieval.

The function correctly retrieves the last update time for a given space.

packages/database/schema.yaml (12)

69-70: New EntityType values for account-centric model
The additions of PlatformAccount and AgentIdentifier to the EntityType enum correctly reflect the refactor.


122-123: Introduce Users class
Defining a Users class for auth-managed accounts is appropriate and required for linking dg_account.


134-137: Define account_local_id slot
The account_local_id attribute is required and its description is clear.


154-158: Unique key for PlatformAccount
The composite unique key on (account_local_id, platform) aligns with the migration constraints.


158-160: Define AgentIdentifier class
Introducing AgentIdentifier with its description is correct.


161-166: AgentIdentifier attributes identifier_type & account
The required typing and foreign-key reference to PlatformAccount are accurate.


175-179: AgentIdentifier unique key
The primary key on (value, identifier_type, account) is well-defined.


186-186: Add platform slot to Space
Ensuring Space.platform references the Platform enum supports the new model.


197-197: Update SpaceAccess account reference
Mapping account to PlatformAccount correctly adapts the access control model.


252-252: Enhance Document description
The new Document description clarifies its role in the model.


351-351: Add ConceptSchema description
The ConceptSchema description addition is clear and valuable.


395-405: Update content-owner slots to PlatformAccount
Changing author, creator, and contributors slots to reference PlatformAccount fully implements the account-centric model.

packages/database/supabase/migrations/20250603144146_account_centric.sql (21)

10-18: Create AgentType enum
Defining AgentType with person, organization, and automated_agent correctly supports the new model.


20-29: Rename Person → PlatformAccount and update defaults
The table and index renames plus the id default are correct; verify that entity_id_seq continues sequencing without gaps.


30-30: Dropping obsolete table AutomatedAgent
Ensure no dependencies remain and backups are in place before this destructive change.


32-44: Add new columns to PlatformAccount
Columns platform, dg_account, and account_local_id lack defaults or NOT NULL until backfill; confirm null-handling and sequencing.


62-62: Deleting accounts without local IDs
Rows deleted by account_local_id IS NULL may include valid records. Confirm cleanup intent.


64-64: Unique index on (account_local_id, platform)
This enforces the intended uniqueness constraint.


67-67: Foreign key to auth.users
Adding dg_account FK with SET NULL and CASCADE is appropriate.


70-79: Update SpaceAccess foreign key
Re-pointing SpaceAccess.account_id to PlatformAccount is correct.


80-80: Dropping legacy Account table
Confirm all references are removed and data migration is complete.


83-91: Create AgentIdentifierType enum
Defining AgentIdentifierType for email and orcid matches the schema changes.


111-117: Migrate email/orcid into AgentIdentifier
The INSERTs assume no duplicates and complete data; verify uniqueness and handle collisions.


119-123: Set NOT NULL on new PlatformAccount columns
Applying constraints post-backfill is the correct order.


134-137: Remove deprecated platform_id and enforce not-null
Dropping platform_id and setting the new enum NOT NULL post-update is correct.


138-139: Drop Platform table and rename enum
The transition from table to enum Platform is handled properly.


141-146: Update Document FK to PlatformAccount
Adjusting Document.author_id to reference PlatformAccount maintains referential integrity.


148-153: Update Content author FK
Rebinding Content.author_id to PlatformAccount with appropriate cascade.


154-159: Update Content creator FK
The new constraint on Content.creator_id is correctly defined.


160-164: Update Concept author FK
Aligning Concept.author_id to the new model is accurate.


167-171: Update content_contributors FK
Updating the contributors join table to reference PlatformAccount is correct.


173-177: Update concept_contributors FK
The migration for concept_contributors is properly handled.


179-179: Dropping legacy Agent table
Ensure no residual data or dependencies exist before this drop.

Comment on lines 1 to 8
COMMENT ON TYPE public."EntityType" IS 'The type of an entity';

CREATE TYPE public."PlatformE" AS ENUM (
'Roam',
'Obsidian'
);

ALTER TYPE public."PlatformE" OWNER TO postgres;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

PlatformE enum casing mismatches schema
The SQL defines PlatformE with 'Roam'/'Obsidian' but the LinkML schema uses lowercase. Harmonize enum definitions to avoid runtime errors.

🤖 Prompt for AI Agents
In packages/database/supabase/migrations/20250603144146_account_centric.sql
lines 1 to 8, the enum values for PlatformE are capitalized ('Roam', 'Obsidian')
but the LinkML schema uses lowercase. Update the enum values in the SQL to
lowercase ('roam', 'obsidian') to match the schema and prevent runtime
mismatches.

Comment on lines 50 to 61
WITH s AS (SELECT agent_id, write_permission, active, account_local_id
FROM public."Account"
JOIN public."Platform" AS p ON (platform_id=p.id)
WHERE url='https://roamresearch.com')
UPDATE public."PlatformAccount" AS pa
SET platform = 'Roam',
active = s.active,
write_permission = s.write_permission,
account_local_id = s.account_local_id
FROM s
WHERE pa.id = s.agent_id;

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Backfill PlatformAccount data only for Roam
This update filters on url='https://roamresearch.com', leaving other platforms unpopulated. Extend logic or document support for multiple platforms.

🤖 Prompt for AI Agents
In packages/database/supabase/migrations/20250603144146_account_centric.sql
around lines 50 to 61, the update query only backfills PlatformAccount data for
the Roam platform by filtering on url='https://roamresearch.com'. To fix this,
either extend the query logic to handle multiple platforms by including
additional platform URLs and corresponding updates, or add documentation
clarifying that this migration currently supports only the Roam platform and
other platforms require separate handling.

Comment on lines 124 to 132
ALTER TABLE public."Space" ADD COLUMN platform public."PlatformE";

WITH s AS (SELECT id
FROM public."Platform"
WHERE url='https://roamresearch.com')
UPDATE public."Space" AS space
SET platform = 'Roam'
FROM s
WHERE platform_id = s.id;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Backfill Space.platform only for Roam
Mirroring the account backfill issue, this update only covers one platform. Extend for full support.

🤖 Prompt for AI Agents
In packages/database/supabase/migrations/20250603144146_account_centric.sql
around lines 124 to 132, the backfill update for the new Space.platform column
only sets the platform for the Roam platform. To fix this, extend the update
logic to backfill the platform column for all existing platforms by joining the
Space table with the Platform table on platform_id and setting Space.platform to
the corresponding PlatformE value for each platform, ensuring full coverage
instead of just one platform.

@maparent maparent changed the base branch from main to ENG-403-refactor-accounts June 9, 2025 16:43
@maparent
Copy link
Collaborator Author

maparent commented Jun 9, 2025

@CodeRabbit apology I should have set the base properly. The only file to analyze here is packages/database/supabase/migrations/20250605133006_update_alpha_functions.sql

Copy link
Contributor

coderabbitai bot commented Jun 9, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@maparent, no worries! Let me focus specifically on the migration file you mentioned.


🏁 Script executed:

#!/bin/bash
# Read the specific migration file content
cat packages/database/supabase/migrations/20250605133006_update_alpha_functions.sql

Length of output: 7671


@maparent, thanks for clarifying! I've reviewed the 20250605133006_update_alpha_functions.sql migration file. Here's my analysis:

Critical Issues

🚨 Major Bug - Undefined Variable:

-- Line 26: Declares v_caller_id
SELECT account_id INTO v_caller_id FROM public."AgentIdentifier" ...

-- Lines 84, 91: Uses undefined v_person_id
VALUES (v_space_id, v_person_id, v_node_created_at, ...)
VALUES (..., v_person_id, v_person_id, ...)

Fix needed:

-- Replace v_person_id with v_caller_id throughout the function
VALUES (v_space_id, v_caller_id, v_node_created_at, ...)
VALUES (..., v_caller_id, v_caller_id, ...)

Potential Issues

  1. Scale Type: Using 'document'::"Scale" but based on other functions, this might should be 'chunk_unit'::"Scale"

  2. Variable Declaration: Missing v_person_id in DECLARE section, but should use v_caller_id consistently

Good Practices Observed

Proper Error Handling: Good use of exception blocks for timestamp and vector parsing
Schema Integration: Correctly uses AgentIdentifier table for the new account-centric model
Upsert Pattern: Proper ON CONFLICT handling for both Document and Content tables
Sync Tracking: Updates sync_info table for synchronization metadata

Suggestions

  1. Immediate Fix: Replace all instances of v_person_id with v_caller_id
  2. Consider: Whether the scale should be 'chunk_unit' instead of 'document'
  3. Future Enhancement: The commented code for handling v_account_local_id looks well thought out for future iterations

The function shows good understanding of the new schema structure and includes thoughtful error handling, but the undefined variable bug would prevent it from executing successfully.

Copy link
Contributor

@mdroidian mdroidian left a comment

Choose a reason for hiding this comment

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

👍

@maparent maparent force-pushed the ENG-417-update-alpha-functions branch from 697fd35 to 9e489d1 Compare June 9, 2025 18:03
@maparent maparent changed the base branch from ENG-403-refactor-accounts to main June 9, 2025 18:07
@maparent maparent merged commit b73c313 into main Jun 9, 2025
3 checks passed
@github-project-automation github-project-automation bot moved this to Done in General Jun 9, 2025
@maparent maparent deleted the ENG-417-update-alpha-functions branch June 9, 2025 18:51
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.

2 participants