Files
superbrain/db/schema.sql
T
Andrew S Erwin f6158f58b5 Settings → Profile: editable particulars (name, bio, location, occupation, organization, website)
The Profile tab was a read-only avatar/name/email stub. It is now a real
form, modeled on the profile surfaces of GitHub/Slack/Nextcloud and scoped
to what a knowledge tool uses: display name, bio (280 chars with counter),
location, occupation, organization and website; email stays read-only
(sign-in identity). Copy explains where the name appears (shares) and
that public bookmark links never reveal identity.

Schema: migration 024_user_profile.sql + schema.sql add five nullable
text columns to User (db-converge green, fresh and upgraded paths).
models.User, userFromObject and the auth identity projection carry them,
so GET /api/me serves the stored truth (Go re-reads identity per request).

PATCH /api/me applies partial allowlisted edits: empty string clears to
NULL, rune-based caps (120/280/120/120/120), website <=2048 and http(s)
with a host; the answer is the fresh identity projection. User has no
version column (identity, not a collaborative collection), so this follows
the settings-save shape rather than the 409 contract; view-as writes stay
blocked by the middleware.

Session propagation: the auth.ts jwt callback gains an "update" trigger
that re-syncs name/email/image from Go via the same assertion the data
proxy signs (fail-quiet when Go is unreachable). The component calls
useSession().update({}) after a save — the {} argument is load-bearing:
in next-auth v5 a bare update() only re-fetches the session, it does not
fire the trigger (caught by the new browser regression). The top bar name
refreshes without a re-login.

Verified: full Go integration suite green incl. new TestProfileUpdate
(partial edits, clearing, rune caps, URL validation, auth gate);
db-converge green; web lint/SSR-lint/build 0 errors; full browser
regressions pass incl. the new profile round-trip (save → toast → top-bar
refresh → form values intact → Save re-disables on a clean baseline).
2026-11-20 17:09:32 -06:00

843 lines
36 KiB
PL/PgSQL

-- superbrain database schema
-- Derived from superbrain_porting_guide.md section 2 and prisma/schema.prisma.
-- IDs are text (CUID/UUID). CASCADE / SetNull per the guide.
-- Run against an EMPTY database. Never drops or recreates a database.
BEGIN;
-- Trigram indexes back the page search substring predicate (review PERF-2).
-- pg_trgm is a trusted extension, so the database owner can enable it.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
-- 2.1 legacy enum
CREATE TYPE "KanbanStatus" AS ENUM ('INBOX','TODO','IN_PROGRESS','DONE','ARCHIVED');
-- 2.1b Tenant (tenancy phase 1, see DESIGN_TENANCY_ENTITLEMENTS.md): the
-- billing/entitlement container. Every user belongs to exactly one tenant;
-- single-tenant deployments (self-hosted, core) use the implicit 'default'
-- row so no code path special-cases "no tenant". Plans are entitlement
-- data, never code forks.
CREATE TABLE "Tenant" (
id text PRIMARY KEY,
name text NOT NULL,
slug text NOT NULL UNIQUE,
plan text NOT NULL DEFAULT 'selfhosted' CHECK (plan IN ('free','standard','premium','core','selfhosted')),
status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','suspended','closed')),
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
-- 2.2 User
CREATE TABLE "User" (
id text PRIMARY KEY,
name text,
email text UNIQUE,
"emailVerified" timestamptz,
image text,
password text,
role text NOT NULL DEFAULT 'USER' CHECK (role IN ('USER','ADMIN')),
"tokenVersion" integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(),
"tenantId" text REFERENCES "Tenant"(id) ON DELETE SET NULL,
bio text,
location text,
occupation text,
organization text,
website text
);
-- 2.2b TenantMember, TenantEntitlement, QuotaUsage (tenancy phase 1).
-- Membership is 1:1 per user in phase 1 (UNIQUE userId). Entitlement rows
-- are per-tenant overrides on top of the in-code plan catalog; QuotaUsage
-- holds maintained counters (advisory-locked upserts) reconciled by the
-- writing code paths.
CREATE TABLE "TenantMember" (
id text PRIMARY KEY,
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
"userId" text NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE CASCADE,
role text NOT NULL DEFAULT 'member' CHECK (role IN ('owner','admin','member')),
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "TenantMember_tenantId_idx" ON "TenantMember"("tenantId");
CREATE TABLE "TenantEntitlement" (
id text PRIMARY KEY,
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
key text NOT NULL,
value text NOT NULL,
"createdAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("tenantId", key)
);
CREATE TABLE "QuotaUsage" (
"tenantId" text NOT NULL REFERENCES "Tenant"(id) ON DELETE CASCADE,
key text NOT NULL,
used bigint NOT NULL DEFAULT 0,
"updatedAt" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("tenantId", key)
);
-- 2.3 Account, Session, VerificationToken
CREATE TABLE "Account" (
id text PRIMARY KEY,
"userId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
type text NOT NULL,
provider text NOT NULL,
"providerAccountId" text NOT NULL,
"refresh_token" text,
"access_token" text,
"expires_at" int,
"token_type" text,
scope text,
"id_token" text,
"session_state" text,
UNIQUE(provider, "providerAccountId")
);
CREATE INDEX "Account_userId_idx" ON "Account"("userId");
CREATE TABLE "Session" (
id text PRIMARY KEY,
"sessionToken" text NOT NULL UNIQUE,
"userId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
expires timestamptz NOT NULL
);
CREATE INDEX "Session_userId_idx" ON "Session"("userId");
CREATE TABLE "VerificationToken" (
identifier text NOT NULL,
token text NOT NULL UNIQUE,
expires timestamptz NOT NULL,
UNIQUE(identifier, token)
);
-- 2.3b PasswordResetToken: single-use, hashed, short-lived password-reset
-- tokens (self-service "forgot password"). Only the SHA-256 hash of the
-- emailed token is stored; issuing a new token deletes the user's previous
-- ones and consuming one marks it used inside a row-locked transaction.
CREATE TABLE "PasswordResetToken" (
id text PRIMARY KEY,
"userId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"tokenHash" text NOT NULL UNIQUE,
"expiresAt" timestamptz NOT NULL,
"usedAt" timestamptz,
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "PasswordResetToken_userId_idx" ON "PasswordResetToken"("userId");
-- 2.4 Bookmark
CREATE TABLE "Bookmark" (
id text PRIMARY KEY,
url text NOT NULL,
title text,
description text,
favicon text,
"ogImage" text,
"ogTitle" text,
"ogDescription" text,
notes text,
"dueDate" timestamptz,
"alertAt" timestamptz,
"alertSent" boolean NOT NULL DEFAULT false,
"kanbanStatus" "KanbanStatus" NOT NULL DEFAULT 'INBOX',
"kanbanColumnId" text,
-- Board ordering within a column. Server-normalized on every card move;
-- legacy rows default to 0 and fall back to updatedAt-desc ordering.
"kanbanPosition" integer NOT NULL DEFAULT 0,
"imapWatchEnabled" boolean NOT NULL DEFAULT false,
"imapQuery" text,
"isPublic" boolean NOT NULL DEFAULT false,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"contactId" text,
-- Optimistic concurrency revision (review CR-04): every owner-driven PUT
-- (fields and tag replacement) requires the expected version and bumps it;
-- the column-deletion move bumps it too. Sharing and server-driven flags
-- (alertSent) are outside the contract — see API.md.
version integer NOT NULL DEFAULT 0,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "Bookmark_ownerId_idx" ON "Bookmark"("ownerId");
CREATE INDEX "Bookmark_ownerId_updatedAt_id_idx" ON "Bookmark"("ownerId","updatedAt" DESC,id DESC);
CREATE INDEX "Bookmark_contactId_idx" ON "Bookmark"("contactId");
CREATE INDEX "Bookmark_kanbanStatus_idx" ON "Bookmark"("kanbanStatus");
CREATE INDEX "Bookmark_kanbanColumnId_idx" ON "Bookmark"("kanbanColumnId");
CREATE INDEX "Bookmark_ownerId_kanbanColumnId_kanbanPosition_idx" ON "Bookmark"("ownerId","kanbanColumnId","kanbanPosition",id);
CREATE INDEX "Bookmark_dueDate_idx" ON "Bookmark"("dueDate");
CREATE INDEX "Bookmark_alertAt_idx" ON "Bookmark"("alertAt");
-- 2.5 Tag
CREATE TABLE "Tag" (
id text PRIMARY KEY,
name text NOT NULL,
color text NOT NULL DEFAULT '#6366f1',
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE(name, "ownerId")
);
CREATE INDEX "Tag_ownerId_idx" ON "Tag"("ownerId");
-- 2.6 BookmarkTag
CREATE TABLE "BookmarkTag" (
"bookmarkId" text NOT NULL REFERENCES "Bookmark"(id) ON DELETE CASCADE,
"tagId" text NOT NULL REFERENCES "Tag"(id) ON DELETE CASCADE,
PRIMARY KEY ("bookmarkId", "tagId")
);
CREATE INDEX "BookmarkTag_tagId_idx" ON "BookmarkTag"("tagId");
-- 2.7 BookmarkShare
CREATE TABLE "BookmarkShare" (
"bookmarkId" text NOT NULL REFERENCES "Bookmark"(id) ON DELETE CASCADE,
"userId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"createdAt" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("bookmarkId", "userId")
);
CREATE INDEX "BookmarkShare_userId_idx" ON "BookmarkShare"("userId");
-- 2.8 TagShare
CREATE TABLE "TagShare" (
"tagId" text NOT NULL REFERENCES "Tag"(id) ON DELETE CASCADE,
"userId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"createdAt" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("tagId", "userId")
);
CREATE INDEX "TagShare_userId_idx" ON "TagShare"("userId");
-- 2.9 Contact
CREATE TABLE "Contact" (
id text PRIMARY KEY,
uid text NOT NULL,
"displayName" text NOT NULL,
email text,
phone text,
"cardDavUrl" text,
-- CardDAV provenance (review CR-07): the address-book URL this contact was
-- imported from. Deletion reconciliation is scoped to it, so manually
-- created contacts (NULL) and other address books' imports are never
-- touched by a sync.
source text,
"userId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE(uid, "userId")
);
CREATE INDEX "Contact_userId_idx" ON "Contact"("userId");
ALTER TABLE "Bookmark" ADD CONSTRAINT "Bookmark_contactId_fkey"
FOREIGN KEY ("contactId") REFERENCES "Contact"(id) ON DELETE SET NULL;
-- 2.10 ImapConfig
CREATE TABLE "ImapConfig" (
id text PRIMARY KEY,
host text NOT NULL,
port int NOT NULL DEFAULT 993,
tls boolean NOT NULL DEFAULT true,
username text NOT NULL,
password text NOT NULL,
folder text NOT NULL DEFAULT 'INBOX',
"userId" text UNIQUE NOT NULL REFERENCES "User"(id) ON DELETE CASCADE
);
-- 2.11 KanbanColumn
CREATE TABLE "KanbanColumn" (
id text PRIMARY KEY,
label text NOT NULL,
color text NOT NULL DEFAULT '#64748b',
position int NOT NULL DEFAULT 0,
"key" text,
"userId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "KanbanColumn_userId_position_idx" ON "KanbanColumn"("userId", position);
-- Legacy status keys are unique per user (review L-12): ResolveColumnID picks
-- the first match, so duplicates would make the legacy fallback ambiguous.
CREATE UNIQUE INDEX "KanbanColumn_userId_key_idx" ON "KanbanColumn"("userId", "key") WHERE "key" IS NOT NULL;
-- Bookmark.kanbanColumnId -> KanbanColumn (SetNull)
ALTER TABLE "Bookmark" ADD CONSTRAINT "Bookmark_kanbanColumnId_fkey"
FOREIGN KEY ("kanbanColumnId") REFERENCES "KanbanColumn"(id) ON DELETE SET NULL;
-- 2.12 Page
CREATE TABLE "Page" (
id text PRIMARY KEY,
title text NOT NULL,
content text NOT NULL DEFAULT '',
icon text,
pinned boolean NOT NULL DEFAULT false,
position int NOT NULL DEFAULT 0,
-- Connected pages (phase 3): a page may live under another page. Deleting
-- the parent promotes its children to the top level instead of deleting
-- them; cycle rejection is enforced by the API.
"parentId" text REFERENCES "Page"(id) ON DELETE SET NULL,
-- Optimistic concurrency revision (review DATA-01): content saves bump it;
-- a stale base version in PATCH is rejected with 409.
version integer NOT NULL DEFAULT 1,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "Page_ownerId_position_idx" ON "Page"("ownerId", position);
CREATE INDEX "Page_parentId_idx" ON "Page"("parentId");
-- Index-backed substring search over the two searchable fields.
CREATE INDEX "Page_title_trgm_idx" ON "Page" USING gin (title gin_trgm_ops);
CREATE INDEX "Page_content_trgm_idx" ON "Page" USING gin (content gin_trgm_ops);
-- PageTag: pages carry tags like bookmarks do (owner-scoped writes; a tag
-- shared WITH you may be attached to your own pages). Powers the sidebar's
-- "Untagged Pages" list and drag-a-page-onto-a-tag. Cascades from both sides.
CREATE TABLE "PageTag" (
"pageId" text NOT NULL REFERENCES "Page"(id) ON DELETE CASCADE,
"tagId" text NOT NULL REFERENCES "Tag"(id) ON DELETE CASCADE,
PRIMARY KEY ("pageId", "tagId")
);
CREATE INDEX "PageTag_tagId_idx" ON "PageTag"("tagId");
-- 2.13 PageBookmark
CREATE TABLE "PageBookmark" (
"pageId" text NOT NULL REFERENCES "Page"(id) ON DELETE CASCADE,
"bookmarkId" text NOT NULL REFERENCES "Bookmark"(id) ON DELETE CASCADE,
position int NOT NULL DEFAULT 0,
"createdAt" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("pageId", "bookmarkId")
);
CREATE INDEX "PageBookmark_bookmarkId_idx" ON "PageBookmark"("bookmarkId");
-- 2.13b PageLink: resolved internal page links, rebuilt from page content on
-- every content save. Targets are only stored when the author owns the target
-- page, so a backlink can never reveal an inaccessible title. Self-links are
-- ignored by the writer and refused here as defense in depth.
CREATE TABLE "PageLink" (
"sourcePageId" text NOT NULL REFERENCES "Page"(id) ON DELETE CASCADE,
"targetPageId" text NOT NULL REFERENCES "Page"(id) ON DELETE CASCADE,
"createdAt" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("sourcePageId", "targetPageId"),
CONSTRAINT "PageLink_no_self" CHECK ("sourcePageId" <> "targetPageId")
);
CREATE INDEX "PageLink_targetPageId_idx" ON "PageLink"("targetPageId");
-- 2.13c PageRevision: server-side content history. A snapshot is recorded for
-- every committed content version (including restore, which is a new version)
-- so an old draft can be inspected and restored without ever rewriting the
-- past. Revision rows cascade with their page.
CREATE TABLE "PageRevision" (
id text PRIMARY KEY,
"pageId" text NOT NULL REFERENCES "Page"(id) ON DELETE CASCADE,
version integer NOT NULL,
title text NOT NULL,
content text NOT NULL,
icon text,
"createdAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("pageId", version)
);
CREATE INDEX "PageRevision_pageId_version_idx" ON "PageRevision"("pageId", version DESC);
-- 2.14 SignalSource
CREATE TABLE "SignalSource" (
id text PRIMARY KEY,
type text NOT NULL,
config jsonb NOT NULL DEFAULT '{}',
enabled boolean NOT NULL DEFAULT true,
"lastCheckedAt" timestamptz,
"lastStatus" text,
"bookmarkId" text NOT NULL REFERENCES "Bookmark"(id) ON DELETE CASCADE,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "SignalSource_bookmarkId_idx" ON "SignalSource"("bookmarkId");
CREATE INDEX "SignalSource_ownerId_idx" ON "SignalSource"("ownerId");
-- 2.14b SignalCheckpoint (review SYNC-02): durable per-source mailbox
-- ingestion state. A poll processes only UIDs newer than lastUid while
-- uidValidity matches; the checkpoint advances only after the batch's
-- signals are durably inserted. A uidValidity change resets ingestion.
CREATE TABLE "SignalCheckpoint" (
"sourceId" text PRIMARY KEY REFERENCES "SignalSource"(id) ON DELETE CASCADE,
"uidValidity" bigint NOT NULL,
"lastUid" bigint NOT NULL,
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
-- 2.15 Signal
CREATE TABLE "Signal" (
id text PRIMARY KEY,
"sourceType" text NOT NULL,
title text NOT NULL,
summary text,
url text,
"externalId" text,
"occurredAt" timestamptz NOT NULL DEFAULT now(),
read boolean NOT NULL DEFAULT false,
"sourceId" text,
"bookmarkId" text NOT NULL REFERENCES "Bookmark"(id) ON DELETE CASCADE,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"createdAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE("sourceId", "externalId")
);
CREATE INDEX "Signal_bookmarkId_occurredAt_idx" ON "Signal"("bookmarkId", "occurredAt");
CREATE INDEX "Signal_ownerId_occurredAt_idx" ON "Signal"("ownerId", "occurredAt");
ALTER TABLE "Signal" ADD CONSTRAINT "Signal_sourceId_fkey"
FOREIGN KEY ("sourceId") REFERENCES "SignalSource"(id) ON DELETE SET NULL;
-- 2.15b Notifications (DESIGN_NOTIFICATIONS.md, phase 1): user-owned
-- channels (secrets encrypted at rest via internal/crypto, never echoed),
-- rules (one channel per rule in phase 1), and fired notifications whose
-- UNIQUE("ruleId","dedupeKey") is the entire exactly-once story — the
-- scanner re-runs freely and conflicting inserts are no-ops.
CREATE TABLE "NotificationChannel" (
id text PRIMARY KEY,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
kind text NOT NULL CHECK (kind IN ('email','slack','matrix','telegram','signal')),
name text NOT NULL,
config jsonb NOT NULL DEFAULT '{}',
enabled boolean NOT NULL DEFAULT true,
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "NotificationChannel_ownerId_idx" ON "NotificationChannel"("ownerId");
CREATE TABLE "NotificationRule" (
id text PRIMARY KEY,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
name text NOT NULL,
trigger text NOT NULL CHECK (trigger IN ('signal_created','bookmark_due','share_received')),
config jsonb NOT NULL DEFAULT '{}',
"channelId" text NOT NULL REFERENCES "NotificationChannel"(id) ON DELETE CASCADE,
"cooldownMinutes" integer NOT NULL DEFAULT 60,
enabled boolean NOT NULL DEFAULT true,
"lastFiredAt" timestamptz,
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "NotificationRule_ownerId_idx" ON "NotificationRule"("ownerId");
CREATE TABLE "Notification" (
id text PRIMARY KEY,
"ruleId" text NOT NULL REFERENCES "NotificationRule"(id) ON DELETE CASCADE,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"dedupeKey" text NOT NULL,
title text NOT NULL,
body text NOT NULL,
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','sent','failed','suppressed')),
attempts integer NOT NULL DEFAULT 0,
"lastError" text,
"nextAttemptAt" timestamptz NOT NULL DEFAULT now(),
"sentAt" timestamptz,
"createdAt" timestamptz NOT NULL DEFAULT now(),
-- NULL = the rule owner (phase-1 behaviour); non-NULL = a targeted user,
-- delivered through that user's own enabled channel of the rule's kind.
"recipientId" text REFERENCES "User"(id) ON DELETE CASCADE,
UNIQUE ("ruleId", "dedupeKey")
);
CREATE INDEX "Notification_recipientId_idx" ON "Notification"("recipientId");
CREATE INDEX "Notification_ownerId_createdAt_idx" ON "Notification"("ownerId", "createdAt" DESC);
CREATE INDEX "Notification_delivery_due_idx" ON "Notification"("status", "nextAttemptAt")
WHERE status IN ('pending','failed');
-- 2.15c Agent automations ("hey superbrain", internal/agent): compiled,
-- user-confirmed tasks. The spec jsonb is the ONLY thing the engine
-- executes and it passes ValidateSpec on every write AND every load.
-- AgentRun is the audit trail (kept to a bounded tail per task).
CREATE TABLE "AgentTask" (
id text PRIMARY KEY,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
name text NOT NULL,
spec jsonb NOT NULL,
enabled boolean NOT NULL DEFAULT true,
status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','done','paused')),
"lastCheckedAt" timestamptz,
"lastFiredAt" timestamptz,
"fireCount" integer NOT NULL DEFAULT 0,
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "AgentTask_ownerId_idx" ON "AgentTask"("ownerId");
CREATE TABLE "AgentRun" (
id text PRIMARY KEY,
"taskId" text NOT NULL REFERENCES "AgentTask"(id) ON DELETE CASCADE,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
outcome text NOT NULL CHECK (outcome IN ('checked','fired','failed','skipped')),
detail text,
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "AgentRun_taskId_createdAt_idx" ON "AgentRun"("taskId", "createdAt" DESC);
-- 2.15d UserAiConfig: per-user BYO AI provider settings ("use your own
-- AI" plans). One row per user; the API key is encrypted at rest via
-- internal/crypto (same versioned format as IMAP passwords and
-- notification channel secrets) and masked in every API response. The
-- server-wide env key (AI_API_KEY) is the fallback and is plan-gated by
-- entitlements.AllowServerAI. "instructions" holds the user's optional
-- custom system instructions for the in-app assistant; server-owned
-- prompts (automation compiler, page extraction) never include them.
CREATE TABLE "UserAiConfig" (
id text PRIMARY KEY,
"ownerId" text NOT NULL UNIQUE REFERENCES "User"(id) ON DELETE CASCADE,
provider text NOT NULL CHECK (provider IN ('openai-compatible','anthropic','gemini')),
"baseUrl" text NOT NULL DEFAULT '',
model text NOT NULL,
instructions text NOT NULL DEFAULT '',
"apiKey" text NOT NULL,
enabled boolean NOT NULL DEFAULT true,
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
-- 2.15e ApiKey: personal long-lived Bearer credentials ("sb_...") for
-- machine clients — the superbrain-mcp server the federated mcpserver
-- gateway spawns, or any REST client. Only the SHA-256 hash is stored; the
-- plaintext is shown exactly once at creation and revocation is deletion of
-- the row. Keys are deliberately independent of User.tokenVersion ("sign
-- out everywhere" targets browser sessions; machine credentials must be
-- revoked explicitly). Issuance AND use are gated on the tenant's mcp-core
-- connector (entitlements catalog: core plan), so a downgrade stops
-- existing keys. See migration 017_api_keys.sql.
CREATE TABLE "ApiKey" (
id text PRIMARY KEY,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
name text NOT NULL,
prefix text NOT NULL,
"keyHash" text NOT NULL UNIQUE,
"lastUsedAt" timestamptz,
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "ApiKey_ownerId_idx" ON "ApiKey"("ownerId");
-- 2.15f McpConnection: user-registered outbound MCP servers (Superbrain as
-- an MCP CLIENT, Notion-style connections). Streamable HTTP or SSE; auth
-- none/bearer/custom header. Secrets encrypted at rest (internal/crypto,
-- same versioned format as IMAP passwords and notification channel
-- secrets), masked in every response, write-only. Dials go through
-- internal/netguard with no trusted-range exemption for user-supplied
-- hosts. Mutating PATCHes carry version (409 on stale). See migration
-- 018_mcp_connections.sql.
CREATE TABLE "McpConnection" (
id text PRIMARY KEY,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
name text NOT NULL,
url text NOT NULL,
transport text NOT NULL CHECK (transport IN ('streamable-http','sse')),
"authKind" text NOT NULL CHECK ("authKind" IN ('none','bearer','header')),
"headerName" text NOT NULL DEFAULT '',
secret text NOT NULL DEFAULT '',
enabled boolean NOT NULL DEFAULT true,
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "McpConnection_ownerId_idx" ON "McpConnection"("ownerId");
-- 2.16 AppSetting: server-owned singleton settings rows. 'adminBootstrap'
-- records that initial provisioning completed (review AUTH-06), so the
-- absence of a qualifying administrator never re-opens first-signup
-- promotion after a demotion or removal.
CREATE TABLE "AppSetting" (
key text PRIMARY KEY,
value jsonb NOT NULL DEFAULT '{}',
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
-- 2.16b Trash: recoverable deletions (trust phase). The row is a private
-- per-owner snapshot taken in the same transaction as the hard delete. It
-- keeps intrinsic data and owner-scoped relationships, but deliberately not
-- access grants (bookmark shares, public flags, collection shares): restoring
-- an item never resurrects a grant that was revoked while it sat in the bin.
CREATE TABLE "Trash" (
id text PRIMARY KEY,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
type text NOT NULL CHECK (type IN ('bookmark','page','collection')),
"originalId" text NOT NULL,
data jsonb NOT NULL,
"deletedAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE (type, "originalId")
);
CREATE INDEX "Trash_ownerId_deletedAt_idx" ON "Trash"("ownerId", "deletedAt" DESC);
-- 2.16 SharedDate
CREATE TABLE "SharedDate" (
id text PRIMARY KEY,
date date NOT NULL,
note text,
"creatorId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"recipientId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"createdAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "SharedDate_recipientId_idx" ON "SharedDate"("recipientId");
CREATE INDEX "SharedDate_creatorId_idx" ON "SharedDate"("creatorId");
CREATE INDEX "SharedDate_date_idx" ON "SharedDate"(date);
-- One row per creator/recipient/date (review L-3): re-sharing the same date
-- updates the note instead of duplicating calendar rows and notifications.
CREATE UNIQUE INDEX "SharedDate_creatorId_recipientId_date_idx" ON "SharedDate"("creatorId","recipientId",date);
CREATE INDEX "Bookmark_ownerId_alertAt_unsent_idx" ON "Bookmark"("ownerId","alertAt") WHERE NOT "alertSent";
-- 2.17 Collections (Notion-like upgrades phase 2; see 002_collections.sql for
-- the design decisions). Contextual workflow state: the same bookmark can
-- live in many collections with independent property values; membership
-- never broadens access and never owns the bookmark.
CREATE TABLE "Collection" (
id text PRIMARY KEY,
name text NOT NULL,
description text,
icon text,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "Collection_ownerId_idx" ON "Collection"("ownerId");
-- 2.17b CollectionShare: explicit, revocable read access to a collection.
-- Recipients get the narrowed bookmark projection for member bookmarks (via
-- BookmarkVisible); sharing therefore widens access only by the owner's
-- deliberate action, is disclosed in the share UI, and revocation removes
-- access immediately. Mutations remain owner-only.
CREATE TABLE "CollectionShare" (
"collectionId" text NOT NULL REFERENCES "Collection"(id) ON DELETE CASCADE,
"userId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
"createdAt" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("collectionId", "userId")
);
CREATE INDEX "CollectionShare_userId_idx" ON "CollectionShare"("userId");
CREATE TABLE "CollectionProperty" (
id text PRIMARY KEY,
"collectionId" text NOT NULL REFERENCES "Collection"(id) ON DELETE CASCADE,
name text NOT NULL,
type text NOT NULL CHECK (type IN ('TEXT','NUMBER','SELECT','MULTI_SELECT','DATE','CHECKBOX','URL','RELATION')),
position integer NOT NULL DEFAULT 0,
config jsonb NOT NULL DEFAULT '{}',
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("collectionId", name)
);
CREATE TABLE "CollectionItem" (
id text PRIMARY KEY,
"collectionId" text NOT NULL REFERENCES "Collection"(id) ON DELETE CASCADE,
"bookmarkId" text NOT NULL REFERENCES "Bookmark"(id) ON DELETE CASCADE,
"propertyValues" jsonb NOT NULL DEFAULT '{}',
position integer NOT NULL DEFAULT 0,
version integer NOT NULL DEFAULT 1,
"addedAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("collectionId", "bookmarkId")
);
CREATE INDEX "CollectionItem_bookmarkId_idx" ON "CollectionItem"("bookmarkId");
CREATE TABLE "CollectionView" (
id text PRIMARY KEY,
"collectionId" text NOT NULL REFERENCES "Collection"(id) ON DELETE CASCADE,
name text NOT NULL,
type text NOT NULL DEFAULT 'TABLE' CHECK (type IN ('TABLE','BOARD','CALENDAR','LIST')),
position integer NOT NULL DEFAULT 0,
filters jsonb NOT NULL DEFAULT '{"operator":"AND","clauses":[]}',
sorts jsonb NOT NULL DEFAULT '[]',
"groupByPropertyId" text REFERENCES "CollectionProperty"(id) ON DELETE SET NULL,
"displaySettings" jsonb NOT NULL DEFAULT '{}',
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "CollectionView_collectionId_idx" ON "CollectionView"("collectionId");
-- 2.17c WebDavConnection: user-connected WebDAV file shares (any service;
-- Settings → WebDAV). Credentials are Basic-auth: the username is stored in
-- the clear, the password/app-token encrypted at rest (internal/crypto, the
-- same versioned format as every other stored credential), masked in every
-- response, write-only. Dials go through internal/netguard with no
-- trusted-range exemption and no redirect following. Mutating PATCHes carry
-- version (409 on stale). collectionId is the materialized Collection the
-- share syncs INTO; losing/removing that collection detaches (SET NULL) and
-- the next sync re-materializes it. lastSyncedAt/lastError are engine-owned
-- bookkeeping and never bump version (AgentTask.lastCheckedAt precedent).
-- See migration 020_webdav_shares.sql.
CREATE TABLE "WebDavConnection" (
id text PRIMARY KEY,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
name text NOT NULL,
url text NOT NULL,
username text NOT NULL,
secret text NOT NULL,
"collectionId" text REFERENCES "Collection"(id) ON DELETE SET NULL,
enabled boolean NOT NULL DEFAULT true,
"lastSyncedAt" timestamptz,
"lastError" text,
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "WebDavConnection_ownerId_idx" ON "WebDavConnection"("ownerId");
-- 2.17d WebDavItem: path↔bookmark map for one share. Each synced file is a
-- Bookmark (its URL is the DAV location of the file) and this row is the
-- provenance reconciliation key (Contact.source precedent): UNIQUE per
-- (connectionId, path), path is relative to the share base and decoded.
-- bookmarkId ON DELETE SET NULL is deliberate: when the user deletes the
-- bookmark the row survives as a tombstone, so a sync never resurrects
-- something the owner removed. Deleting the connection cascades only this
-- map — the Collection and its bookmarks stay as ordinary user data.
CREATE TABLE "WebDavItem" (
id text PRIMARY KEY,
"connectionId" text NOT NULL REFERENCES "WebDavConnection"(id) ON DELETE CASCADE,
path text NOT NULL,
"bookmarkId" text REFERENCES "Bookmark"(id) ON DELETE SET NULL,
etag text NOT NULL DEFAULT '',
"sizeBytes" bigint NOT NULL DEFAULT 0,
"modifiedAt" timestamptz,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("connectionId", path)
);
CREATE INDEX "WebDavItem_connectionId_idx" ON "WebDavItem"("connectionId");
-- 2.17e CalDavConnection: user-connected CalDAV endpoints (any RFC 4791
-- service; Settings → CalDAV). A calendar is a Collection and every event a
-- Bookmark (URL = the event's DAV location). Credentials follow the house
-- discipline: username in the clear, password encrypted at rest, masked in
-- every response, write-only. Dials are netguard-pinned (ports 80/443
-- outside tests), Basic auth travels only in the Authorization header, and
-- redirects are refused. Mutating PATCHes carry version (409 on stale);
-- lastSyncedAt/lastError are engine-owned bookkeeping and never bump
-- version. Discovery accepts a calendar collection, a calendar home, or a
-- principal/root URL (following current-user-principal -> calendar-home-set).
-- See migration 021_caldav_calendars.sql.
CREATE TABLE "CalDavConnection" (
id text PRIMARY KEY,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
name text NOT NULL,
url text NOT NULL,
username text NOT NULL,
secret text NOT NULL,
enabled boolean NOT NULL DEFAULT true,
"lastSyncedAt" timestamptz,
"lastError" text,
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "CalDavConnection_ownerId_idx" ON "CalDavConnection"("ownerId");
-- 2.17f CalDavCalendar: one discovered calendar under a connection, with
-- the Collection it materializes into. Losing the collection (user delete,
-- FK SET NULL) makes the next sync re-create and re-link it; the calendar
-- disappearing server-side detaches (delete cascades membership rows'
-- ledger, never the bookmarks).
CREATE TABLE "CalDavCalendar" (
id text PRIMARY KEY,
"connectionId" text NOT NULL REFERENCES "CalDavConnection"(id) ON DELETE CASCADE,
href text NOT NULL,
"displayName" text NOT NULL DEFAULT '',
"collectionId" text REFERENCES "Collection"(id) ON DELETE SET NULL,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("connectionId", href)
);
CREATE INDEX "CalDavCalendar_connectionId_idx" ON "CalDavCalendar"("connectionId");
-- 2.17g CalDavEvent: path↔bookmark ledger per calendar, the exact WebDavItem
-- semantics: bookmarkId NULL = user-deleted tombstone (never resurrected);
-- the event key is its path relative to the calendar href; etag refreshes
-- never touch user-edited bookmark fields; window/vanished events detach
-- membership only. UNIQUE(calendarId, path).
CREATE TABLE "CalDavEvent" (
id text PRIMARY KEY,
"calendarId" text NOT NULL REFERENCES "CalDavCalendar"(id) ON DELETE CASCADE,
path text NOT NULL,
"bookmarkId" text REFERENCES "Bookmark"(id) ON DELETE SET NULL,
etag text NOT NULL DEFAULT '',
uid text NOT NULL DEFAULT '',
"startAt" timestamptz,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("calendarId", path)
);
CREATE INDEX "CalDavEvent_calendarId_idx" ON "CalDavEvent"("calendarId");
-- 2.17h CardDavConnection: user-connected CardDAV address books (any RFC
-- 6352 service; Settings -> CardDAV). The endpoint may be one address book or
-- a home holding several - each address book materializes as its own
-- Collection (2.17i) and every contact becomes a Bookmark (URL = the card's
-- DAV .vcf location, 2.17j). Credentials follow the house discipline:
-- username in the clear, password encrypted at rest, masked in every
-- response, write-only. Production dials are pinned to 443 (CardDAV carries
-- Basic-auth credentials; the existing contacts sync set that precedent in
-- review M-3/CR-01 and this surface keeps it), redirects are refused, and
-- user-supplied hosts get no netguard exemption. Mutating PATCHes carry
-- version (409 on stale); engine bookkeeping never bumps it. This is
-- separate from the single-configuration Contacts sync (Contact rows +
-- provenance) that powers contact-linking: same transport, different
-- product surface. See migration 022_carddav_shares.sql.
CREATE TABLE "CardDavConnection" (
id text PRIMARY KEY,
"ownerId" text NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
name text NOT NULL,
url text NOT NULL,
username text NOT NULL,
secret text NOT NULL,
enabled boolean NOT NULL DEFAULT true,
"lastSyncedAt" timestamptz,
"lastError" text,
version integer NOT NULL DEFAULT 1,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX "CardDavConnection_ownerId_idx" ON "CardDavConnection"("ownerId");
-- 2.17i CardDavAddressbook: one discovered address book under a connection,
-- with the Collection it materializes into (calendar-pattern re-materialize
-- on user-deleted collection via SET NULL).
CREATE TABLE "CardDavAddressbook" (
id text PRIMARY KEY,
"connectionId" text NOT NULL REFERENCES "CardDavConnection"(id) ON DELETE CASCADE,
href text NOT NULL,
"displayName" text NOT NULL DEFAULT '',
"collectionId" text REFERENCES "Collection"(id) ON DELETE SET NULL,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("connectionId", href)
);
CREATE INDEX "CardDavAddressbook_connectionId_idx" ON "CardDavAddressbook"("connectionId");
-- 2.17j CardDavItem: path-bookmark ledger per address book - the exact
-- WebDavItem/CalDavEvent semantics: bookmarkId NULL = user-deleted
-- tombstone (never resurrected), etag refreshes never touch user-edited
-- bookmark fields, a vanished card detaches membership but keeps the
-- bookmark. UNIQUE(addressbookId, path).
CREATE TABLE "CardDavItem" (
id text PRIMARY KEY,
"addressbookId" text NOT NULL REFERENCES "CardDavAddressbook"(id) ON DELETE CASCADE,
path text NOT NULL,
"bookmarkId" text REFERENCES "Bookmark"(id) ON DELETE SET NULL,
etag text NOT NULL DEFAULT '',
uid text NOT NULL DEFAULT '',
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(),
UNIQUE ("addressbookId", path)
);
CREATE INDEX "CardDavItem_addressbookId_idx" ON "CardDavItem"("addressbookId");
-- 2.18 PageEmbed (Notion-like upgrades phase 3): a live collection view
-- embedded in a page. The reference is resolved from the page's Markdown
-- (`{{collection:<id>|view=<id>}}`) on every content save. Only collections
-- owned by the page's author are stored; embedding displays data and never
-- publishes it or widens bookmark access. Deleting the collection or the
-- chosen view removes/falls back rather than leaving a dangling embed.
CREATE TABLE "PageEmbed" (
"pageId" text NOT NULL REFERENCES "Page"(id) ON DELETE CASCADE,
"collectionId" text NOT NULL REFERENCES "Collection"(id) ON DELETE CASCADE,
"viewId" text REFERENCES "CollectionView"(id) ON DELETE SET NULL,
position integer NOT NULL DEFAULT 0,
"createdAt" timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY ("pageId", "collectionId")
);
CREATE INDEX "PageEmbed_collectionId_idx" ON "PageEmbed"("collectionId");
CREATE INDEX "PageEmbed_viewId_idx" ON "PageEmbed"("viewId");
COMMIT;