import { subscriptionConnections } from "./subscription-core-schema"; import type { StoredSessionAdmissionBlock } from "./session-admission-block"; import type { StoredApiIntegrationRevision } from "./capability-integrations"; import { commentaryExclusiveMeaningfulSessionEventSql, commentaryInclusiveMeaningfulSessionEventSql, meaningfulAttentionIndexPredicateSql, } from "./session-meaningful-events"; import type { OrganizationAccessPolicy, SandboxProviderCommand, CommandSupervisionReceipt, ConnectionAccountIntent, AttemptToolCatalog, AttemptToolResult, DraftTimelineAnnotation, FirstPartyMcpToolName, McpPersonalConnectionDelegation, McpConnectionAccountBinding, PersonalResourceAttachmentIntent, PersonalResourceAttachmentSummary, Permission, McpServerConnectionRef, ModelContextContributionSummary, ModelContextSnapshot, ModelCallProcessingResidencyV1, PromptCacheDiagnostics, RigProviderImages, SessionMcpApprovalPolicy, SessionRemovedRepository, SessionGoalChangeKind, SessionGoalMutationPolicy, SessionGoalSnapshot, SlackUserLinkAccessRequest, SubscriptionPersonalAuthorityV2, TimelineAnnotation, SiteAssetManifest, AppServerManifest, ToolGatewayIdentity, UserResourceDelegation, VaultPolicy, XaiProviderAccountAuthoritySnapshotV1, ClaudeProviderAccountAuthoritySnapshotV1, } from "@opengeni/contracts"; import { WORKSPACE_XAI_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1, WORKSPACE_CLAUDE_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1, } from "@opengeni/contracts"; import { sql } from "drizzle-orm"; export * from "./knowledge-entries-schema"; export * from "./subscription-core-schema"; import type { ApiIntegrationAuthPreview, ResolvedAgentConfig, SessionAvatar, SessionLink, SessionToolPolicy, SessionWaitingOn, } from "@opengeni/contracts"; import type { HumanInputQuestion, HumanInputResponse } from "@opengeni/contracts"; import type { SessionEventPayloadTruncation } from "@opengeni/contracts"; import { bigint, boolean, check, customType, date, foreignKey, index, integer, jsonb, numeric, pgSchema, pgTable, primaryKey, smallint, text, timestamp, unique, uniqueIndex, uuid, } from "drizzle-orm/pg-core"; import { losslessCodecVersion, losslessJsonb, losslessOrderedJson, losslessText, } from "./lossless-columns"; export * from "./agents-schema"; export * from "./automation-templates-schema"; export * from "./editable-artifacts-schema"; export * from "./event-triggers-schema"; export * from "./managed-auth-session-set-schema"; export * from "./secret-approvals-schema"; export * from "./credential-profiles-schema"; export * from "./slack-api-rate-limit-schema"; export * from "./mcp-connection-rate-limit-schema"; export * from "./organization-recovery-schema"; const vector = customType<{ data: number[]; driverData: string }>({ dataType() { return "vector(3072)"; }, toDriver(value) { return `[${value.join(",")}]`; }, }); const bytea = customType<{ data: Uint8Array; driverData: Uint8Array }>({ dataType() { return "bytea"; }, }); const opengeniPrivateSchema = pgSchema("opengeni_private"); /** Who asked for a pending context compaction (`sessions.compact_request_trigger`). */ export type CompactRequestTrigger = "operator" | "proactive"; /** * A pending tool call's output as its agent.toolCall.output event carries it, * bounded on write like the event itself; `truncation` is present only when * the bound omitted part of the value. */ export type PendingToolCallEventOutput = { value: unknown; truncation?: SessionEventPayloadTruncation; }; export type ConnectorActionPolicyDecision = "allow" | "ask" | "block"; export type ConnectorActionPolicySnapshotEntry = { id: string; connectionId: string; serverId: string; toolName: string; actionName: string; policy: ConnectorActionPolicyDecision; version: number; }; export const managedAccounts = pgTable( "managed_accounts", { id: uuid("id").primaryKey().defaultRandom(), name: text("name").notNull(), externalSource: text("external_source"), externalId: text("external_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ external: uniqueIndex("managed_accounts_external_idx").on( table.externalSource, table.externalId, ), }), ); export const organizationIntegrationPolicies = pgTable( "organization_integration_policies", { accountId: uuid("account_id") .primaryKey() .references(() => managedAccounts.id, { onDelete: "cascade" }), mode: text("mode").$type<"unrestricted" | "restricted">().notNull(), allowedIntegrationKeys: jsonb("allowed_integration_keys").$type().notNull(), personalIntegrationSetup: text("personal_integration_setup") .$type<"members" | "admins">() .notNull() .default("members"), revision: bigint("revision", { mode: "number" }).notNull(), }, (table) => ({ modeCheck: check( "organization_integration_policies_mode_check", sql`${table.mode} in ('unrestricted', 'restricted')`, ), personalIntegrationSetupCheck: check( "organization_integration_policies_personal_setup_check", sql`${table.personalIntegrationSetup} in ('members', 'admins')`, ), keysCheck: check( "organization_integration_policies_allowed_integration_keys_check", sql`jsonb_typeof(${table.allowedIntegrationKeys}) = 'array'`, ), revisionCheck: check( "organization_integration_policies_revision_check", sql`${table.revision} between 1 and 9007199254740991`, ), }), ); export const organizationIntegrationPolicyOperations = pgTable( "organization_integration_policy_operations", { accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), operationId: uuid("operation_id").notNull(), actorSubjectId: text("actor_subject_id").notNull(), request: jsonb("request").notNull(), result: jsonb("result").notNull(), }, (table) => ({ identity: primaryKey({ columns: [table.accountId, table.operationId] }) }), ); export const workspaces = pgTable( "workspaces", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), name: text("name").notNull(), slug: text("slug"), externalSource: text("external_source"), externalId: text("external_id"), // White-label agent persona template override. NULL means the deployment // default (OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE / DEFAULT_AGENT_INSTRUCTIONS). agentInstructions: text("agent_instructions"), // Growth-ready per-workspace settings bag (migration 0045). Migration 0393 // makes Memory enabled by default; explicit false remains authoritative. settings: jsonb("settings") .$type>() .notNull() .default({ memoryEnabled: true }), // The workspace's default rig (migration 0047). NULL ⇒ no default; sessions // created without an explicit rig ride no rig (today's behavior exactly). FK // (-> rigs(id) ON DELETE SET NULL) lives in migration 0047, not a Drizzle // .references(), because `rigs` is declared later in this file (same // forward-reference pattern as sessions.activeSandboxId). Consumed in M3. defaultRigId: uuid("default_rig_id"), // Workspace-wide viewer admission intent set by the warm-meter reaper when // managed credits or the monthly warm allowance are exhausted. It is // deliberately independent of a lease so a dashboard cannot re-arm a // draining box or spawn a cold successor before a fresh limit evaluation // clears the gate. sandboxViewerForceDrainReason: text("sandbox_viewer_force_drain_reason", { enum: ["balance", "warm_cap"], }), sandboxViewerForceDrainRequestedAt: timestamp("sandbox_viewer_force_drain_requested_at", { withTimezone: true, }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ account: index("workspaces_account_idx").on(table.accountId), accountSlug: uniqueIndex("workspaces_account_slug_idx") .on(table.accountId, table.slug) .where(sql`${table.slug} is not null`), external: uniqueIndex("workspaces_external_idx").on( table.accountId, table.externalSource, table.externalId, ), sandboxViewerForceDrain: index("workspaces_sandbox_viewer_force_drain_idx") .on(table.id) .where(sql`${table.sandboxViewerForceDrainReason} is not null`), sandboxViewerForceDrainValid: check( "workspaces_sandbox_viewer_force_drain_check", sql`( ${table.sandboxViewerForceDrainReason} is null and ${table.sandboxViewerForceDrainRequestedAt} is null ) or ( ${table.sandboxViewerForceDrainReason} in ('balance', 'warm_cap') and ${table.sandboxViewerForceDrainRequestedAt} is not null )`, ), }), ); // A single generic workspace-published surface. Presentation labels such as // app, page, gallery, or document are intentionally not persisted as types. export const workspaceArtifacts = pgTable( "workspace_artifacts", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), slug: text("slug").notNull(), title: text("title").notNull(), description: text("description"), status: text("status").$type<"active" | "archived">().notNull().default("active"), // The FK to workspace_artifact_versions is installed by migration after // that table exists. Keeping this pointer here makes reads inexpensive. currentVersionId: uuid("current_version_id"), createdBySubjectId: text("created_by_subject_id").notNull(), // Who can see the Site (migration 0737), like a chat or a schedule: the // whole workspace (`workspace_shared`) or only its owner (`user_private`). // The owner is the person it was published for and never changes; only // they can change the audience. An Only me Site needs an owner. visibility: text("visibility") .$type<"workspace_shared" | "user_private">() .notNull() .default("workspace_shared"), ownerSubjectId: text("owner_subject_id"), // Migration 1548: the app package it was installed or last upgraded from. packageId: uuid("package_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "workspace_artifacts_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSlug: uniqueIndex("workspace_artifacts_workspace_slug_uq").on( table.workspaceId, table.slug, ), workspaceId: uniqueIndex("workspace_artifacts_workspace_id_uq").on(table.workspaceId, table.id), list: index("workspace_artifacts_list_idx").on(table.workspaceId, table.updatedAt), statusList: index("workspace_artifacts_status_list_idx").on( table.workspaceId, table.status, table.updatedAt, ), visibilityValid: check( "workspace_artifacts_visibility_check", sql`${table.visibility} in ('workspace_shared', 'user_private') and (${table.visibility} = 'workspace_shared' or ${table.ownerSubjectId} is not null)`, ), }), ); export const siteSessionAccess = pgTable( "site_session_access", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), siteId: uuid("site_id").notNull(), sessionId: uuid("session_id").notNull(), ownerSubjectId: text("owner_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => [ primaryKey({ columns: [table.workspaceId, table.siteId, table.sessionId] }), foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), foreignKey({ columns: [table.workspaceId, table.siteId], foreignColumns: [workspaceArtifacts.workspaceId, workspaceArtifacts.id], }).onDelete("cascade"), foreignKey({ columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), ], ); /** When each person last opened a Site (migration 0908); personal ordering only. */ export const siteOpens = pgTable( "site_opens", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), subjectId: text("subject_id").notNull(), siteId: uuid("site_id").notNull(), openedAt: timestamp("opened_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => [ primaryKey({ columns: [table.workspaceId, table.subjectId, table.siteId] }), foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), foreignKey({ columns: [table.workspaceId, table.siteId], foreignColumns: [workspaceArtifacts.workspaceId, workspaceArtifacts.id], }).onDelete("cascade"), index("site_opens_site_idx").on(table.workspaceId, table.siteId), ], ); /** * Each person's sidebar state for a Site row (migration 0949): pinned, or * archived (hidden from their sidebar). Personal; grants nothing. */ export const siteSidebarStates = pgTable( "site_sidebar_states", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), subjectId: text("subject_id").notNull(), siteId: uuid("site_id").notNull(), pinnedAt: timestamp("pinned_at", { withTimezone: true }), archivedAt: timestamp("archived_at", { withTimezone: true }), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => [ primaryKey({ columns: [table.workspaceId, table.subjectId, table.siteId] }), foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), foreignKey({ columns: [table.workspaceId, table.siteId], foreignColumns: [workspaceArtifacts.workspaceId, workspaceArtifacts.id], }).onDelete("cascade"), index("site_sidebar_states_site_idx").on(table.workspaceId, table.siteId), ], ); /** * A Site's project in the sidebar, chosen by a person (migration 1071). Without * a row a Site sits in the project of the chat that created it. Shared like a * chat's project; a null channel is Default (no project). Grants nothing. */ export const siteProjectPlacements = pgTable( "site_project_placements", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), siteId: uuid("site_id").notNull(), // Composite FK to channels(workspace_id, id) ON DELETE SET NULL (channel_id), // owned by the migration. channelId: uuid("channel_id"), placedBySubjectId: text("placed_by_subject_id").notNull(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => [ primaryKey({ columns: [table.workspaceId, table.siteId] }), foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), foreignKey({ columns: [table.workspaceId, table.siteId], foreignColumns: [workspaceArtifacts.workspaceId, workspaceArtifacts.id], }).onDelete("cascade"), index("site_project_placements_channel_idx").on(table.workspaceId, table.channelId), ], ); /** * "Always allow for this Site" (migration 1031): one person's standing consent * for one Site to run one tool on one of their own connections. Personal; * consulted only for that Site's calls; never overrides Block and never * changes the connection-wide permission. */ export const siteToolAllowances = pgTable( "site_tool_allowances", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), subjectId: text("subject_id").notNull(), siteId: uuid("site_id").notNull(), serverId: text("server_id").notNull(), toolName: text("tool_name").notNull(), connectionId: text("connection_id").notNull().default(""), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => [ primaryKey({ columns: [ table.workspaceId, table.subjectId, table.siteId, table.serverId, table.toolName, table.connectionId, ], }), foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), foreignKey({ columns: [table.workspaceId, table.siteId], foreignColumns: [workspaceArtifacts.workspaceId, workspaceArtifacts.id], }).onDelete("cascade"), index("site_tool_allowances_site_idx").on(table.workspaceId, table.siteId), ], ); /** * "Your default machine" (migration 1090): one person's own placement for the * new chats they start in one workspace, ahead of the workspace default. * Personal (RLS: own subject only). Session creation revalidates it on every * use and falls back to the workspace default when it is no longer usable. */ export const workspaceMemberExecutionDefaults = pgTable( "workspace_member_execution_defaults", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), subjectId: text("subject_id").notNull(), target: jsonb("target").$type>().notNull(), version: integer("version").notNull().default(1), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => [ primaryKey({ columns: [table.workspaceId, table.subjectId] }), foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), ], ); export const workspaceArtifactUploads = pgTable( "workspace_artifact_uploads", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), ownerId: text("owner_id").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), status: text("status") .$type<"pending" | "published" | "expired">() .notNull() .default("pending"), }, (table) => [ foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), index("workspace_artifact_uploads_expiry_idx") .on(table.workspaceId, table.expiresAt) .where(sql`${table.status} <> 'published'`), check( "workspace_artifact_uploads_status_check", sql`${table.status} in ('pending', 'published', 'expired')`, ), ], ); export const workspaceArtifactVersions = pgTable( "workspace_artifact_versions", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), artifactId: uuid("artifact_id").notNull(), revision: integer("revision").notNull(), contentKey: text("content_key").notNull(), contentType: text("content_type").$type<"text/html">().notNull().default("text/html"), contentSha256: text("content_sha256"), sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(), sourceKey: text("source_key"), sourceSha256: text("source_sha256"), sourceSizeBytes: bigint("source_size_bytes", { mode: "number" }), requestedTools: jsonb("requested_tools").$type().notNull().default([]), /** Asset files of a multi-file build (migration 1522); null for a single-file app. */ assetManifest: jsonb("asset_manifest").$type(), /** App server code of this version (migration 1554); null without server code. */ serverManifest: jsonb("server_manifest").$type(), operationKey: text("operation_key").notNull(), sourceSessionId: uuid("source_session_id"), sourceTurnId: uuid("source_turn_id"), sourceAttemptId: uuid("source_attempt_id"), sourceExecutionGeneration: integer("source_execution_generation"), createdBySubjectId: text("created_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "workspace_artifact_versions_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), artifact: foreignKey({ name: "workspace_artifact_versions_artifact_fk", columns: [table.workspaceId, table.artifactId], foreignColumns: [workspaceArtifacts.workspaceId, workspaceArtifacts.id], }).onDelete("cascade"), workspaceId: uniqueIndex("workspace_artifact_versions_workspace_id_uq").on( table.workspaceId, table.id, ), revision: uniqueIndex("workspace_artifact_versions_revision_uq").on( table.workspaceId, table.artifactId, table.revision, ), operation: uniqueIndex("workspace_artifact_versions_operation_uq").on( table.workspaceId, table.operationKey, ), provenance: check( "workspace_artifact_versions_provenance_chk", sql`( ${table.sourceSessionId} is null and ${table.sourceTurnId} is null and ${table.sourceAttemptId} is null and ${table.sourceExecutionGeneration} is null ) or ( ${table.sourceSessionId} is not null and ${table.sourceTurnId} is not null and ${table.sourceAttemptId} is not null and ${table.sourceExecutionGeneration} > 0 )`, ), }), ); export const workspaceArtifactEvents = pgTable( "workspace_artifact_events", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), artifactId: uuid("artifact_id").notNull(), type: text("type").$type<"published" | "rolled_back" | "archived" | "restored">().notNull(), fromVersionId: uuid("from_version_id"), toVersionId: uuid("to_version_id").notNull(), operationKey: text("operation_key").notNull(), requestDigest: text("request_digest"), requestInput: jsonb("request_input").$type>(), sourceSessionId: uuid("source_session_id"), sourceTurnId: uuid("source_turn_id"), sourceAttemptId: uuid("source_attempt_id"), sourceExecutionGeneration: integer("source_execution_generation"), actorSubjectId: text("actor_subject_id").notNull(), reason: text("reason").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "workspace_artifact_events_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), artifact: foreignKey({ name: "workspace_artifact_events_artifact_fk", columns: [table.workspaceId, table.artifactId], foreignColumns: [workspaceArtifacts.workspaceId, workspaceArtifacts.id], }).onDelete("cascade"), operation: uniqueIndex("workspace_artifact_events_operation_uq").on( table.workspaceId, table.operationKey, ), list: index("workspace_artifact_events_list_idx").on( table.workspaceId, table.artifactId, table.createdAt, ), provenance: check( "workspace_artifact_events_provenance_chk", sql`( ${table.sourceSessionId} is null and ${table.sourceTurnId} is null and ${table.sourceAttemptId} is null and ${table.sourceExecutionGeneration} is null ) or ( ${table.sourceSessionId} is not null and ${table.sourceTurnId} is not null and ${table.sourceAttemptId} is not null and ${table.sourceExecutionGeneration} > 0 )`, ), }), ); // One target-schema-local deployment fallback. The migration runner reconciles // this singleton from OPENGENI_MAX_NESTED_AGENT_DEPTH; session admission locks // and reads it through the SECURITY DEFINER capability installed by the // boundary migration so the application role cannot mutate policy authority. export const nestedAgentDepthConfiguration = pgTable( "nested_agent_depth_configuration", { singleton: boolean("singleton").primaryKey().notNull().default(true), maxNestedAgentDepth: integer("max_nested_agent_depth").notNull(), policySource: text("policy_source").$type<"deployment" | "default">().notNull(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ singletonOnly: check( "nested_agent_depth_configuration_singleton_check", sql`${table.singleton}`, ), maxValid: check( "nested_agent_depth_configuration_max_check", sql`${table.maxNestedAgentDepth} >= 0`, ), sourceValid: check( "nested_agent_depth_configuration_source_check", sql`${table.policySource} in ('deployment', 'default')`, ), }), ); // One mandatory workspace-wide admission barrier. Every inference-admitting // transaction locks this row before it touches a session; Pause/Resume and // foreground Send/Steer advance its monotonic revision under FOR UPDATE. export const workspaceInferenceControls = pgTable( "workspace_inference_controls", { workspaceId: uuid("workspace_id").primaryKey(), accountId: uuid("account_id").notNull(), revision: bigint("revision", { mode: "number" }).notNull().default(0), workspaceState: text("workspace_state").notNull().default("active"), timerId: uuid("timer_id"), timerAction: text("timer_action"), timerDueAt: timestamp("timer_due_at", { withTimezone: true }), timerPauseForSeconds: integer("timer_pause_for_seconds"), timerPauseRevision: bigint("timer_pause_revision", { mode: "number" }), workspacePauseRevision: bigint("workspace_pause_revision", { mode: "number", }), reason: text("reason"), changedBy: text("changed_by"), changedAt: timestamp("changed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "workspace_inference_controls_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), timerDue: index("workspace_pause_timer_due_idx") .on(table.timerDueAt, table.workspaceId) .where(sql`${table.timerId} is not null`), timerShape: check( "workspace_pause_timer_shape", sql` (${table.timerId} is null and ${table.timerAction} is null and ${table.timerDueAt} is null and ${table.timerPauseForSeconds} is null and ${table.timerPauseRevision} is null) or (${table.timerId} is not null and ${table.timerAction} is not null and ${table.timerDueAt} is not null and ((${table.timerAction} = 'pause' and ${table.timerPauseRevision} is null) or (${table.timerAction} = 'resume' and ${table.timerPauseRevision} is not null and ${table.timerPauseForSeconds} is null)) and (${table.timerPauseForSeconds} is null or ${table.timerPauseForSeconds} between 60 and 2592000)) `, ), workspaceAccountIdentity: uniqueIndex("workspace_inference_controls_workspace_account_uq").on( table.workspaceId, table.accountId, ), stateValid: check( "workspace_inference_controls_state_check", sql`${table.workspaceState} in ('active', 'paused')`, ), pauseRevisionConsistent: check( "workspace_inference_controls_pause_revision_check", sql`(${table.workspaceState} = 'active' and ${table.workspacePauseRevision} is null) or (${table.workspaceState} = 'paused' and ${table.workspacePauseRevision} is not null)`, ), revisionValid: check( "workspace_inference_controls_revision_check", sql`${table.revision} >= 0 and (${table.workspacePauseRevision} is null or ${table.workspacePauseRevision} <= ${table.revision})`, ), }), ); // Legacy rolling-compatibility shape, not the activity clock for new readers or // writers. Retain until old binaries and SQL lifecycle finalizers are retired. export const workspaceSessionActivityRevisions = pgTable( "workspace_session_activity_revisions", { workspaceId: uuid("workspace_id").primaryKey(), accountId: uuid("account_id").notNull(), revision: bigint("revision", { mode: "number" }).notNull().default(0), }, (table) => ({ workspaceAccount: foreignKey({ name: "workspace_session_activity_revisions_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), revisionValid: check( "workspace_session_activity_revisions_revision_check", sql`${table.revision} >= 0`, ), }), ); export const workspaceMemberships = pgTable( "workspace_memberships", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), subjectId: text("subject_id").notNull(), subjectLabel: text("subject_label"), role: text("role").notNull().default("member"), permissions: jsonb("permissions").$type().notNull().default([]), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ subjectWorkspace: uniqueIndex("workspace_memberships_subject_workspace_idx").on( table.subjectId, table.workspaceId, ), subject: index("workspace_memberships_subject_idx").on(table.subjectId), account: index("workspace_memberships_account_idx").on(table.accountId), }), ); // Organization membership is distinct from workspace access. `account_id` is // the physical organization identifier; `personal_workspace_id` is lifecycle // metadata only and never the ownership anchor for user resources. export const externalIdentities = pgTable( "external_identities", { id: uuid("id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), source: text("source").notNull(), externalId: text("external_id").notNull(), subjectId: text("subject_id").notNull(), organizationMembershipId: uuid("organization_membership_id").notNull(), personalWorkspaceId: uuid("personal_workspace_id").notNull(), status: text("status").notNull().default("active"), authorizationRevision: bigint("authorization_revision", { mode: "number" }) .notNull() .default(1), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ mapping: uniqueIndex("external_identities_account_id_source_external_id_key").on( table.accountId, table.source, table.externalId, ), subject: uniqueIndex("external_identities_account_id_subject_id_key").on( table.accountId, table.subjectId, ), membership: foreignKey({ columns: [table.organizationMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }), personalWorkspace: foreignKey({ columns: [table.personalWorkspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }), }), ); export const organizationMemberships = pgTable( "organization_memberships", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), subjectId: text("subject_id").notNull(), role: text("role").notNull().default("member"), status: text("status").notNull().default("provisioning"), personalWorkspaceId: uuid("personal_workspace_id"), authorizationRevision: bigint("authorization_revision", { mode: "number" }) .notNull() .default(1), revokedAt: timestamp("revoked_at", { withTimezone: true }), personalRetentionUntil: timestamp("personal_retention_until", { withTimezone: true, }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ accountIdentity: uniqueIndex("organization_memberships_id_account_idx").on( table.id, table.accountId, ), accountSubject: uniqueIndex("organization_memberships_account_subject_idx").on( table.accountId, table.subjectId, ), personalWorkspace: uniqueIndex("organization_memberships_personal_workspace_idx") .on(table.accountId, table.personalWorkspaceId) .where(sql`${table.personalWorkspaceId} is not null`), retentionDue: index("organization_memberships_retention_due_idx") .on(table.accountId, table.personalRetentionUntil, table.id) .where(sql`${table.status} = 'revoked' and ${table.personalRetentionUntil} is not null`), personalWorkspaceAccount: foreignKey({ name: "organization_memberships_personal_workspace_account_fk", columns: [table.personalWorkspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("restrict"), statusValid: check( "organization_memberships_status_check", sql`${table.status} in ('provisioning', 'active', 'suspended', 'revoked')`, ), roleValid: check( "organization_memberships_role_check", sql`${table.role} in ('owner', 'admin', 'member')`, ), activePersonalWorkspace: check( "organization_memberships_active_personal_workspace_check", sql`${table.status} <> 'active' or ${table.personalWorkspaceId} is not null`, ), subjectValid: check( "organization_memberships_subject_check", sql`length(btrim(${table.subjectId})) between 1 and 1024`, ), revisionValid: check( "organization_memberships_revision_check", sql`${table.authorizationRevision} > 0`, ), revocationValid: check( "organization_memberships_revocation_check", sql`(${table.status} = 'revoked' and ${table.revokedAt} is not null) or (${table.status} <> 'revoked' and ${table.revokedAt} is null)`, ), }), ); export const organizationProfileEvents = pgTable( "organization_profile_events", { id: uuid("id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), actorMembershipId: uuid("actor_membership_id").notNull(), previousName: text("previous_name").notNull(), requestedName: text("requested_name").notNull(), expectedUpdatedAt: timestamp("expected_updated_at", { withTimezone: true, }).notNull(), resultUpdatedAt: timestamp("result_updated_at", { withTimezone: true, }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ actorMembership: foreignKey({ name: "organization_profile_events_actor_fk", columns: [table.actorMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), }), ); // Forward-only organization-scoped activation receipt for the product session- // tenancy surface. Runtime may observe this marker, but only the drained // migration-owner activation seam may insert it. export const sessionTenancyActivations = pgTable( "session_tenancy_activations", { accountId: uuid("account_id") .primaryKey() .references(() => managedAccounts.id, { onDelete: "restrict" }), activationVersion: integer("activation_version").notNull(), inventoryDigest: text("inventory_digest").notNull(), parityDigest: text("parity_digest").notNull(), activatedBy: text("activated_by").notNull(), backfillReceiptIds: uuid("backfill_receipt_ids") .array() .notNull() .default(sql`'{}'::uuid[]`), activatedAt: timestamp("activated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ versionValid: check( "session_tenancy_activations_version_check", sql`${table.activationVersion} = 1`, ), digestsValid: check( "session_tenancy_activations_digests_check", sql`${table.inventoryDigest} ~ '^[0-9a-f]{64}$' and ${table.parityDigest} ~ '^[0-9a-f]{64}$'`, ), actorValid: check( "session_tenancy_activations_actor_check", sql`octet_length(${table.activatedBy}) between 1 and 256`, ), backfillReceiptsValid: check( "session_tenancy_activation_backfill_receipts_check", sql`cardinality(${table.backfillReceiptIds}) in (0, 5, 6)`, ), }), ); export const organizationPrivateSessionSettings = pgTable( "organization_private_session_settings", { accountId: uuid("account_id") .primaryKey() .references(() => managedAccounts.id, { onDelete: "cascade" }), enabled: boolean("enabled").notNull().default(false), version: bigint("version", { mode: "number" }).notNull().default(1), updatedByMembershipId: uuid("updated_by_membership_id"), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ updater: foreignKey({ name: "organization_private_session_settings_updater_fk", columns: [table.updatedByMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), versionValid: check( "organization_private_session_settings_version_check", sql`${table.version} > 0`, ), }), ); export const organizationPrivateSessionSettingEvents = pgTable( "organization_private_session_setting_events", { id: uuid("id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), actorMembershipId: uuid("actor_membership_id"), actorSubjectId: text("actor_subject_id"), requestedEnabled: boolean("requested_enabled").notNull(), expectedVersion: bigint("expected_version", { mode: "number" }).notNull(), resultEnabled: boolean("result_enabled").notNull(), resultVersion: bigint("result_version", { mode: "number" }).notNull(), resultUpdatedAt: timestamp("result_updated_at", { withTimezone: true, }).notNull(), changed: boolean("changed").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ actor: foreignKey({ name: "organization_private_session_setting_events_actor_fk", columns: [table.actorMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), versionsValid: check( "organization_private_session_setting_events_versions_check", sql`${table.expectedVersion} >= 0 and ${table.resultVersion} > 0`, ), actorValid: check( "organization_private_session_setting_events_actor_check", sql`${table.actorMembershipId} is not null or (${table.actorSubjectId} is not null and ${table.actorSubjectId} like 'api_key:%')`, ), }), ); export const organizationUserRetentionPolicies = pgTable( "organization_user_retention_policies", { accountId: uuid("account_id") .primaryKey() .references(() => managedAccounts.id, { onDelete: "cascade" }), mode: text("mode").notNull().default("retain"), retentionDays: integer("retention_days"), version: bigint("version", { mode: "number" }).notNull().default(1), updatedByMembershipId: uuid("updated_by_membership_id"), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ updater: foreignKey({ name: "organization_user_retention_policies_updater_fk", columns: [table.updatedByMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), modeValid: check( "organization_user_retention_policies_mode_check", sql`${table.mode} in ('retain', 'delete_after')`, ), durationValid: check( "organization_user_retention_policies_duration_check", sql`(${table.mode} = 'retain' and ${table.retentionDays} is null) or ( ${table.mode} = 'delete_after' and ${table.retentionDays} is not null and ${table.retentionDays} between 30 and 90 )`, ), versionValid: check( "organization_user_retention_policies_version_check", sql`${table.version} > 0`, ), }), ); export const organizationMembershipInvitations = pgTable( "organization_membership_invitations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), targetSubjectId: text("target_subject_id"), targetEmail: text("target_email").notNull(), targetName: text("target_name"), initialWorkspaceIds: uuid("initial_workspace_ids") .array() .notNull() .default(sql`'{}'::uuid[]`), role: text("role").notNull().default("member"), status: text("status").notNull().default("pending"), revision: bigint("revision", { mode: "number" }).notNull().default(1), createdByMembershipId: uuid("created_by_membership_id").notNull(), acceptedMembershipId: uuid("accepted_membership_id"), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ accountIdentity: uniqueIndex("organization_membership_invitations_id_account_idx").on( table.id, table.accountId, ), pendingTarget: uniqueIndex("organization_membership_invitations_pending_target_uq") .on(table.accountId, table.targetSubjectId) .where(sql`${table.status} = 'pending' AND ${table.targetSubjectId} IS NOT NULL`), pendingEmail: uniqueIndex("organization_membership_invitations_pending_email_uq") .on(table.accountId, table.targetEmail) .where(sql`${table.status} = 'pending'`), accountCreated: index("organization_membership_invitations_account_created_idx").on( table.accountId, table.createdAt.desc(), table.id.desc(), ), subjectCreated: index("organization_membership_invitations_subject_created_idx").on( table.targetSubjectId, table.createdAt.desc(), table.id.desc(), ), creator: foreignKey({ name: "organization_membership_invitations_creator_fk", columns: [table.createdByMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), acceptedMembership: foreignKey({ name: "organization_membership_invitations_accepted_membership_fk", columns: [table.acceptedMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), roleValid: check( "organization_membership_invitations_role_check", sql`${table.role} in ('owner', 'admin', 'member')`, ), statusValid: check( "organization_membership_invitations_status_check", sql`${table.status} in ('pending', 'accepted', 'revoked', 'expired')`, ), revisionValid: check( "organization_membership_invitations_revision_check", sql`${table.revision} > 0`, ), acceptanceValid: check( "organization_membership_invitations_acceptance_check", sql`(${table.status} = 'accepted' and ${table.acceptedMembershipId} is not null) or (${table.status} <> 'accepted' and ${table.acceptedMembershipId} is null)`, ), }), ); export const organizationInvitationBindingEvents = pgTable( "organization_invitation_binding_events", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), invitationId: uuid("invitation_id").notNull(), targetSubjectId: text("target_subject_id").notNull(), resultingRevision: bigint("resulting_revision", { mode: "number", }).notNull(), boundAt: timestamp("bound_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ invitation: foreignKey({ name: "organization_invitation_binding_events_invitation_fk", columns: [table.invitationId, table.accountId], foreignColumns: [ organizationMembershipInvitations.id, organizationMembershipInvitations.accountId, ], }).onDelete("restrict"), invitationIdentity: uniqueIndex("organization_invitation_binding_events_invitation_uq").on( table.accountId, table.invitationId, ), subjectValid: check( "organization_invitation_binding_events_subject_check", sql`${table.targetSubjectId} = btrim(${table.targetSubjectId}) and ${table.targetSubjectId} like 'user:%' and octet_length(convert_to(${table.targetSubjectId}, 'UTF8')) between 6 and 1024`, ), revisionValid: check( "organization_invitation_binding_events_revision_check", sql`${table.resultingRevision} > 1`, ), }), ); export const organizationMembershipOperationReceipts = pgTable( "organization_membership_operation_receipts", { accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), operationId: uuid("operation_id").notNull(), action: text("action").notNull(), inputHash: text("input_hash").notNull(), result: jsonb("result").$type>().notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ identity: primaryKey({ columns: [table.accountId, table.operationId] }), actionValid: check( "organization_membership_operation_receipts_action_check", sql`${table.action} in ('invite', 'accept', 'revoke_invitation', 'change_role', 'suspend', 'reactivate', 'offboard', 'retention', 'create_workspace')`, ), inputHashValid: check( "organization_membership_operation_receipts_input_hash_check", sql`${table.inputHash} ~ '^[0-9a-f]{64}$'`, ), }), ); export const organizationMembershipLifecycleEvents = pgTable( "organization_membership_lifecycle_events", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), operationId: uuid("operation_id").notNull(), actorMembershipId: uuid("actor_membership_id"), actorServiceSubject: text("actor_service_subject"), targetMembershipId: uuid("target_membership_id"), kind: text("kind").notNull(), priorAuthorizationRevision: bigint("prior_authorization_revision", { mode: "number", }), resultingAuthorizationRevision: bigint("resulting_authorization_revision", { mode: "number", }), reason: text("reason"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ operation: uniqueIndex("organization_membership_lifecycle_events_operation_uq").on( table.accountId, table.operationId, ), actor: foreignKey({ name: "organization_membership_lifecycle_events_actor_fk", columns: [table.actorMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), target: foreignKey({ name: "organization_membership_lifecycle_events_target_fk", columns: [table.targetMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), kindValid: check( "organization_membership_lifecycle_events_kind_check", sql`${table.kind} in ('invite', 'accept', 'revoke_invitation', 'change_role', 'suspend', 'reactivate', 'offboard', 'retention')`, ), actorKindValid: check( "organization_membership_lifecycle_events_actor_kind_check", sql`(${table.actorMembershipId} is not null and ${table.actorServiceSubject} is null) or (${table.actorMembershipId} is null and ${table.actorServiceSubject} is not null and ${table.actorServiceSubject} ~ '^api_key:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')`, ), }), ); export const organizationUserRetentionDeletions = pgTable( "organization_user_retention_deletions", { accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), membershipId: uuid("membership_id").notNull(), retentionUntil: timestamp("retention_until", { withTimezone: true, }).notNull(), state: text("state").notNull().default("claimed"), claimOperationId: uuid("claim_operation_id").notNull(), claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true, }).notNull(), attemptCount: integer("attempt_count").notNull().default(1), databaseResult: jsonb("database_result").$type>(), databaseFinalizedAt: timestamp("database_finalized_at", { withTimezone: true, }), result: jsonb("result").$type>(), completedAt: timestamp("completed_at", { withTimezone: true }), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ identity: primaryKey({ columns: [table.accountId, table.membershipId] }), operation: uniqueIndex("organization_user_retention_deletions_operation_uq").on( table.claimOperationId, ), claim: index("organization_user_retention_deletions_claim_idx").on( table.accountId, table.state, table.claimExpiresAt, ), membership: foreignKey({ name: "organization_user_retention_deletions_membership_fk", columns: [table.membershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), stateValid: check( "organization_user_retention_deletions_state_check", sql`${table.state} in ('claimed', 'failed', 'completed')`, ), attemptValid: check( "organization_user_retention_deletions_attempt_check", sql`${table.attemptCount} > 0`, ), completionValid: check( "organization_user_retention_deletions_completion_check", sql`(${table.state} = 'completed' and ${table.completedAt} is not null and ${table.result} is not null) or (${table.state} <> 'completed' and ${table.completedAt} is null and ${table.result} is null)`, ), databaseFinalizationValid: check( "organization_retention_deletions_db_finalized_chk", sql`(${table.databaseFinalizedAt} is null and ${table.databaseResult} is null) or (${table.databaseFinalizedAt} is not null and ${table.databaseResult} is not null)`, ), }), ); export const organizationUserRetentionObjectObligations = pgTable( "organization_user_retention_object_obligations", { accountId: uuid("account_id").notNull(), membershipId: uuid("membership_id").notNull(), objectKind: text("object_kind").notNull(), sourceId: text("source_id").notNull(), objectBucket: text("object_bucket").notNull(), objectKey: text("object_key").notNull(), preparedOperationId: uuid("prepared_operation_id").notNull(), objectKeyHash: text("object_key_hash").notNull(), preparedAt: timestamp("prepared_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ identity: primaryKey({ columns: [ table.accountId, table.membershipId, table.objectKind, table.sourceId, table.objectBucket, ], }), deletion: foreignKey({ name: "organization_retention_object_obligations_deletion_fk", columns: [table.accountId, table.membershipId], foreignColumns: [ organizationUserRetentionDeletions.accountId, organizationUserRetentionDeletions.membershipId, ], }).onDelete("restrict"), hashValid: check( "organization_user_retention_object_obligations_hash_check", sql`${table.objectKeyHash} ~ '^[0-9a-f]{64}$'`, ), shapeValid: check( "organization_user_retention_object_obligations_shape_check", sql`${table.objectKind} in ( 'file', 'session_recording', 'browser_state_artifact', 'browser_state_upload', 'transcription_recording_object', 'video_staging_reference', 'workspace_artifact_version', 'editable_artifact_blob', 'workspace_capture_manifest', 'workspace_capture_tree_index', 'workspace_capture_blob' ) and octet_length(${table.sourceId}) between 1 and 2048 and octet_length(${table.objectBucket}) between 1 and 1024 and octet_length(${table.objectKey}) between 1 and 4096`, ), }), ); export const organizationUserRetentionObjectDeletionReceipts = pgTable( "organization_user_retention_object_deletion_receipts", { accountId: uuid("account_id").notNull(), membershipId: uuid("membership_id").notNull(), objectKind: text("object_kind").notNull(), sourceId: text("source_id").notNull(), objectBucket: text("object_bucket").notNull(), operationId: uuid("operation_id").notNull(), deletedAt: timestamp("deleted_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ identity: primaryKey({ columns: [ table.accountId, table.membershipId, table.objectKind, table.sourceId, table.objectBucket, ], }), obligation: foreignKey({ name: "organization_retention_object_deletions_obligation_fk", columns: [ table.accountId, table.membershipId, table.objectKind, table.sourceId, table.objectBucket, ], foreignColumns: [ organizationUserRetentionObjectObligations.accountId, organizationUserRetentionObjectObligations.membershipId, organizationUserRetentionObjectObligations.objectKind, organizationUserRetentionObjectObligations.sourceId, organizationUserRetentionObjectObligations.objectBucket, ], }).onDelete("restrict"), }), ); export const organizationUserRetentionDeletionEvents = pgTable( "organization_user_retention_deletion_events", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), membershipId: uuid("membership_id").notNull(), operationId: uuid("operation_id").notNull(), kind: text("kind").notNull(), reasonCode: text("reason_code"), result: jsonb("result").$type>().notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ operationKind: uniqueIndex("organization_user_retention_deletion_events_operation_kind_uq").on( table.accountId, table.operationId, table.kind, ), membershipCreated: index("organization_retention_events_member_created_idx").on( table.accountId, table.membershipId, table.createdAt, table.id, ), membership: foreignKey({ name: "organization_user_retention_deletion_events_membership_fk", columns: [table.membershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), kindValid: check( "organization_user_retention_deletion_events_kind_check", sql`${table.kind} in ('claimed', 'failed', 'completed')`, ), reasonValid: check( "organization_user_retention_deletion_events_reason_check", sql`${table.reasonCode} is null or ${table.reasonCode} ~ '^[a-z0-9_]{1,64}$'`, ), }), ); export const organizationUserResourceAuthorities = pgTable( "organization_user_resource_authorities", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), organizationMembershipId: uuid("organization_membership_id").notNull(), resourceKind: text("resource_kind").notNull(), resourceId: uuid("resource_id").notNull(), // Provenance only. The migration owns a composite same-organization FK // whose delete action clears only this column, never account_id. originWorkspaceId: uuid("origin_workspace_id"), generation: bigint("generation", { mode: "number" }).notNull().default(1), status: text("status").notNull().default("active"), revokedAt: timestamp("revoked_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ accountIdentity: uniqueIndex("organization_user_resource_authorities_id_account_idx").on( table.id, table.accountId, ), accountMembershipIdentity: uniqueIndex( "organization_user_resource_authorities_id_account_membership_idx", ).on(table.id, table.accountId, table.organizationMembershipId), resourceIdentity: uniqueIndex( "organization_user_resource_authorities_resource_identity_idx", ).on(table.accountId, table.organizationMembershipId, table.resourceKind, table.resourceId), membership: foreignKey({ name: "organization_user_resource_authorities_membership_fk", columns: [table.organizationMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), resourceKindValid: check( "organization_user_resource_authorities_kind_check", sql`${table.resourceKind} = lower(btrim(${table.resourceKind})) and length(${table.resourceKind}) between 1 and 64 and ${table.resourceKind} ~ '^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$'`, ), generationValid: check( "organization_user_resource_authorities_generation_check", sql`${table.generation} > 0`, ), statusValid: check( "organization_user_resource_authorities_status_check", sql`${table.status} in ('active', 'retained', 'revoked')`, ), revocationValid: check( "organization_user_resource_authorities_revocation_check", sql`(${table.status} = 'revoked' and ${table.revokedAt} is not null) or (${table.status} <> 'revoked' and ${table.revokedAt} is null)`, ), }), ); export type OrganizationServiceAccountRole = "admin" | "member"; /** An organization identity with no person behind it; it holds organization API keys. */ export const organizationServiceAccounts = pgTable( "organization_service_accounts", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), name: text("name").notNull(), description: text("description"), role: text("role").$type().notNull().default("admin"), createdBySubjectId: text("created_by_subject_id"), deletedAt: timestamp("deleted_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ accountIdentity: uniqueIndex("organization_service_accounts_id_account_idx").on( table.id, table.accountId, ), account: index("organization_service_accounts_account_idx") .on(table.accountId, table.createdAt) .where(sql`${table.deletedAt} is null`), roleValid: check( "organization_service_accounts_role_check", sql`${table.role} in ('admin', 'member')`, ), nameValid: check( "organization_service_accounts_name_check", sql`length(btrim(${table.name})) between 1 and 200`, ), descriptionValid: check( "organization_service_accounts_description_check", sql`${table.description} is null or length(${table.description}) between 1 and 500`, ), creatorValid: check( "organization_service_accounts_creator_check", sql`${table.createdBySubjectId} is null or length(btrim(${table.createdBySubjectId})) between 1 and 1024`, ), }), ); export type ApiKeyCredentialKind = "workspace" | "organization" | "legacy_account" | "personal"; export const apiKeys = pgTable( "api_keys", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade", }), name: text("name").notNull(), description: text("description"), credentialKind: text("credential_kind").$type().notNull(), workspaceScope: text("workspace_scope").$type<"all" | "selected">().notNull().default("all"), permissionMode: text("permission_mode") .$type<"legacy" | "explicit">() .notNull() .default("legacy"), prefix: text("prefix").notNull(), keyHash: text("key_hash").notNull(), permissions: jsonb("permissions").$type().notNull().default([]), /** Organization keys: the service account that holds the key. */ serviceAccountId: uuid("service_account_id"), /** Personal keys: the person the key acts as, with their live access. */ ownerSubjectId: text("owner_subject_id"), /** Personal keys: the most the key may do; `permissions` stays empty. */ ownerPermissions: jsonb("owner_permissions").$type(), expiresAt: timestamp("expires_at", { withTimezone: true }), revokedAt: timestamp("revoked_at", { withTimezone: true }), lastUsedAt: timestamp("last_used_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ prefix: index("api_keys_prefix_idx").on(table.prefix), hash: uniqueIndex("api_keys_key_hash_idx").on(table.keyHash), account: index("api_keys_account_idx").on(table.accountId), workspace: index("api_keys_workspace_idx").on(table.workspaceId), accountIdentity: uniqueIndex("api_keys_id_account_idx").on(table.id, table.accountId), serviceAccountIndex: index("api_keys_service_account_idx") .on(table.serviceAccountId) .where(sql`${table.serviceAccountId} is not null`), serviceAccount: foreignKey({ name: "api_keys_service_account_fk", columns: [table.serviceAccountId, table.accountId], foreignColumns: [organizationServiceAccounts.id, organizationServiceAccounts.accountId], }).onDelete("restrict"), serviceAccountKind: check( "api_keys_service_account_kind_check", sql`${table.serviceAccountId} is null or ${table.credentialKind} = 'organization'`, ), accessPolicyValid: check( "api_keys_access_policy_check", sql`${table.workspaceScope} in ('all', 'selected') and ${table.permissionMode} in ('legacy', 'explicit') and (${table.workspaceScope} = 'all' or (${table.credentialKind} in ('organization', 'personal') and ${table.permissionMode} = 'explicit')) and (${table.permissionMode} = 'legacy' or ${table.credentialKind} in ('organization', 'personal'))`, ), personalOwner: check( "api_keys_personal_owner_check", sql`(${table.credentialKind} = 'personal') = (${table.ownerSubjectId} is not null) and (${table.credentialKind} = 'personal') = (${table.ownerPermissions} is not null) and (${table.credentialKind} <> 'personal' or ( ${table.ownerSubjectId} ~ '^user:[^[:space:][:cntrl:]]+$' and length(${table.ownerSubjectId}) <= 1024 and jsonb_typeof(${table.ownerPermissions}) = 'array' and ${table.permissions} = '[]'::jsonb and ${table.permissionMode} = 'explicit' and ${table.serviceAccountId} is null ))`, ), personalOwnerIndex: index("api_keys_personal_owner_idx") .on(table.accountId, table.ownerSubjectId, table.createdAt.desc()) .where(sql`${table.credentialKind} = 'personal'`), descriptionValid: check( "api_keys_description_check", sql`${table.description} is null or length(${table.description}) between 1 and 500`, ), credentialKindValid: check( "api_keys_credential_kind_check", sql`( ${table.workspaceId} is not null and ${table.credentialKind} = 'workspace' ) or ( ${table.workspaceId} is null and ${table.credentialKind} = 'organization' ) or ( ${table.workspaceId} is null and ${table.credentialKind} = 'legacy_account' and ${table.revokedAt} is not null ) or ( ${table.workspaceId} is null and ${table.credentialKind} = 'personal' )`, ), }), ); export const organizationApiKeyWorkspaces = pgTable( "organization_api_key_workspaces", { apiKeyId: uuid("api_key_id").notNull(), workspaceId: uuid("workspace_id").notNull(), accountId: uuid("account_id").notNull(), }, (table) => ({ keyWorkspace: primaryKey({ columns: [table.apiKeyId, table.workspaceId] }), workspace: index("organization_api_key_workspaces_workspace_idx").on( table.workspaceId, table.accountId, ), keyAccount: foreignKey({ name: "organization_api_key_workspaces_key_account_fk", columns: [table.apiKeyId, table.accountId], foreignColumns: [apiKeys.id, apiKeys.accountId], }).onDelete("cascade"), workspaceAccount: foreignKey({ name: "organization_api_key_workspaces_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); // Vaults (migration 0739). Every table is FORCE row-security with no runtime // role privileges: the application reads and writes only through the // SECURITY DEFINER routines in 0739 (see `./vaults.ts`). These definitions // exist for typing and Drizzle introspection; the migration owns the exact // constraints, partial indexes, composite foreign keys and policies. export const vaults = pgTable( "vaults", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), ownerKind: text("owner_kind").notNull(), authorityId: uuid("authority_id"), ownerOrganizationMembershipId: uuid("owner_organization_membership_id"), originWorkspaceId: uuid("origin_workspace_id"), rootSessionId: uuid("root_session_id"), name: text("name").notNull(), nameKey: text("name_key").generatedAlwaysAs(sql`vault_name_key(name)`), description: text("description"), source: text("source").notNull().default("opengeni"), mode: text("mode").notNull().default("read_write"), providerConnectionId: uuid("provider_connection_id"), providerVaultRef: text("provider_vault_ref"), providerContentVersion: text("provider_content_version"), syncStatus: text("sync_status").notNull().default("ok"), syncErrorCode: text("sync_error_code"), syncErrorMessage: text("sync_error_message"), lastSyncedAt: timestamp("last_synced_at", { withTimezone: true }), rateLimitedUntil: timestamp("rate_limited_until", { withTimezone: true }), allowedWorkspaceIds: uuid("allowed_workspace_ids").array(), allowPersonalWorkspaces: boolean("allow_personal_workspaces").notNull().default(true), isDefault: boolean("is_default").notNull().default(false), generation: bigint("generation", { mode: "number" }).notNull().default(1), createdBySubjectId: text("created_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ idAccount: uniqueIndex("vaults_id_account_idx").on(table.id, table.accountId), accountOwner: index("vaults_account_owner_idx").on(table.accountId, table.ownerKind), workspace: index("vaults_workspace_idx").on(table.workspaceId), ownerKindValid: check( "vaults_owner_kind_check", sql`${table.ownerKind} in ('user', 'workspace', 'organization', 'task')`, ), authority: foreignKey({ name: "vaults_authority_fk", columns: [table.authorityId, table.accountId, table.ownerOrganizationMembershipId], foreignColumns: [ organizationUserResourceAuthorities.id, organizationUserResourceAuthorities.accountId, organizationUserResourceAuthorities.organizationMembershipId, ], }).onDelete("restrict"), // The origin-workspace (column-subset SET NULL), root-session and // provider-connection foreign keys are owned by migration 0739. }), ); export const vaultItems = pgTable( "vault_items", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), vaultId: uuid("vault_id").notNull(), type: text("type").notNull(), name: text("name").notNull(), nameKey: text("name_key").generatedAlwaysAs(sql`vault_name_key(name)`), websites: text("websites") .array() .notNull() .default(sql`'{}'::text[]`), expiresAt: timestamp("expires_at", { withTimezone: true }), primaryFieldId: uuid("primary_field_id"), providerItemRef: text("provider_item_ref"), providerVersion: text("provider_version"), usernameHintEncrypted: text("username_hint_encrypted"), passkeySignCount: bigint("passkey_sign_count", { mode: "number" }), lastUsedAt: timestamp("last_used_at", { withTimezone: true }), archivedAt: timestamp("archived_at", { withTimezone: true }), generation: bigint("generation", { mode: "number" }).notNull().default(1), secureAnswerSessionId: uuid("secure_answer_session_id"), secureAnswerGeneration: bigint("secure_answer_generation", { mode: "number" }), createdBySubjectId: text("created_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ vault: foreignKey({ name: "vault_items_vault_fk", columns: [table.vaultId, table.accountId], foreignColumns: [vaults.id, vaults.accountId], }).onDelete("cascade"), activeName: uniqueIndex("vault_items_name_idx") .on(table.vaultId, table.nameKey) .where(sql`${table.archivedAt} is null`), vaultUpdated: index("vault_items_vault_updated_idx").on(table.vaultId, table.updatedAt), nameKey: index("vault_items_name_key_idx").on(table.nameKey), }), ); export const vaultItemFields = pgTable( "vault_item_fields", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), itemId: uuid("item_id") .notNull() .references(() => vaultItems.id, { onDelete: "cascade" }), name: text("name").notNull(), nameKey: text("name_key").generatedAlwaysAs(sql`vault_name_key(name)`), kind: text("kind").notNull(), position: integer("position").notNull().default(0), // NULL for provider-backed fields. currentVersion: integer("current_version"), providerFieldRef: text("provider_field_ref"), fileName: text("file_name"), fileSize: integer("file_size"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ itemName: uniqueIndex("vault_item_fields_name_idx").on(table.itemId, table.nameKey), }), ); export const vaultFieldVersions = pgTable( "vault_field_versions", { fieldId: uuid("field_id") .notNull() .references(() => vaultItemFields.id, { onDelete: "cascade" }), version: integer("version").notNull(), accountId: uuid("account_id").notNull(), // v1/v2 envelope from environment-crypto.ts for every field kind. Never // returned by an API except through the audited reveal route. valueEncrypted: text("value_encrypted").notNull(), createdByKind: text("created_by_kind").notNull(), createdBySubjectId: text("created_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ columns: [table.fieldId, table.version] }), }), ); export const vaultItemNameAliases = pgTable( "vault_item_name_aliases", { vaultId: uuid("vault_id") .notNull() .references(() => vaults.id, { onDelete: "cascade" }), nameKey: text("name_key").notNull(), itemId: uuid("item_id") .notNull() .references(() => vaultItems.id, { onDelete: "cascade" }), accountId: uuid("account_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ columns: [table.vaultId, table.nameKey] }), item: index("vault_item_name_aliases_item_idx").on(table.itemId), }), ); export const vaultNameAliases = pgTable( "vault_name_aliases", { accountId: uuid("account_id").notNull(), scopeKey: text("scope_key").notNull(), nameKey: text("name_key").notNull(), vaultId: uuid("vault_id") .notNull() .references(() => vaults.id, { onDelete: "cascade" }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ columns: [table.accountId, table.scopeKey, table.nameKey] }), vault: index("vault_name_aliases_vault_idx").on(table.vaultId), }), ); export const vaultPasskeyLeases = pgTable( "vault_passkey_leases", { itemId: uuid("item_id") .primaryKey() .references(() => vaultItems.id, { onDelete: "cascade" }), accountId: uuid("account_id").notNull(), holder: text("holder").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), }, (table) => ({ holder: index("vault_passkey_leases_holder_idx").on(table.holder), }), ); // One durable logical human redemption. `processing` means the fresh provider // detail preflight is still owed; `provider_started` means the POST may have // reached upstream and every retry must reuse upstreamIdempotencyKey without // requiring the credit to remain visible as available. export const codexResetRedemptionAttempts = pgTable( "codex_reset_redemption_attempts", { id: uuid("id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), credentialId: uuid("credential_id").notNull(), subjectId: text("subject_id").notNull(), browserSessionHash: text("browser_session_hash").notNull(), creditId: text("credit_id").notNull(), upstreamIdempotencyKey: uuid("upstream_idempotency_key").notNull().defaultRandom(), status: text("status").notNull().default("processing"), outcome: text("outcome"), claimHolderId: uuid("claim_holder_id"), claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true }), confirmationExpiresAt: timestamp("confirmation_expires_at", { withTimezone: true, }).notNull(), providerStartedAt: timestamp("provider_started_at", { withTimezone: true }), completedAt: timestamp("completed_at", { withTimezone: true }), lastFailureKind: text("last_failure_kind"), retryCount: integer("retry_count").notNull().default(0), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "codex_reset_redemption_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), upstreamKey: uniqueIndex("codex_reset_redemption_upstream_key_idx").on( table.upstreamIdempotencyKey, ), credentialCredit: uniqueIndex("codex_reset_redemption_credential_credit_idx") .on(table.workspaceId, table.credentialId, table.creditId) .where( sql`${table.status} <> 'completed' or ${table.outcome} in ('reset', 'alreadyRedeemed')`, ), workspaceCredential: index("codex_reset_redemption_workspace_credential_idx").on( table.workspaceId, table.credentialId, table.createdAt, ), claimExpiry: index("codex_reset_redemption_claim_expiry_idx") .on(table.claimExpiresAt) .where(sql`${table.status} <> 'completed'`), statusValid: check( "codex_reset_redemption_status_check", sql`${table.status} in ('processing', 'provider_started', 'completed')`, ), outcomeValid: check( "codex_reset_redemption_outcome_check", sql`${table.outcome} is null or ${table.outcome} in ('reset', 'nothingToReset', 'noCredit', 'alreadyRedeemed')`, ), completionConsistent: check( "codex_reset_redemption_completed_check", sql`(${table.status} = 'completed') = (${table.outcome} is not null and ${table.completedAt} is not null)`, ), retryCountValid: check( "codex_reset_redemption_retry_count_check", sql`${table.retryCount} >= 0`, ), humanSubjectValid: check( "codex_reset_redemption_human_subject_check", sql`${table.subjectId} like 'user:_%'`, ), }), ); // Generic external-service credential spine. credential_encrypted is the ONLY // secret-bearing column; normal API reads use metadata-only helpers below the DB // layer. Runtime token material is decrypted only by the broker accessor. export const connections = pgTable( "connections", { allowedModelIds: text("allowed_model_ids").array(), allowedWorkspaceIds: uuid("allowed_workspace_ids").array(), allowPersonalWorkspaces: boolean("allow_personal_workspaces").notNull().default(true), accessPolicyVersion: integer("access_policy_version").notNull().default(1), accessPolicyUpdatedBy: text("access_policy_updated_by"), accessPolicyUpdatedAt: timestamp("access_policy_updated_at", { withTimezone: true }), id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), subjectId: text("subject_id"), providerDomain: text("provider_domain").notNull(), kind: text("kind").notNull(), status: text("status").notNull().default("active"), credentialEncrypted: text("credential_encrypted").notNull(), createOperationId: text("create_operation_id"), createRequestDigest: text("create_request_digest"), grantedScopes: jsonb("granted_scopes").$type().notNull().default([]), expiresAt: timestamp("expires_at", { withTimezone: true }), lastRefreshAt: timestamp("last_refresh_at", { withTimezone: true }), lastUsedAt: timestamp("last_used_at", { withTimezone: true }), lastError: text("last_error"), version: integer("version").notNull().default(1), // Server-owned proof that the dedicated install route verified the exact // credential at this connection version. Generic/legacy writers cannot set // these columns, and migration 0131 clears them when protected fields change // without a fresh verification in the same statement. verifiedInstallAt: timestamp("verified_install_at", { withTimezone: true }), verifiedInstallVersion: integer("verified_install_version"), metadata: jsonb("metadata").$type>().notNull().default({}), // Opaque key of the integration and verified provider account behind this // connection (see connectionAccountIdentityKey); null when unverified. At // most one live row per organization, owner and key (migration 1481). accountIdentityKey: text("account_identity_key"), // The person's own name for the connection, shown when the provider gives // no account identity. Display only: never part of `version` or the // authority generation, and never used to select credentials. label: text("label"), // A workspace's own OpenAI, Azure OpenAI or OpenAI-compatible model key // only: what its model's usage costs, for usage estimates and spend limits // (see organizationModelProviderCustomModels). The catalogue model whose // list rate it shares, or the administrator's own rate; both null when // unknown. Never part of `version`, so the model's id is unaffected. priceBasisModelId: text("price_basis_model_id"), listPricing: jsonb("list_pricing").$type(), createdBySubjectId: text("created_by_subject_id"), updatedBySubjectId: text("updated_by_subject_id"), // Explicit execution authority. Workspace rows have no member authority; // user rows bind one immutable organization membership and common resource // authority. `legacy_user` preserves pre-tenancy personal rows without // inventing an owner membership; it is ineligible for delegated use until // the migration cutover binds it. Public metadata projects only the opaque // authority id to the exact subject owner; membership, scope, origin, and // generation remain internal. authorityScope: text("authority_scope").notNull().default("workspace"), authorityId: uuid("authority_id"), ownerOrganizationMembershipId: uuid("owner_organization_membership_id"), originWorkspaceId: uuid("origin_workspace_id"), // Separate from credential version: refresh may rotate token material // without invalidating already accepted work, while reconnect/disconnect // and identity/status transitions advance this generation. authorityGeneration: bigint("authority_generation", { mode: "number" }).notNull().default(1), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceProviderStatus: index("connections_workspace_provider_status_idx").on( table.workspaceId, table.providerDomain, table.status, ), createOperation: uniqueIndex("connections_create_operation_uq") .on(table.workspaceId, table.createdBySubjectId, table.createOperationId) .where(sql`${table.createOperationId} is not null`), createOperationPair: check( "connections_create_operation_pair_check", sql`(${table.createOperationId} is null and ${table.createRequestDigest} is null) or (${table.createOperationId} is not null and ${table.createRequestDigest} is not null and ${table.createdBySubjectId} is not null)`, ), workspaceSubjectProvider: index("connections_workspace_subject_provider_idx").on( table.workspaceId, table.subjectId, table.providerDomain, ), workspaceKind: index("connections_workspace_kind_idx").on(table.workspaceId, table.kind), workspaceExpires: index("connections_workspace_expires_idx").on( table.workspaceId, table.expiresAt, ), liveAccountIdentity: uniqueIndex("connections_live_account_identity_uq") .on( table.accountId, sql`coalesce(${table.subjectId}, ${table.workspaceId}::text)`, table.accountIdentityKey, ) .where(sql`${table.accountIdentityKey} is not null and ${table.status} <> 'revoked'`), accountIdentityKeyValid: check( "connections_account_identity_key_check", sql`${table.accountIdentityKey} is null or ${table.accountIdentityKey} ~ '^[0-9a-f]{64}$'`, ), authorityIdentity: uniqueIndex("connections_authority_identity_uq") .on(table.accountId, table.authorityId) .where(sql`${table.authorityId} is not null`), ownerAuthority: index("connections_owner_authority_idx") .on( table.accountId, table.ownerOrganizationMembershipId, table.status, table.updatedAt, table.id, ) .where(sql`${table.authorityScope} = 'user'`), authorityScopeValid: check( "connections_authority_scope_check", sql`${table.authorityScope} in ('workspace', 'user', 'legacy_user')`, ), authorityShapeValid: check( "connections_authority_shape_check", sql`( ${table.authorityScope} = 'workspace' and ${table.subjectId} is null and ${table.authorityId} is null and ${table.ownerOrganizationMembershipId} is null and ${table.originWorkspaceId} = ${table.workspaceId} ) or ( ${table.authorityScope} = 'user' and ${table.subjectId} is not null and ${table.authorityId} is not null and ${table.ownerOrganizationMembershipId} is not null and ${table.originWorkspaceId} is not null ) or ( ${table.authorityScope} = 'legacy_user' and ${table.subjectId} is not null and ${table.authorityId} is null and ${table.ownerOrganizationMembershipId} is null and ${table.originWorkspaceId} is not null )`, ), authorityGenerationValid: check( "connections_authority_generation_check", sql`${table.authorityGeneration} > 0`, ), listPriceValid: check( "connections_list_price_chk", sql`(${table.priceBasisModelId} is null or ${table.listPricing} is null) and ((${table.priceBasisModelId} is null and ${table.listPricing} is null) or (${table.subjectId} is null and ${table.kind} = 'api_key' and ${table.metadata} ? 'directModelProvider')) and (${table.priceBasisModelId} is null or (octet_length(${table.priceBasisModelId}) between 1 and 256 and ${table.priceBasisModelId} ~ '^[!-~]+$')) and (${table.listPricing} is null or jsonb_typeof(${table.listPricing}) = 'object')`, ), authority: foreignKey({ name: "connections_authority_fk", columns: [table.authorityId, table.accountId, table.ownerOrganizationMembershipId], foreignColumns: [ organizationUserResourceAuthorities.id, organizationUserResourceAuthorities.accountId, organizationUserResourceAuthorities.organizationMembershipId, ], }).onDelete("restrict"), // Migrations own the same-organization origin FK (ON DELETE CASCADE since // 0857, as origin_workspace_id always equals workspace_id). }), ); /** * Monotonic authority head for one personal GitHub connection's selected * repository set. The head is separate from the selected rows so replacing * the set with an empty array still advances durable authority. */ export const personalGitHubRepositorySelectionHeads = pgTable( "personal_github_repository_selection_heads", { connectionId: uuid("connection_id") .primaryKey() .references(() => connections.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), originWorkspaceId: uuid("origin_workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), ownerSubjectId: text("owner_subject_id").notNull(), providerPrincipalId: text("provider_principal_id").notNull(), credentialBindingId: uuid("credential_binding_id").notNull(), connectionAuthorityGeneration: bigint("connection_authority_generation", { mode: "number", }).notNull(), generation: bigint("generation", { mode: "number" }).notNull().default(1), /** "All my repositories": null, or the access every repository the person can reach gets. */ allRepositoriesAccess: text("all_repositories_access"), allRepositoriesGeneration: bigint("all_repositories_generation", { mode: "number" }), updatedBySubjectId: text("updated_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ tenantConnection: uniqueIndex("personal_github_repository_selection_heads_tenant_uq").on( table.accountId, table.originWorkspaceId, table.ownerSubjectId, table.connectionId, ), owner: index("personal_github_repository_selection_heads_owner_idx").on( table.accountId, table.ownerSubjectId, table.connectionId, ), generationValid: check( "personal_github_repository_selection_heads_generation_chk", sql`${table.connectionAuthorityGeneration} > 0 and ${table.generation} > 0`, ), allAccessValid: check( "personal_github_repository_selection_heads_all_access_chk", sql`${table.allRepositoriesAccess} is null or ${table.allRepositoriesAccess} in ('read', 'write')`, ), }), ); /** Only explicitly selected repositories are persisted; discovery stays live. */ export const personalGitHubRepositorySelections = pgTable( "personal_github_repository_selections", { connectionId: uuid("connection_id").notNull(), repositoryId: bigint("repository_id", { mode: "bigint" }).notNull(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), originWorkspaceId: uuid("origin_workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), ownerSubjectId: text("owner_subject_id").notNull(), canonicalFullName: text("canonical_full_name").notNull(), canonicalHttpsUri: text("canonical_https_uri").notNull(), defaultBranch: text("default_branch").notNull(), visibility: text("visibility").notNull(), private: boolean("private").notNull(), archived: boolean("archived").notNull(), disabled: boolean("disabled").notNull(), permissions: jsonb("permissions").$type>().notNull(), selectedAccess: text("selected_access").notNull(), selectionGeneration: bigint("selection_generation", { mode: "number", }).notNull(), selectedBySubjectId: text("selected_by_subject_id").notNull(), selectedAt: timestamp("selected_at", { withTimezone: true }).notNull().defaultNow(), verifiedAt: timestamp("verified_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ identity: primaryKey({ columns: [table.connectionId, table.repositoryId] }), head: foreignKey({ name: "personal_github_repository_selections_head_fk", columns: [table.accountId, table.originWorkspaceId, table.ownerSubjectId, table.connectionId], foreignColumns: [ personalGitHubRepositorySelectionHeads.accountId, personalGitHubRepositorySelectionHeads.originWorkspaceId, personalGitHubRepositorySelectionHeads.ownerSubjectId, personalGitHubRepositorySelectionHeads.connectionId, ], }).onDelete("cascade"), tenant: index("personal_github_repository_selections_tenant_idx").on( table.accountId, table.originWorkspaceId, table.connectionId, ), shapeValid: check( "personal_github_repository_selections_shape_chk", sql`${table.repositoryId} > 0 and ${table.selectionGeneration} > 0 and ${table.selectedAccess} in ('read', 'write') and ${table.visibility} in ('public', 'private', 'internal') and ${table.private} = (${table.visibility} = 'private') and jsonb_typeof(${table.permissions}) = 'object' and ${table.permissions} ?& array['pull','push','admin','maintain','triage'] and ${table.permissions} - array['pull','push','admin','maintain','triage']::text[] = '{}'::jsonb and jsonb_typeof(${table.permissions}->'pull') = 'boolean' and jsonb_typeof(${table.permissions}->'push') = 'boolean' and jsonb_typeof(${table.permissions}->'admin') = 'boolean' and jsonb_typeof(${table.permissions}->'maintain') = 'boolean' and jsonb_typeof(${table.permissions}->'triage') = 'boolean' and (${table.permissions}->'pull' = 'true'::jsonb or ${table.permissions}->'push' = 'true'::jsonb or ${table.permissions}->'admin' = 'true'::jsonb or ${table.permissions}->'maintain' = 'true'::jsonb or ${table.permissions}->'triage' = 'true'::jsonb) and (${table.selectedAccess} <> 'write' or ( not ${table.archived} and not ${table.disabled} and (${table.permissions}->'push' = 'true'::jsonb or ${table.permissions}->'admin' = 'true'::jsonb or ${table.permissions}->'maintain' = 'true'::jsonb) )) and octet_length(${table.ownerSubjectId}) between 1 and 512 and ${table.canonicalFullName} ~ '^[A-Za-z0-9][A-Za-z0-9_-]{0,38}/[A-Za-z0-9_.-]{1,100}$' and octet_length(${table.canonicalFullName}) between 3 and 140 and octet_length(${table.defaultBranch}) between 1 and 255`, ), }), ); /** Bounded idempotency receipt for an owner-issued full selection replacement. */ export const personalGitHubRepositorySelectionOperations = pgTable( "personal_github_repository_selection_operations", { connectionId: uuid("connection_id").notNull(), idempotencyKey: text("idempotency_key").notNull(), accountId: uuid("account_id").notNull(), originWorkspaceId: uuid("origin_workspace_id").notNull(), ownerSubjectId: text("owner_subject_id").notNull(), requestDigest: bytea("request_digest").notNull(), resultingGeneration: bigint("resulting_generation", { mode: "number", }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ identity: primaryKey({ columns: [table.connectionId, table.idempotencyKey], }), head: foreignKey({ name: "personal_github_repository_selection_operations_head_fk", columns: [table.accountId, table.originWorkspaceId, table.ownerSubjectId, table.connectionId], foreignColumns: [ personalGitHubRepositorySelectionHeads.accountId, personalGitHubRepositorySelectionHeads.originWorkspaceId, personalGitHubRepositorySelectionHeads.ownerSubjectId, personalGitHubRepositorySelectionHeads.connectionId, ], }).onDelete("cascade"), shapeValid: check( "personal_github_repository_selection_operations_shape_chk", sql`${table.resultingGeneration} > 0 and octet_length(${table.idempotencyKey}) between 1 and 200 and octet_length(${table.ownerSubjectId}) between 1 and 512 and octet_length(${table.requestDigest}) = 32`, ), }), ); export const connectionUseOnceConsumptionReceipts = pgTable( "connection_use_once_consumption_receipts", { grantId: uuid("grant_id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), authorityId: uuid("authority_id").notNull(), authorityGeneration: bigint("authority_generation", { mode: "number", }).notNull(), grantGeneration: bigint("grant_generation", { mode: "number" }).notNull(), acceptedWorkKind: text("accepted_work_kind").notNull(), acceptedWorkId: uuid("accepted_work_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ authority: foreignKey({ name: "connection_once_receipts_authority_fk", columns: [table.authorityId, table.accountId], foreignColumns: [ organizationUserResourceAuthorities.id, organizationUserResourceAuthorities.accountId, ], }).onDelete("cascade"), grant: foreignKey({ name: "connection_once_receipts_grant_fk", columns: [table.grantId, table.accountId], foreignColumns: [organizationUserResourceGrants.id, organizationUserResourceGrants.accountId], }).onDelete("cascade"), generationValid: check( "connection_once_receipts_generation_check", sql`${table.authorityGeneration} > 0 and ${table.grantGeneration} > 0`, ), acceptedWorkKindValid: check( "connection_once_receipts_work_kind_check", sql`${table.acceptedWorkKind} in ('turn', 'scheduled_task')`, ), }), ); // One durable routing authority per installed Slack team. The active partial // unique index is the database fence that prevents a team from being routed to // two Opengeni workspaces. Legacy ambiguous rows are retained as quarantined // evidence instead of deleting credentials or guessing a winner. export const slackInstallationBindings = pgTable( "slack_installation_bindings", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), slackTeamId: text("slack_team_id").notNull(), slackTeamName: text("slack_team_name").notNull(), botId: text("bot_id").notNull(), botUserId: text("bot_user_id").notNull(), botDisplayName: text("bot_display_name").notNull(), state: text("state").$type<"active" | "quarantined">().notNull(), quarantineReason: text("quarantine_reason"), version: integer("version").notNull().default(1), createdBySubjectId: text("created_by_subject_id"), updatedBySubjectId: text("updated_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ connection: uniqueIndex("slack_installation_bindings_connection_uq").on(table.connectionId), activeTeam: uniqueIndex("slack_installation_bindings_active_team_uq") .on(table.slackTeamId) .where(sql`${table.state} = 'active'`), workspaceState: index("slack_installation_bindings_workspace_state_idx").on( table.workspaceId, table.state, table.updatedAt, ), workspaceAccount: foreignKey({ name: "slack_installation_bindings_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), stateValid: check( "slack_installation_bindings_state_check", sql`${table.state} in ('active', 'quarantined')`, ), quarantineConsistent: check( "slack_installation_bindings_quarantine_check", sql`(${table.state} = 'active' and ${table.quarantineReason} is null) or (${table.state} = 'quarantined' and length(btrim(${table.quarantineReason})) > 0)`, ), identityBounded: check( "slack_installation_bindings_identity_check", sql`octet_length(${table.slackTeamId}) between 1 and 64 and octet_length(${table.slackTeamName}) between 1 and 256 and octet_length(${table.botId}) between 1 and 64 and octet_length(${table.botUserId}) between 1 and 64 and ${table.botDisplayName} in ('Opengeni', 'Opengeni Staging', 'OpenGeni', 'OpenGeni Staging')`, ), versionPositive: check("slack_installation_bindings_version_check", sql`${table.version} > 0`), }), ); /** Per Slack person and agent: the one-time "next time" hint and first use. */ export const slackAgentUserStates = pgTable( "slack_agent_user_states", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), // With connection_id, a foreign key to agent_slack_installs (agent_id, // connection_id) ON DELETE CASCADE (migration 1385). slackAgentId: uuid("slack_agent_id").notNull(), slackUserId: text("slack_user_id").notNull(), hintInteractionId: uuid("hint_interaction_id"), /** The open-agent chat that showed this person the visibility notice. */ openNoticeInteractionId: uuid("open_notice_interaction_id"), firstUsedAt: timestamp("first_used_at", { withTimezone: true }).notNull().defaultNow(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ // 1398: per installation (1440 dropped the per-agent key). installUser: uniqueIndex("slack_agent_user_states_install_user_uq").on( table.connectionId, table.slackAgentId, table.slackUserId, ), workspaceAccount: foreignKey({ name: "slack_agent_user_states_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), user: index("slack_agent_user_states_user_idx").on(table.connectionId, table.slackUserId), bounded: check( "slack_agent_user_states_bounds_check", sql`octet_length(${table.slackUserId}) between 1 and 64`, ), }), ); /** A Slack agent a chat proposed from Slack; a workspace admin confirms it on the card. */ export const slackAgentProposals = pgTable( "slack_agent_proposals", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), slackTeamId: text("slack_team_id").notNull(), targetAccountId: uuid("target_account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), targetWorkspaceId: uuid("target_workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), proposedBySessionId: uuid("proposed_by_session_id").notNull(), proposedBySlackUserId: text("proposed_by_slack_user_id"), slackChannelId: text("slack_channel_id").notNull(), slackThreadTs: text("slack_thread_ts").notNull(), slackMessageTs: text("slack_message_ts"), messageOperationId: uuid("message_operation_id").notNull(), name: text("name").notNull(), nameKey: text("name_key").notNull(), description: text("description").notNull(), avatar: jsonb("avatar").$type().notNull(), instructions: text("instructions").notNull().default(""), status: text("status") .$type<"pending" | "creating" | "created" | "cancelled">() .notNull() .default("pending"), // With connection_id, a foreign key to agent_slack_installs (agent_id, // connection_id) ON DELETE SET NULL (created_slack_agent_id) (migration 1386). createdSlackAgentId: uuid("created_slack_agent_id"), decidedBySubjectId: text("decided_by_subject_id"), decidedBySlackUserId: text("decided_by_slack_user_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "slack_agent_proposals_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), targetWorkspaceAccount: foreignKey({ name: "slack_agent_proposals_target_workspace_account_fk", columns: [table.targetWorkspaceId, table.targetAccountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspace: index("slack_agent_proposals_workspace_idx").on(table.workspaceId), target: index("slack_agent_proposals_target_idx").on(table.targetWorkspaceId), createdAgent: index("slack_agent_proposals_created_agent_idx") .on(table.createdSlackAgentId) .where(sql`${table.createdSlackAgentId} is not null`), sameAccount: check( "slack_agent_proposals_same_account_check", sql`${table.targetAccountId} = ${table.accountId}`, ), status: check( "slack_agent_proposals_status_check", sql`${table.status} in ('pending', 'creating', 'created', 'cancelled')`, ), bounded: check( "slack_agent_proposals_bounds_check", sql`octet_length(${table.slackTeamId}) between 1 and 64 and (${table.proposedBySlackUserId} is null or octet_length(${table.proposedBySlackUserId}) between 1 and 64) and octet_length(${table.slackChannelId}) between 1 and 64 and octet_length(${table.slackThreadTs}) between 1 and 64 and (${table.slackMessageTs} is null or octet_length(${table.slackMessageTs}) between 1 and 64) and char_length(btrim(${table.name})) between 1 and 80 and char_length(${table.nameKey}) between 1 and 80 and char_length(btrim(${table.description})) between 1 and 200 and jsonb_typeof(${table.avatar}) = 'object' and pg_column_size(${table.avatar}) <= 4096 and char_length(${table.instructions}) <= 8000 and (${table.decidedBySubjectId} is null or octet_length(${table.decidedBySubjectId}) between 1 and 1024) and (${table.decidedBySlackUserId} is null or octet_length(${table.decidedBySlackUserId}) between 1 and 64)`, ), }), ); /** The message an open Ask form came from (message shortcut), until it is submitted. */ export const slackAskForms = pgTable( "slack_ask_forms", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), slackTeamId: text("slack_team_id").notNull(), slackUserId: text("slack_user_id").notNull(), slackChannelId: text("slack_channel_id").notNull(), slackMessageTs: text("slack_message_ts").notNull(), slackThreadTs: text("slack_thread_ts"), providerEventId: text("provider_event_id").notNull(), messageText: text("message_text").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "slack_ask_forms_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), expiry: index("slack_ask_forms_expiry_idx").on(table.connectionId, table.expiresAt), bounded: check( "slack_ask_forms_bounds_check", sql`octet_length(${table.slackTeamId}) between 1 and 64 and octet_length(${table.slackUserId}) between 1 and 64 and octet_length(${table.slackChannelId}) between 1 and 64 and octet_length(${table.slackMessageTs}) between 1 and 64 and (${table.slackThreadTs} is null or octet_length(${table.slackThreadTs}) between 1 and 64) and octet_length(${table.providerEventId}) between 1 and 300 and octet_length(${table.messageText}) between 1 and 32000`, ), }), ); /** Per Slack installation (HOME tenancy): the organization admin's update-message choices. */ export const slackAgentUpdateSettings = pgTable( "slack_agent_update_settings", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), updatesEnabled: boolean("updates_enabled").notNull().default(false), channelPostsOnly: boolean("channel_posts_only").notNull().default(false), /** Where new agents are introduced by default (1235). */ announcementChannelId: text("announcement_channel_id"), updatesEnabledAt: timestamp("updates_enabled_at", { withTimezone: true }), updatedBySubjectId: text("updated_by_subject_id"), sweepHolder: uuid("sweep_holder"), sweepLeaseUntil: timestamp("sweep_lease_until", { withTimezone: true }), lastSweptAt: timestamp("last_swept_at", { withTimezone: true }), version: integer("version").notNull().default(1), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ connection: unique("slack_agent_update_settings_connection_uq").on(table.connectionId), workspaceAccount: foreignKey({ name: "slack_agent_update_settings_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), account: index("slack_agent_update_settings_account_idx").on(table.accountId), bounded: check( "slack_agent_update_settings_bounds_check", sql`(${table.updatedBySubjectId} is null or octet_length(${table.updatedBySubjectId}) between 1 and 1024) and ${table.version} > 0`, ), }), ); /** Channels a Slack agent's intro was posted in (1235). HOME-owned. */ export const slackAgentIntroPosts = pgTable( "slack_agent_intro_posts", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), // With connection_id, a foreign key to agent_slack_installs (agent_id, // connection_id) ON DELETE CASCADE (migration 1387). slackAgentId: uuid("slack_agent_id").notNull(), slackChannelId: text("slack_channel_id").notNull(), postedBySubjectId: text("posted_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ // 1399: per installation (1441 dropped the per-agent key). installChannel: uniqueIndex("slack_agent_intro_posts_install_channel_uq").on( table.connectionId, table.slackAgentId, table.slackChannelId, ), workspaceAccount: foreignKey({ name: "slack_agent_intro_posts_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), account: index("slack_agent_intro_posts_account_idx").on(table.accountId), workspace: index("slack_agent_intro_posts_workspace_idx").on(table.workspaceId), connection: index("slack_agent_intro_posts_connection_idx").on(table.connectionId), bounded: check( "slack_agent_intro_posts_bounds_check", sql`octet_length(${table.slackChannelId}) between 1 and 64 and octet_length(${table.postedBySubjectId}) between 1 and 1024`, ), }), ); /** * A Slack chat suggested asking an agent after answering one Slack message * (1235). HOME-owned. Delivery posts it after the answer; its button re-sends * that message to the agent for whoever clicks it. */ export const slackAgentSuggestions = pgTable( "slack_agent_suggestions", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), // With connection_id, a foreign key to agent_slack_installs (agent_id, // connection_id) ON DELETE CASCADE (migration 1388). slackAgentId: uuid("slack_agent_id").notNull(), interactionId: uuid("interaction_id").notNull(), turnId: uuid("turn_id").notNull(), providerEventId: text("provider_event_id").notNull(), slackTeamId: text("slack_team_id").notNull(), slackUserId: text("slack_user_id").notNull(), slackChannelId: text("slack_channel_id").notNull(), slackThreadTs: text("slack_thread_ts").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ turn: unique("slack_agent_suggestions_turn_uq").on(table.interactionId, table.turnId), workspaceAccount: foreignKey({ name: "slack_agent_suggestions_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), agent: index("slack_agent_suggestions_agent_idx").on(table.slackAgentId), account: index("slack_agent_suggestions_account_idx").on(table.accountId), workspace: index("slack_agent_suggestions_workspace_idx").on(table.workspaceId), connection: index("slack_agent_suggestions_connection_idx").on(table.connectionId), bounded: check( "slack_agent_suggestions_bounds_check", sql`octet_length(${table.providerEventId}) between 1 and 512 and octet_length(${table.slackTeamId}) between 1 and 64 and octet_length(${table.slackUserId}) between 1 and 64 and octet_length(${table.slackChannelId}) between 1 and 64 and octet_length(${table.slackThreadTs}) between 1 and 64`, ), }), ); /** Per Slack person: cached profile facts and which update messages they were sent. */ export const slackAgentUpdateRecipients = pgTable( "slack_agent_update_recipients", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), slackUserId: text("slack_user_id").notNull(), tz: text("tz"), tzOffset: integer("tz_offset"), profileState: text("profile_state").$type< "eligible" | "guest" | "external" | "deactivated" | "bot" >(), profileCheckedAt: timestamp("profile_checked_at", { withTimezone: true }), lastSentAt: timestamp("last_sent_at", { withTimezone: true }), lastKind: text("last_kind").$type<"welcome" | "update" | "dormant">(), welcomeSentAt: timestamp("welcome_sent_at", { withTimezone: true }), dormantSentAt: timestamp("dormant_sent_at", { withTimezone: true }), announcedAgentIds: uuid("announced_agent_ids") .array() .notNull() .default(sql`'{}'`), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ user: unique("slack_agent_update_recipients_user_uq").on(table.connectionId, table.slackUserId), workspaceAccount: foreignKey({ name: "slack_agent_update_recipients_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); /** Each update message: what went to whom, under a deterministic post operation id. */ export const slackAgentUpdateDeliveries = pgTable( "slack_agent_update_deliveries", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), slackUserId: text("slack_user_id").notNull(), kind: text("kind").$type<"welcome" | "update" | "dormant">().notNull(), dedupeKey: text("dedupe_key").notNull(), operationId: uuid("operation_id").notNull(), agentIds: uuid("agent_ids") .array() .notNull() .default(sql`'{}'`), text: text("text").notNull(), blocks: jsonb("blocks").$type().notNull(), state: text("state").$type<"pending" | "sent" | "failed">().notNull().default("pending"), attempts: integer("attempts").notNull().default(0), nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(), slackChannelId: text("slack_channel_id"), slackMessageTs: text("slack_message_ts"), errorCode: text("error_code"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), sentAt: timestamp("sent_at", { withTimezone: true }), }, (table) => ({ dedupe: unique("slack_agent_update_deliveries_dedupe_uq").on( table.connectionId, table.dedupeKey, ), operation: unique("slack_agent_update_deliveries_operation_uq").on(table.operationId), workspaceAccount: foreignKey({ name: "slack_agent_update_deliveries_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), pending: index("slack_agent_update_deliveries_pending_idx") .on(table.connectionId, table.nextAttemptAt) .where(sql`state = 'pending'`), }), ); /** * Per-channel Slack workspace routing within one organization. * * HOME tenancy (`accountId`/`workspaceId`) is the installation binding's own * workspace: it owns the bot credential every provider call is fenced on. The * TARGET (`targetAccountId`/`targetWorkspaceId`) is where the session, its * grant, and its events live. `slack_channel_routes_same_account_check` keeps * both sides in one organization; cross-organization routing is out of scope. * * The row is the durable ask-once memory: once a human picks in the Slack * picker, or an admin sets it in the web sheet, later messages in that channel * never ask again. */ export const slackChannelRoutes = pgTable( "slack_channel_routes", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), slackTeamId: text("slack_team_id").notNull(), slackChannelId: text("slack_channel_id").notNull(), targetAccountId: uuid("target_account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), targetWorkspaceId: uuid("target_workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), decidedBySubjectId: text("decided_by_subject_id").notNull(), decidedBySlackUserId: text("decided_by_slack_user_id").notNull(), source: text("source").$type<"picker" | "admin">().notNull(), // Set when the channel's answer is a Slack agent rather than plain Opengeni // in the target workspace. The target then equals the agent's own target. // With connection_id, a foreign key to agent_slack_installs (agent_id, // connection_id) ON DELETE CASCADE (migration 1383). slackAgentId: uuid("slack_agent_id"), version: integer("version").notNull().default(1), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ channel: unique("slack_channel_routes_channel_uq").on(table.connectionId, table.slackChannelId), workspaceAccount: foreignKey({ name: "slack_channel_routes_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), targetWorkspaceAccount: foreignKey({ name: "slack_channel_routes_target_workspace_account_fk", columns: [table.targetWorkspaceId, table.targetAccountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), target: index("slack_channel_routes_target_idx").on(table.targetWorkspaceId, table.slackTeamId), sameAccount: check( "slack_channel_routes_same_account_check", sql`${table.targetAccountId} = ${table.accountId}`, ), bounded: check( "slack_channel_routes_bounds_check", sql`octet_length(${table.slackTeamId}) between 1 and 64 and octet_length(${table.slackChannelId}) between 1 and 64 and octet_length(${table.decidedBySubjectId}) between 1 and 1024 and octet_length(${table.decidedBySlackUserId}) between 1 and 64 and ${table.source} in ('picker', 'admin') and ${table.version} > 0`, ), }), ); /** * Per-Slack-human direct-message workspace routing, same HOME/TARGET split as * {@link slackChannelRoutes}. Absent a row, a DM derives that human's own * personal workspace from their active organization membership pointer; the * workspace id is never accepted from a Slack payload or from this table. */ export const slackUserDmRoutes = pgTable( "slack_user_dm_routes", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), slackTeamId: text("slack_team_id").notNull(), slackUserId: text("slack_user_id").notNull(), targetAccountId: uuid("target_account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), targetWorkspaceId: uuid("target_workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), decidedBySubjectId: text("decided_by_subject_id").notNull(), decidedBySlackUserId: text("decided_by_slack_user_id").notNull(), source: text("source").$type<"picker" | "admin">().notNull(), version: integer("version").notNull().default(1), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ user: unique("slack_user_dm_routes_user_uq").on(table.connectionId, table.slackUserId), workspaceAccount: foreignKey({ name: "slack_user_dm_routes_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), targetWorkspaceAccount: foreignKey({ name: "slack_user_dm_routes_target_workspace_account_fk", columns: [table.targetWorkspaceId, table.targetAccountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), target: index("slack_user_dm_routes_target_idx").on(table.targetWorkspaceId, table.slackTeamId), sameAccount: check( "slack_user_dm_routes_same_account_check", sql`${table.targetAccountId} = ${table.accountId}`, ), bounded: check( "slack_user_dm_routes_bounds_check", sql`octet_length(${table.slackTeamId}) between 1 and 64 and octet_length(${table.slackUserId}) between 1 and 64 and octet_length(${table.decidedBySubjectId}) between 1 and 1024 and octet_length(${table.decidedBySlackUserId}) between 1 and 64 and ${table.source} in ('picker', 'admin') and ${table.version} > 0`, ), }), ); /** * The pending first-use Slack workspace picker. * * `slack_interaction_action_handles` cannot carry it: that table's `sessionId` * is NOT NULL and composite-FK'd to an existing `slack_interactions` row, while * a picker exists BEFORE any session. * * `inboxId` deliberately carries no foreign key. The `awaiting_choice` inbox row * is settled `processed` before the human answers - the answer arrives as its * own `block_action` inbox row - so this column is provenance, not a live edge. * * `requestText` mirrors the inbox's exact 12000 byte bound so a prompt can * always carry the originating row's text losslessly. * * `providerEventId` is the ORIGINAL event, and it is PROVENANCE, not the id the * answer re-materializes under. Migration 0335's comment claims the answer can * re-insert the original event id under the inbox's own * `(connection_id, provider_event_id)` dedupe unique; that is wrong, and the * migration's bytes are frozen so the claim is corrected here instead. The * original inbox row still exists and is settled `processed`, so re-inserting * its id conflicts and does nothing, and the chosen workspace would never start * any work at all. The answer must enqueue a DERIVED id - * `:route:` - which is unique per prompt and * still idempotent, so a double-click cannot create two sessions. The * `(connection_id, provider_event_id)` unique on this table is what makes * Slack's retries of the same event unable to post a second picker. */ export const slackRoutePrompts = pgTable( "slack_route_prompts", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), inboxId: uuid("inbox_id").notNull(), slackTeamId: text("slack_team_id").notNull(), slackUserId: text("slack_user_id").notNull(), slackChannelId: text("slack_channel_id").notNull(), slackMessageTs: text("slack_message_ts").notNull(), providerEventId: text("provider_event_id").notNull(), triggerKind: text("trigger_kind") .$type< | "app_mention" | "dm" | "reaction" | "slash_command" | "message_shortcut" | "thread_reply" | "block_action" >() .notNull(), requestText: text("request_text").notNull(), hasFiles: boolean("has_files").notNull().default(false), slackThreadTs: text("slack_thread_ts"), messageOperationId: uuid("message_operation_id").notNull(), status: text("status") .$type<"pending" | "answered" | "expired" | "cancelled">() .notNull() .default("pending"), answeredTargetAccountId: uuid("answered_target_account_id"), answeredTargetWorkspaceId: uuid("answered_target_workspace_id"), answeredBySubjectId: text("answered_by_subject_id"), answeredAt: timestamp("answered_at", { withTimezone: true }), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ inbox: unique("slack_route_prompts_inbox_uq").on(table.connectionId, table.inboxId), providerEvent: unique("slack_route_prompts_event_uq").on( table.connectionId, table.providerEventId, ), tenantIdentity: unique("slack_route_prompts_identity_uq").on( table.accountId, table.workspaceId, table.id, ), workspaceAccount: foreignKey({ name: "slack_route_prompts_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), pending: index("slack_route_prompts_pending_idx") .on(table.expiresAt, table.id) .where(sql`${table.status} = 'pending'`), // One live card per person per conversation. The existing uniques are keyed // to the originating event, so they stop Slack's retries of ONE event from // posting twice but not two different messages. `slackUserId` is in the key // on purpose: a shared channel has many people in it, and asking one of them // must not swallow another's request. A direct message is already one // channel per person, so the same index covers both surfaces. // // Expiry is not in the predicate because `now()` is not immutable. A // timed-out row is settled `expired` by the writer before it opens a new // prompt. pendingConversation: uniqueIndex("slack_route_prompts_pending_conversation_uq") .on(table.connectionId, table.slackChannelId, table.slackUserId) .where(sql`${table.status} = 'pending'`), statusValid: check( "slack_route_prompts_status_check", sql`${table.status} in ('pending', 'answered', 'expired', 'cancelled')`, ), triggerValid: check( "slack_route_prompts_trigger_check", sql`${table.triggerKind} in ( 'app_mention', 'dm', 'reaction', 'slash_command', 'message_shortcut', 'thread_reply', 'block_action' )`, ), answerConsistent: check( "slack_route_prompts_answer_check", sql`(${table.status} = 'answered') = (${table.answeredTargetWorkspaceId} is not null) and (${table.answeredTargetAccountId} is null) = (${table.answeredTargetWorkspaceId} is null) and (${table.answeredTargetAccountId} is null or ${table.answeredTargetAccountId} = ${table.accountId}) and (${table.answeredTargetWorkspaceId} is null) = (${table.answeredAt} is null)`, ), bounded: check( "slack_route_prompts_bounds_check", sql`octet_length(${table.slackTeamId}) between 1 and 64 and octet_length(${table.slackUserId}) between 1 and 64 and octet_length(${table.slackChannelId}) between 1 and 64 and octet_length(${table.slackMessageTs}) between 1 and 64 and octet_length(${table.providerEventId}) between 1 and 256 and octet_length(${table.requestText}) between 1 and 12000 and (${table.slackThreadTs} is null or octet_length(${table.slackThreadTs}) between 1 and 64) and (${table.answeredBySubjectId} is null or octet_length(${table.answeredBySubjectId}) between 1 and 1024)`, ), }), ); /** * One row per workspace offered by a {@link slackRoutePrompts} card. The row id * is the Slack button `value`, so it must be a UUID: the block-action normalizer * already requires that shape, which is why the picker uses buttons rather than * a `static_select` (whose `selected_option.value` the normalizer never reads). * * These rows are a snapshot taken at prompt time and are NEVER authority. The * answer path re-authorizes the chosen workspace live. */ export const slackRoutePromptOptions = pgTable( "slack_route_prompt_options", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), promptId: uuid("prompt_id").notNull(), candidateAccountId: uuid("candidate_account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), candidateWorkspaceId: uuid("candidate_workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), candidateLabel: text("candidate_label").notNull(), // Set when the option is a Slack agent. Rechecked live when chosen. candidateSlackAgentId: uuid("candidate_slack_agent_id"), position: integer("position").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "slack_route_prompt_options_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), promptIdentity: foreignKey({ name: "slack_route_prompt_options_prompt_fk", columns: [table.accountId, table.workspaceId, table.promptId], foreignColumns: [ slackRoutePrompts.accountId, slackRoutePrompts.workspaceId, slackRoutePrompts.id, ], }).onDelete("cascade"), candidateWorkspaceAccount: foreignKey({ name: "slack_route_prompt_options_candidate_workspace_account_fk", columns: [table.candidateWorkspaceId, table.candidateAccountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), // An option is one choice: Opengeni in a workspace, or one Slack agent // working there. The same workspace may appear once for each. promptChoice: unique("slack_route_prompt_options_prompt_choice_uq") .on(table.promptId, table.candidateWorkspaceId, table.candidateSlackAgentId) .nullsNotDistinct(), promptPosition: unique("slack_route_prompt_options_prompt_position_uq").on( table.promptId, table.position, ), sameAccount: check( "slack_route_prompt_options_same_account_check", sql`${table.candidateAccountId} = ${table.accountId}`, ), bounded: check( "slack_route_prompt_options_bounds_check", sql`octet_length(${table.candidateLabel}) between 1 and 128 and ${table.position} >= 0`, ), }), ); export const connectionDisconnectOperations = pgTable( "connection_disconnect_operations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), subjectId: text("subject_id").notNull(), idempotencyKey: text("idempotency_key").notNull(), expectedVersion: integer("expected_version").notNull(), resultVersion: integer("result_version").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceSubjectKey: uniqueIndex("connection_disconnect_operations_subject_key_uq").on( table.workspaceId, table.subjectId, table.idempotencyKey, ), connectionGeneration: uniqueIndex( "connection_disconnect_operations_connection_generation_uq", ).on(table.workspaceId, table.connectionId, table.expectedVersion), identityValid: check( "connection_disconnect_operations_identity_check", sql`length(${table.subjectId}) between 1 and 512 and length(${table.idempotencyKey}) between 1 and 200 and ${table.idempotencyKey} = btrim(${table.idempotencyKey}) and ${table.expectedVersion} > 0 and ${table.resultVersion} = ${table.expectedVersion} + 1`, ), }), ); export const connectorActionPolicies = pgTable( "connector_action_policies", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: text("connection_id").notNull(), serverId: text("server_id").notNull(), toolName: text("tool_name").notNull(), actionName: text("action_name").notNull(), policy: text("policy").$type().notNull(), version: integer("version").notNull().default(1), createdBySubjectId: text("created_by_subject_id").notNull(), updatedBySubjectId: text("updated_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "connector_action_policies_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), scope: uniqueIndex("connector_action_policies_scope_uq").on( table.workspaceId, table.connectionId, table.serverId, table.toolName, table.actionName, ), workspaceConnection: index("connector_action_policies_workspace_connection_idx").on( table.workspaceId, table.connectionId, table.serverId, ), policyValid: check( "connector_action_policies_policy_chk", sql`${table.policy} in ('allow', 'ask', 'block')`, ), versionValid: check("connector_action_policies_version_chk", sql`${table.version} > 0`), }), ); export const slackBotUserLinks = pgTable( "slack_bot_user_links", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), slackTeamId: text("slack_team_id").notNull(), slackUserId: text("slack_user_id").notNull(), subjectId: text("subject_id").notNull(), linkedBySubjectId: text("linked_by_subject_id").notNull(), // The exact interaction id that won this identity's one-time onboarding // hint. NULL means the hint has not been shown yet. firstTaskHintInteractionId: uuid("first_task_hint_interaction_id"), // Set when this person muted occasional update messages about new agents. updatesMutedAt: timestamp("updates_muted_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ connectionUser: uniqueIndex("slack_bot_user_links_connection_user_uq").on( table.connectionId, table.slackUserId, ), workspaceSubject: index("slack_bot_user_links_workspace_subject_idx").on( table.workspaceId, table.subjectId, ), }), ); export const slackUserLinkAccessRequests = pgTable( "slack_user_link_access_requests", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), tokenDigest: text("token_digest").notNull(), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), slackTeamId: text("slack_team_id").notNull(), slackUserId: text("slack_user_id").notNull(), subjectId: text("subject_id").notNull(), subjectLabel: text("subject_label"), status: text("status").notNull().default("prepared"), version: integer("version").notNull().default(1), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), requestedAt: timestamp("requested_at", { withTimezone: true }), decidedAt: timestamp("decided_at", { withTimezone: true }), decisionBySubjectId: text("decision_by_subject_id"), approvedRole: text("approved_role"), approvedPermissions: jsonb("approved_permissions").$type(), completedAt: timestamp("completed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "slack_user_link_access_requests_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), tenantIdentity: unique("slack_user_link_access_requests_tenant_uq").on( table.id, table.workspaceId, table.accountId, ), tokenDigestUnique: uniqueIndex("slack_user_link_access_requests_token_digest_uq").on( table.tokenDigest, ), activePrincipal: uniqueIndex("slack_user_link_access_requests_active_principal_uq") .on(table.workspaceId, table.connectionId, table.slackUserId, table.subjectId) .where(sql`${table.status} in ('prepared', 'pending')`), workspacePending: index("slack_user_link_access_requests_workspace_pending_idx").on( table.workspaceId, table.status, table.expiresAt, table.createdAt, ), subjectLookup: index("slack_user_link_access_requests_subject_idx").on( table.workspaceId, table.subjectId, table.id, ), identityValid: check( "slack_user_link_access_requests_identity_check", sql`length(${table.tokenDigest}) = 64 and ${table.tokenDigest} ~ '^[0-9a-f]{64}$' and length(${table.slackTeamId}) between 1 and 64 and length(${table.slackUserId}) between 1 and 64 and length(${table.subjectId}) between 1 and 512 and (${table.subjectLabel} is null or length(${table.subjectLabel}) between 1 and 512) and ${table.version} > 0`, ), statusValid: check( "slack_user_link_access_requests_status_check", sql`${table.status} in ('prepared', 'pending', 'completed', 'denied', 'cancelled', 'expired')`, ), lifecycleValid: check( "slack_user_link_access_requests_lifecycle_check", sql`(${table.status} = 'prepared' and ${table.requestedAt} is null and ${table.decidedAt} is null and ${table.completedAt} is null) or (${table.status} = 'pending' and ${table.requestedAt} is not null and ${table.decidedAt} is null and ${table.completedAt} is null) or (${table.status} = 'completed' and ${table.completedAt} is not null) or (${table.status} in ('denied', 'cancelled', 'expired') and ${table.decidedAt} is not null and ${table.completedAt} is null)`, ), }), ); export const slackUserLinkAccessRequestOperations = pgTable( "slack_user_link_access_request_operations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), requestId: uuid("request_id").notNull(), actorSubjectId: text("actor_subject_id").notNull(), operation: text("operation").notNull(), idempotencyKey: text("idempotency_key").notNull(), requestDigest: text("request_digest").notNull(), expectedVersion: integer("expected_version").notNull(), resultVersion: integer("result_version").notNull(), resultStatus: text("result_status").notNull(), result: jsonb("result").$type().notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "slack_user_link_access_request_operations_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), requestTenant: foreignKey({ name: "slack_user_link_access_request_operations_request_tenant_fk", columns: [table.requestId, table.workspaceId, table.accountId], foreignColumns: [ slackUserLinkAccessRequests.id, slackUserLinkAccessRequests.workspaceId, slackUserLinkAccessRequests.accountId, ], }).onDelete("cascade"), idempotency: uniqueIndex("slack_user_link_access_request_operations_idempotency_uq").on( table.requestId, table.actorSubjectId, table.operation, table.idempotencyKey, ), resultVersionUnique: uniqueIndex( "slack_user_link_access_request_operations_result_version_uq", ).on(table.requestId, table.resultVersion), identityValid: check( "slack_user_link_access_request_operations_identity_check", sql`length(${table.actorSubjectId}) between 1 and 512 and length(${table.idempotencyKey}) between 1 and 200 and ${table.idempotencyKey} = btrim(${table.idempotencyKey}) and length(${table.requestDigest}) = 64 and ${table.requestDigest} ~ '^[0-9a-f]{64}$' and ${table.expectedVersion} > 0 and ${table.resultVersion} = ${table.expectedVersion} + 1 and ${table.operation} in ('request', 'cancel', 'approve', 'deny') and ${table.resultStatus} in ('pending', 'completed', 'denied', 'cancelled') and jsonb_typeof(${table.result}) = 'object' and ${table.result} ?& array[ 'id', 'workspaceId', 'workspaceDisplayName', 'subjectLabel', 'status', 'version', 'expiresAt', 'requestedAt', 'decidedAt', 'completedAt', 'createdAt', 'updatedAt' ] and ${table.result} - array[ 'id', 'workspaceId', 'workspaceDisplayName', 'subjectLabel', 'status', 'version', 'expiresAt', 'requestedAt', 'decidedAt', 'completedAt', 'createdAt', 'updatedAt' ] = '{}'::jsonb and jsonb_typeof(${table.result}->'id') = 'string' and jsonb_typeof(${table.result}->'workspaceId') = 'string' and jsonb_typeof(${table.result}->'workspaceDisplayName') in ('string', 'null') and jsonb_typeof(${table.result}->'subjectLabel') in ('string', 'null') and jsonb_typeof(${table.result}->'status') = 'string' and jsonb_typeof(${table.result}->'version') = 'number' and jsonb_typeof(${table.result}->'expiresAt') = 'string' and jsonb_typeof(${table.result}->'requestedAt') in ('string', 'null') and jsonb_typeof(${table.result}->'decidedAt') in ('string', 'null') and jsonb_typeof(${table.result}->'completedAt') in ('string', 'null') and jsonb_typeof(${table.result}->'createdAt') = 'string' and jsonb_typeof(${table.result}->'updatedAt') = 'string' and ${table.result}->>'id' = ${table.requestId}::text and ${table.result}->>'workspaceId' = ${table.workspaceId}::text and ${table.result}->>'status' = ${table.resultStatus} and ${table.result}->'version' = to_jsonb(${table.resultVersion})`, ), }), ); export const slackInteractionInbox = pgTable( "slack_interaction_inbox", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), providerEventId: text("provider_event_id").notNull(), providerMessageId: text("provider_message_id").notNull(), slackTeamId: text("slack_team_id").notNull(), slackUserId: text("slack_user_id").notNull(), slackChannelId: text("slack_channel_id").notNull(), slackMessageTs: text("slack_message_ts").notNull(), slackThreadTs: text("slack_thread_ts"), triggerKind: text("trigger_kind") .$type< | "app_mention" | "dm" | "reaction" | "slash_command" | "message_shortcut" | "thread_reply" | "block_action" >() .notNull(), text: text("text").notNull(), hasFiles: boolean("has_files").notNull().default(false), status: text("status") .$type<"pending" | "processing" | "processed" | "failed">() .notNull() .default("pending"), claimHolderId: uuid("claim_holder_id"), claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true }), attemptCount: integer("attempt_count").notNull().default(0), retryAt: timestamp("retry_at", { withTimezone: true }), lastErrorCode: text("last_error_code"), reactionContextCheckpoint: jsonb("reaction_context_checkpoint").$type(), // Workspace routing decision, persisted on the claimed row so a retry after // a crash re-uses the same decision rather than re-asking. `accountId` and // `workspaceId` above stay HOME (the installation's credential tenancy) and // stay NOT NULL: `workspace_rls_visible` is strict equality, so a NULL // workspace would make an un-routed row invisible to every tenant including // its own. NULL `routeState` means "legacy / never routed" and is exactly // pre-routing behaviour. routeState: text("route_state").$type<"resolved" | "awaiting_choice" | "denied">(), // Deliberately no foreign key: an inbox row is short-lived and // definer-claimed, so a runtime re-check degrades to "ask again" while an FK // would hard-fail on a workspace deleted mid-flight. targetAccountId: uuid("target_account_id"), targetWorkspaceId: uuid("target_workspace_id"), routePromptId: uuid("route_prompt_id"), // A request routed to one exact Slack agent: a handoff from another chat. // Rechecked when processed, like the target columns above. targetSlackAgentId: uuid("target_slack_agent_id"), handoffFromInteractionId: uuid("handoff_from_interaction_id"), handoffFromSlackAgentId: uuid("handoff_from_slack_agent_id"), routePromptExpiresAt: timestamp("route_prompt_expires_at", { withTimezone: true, }), processedAt: timestamp("processed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ providerEvent: uniqueIndex("slack_interaction_inbox_provider_event_uq").on( table.connectionId, table.providerEventId, ), providerMessage: uniqueIndex("slack_interaction_inbox_provider_message_uq").on( table.connectionId, table.providerMessageId, ), pending: index("slack_interaction_inbox_pending_idx").on( table.status, table.retryAt, table.createdAt, table.id, ), // Thread-context reads (migration 1013): a mention in a mapped thread // attaches the untagged messages recorded since the last invocation. threadContext: index("slack_interaction_inbox_thread_context_idx") .on(table.connectionId, table.slackChannelId, table.slackThreadTs, table.createdAt.desc()) .where(sql`${table.slackThreadTs} is not null`), }), ); // Coalesced private App Home refresh authority. One row per installed Slack // connection/user serializes provider replacement calls while allowing event // retries and newer opens to converge on the latest requested revision. export const slackAppHomeRefreshes = pgTable( "slack_app_home_refreshes", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), slackTeamId: text("slack_team_id").notNull(), slackUserId: text("slack_user_id").notNull(), providerEventId: text("provider_event_id").notNull(), providerViewHash: text("provider_view_hash"), desiredRevision: integer("desired_revision").notNull().default(1), processedRevision: integer("processed_revision").notNull().default(0), claimHolderId: uuid("claim_holder_id"), claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true }), attemptCount: integer("attempt_count").notNull().default(0), retryAt: timestamp("retry_at", { withTimezone: true }), lastErrorCode: text("last_error_code"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ connectionUser: uniqueIndex("slack_app_home_refreshes_connection_user_uq").on( table.connectionId, table.slackUserId, ), pending: index("slack_app_home_refreshes_pending_idx") .on(table.retryAt, table.updatedAt, table.id) .where(sql`${table.processedRevision} < ${table.desiredRevision}`), workspaceAccount: foreignKey({ name: "slack_app_home_refreshes_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), bounds: check( "slack_app_home_refreshes_bounds_check", sql`octet_length(${table.slackTeamId}) between 1 and 64 and octet_length(${table.slackUserId}) between 1 and 64 and octet_length(${table.providerEventId}) between 1 and 256 and (${table.providerViewHash} is null or octet_length(${table.providerViewHash}) between 1 and 256) and (${table.lastErrorCode} is null or octet_length(${table.lastErrorCode}) between 1 and 128)`, ), revisions: check( "slack_app_home_refreshes_revisions_check", sql`${table.desiredRevision} > 0 and ${table.processedRevision} >= 0 and ${table.processedRevision} <= ${table.desiredRevision} and ${table.attemptCount} >= 0`, ), claim: check( "slack_app_home_refreshes_claim_check", sql`(${table.claimHolderId} is null) = (${table.claimExpiresAt} is null)`, ), }), ); export const slackInteractions = pgTable( "slack_interactions", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), slackTeamId: text("slack_team_id").notNull(), slackChannelId: text("slack_channel_id").notNull(), slackThreadTs: text("slack_thread_ts").notNull(), routeKey: text("route_key").notNull(), triggeringProviderEventId: text("triggering_provider_event_id").notNull(), initiatingSlackUserId: text("initiating_slack_user_id"), owningSubjectId: text("owning_subject_id").notNull(), visibility: text("visibility").$type<"private" | "workspace">().notNull(), sessionReservationId: uuid("session_reservation_id").notNull().defaultRandom(), sessionId: uuid("session_id").references(() => sessions.id, { onDelete: "cascade", }), lastDeliveredSessionEventSequence: integer("last_delivered_session_event_sequence") .notNull() .default(0), deliveryClaimHolderId: uuid("delivery_claim_holder_id"), deliveryClaimExpiresAt: timestamp("delivery_claim_expires_at", { withTimezone: true, }), deliveryAttemptCount: integer("delivery_attempt_count").notNull().default(0), deliveryRetryAt: timestamp("delivery_retry_at", { withTimezone: true }), deliveryLastErrorCode: text("delivery_last_error_code"), ackSlackMessageTs: text("ack_slack_message_ts"), // Frozen once: whether this interaction's acknowledgement renders the // one-time onboarding hint. NULL means the decision has not been resolved. firstTaskHint: boolean("first_task_hint"), // The routed workspace's display name, frozen when the interaction binds. // A live lookup at post time would be wrong: a workspace rename between the // original post and a reconciliation makes `reconcilePostMessage`'s // byte-compare raise `post_reconciliation_mismatch`. NULL means no // per-message workspace line. routedWorkspaceLabel: text("routed_workspace_label"), // What the bound session started with (connectors, repositories, Sandbox // Environment), rendered once when the session binds and shown in the // acknowledgement. Frozen for the same byte-compare reason as the label // above: the session's tools and resources can change after creation. // NULL means no line. No longer written: new tasks do not list what they // started with, and older rows keep their line so a repair of an already // posted acknowledgement still renders the same bytes. sessionDefaultsLine: text("session_defaults_line"), // The first message's opening sentence (session link, routed workspace, // privacy note), rendered once when the session binds. Frozen for the same // byte-compare reason as the label above: the first message is re-rendered // on repair, on every Stop/Resume click, and when the task settles. NULL // means the interaction keeps the previous message format (bound before // this column existed, or by an older image). startMessageLine: text("start_message_line"), // The Slack agent this chat was started for, frozen when the thread binds. // With connection_id, a foreign key to agent_slack_installs (agent_id, // connection_id) ON DELETE SET NULL (slack_agent_id) (migration 1384). slackAgentId: uuid("slack_agent_id"), // The agent whose chat passed this thread on, so it is never handed back. handoffFromSlackAgentId: uuid("handoff_from_slack_agent_id"), // The latest Slack message this chat was given and who sent it. A message // that was itself passed on is never passed on again. lastInboundProviderEventId: text("last_inbound_provider_event_id"), lastInboundSlackUserId: text("last_inbound_slack_user_id"), progressCount: integer("progress_count").notNull().default(0), terminalDeliveryState: text("terminal_delivery_state") .$type<"open" | "completed" | "failed" | "cancelled" | "blocked">() .notNull() .default("open"), // A wake asked to reopen the delivery while it was open: a run settling at // or before this sequence leaves it open for the woken answer. deliveryReopenAfterSequence: integer("delivery_reopen_after_sequence"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ route: uniqueIndex("slack_interactions_route_uq").on(table.connectionId, table.routeKey), identity: uniqueIndex("slack_interactions_identity_uq").on( table.accountId, table.workspaceId, table.id, ), workspaceReservation: uniqueIndex("slack_interactions_workspace_reservation_uq").on( table.workspaceId, table.sessionReservationId, ), workspaceSession: uniqueIndex("slack_interactions_workspace_session_uq") .on(table.workspaceId, table.sessionId) .where(sql`${table.sessionId} is not null`), slackAgent: index("slack_interactions_slack_agent_idx") .on(table.slackAgentId, table.createdAt.desc()) .where(sql`${table.slackAgentId} is not null`), delivery: index("slack_interactions_delivery_idx").on( table.terminalDeliveryState, table.deliveryRetryAt, table.updatedAt, table.id, ), }), ); export const slackInteractionActionHandles = pgTable( "slack_interaction_action_handles", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), interactionId: uuid("interaction_id").notNull(), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), sessionEventSequence: integer("session_event_sequence").notNull(), actionKind: text("action_kind") .$type< | "approval_approve" | "approval_reject" | "human_input_select" | "human_input_skip" | "session_status" | "session_pause" | "session_resume" | "shared_result_publish" >() .notNull(), actionKey: text("action_key").notNull(), targetId: text("target_id"), targetValue: text("target_value"), authorizedSubjectId: text("authorized_subject_id").notNull(), authorizedSlackUserId: text("authorized_slack_user_id").notNull(), messageOperationId: uuid("message_operation_id").notNull(), status: text("status").$type<"pending" | "completed" | "stale">().notNull().default("pending"), result: text("result"), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), completedAt: timestamp("completed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ interactionIdentity: foreignKey({ columns: [table.accountId, table.workspaceId, table.interactionId], foreignColumns: [ slackInteractions.accountId, slackInteractions.workspaceId, slackInteractions.id, ], name: "slack_interaction_action_handles_interaction_fk", }).onDelete("cascade"), identity: uniqueIndex("slack_interaction_action_handles_identity_uq").on( table.interactionId, table.sessionEventSequence, table.actionKey, ), pending: index("slack_interaction_action_handles_pending_idx").on( table.workspaceId, table.status, table.expiresAt, table.id, ), }), ); export const slackInteractionProgressDeliveries = pgTable( "slack_interaction_progress_deliveries", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), interactionId: uuid("interaction_id").notNull(), sessionEventSequence: integer("session_event_sequence").notNull(), slot: integer("slot").notNull(), operationId: uuid("operation_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ interactionIdentity: foreignKey({ columns: [table.accountId, table.workspaceId, table.interactionId], foreignColumns: [ slackInteractions.accountId, slackInteractions.workspaceId, slackInteractions.id, ], name: "slack_interaction_progress_deliveries_interaction_fk", }).onDelete("cascade"), event: uniqueIndex("slack_interaction_progress_deliveries_event_uq").on( table.interactionId, table.sessionEventSequence, ), slot: uniqueIndex("slack_interaction_progress_deliveries_slot_uq").on( table.interactionId, table.slot, ), operation: uniqueIndex("slack_interaction_progress_deliveries_operation_uq").on( table.workspaceId, table.operationId, ), }), ); // Durable provider-operation identity for Opengeni Slack bot posts. The // server-owned durable operation UUID is also Slack's client_msg_id. `pending` is // safe to send, `provider_started` and `outcome_unknown` require provider read // reconciliation, and only `completed` may expose the provider result. export const slackBotPostOperations = pgTable( "slack_bot_post_operations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), operationId: uuid("operation_id").notNull(), clientMessageId: uuid("client_message_id").notNull(), targetKind: text("target_kind").$type<"channel" | "user">().notNull(), targetId: text("target_id").notNull(), requestDigest: text("request_digest").notNull(), status: text("status") .$type<"pending" | "provider_started" | "outcome_unknown" | "completed">() .notNull(), claimHolderId: uuid("claim_holder_id"), claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true }), claimMode: text("claim_mode").$type<"send" | "reconcile">(), attemptCount: integer("attempt_count").notNull().default(0), lastFailureCode: text("last_failure_code"), slackChannelId: text("slack_channel_id"), slackMessageTimestamp: text("slack_message_timestamp"), completedAt: timestamp("completed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceOperation: uniqueIndex("slack_bot_post_operations_workspace_operation_uq").on( table.workspaceId, table.connectionId, table.operationId, ), workspaceStatus: index("slack_bot_post_operations_workspace_status_idx").on( table.workspaceId, table.status, table.updatedAt, ), targetKindValid: check( "slack_bot_post_operations_target_kind_check", sql`${table.targetKind} in ('channel', 'user')`, ), statusValid: check( "slack_bot_post_operations_status_check", sql`${table.status} in ('pending', 'provider_started', 'outcome_unknown', 'completed')`, ), identityValid: check( "slack_bot_post_operations_identity_check", sql`${table.clientMessageId} = ${table.operationId} and length(${table.targetId}) between 1 and 64 and ${table.requestDigest} ~ '^[0-9a-f]{64}$' and ${table.attemptCount} > 0 and ( ( ${table.claimHolderId} is null and ${table.claimExpiresAt} is null and ${table.claimMode} is null ) or ( ${table.claimHolderId} is not null and ${table.claimExpiresAt} is not null and ( (${table.claimMode} = 'send' and ${table.status} in ('pending', 'provider_started')) or (${table.claimMode} = 'reconcile' and ${table.status} = 'outcome_unknown') ) ) )`, ), completionValid: check( "slack_bot_post_operations_completion_check", sql`( ${table.status} <> 'completed' and ${table.slackChannelId} is null and ${table.slackMessageTimestamp} is null and ${table.completedAt} is null ) or ( ${table.status} = 'completed' and ${table.claimHolderId} is null and ${table.claimExpiresAt} is null and ${table.slackChannelId} is not null and ${table.slackMessageTimestamp} is not null and ${table.completedAt} is not null )`, ), }), ); export const slackBotUpdateOperations = pgTable( "slack_bot_update_operations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), operationId: uuid("operation_id").notNull(), slackChannelId: text("slack_channel_id").notNull(), slackMessageTimestamp: text("slack_message_timestamp").notNull(), requestDigest: text("request_digest").notNull(), status: text("status").$type<"provider_started" | "completed">().notNull(), claimHolderId: uuid("claim_holder_id"), claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true }), attemptCount: integer("attempt_count").notNull().default(0), lastFailureCode: text("last_failure_code"), completedAt: timestamp("completed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceOperation: uniqueIndex("slack_bot_update_operations_workspace_operation_uq").on( table.workspaceId, table.connectionId, table.operationId, ), workspaceStatus: index("slack_bot_update_operations_workspace_status_idx").on( table.workspaceId, table.status, table.updatedAt, ), }), ); export const memorySlackPublicationConfigurations = pgTable( "memory_slack_publication_configurations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), revision: integer("revision").notNull(), enabled: boolean("enabled").notNull(), connectionId: uuid("connection_id"), slackTeamId: text("slack_team_id"), slackChannelId: text("slack_channel_id"), slackChannelName: text("slack_channel_name"), autoImportances: text("auto_importances").array().notNull().default(["major"]), reviewImportances: text("review_importances").array().notNull().default(["normal"]), createdBySubjectId: text("created_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceRevision: uniqueIndex( "memory_slack_publication_configurations_workspace_revision_uq", ).on(table.workspaceId, table.revision), workspaceCreated: index("memory_slack_publication_configurations_workspace_created_idx").on( table.workspaceId, table.revision, ), revisionValid: check( "memory_slack_publication_configurations_revision_check", sql`${table.revision} > 0`, ), destinationValid: check( "memory_slack_publication_configurations_destination_check", sql`not ${table.enabled} or ( ${table.connectionId} is not null and octet_length(${table.slackTeamId}) between 1 and 64 and octet_length(${table.slackChannelId}) between 1 and 64 )`, ), channelNameValid: check( "memory_slack_publication_configurations_channel_name_check", sql`${table.slackChannelName} is null or octet_length(${table.slackChannelName}) between 1 and 256`, ), policyValid: check( "memory_slack_publication_configurations_policy_check", sql`${table.autoImportances} <@ array['major', 'normal', 'minor']::text[] and ${table.reviewImportances} <@ array['major', 'normal', 'minor']::text[] and cardinality(${table.autoImportances}) <= 3 and cardinality(${table.reviewImportances}) <= 3 and not (${table.autoImportances} && ${table.reviewImportances})`, ), actorValid: check( "memory_slack_publication_configurations_actor_check", sql`octet_length(${table.createdBySubjectId}) between 1 and 1024`, ), }), ); export const memorySlackPublications = pgTable( "memory_slack_publications", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), configurationId: uuid("configuration_id") .notNull() .references(() => memorySlackPublicationConfigurations.id, { onDelete: "restrict", }), configurationRevision: integer("configuration_revision").notNull(), connectionId: uuid("connection_id").notNull(), slackTeamId: text("slack_team_id").notNull(), slackChannelId: text("slack_channel_id").notNull(), sourceType: text("source_type").$type<"workspace_memory" | "durable_learning">().notNull(), sourceId: text("source_id").notNull(), sourceVersion: text("source_version"), sourceIdempotencyKey: text("source_idempotency_key").notNull(), projection: jsonb("projection").$type>().notNull(), projectionSha256: text("projection_sha256").notNull(), importance: text("importance").$type<"major" | "normal" | "minor">().notNull(), deliveryMode: text("delivery_mode").$type<"auto" | "review">().notNull(), state: text("state") .$type< | "review_pending" | "queued" | "delivering" | "retry_wait" | "delivered" | "rejected" | "failed" | "cancelled" >() .notNull(), operationId: uuid("operation_id").notNull(), initiatorKind: text("initiator_kind").$type<"human" | "agent" | "service">().notNull(), initiatorSubjectId: text("initiator_subject_id").notNull(), initiatingHumanSubjectId: text("initiating_human_subject_id"), sessionId: uuid("session_id"), turnId: uuid("turn_id"), attemptId: uuid("attempt_id"), claimHolderId: uuid("claim_holder_id"), claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true }), attemptCount: integer("attempt_count").notNull().default(0), retryAt: timestamp("retry_at", { withTimezone: true }), lastErrorCode: text("last_error_code"), slackMessageTimestamp: text("slack_message_timestamp"), deliveredAt: timestamp("delivered_at", { withTimezone: true }), terminalAt: timestamp("terminal_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ source: uniqueIndex("memory_slack_publications_source_uq").on( table.workspaceId, table.sourceIdempotencyKey, ), operation: uniqueIndex("memory_slack_publications_operation_uq").on( table.workspaceId, table.operationId, ), claim: index("memory_slack_publications_claim_idx").on( table.state, table.retryAt, table.createdAt, table.id, ), workspaceHistory: index("memory_slack_publications_workspace_history_idx").on( table.workspaceId, table.createdAt, table.id, ), sourceTypeValid: check( "memory_slack_publications_source_type_check", sql`${table.sourceType} in ('workspace_memory', 'durable_learning')`, ), sourceValid: check( "memory_slack_publications_source_check", sql`octet_length(${table.sourceId}) between 1 and 1024 and (${table.sourceVersion} is null or octet_length(${table.sourceVersion}) between 1 and 512) and octet_length(${table.sourceIdempotencyKey}) between 1 and 256`, ), projectionValid: check( "memory_slack_publications_projection_check", sql`jsonb_typeof(${table.projection}) = 'object' and octet_length(${table.projection}::text) between 2 and 8192 and ${table.projectionSha256} ~ '^[0-9a-f]{64}$'`, ), distributionValid: check( "memory_slack_publications_distribution_check", sql`${table.importance} in ('major', 'normal', 'minor') and ${table.deliveryMode} in ('auto', 'review')`, ), stateValid: check( "memory_slack_publications_state_check", sql`${table.state} in ( 'review_pending', 'queued', 'delivering', 'retry_wait', 'delivered', 'rejected', 'failed', 'cancelled' )`, ), destinationValid: check( "memory_slack_publications_destination_check", sql`${table.configurationRevision} > 0 and octet_length(${table.slackTeamId}) between 1 and 64 and octet_length(${table.slackChannelId}) between 1 and 64`, ), initiatorValid: check( "memory_slack_publications_initiator_check", sql`${table.initiatorKind} in ('human', 'agent', 'service') and octet_length(${table.initiatorSubjectId}) between 1 and 1024 and (${table.initiatingHumanSubjectId} is null or octet_length(${table.initiatingHumanSubjectId}) between 1 and 1024)`, ), claimValid: check( "memory_slack_publications_claim_check", sql`(${table.state} = 'delivering' and ${table.claimHolderId} is not null and ${table.claimExpiresAt} is not null and ${table.retryAt} is null) or (${table.state} = 'retry_wait' and ${table.claimHolderId} is null and ${table.claimExpiresAt} is null and ${table.retryAt} is not null) or (${table.state} not in ('delivering', 'retry_wait') and ${table.claimHolderId} is null and ${table.claimExpiresAt} is null and ${table.retryAt} is null)`, ), attemptValid: check("memory_slack_publications_attempt_check", sql`${table.attemptCount} >= 0`), errorValid: check( "memory_slack_publications_error_check", sql`${table.lastErrorCode} is null or octet_length(${table.lastErrorCode}) between 1 and 128`, ), }), ); export const memorySlackPublicationReceipts = pgTable( "memory_slack_publication_receipts", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), publicationId: uuid("publication_id") .notNull() .references(() => memorySlackPublications.id, { onDelete: "cascade" }), sequence: integer("sequence").notNull(), kind: text("kind") .$type< | "enqueued" | "review_approved" | "review_rejected" | "delivery_claimed" | "retry_scheduled" | "delivered" | "failed" | "cancelled" | "manual_retry" >() .notNull(), state: text("state") .$type< | "review_pending" | "queued" | "delivering" | "retry_wait" | "delivered" | "rejected" | "failed" | "cancelled" >() .notNull(), attemptNumber: integer("attempt_number").notNull(), actorKind: text("actor_kind").$type<"human" | "agent" | "service">().notNull(), actorSubjectId: text("actor_subject_id").notNull(), operationId: uuid("operation_id").notNull(), errorCode: text("error_code"), retryAt: timestamp("retry_at", { withTimezone: true }), slackChannelId: text("slack_channel_id"), slackMessageTimestamp: text("slack_message_timestamp"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ sequenceUnique: uniqueIndex("memory_slack_publication_receipts_sequence_uq").on( table.publicationId, table.sequence, ), workspaceHistory: index("memory_slack_publication_receipts_workspace_history_idx").on( table.workspaceId, table.publicationId, table.sequence, ), kindValid: check( "memory_slack_publication_receipts_kind_check", sql`${table.kind} in ( 'enqueued', 'review_approved', 'review_rejected', 'delivery_claimed', 'retry_scheduled', 'delivered', 'failed', 'cancelled', 'manual_retry' )`, ), stateValid: check( "memory_slack_publication_receipts_state_check", sql`${table.state} in ( 'review_pending', 'queued', 'delivering', 'retry_wait', 'delivered', 'rejected', 'failed', 'cancelled' )`, ), attemptValid: check( "memory_slack_publication_receipts_attempt_check", sql`${table.sequence} > 0 and ${table.attemptNumber} >= 0`, ), actorValid: check( "memory_slack_publication_receipts_actor_check", sql`${table.actorKind} in ('human', 'agent', 'service') and octet_length(${table.actorSubjectId}) between 1 and 1024`, ), errorValid: check( "memory_slack_publication_receipts_error_check", sql`${table.errorCode} is null or octet_length(${table.errorCode}) between 1 and 128`, ), providerValid: check( "memory_slack_publication_receipts_provider_check", sql`((${table.slackChannelId} is null) = (${table.slackMessageTimestamp} is null)) and (${table.slackChannelId} is null or octet_length(${table.slackChannelId}) between 1 and 64) and (${table.slackMessageTimestamp} is null or octet_length(${table.slackMessageTimestamp}) between 1 and 64)`, ), }), ); // Durable provider-operation identity for Opengeni Slack bot deletions. Slack // has no client-supplied idempotency key for chat.delete, so an expired // provider_started claim becomes outcome_unknown and must be reconciled before // another mutation is admitted. export const slackBotDeleteOperations = pgTable( "slack_bot_delete_operations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), operationId: uuid("operation_id").notNull(), principalType: text("principal_type").$type<"subject" | "service">().notNull(), principalId: text("principal_id").notNull(), toolName: text("tool_name").notNull(), channelId: text("channel_id").notNull(), messageTimestamp: text("message_timestamp").notNull(), requestDigest: text("request_digest").notNull(), status: text("status") .$type<"pending" | "provider_started" | "outcome_unknown" | "completed">() .notNull(), claimHolderId: uuid("claim_holder_id"), claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true }), attemptCount: integer("attempt_count").notNull().default(0), lastFailureCode: text("last_failure_code"), slackChannelId: text("slack_channel_id"), slackMessageTimestamp: text("slack_message_timestamp"), completedAt: timestamp("completed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceOperation: uniqueIndex("slack_bot_delete_operations_workspace_operation_uq").on( table.workspaceId, table.operationId, ), workspaceStatus: index("slack_bot_delete_operations_workspace_status_idx").on( table.workspaceId, table.status, table.updatedAt, ), principalValid: check( "slack_bot_delete_operations_principal_check", sql`${table.principalType} in ('subject', 'service') and length(${table.principalId}) between 1 and 512`, ), identityValid: check( "slack_bot_delete_operations_identity_check", sql`${table.toolName} = 'slack_bot_delete_message' and length(${table.channelId}) between 1 and 64 and length(${table.messageTimestamp}) between 1 and 64 and ${table.requestDigest} ~ '^[0-9a-f]{64}$' and ${table.attemptCount} > 0 and ((${table.claimHolderId} is null) = (${table.claimExpiresAt} is null))`, ), statusValid: check( "slack_bot_delete_operations_status_check", sql`${table.status} in ('pending', 'provider_started', 'outcome_unknown', 'completed')`, ), completionValid: check( "slack_bot_delete_operations_completion_check", sql`( ${table.status} <> 'completed' and ${table.slackChannelId} is null and ${table.slackMessageTimestamp} is null and ${table.completedAt} is null ) or ( ${table.status} = 'completed' and ${table.claimHolderId} is null and ${table.claimExpiresAt} is null and ${table.slackChannelId} is not null and ${table.slackMessageTimestamp} is not null and ${table.completedAt} is not null )`, ), }), ); // OAuth client registrations minted through MCP DCR, keyed by authorization // server issuer. This is deployment-wide client identity, not a workspace // credential; per-user/provider tokens still live only in connections. export const integrationOauthClients = pgTable( "integration_oauth_clients", { id: uuid("id").primaryKey().defaultRandom(), issuer: text("issuer").notNull(), authorizationServer: text("authorization_server").notNull(), clientId: text("client_id").notNull(), clientSecretEncrypted: text("client_secret_encrypted"), tokenEndpointAuthMethod: text("token_endpoint_auth_method").notNull().default("none"), metadata: jsonb("metadata").$type>().notNull().default({}), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ issuer: uniqueIndex("integration_oauth_clients_issuer_idx").on(table.issuer), authorizationServer: index("integration_oauth_clients_as_idx").on(table.authorizationServer), }), ); // Consumed OAuth state nonces. Rows are inserted only on callback; the primary // key makes a verified state single-use across API instances. export const hostMcpTurnAuthorities = pgTable( "host_mcp_turn_authorities", { turnId: uuid("turn_id") .notNull() .references(() => sessionTurns.id, { onDelete: "cascade" }), serverId: text("server_id").notNull(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), ownerSubjectId: text("owner_subject_id").notNull(), bindingId: uuid("binding_id") .notNull() .references(() => hostMcpBindings.id), delegationId: uuid("delegation_id") .notNull() .references(() => hostMcpDelegations.id), canonicalSnapshot: jsonb("canonical_snapshot") .$type() .notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ columns: [table.turnId, table.serverId] }), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), serverBounds: check( "host_mcp_turn_authorities_server_id_check", sql`octet_length(${table.serverId}) between 1 and 1024`, ), snapshotBounds: check( "host_mcp_turn_authorities_canonical_snapshot_check", sql`jsonb_typeof(${table.canonicalSnapshot}) = 'object' and octet_length(${table.canonicalSnapshot}::text) <= 262144`, ), }), ); export const integrationOauthStateNonces = pgTable( "integration_oauth_state_nonces", { nonce: text("nonce").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), subjectId: text("subject_id").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), usedAt: timestamp("used_at", { withTimezone: true }).notNull().defaultNow(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspace: index("integration_oauth_state_nonces_workspace_idx").on(table.workspaceId), expires: index("integration_oauth_state_nonces_expires_idx").on(table.expiresAt), }), ); export const integrationOauthPendingStates = pgTable( "integration_oauth_pending_states", { id: uuid("id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id"), stateEncrypted: text("state_encrypted").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "integration_oauth_pending_states_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), expiry: index("integration_oauth_pending_states_expiry_idx").on( table.workspaceId, table.expiresAt, ), }), ); export const workspaceCredentialProviders = pgTable( "workspace_credential_providers", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id").notNull(), url: text("url").notNull(), secretEncrypted: text("secret_encrypted").notNull(), enabled: boolean("enabled").notNull().default(true), timeoutMs: integer("timeout_ms").notNull().default(10000), createdBySubjectId: text("created_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "workspace_credential_providers_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceUnique: uniqueIndex("workspace_credential_providers_workspace_uq").on( table.workspaceId, ), }), ); export const workspaceWebhooks = pgTable( "workspace_webhooks", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id").notNull(), url: text("url").notNull(), secretEncrypted: text("secret_encrypted").notNull(), eventTypes: text("event_types").array().notNull(), enabled: boolean("enabled").notNull().default(true), description: text("description"), createdBySubjectId: text("created_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "workspace_webhooks_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceIdUnique: unique("workspace_webhooks_workspace_id_uq").on(table.workspaceId, table.id), workspaceIndex: index("workspace_webhooks_workspace_idx").on( table.workspaceId, table.createdAt, ), }), ); export const workspaceWebhookDeliveries = pgTable( "workspace_webhook_deliveries", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id").notNull(), webhookId: uuid("webhook_id").notNull(), eventId: uuid("event_id").notNull(), eventType: text("event_type").notNull(), payload: jsonb("payload").notNull(), attempts: integer("attempts").notNull().default(0), nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(), deliveredAt: timestamp("delivered_at", { withTimezone: true }), failedAt: timestamp("failed_at", { withTimezone: true }), lastStatus: integer("last_status"), lastError: text("last_error"), claimId: uuid("claim_id"), claimUntil: timestamp("claim_until", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "workspace_webhook_deliveries_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), webhook: foreignKey({ name: "workspace_webhook_deliveries_webhook_fk", columns: [table.workspaceId, table.webhookId], foreignColumns: [workspaceWebhooks.workspaceId, workspaceWebhooks.id], }).onDelete("cascade"), eventUnique: uniqueIndex("workspace_webhook_deliveries_event_uq").on( table.webhookId, table.eventId, ), recent: index("workspace_webhook_deliveries_webhook_recent_idx").on( table.webhookId, table.createdAt, ), }), ); export type IntegrationWorkspaceFilter = { externalSource: string }; export const organizationCredentialProviders = pgTable( "organization_credential_providers", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), url: text("url").notNull(), secretEncrypted: text("secret_encrypted").notNull(), enabled: boolean("enabled").notNull().default(true), timeoutMs: integer("timeout_ms").notNull().default(10000), workspaceFilter: jsonb("workspace_filter").$type(), /** Personal workspaces; the workspace filter applies to shared ones only. */ allowPersonalWorkspaces: boolean("allow_personal_workspaces").notNull().default(false), /** Shared workspaces it serves; null is every one. The filter applies on top. */ allowedWorkspaceIds: uuid("allowed_workspace_ids").array(), createdBySubjectId: text("created_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ accountUnique: uniqueIndex("organization_credential_providers_account_uq").on(table.accountId), }), ); export const organizationWebhooks = pgTable( "organization_webhooks", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), url: text("url").notNull(), secretEncrypted: text("secret_encrypted").notNull(), eventTypes: text("event_types").array().notNull(), enabled: boolean("enabled").notNull().default(true), description: text("description"), workspaceFilter: jsonb("workspace_filter").$type(), /** Shared workspaces whose events it receives; null is every one. Never Personal ones. */ allowedWorkspaceIds: uuid("allowed_workspace_ids").array(), createdBySubjectId: text("created_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ accountIdUnique: unique("organization_webhooks_account_id_uq").on(table.accountId, table.id), accountIndex: index("organization_webhooks_account_idx").on(table.accountId, table.createdAt), }), ); export const organizationWebhookDeliveries = pgTable( "organization_webhook_deliveries", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id").notNull(), webhookId: uuid("webhook_id").notNull(), eventId: uuid("event_id").notNull(), eventType: text("event_type").notNull(), payload: jsonb("payload").notNull(), attempts: integer("attempts").notNull().default(0), nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(), deliveredAt: timestamp("delivered_at", { withTimezone: true }), failedAt: timestamp("failed_at", { withTimezone: true }), lastStatus: integer("last_status"), lastError: text("last_error"), claimId: uuid("claim_id"), claimUntil: timestamp("claim_until", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "organization_webhook_deliveries_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), webhook: foreignKey({ name: "organization_webhook_deliveries_webhook_fk", columns: [table.accountId, table.webhookId], foreignColumns: [organizationWebhooks.accountId, organizationWebhooks.id], }).onDelete("cascade"), eventUnique: uniqueIndex("organization_webhook_deliveries_event_uq").on( table.webhookId, table.eventId, ), recent: index("organization_webhook_deliveries_webhook_recent_idx").on( table.webhookId, table.createdAt, ), }), ); export const hostMcpBindings = pgTable( "host_mcp_bindings", { id: uuid("id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id").notNull(), ownerSubjectId: text("owner_subject_id").notNull(), authorizationRevision: bigint("authorization_revision", { mode: "number" }).notNull(), operationId: uuid("operation_id").notNull(), requestDigest: text("request_digest").notNull(), definition: jsonb("definition").notNull(), generation: bigint("generation", { mode: "number" }).notNull().default(1), status: text("status").notNull().default("active"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), revokedAt: timestamp("revoked_at", { withTimezone: true }), }, (table) => ({ workspace: foreignKey({ name: "host_mcp_bindings_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), owner: foreignKey({ name: "host_mcp_bindings_member_owner_fk", columns: [table.accountId, table.ownerSubjectId], foreignColumns: [organizationMemberships.accountId, organizationMemberships.subjectId], }), operation: uniqueIndex("host_mcp_bindings_workspace_id_owner_subject_id_operation_id_key").on( table.workspaceId, table.ownerSubjectId, table.operationId, ), inventory: index("host_mcp_bindings_owner_idx").on( table.workspaceId, table.ownerSubjectId, table.createdAt, table.id, ), }), ); export const hostMcpDelegations = pgTable( "host_mcp_delegations", { id: uuid("id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id").notNull(), ownerSubjectId: text("owner_subject_id").notNull(), ownerAuthorizationRevision: bigint("owner_authorization_revision", { mode: "number", }).notNull(), bindingId: uuid("binding_id") .notNull() .references(() => hostMcpBindings.id), bindingGeneration: bigint("binding_generation", { mode: "number" }).notNull(), operationId: uuid("operation_id").notNull(), requestDigest: text("request_digest").notNull(), grantDefinition: jsonb("grant_definition").notNull(), generation: bigint("generation", { mode: "number" }).notNull().default(1), status: text("status").notNull().default("active"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), revokedAt: timestamp("revoked_at", { withTimezone: true }), }, (table) => ({ workspace: foreignKey({ name: "host_mcp_delegations_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), owner: foreignKey({ name: "host_mcp_delegations_member_owner_fk", columns: [table.accountId, table.ownerSubjectId], foreignColumns: [organizationMemberships.accountId, organizationMemberships.subjectId], }), operation: uniqueIndex( "host_mcp_delegations_workspace_id_owner_subject_id_operation_id_key", ).on(table.workspaceId, table.ownerSubjectId, table.operationId), inventory: index("host_mcp_delegations_owner_idx").on( table.workspaceId, table.ownerSubjectId, table.bindingId, table.id, ), }), ); export const connectAttempts = pgTable( "connect_attempts", { id: uuid("id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id").notNull(), subjectId: text("subject_id").notNull(), idempotencyKeyHash: text("idempotency_key_hash").notNull(), requestDigest: text("request_digest").notNull(), returnUrl: text("return_url").notNull(), externalContinuation: jsonb("external_continuation"), projection: jsonb("projection").notNull(), operationId: text("operation_id"), operationDigest: text("operation_digest"), receipts: jsonb("receipts").notNull().default({}), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "connect_attempts_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), idempotency: uniqueIndex("connect_attempts_actor_idempotency_idx").on( table.workspaceId, table.subjectId, table.idempotencyKeyHash, ), pending: index("connect_attempts_actor_pending_idx") .on(table.workspaceId, table.subjectId, table.createdAt.desc(), table.id.desc()) .where(sql`${table.projection}->>'state' not in ('complete','cancelled','expired')`), expiry: index("connect_attempts_expiry_idx").on(table.expiresAt, table.id), }), ); export const mcpOauthClients = pgTable( "mcp_oauth_clients", { clientId: text("client_id").primaryKey(), redirectUris: jsonb("redirect_uris").$type().notNull(), clientName: text("client_name"), tokenEndpointAuthMethod: text("token_endpoint_auth_method").notNull().default("none"), grantTypes: jsonb("grant_types") .$type>() .notNull(), responseTypes: jsonb("response_types").$type<["code"]>().notNull(), registrationScopeHash: text("registration_scope_hash").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), }, (table) => ({ created: index("mcp_oauth_clients_created_idx").on(table.createdAt), scopeCreated: index("mcp_oauth_clients_scope_created_idx").on( table.registrationScopeHash, table.createdAt, ), expires: index("mcp_oauth_clients_expires_idx").on(table.expiresAt, table.clientId), }), ); const mcpOauthGrantColumns = () => ({ accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), // Null for an organization connection, which holds organizationAccess instead. workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }), subjectId: text("subject_id").notNull(), resource: text("resource").notNull(), permissions: jsonb("permissions").$type().notNull(), toolIdentities: jsonb("tool_identities").$type().notNull(), organizationAccess: jsonb("organization_access").$type(), }); export const mcpOauthAuthorizationRequests = pgTable( "mcp_oauth_authorization_requests", { requestHash: text("request_hash").primaryKey(), clientId: text("client_id") .notNull() .references(() => mcpOauthClients.clientId, { onDelete: "cascade" }), ...mcpOauthGrantColumns(), redirectUri: text("redirect_uri").notNull(), codeChallenge: text("code_challenge").notNull(), state: text("state"), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "mcp_oauth_authorization_requests_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), expires: index("mcp_oauth_authorization_requests_expires_idx").on(table.expiresAt), }), ); export const mcpOauthAuthorizationCodes = pgTable( "mcp_oauth_authorization_codes", { codeHash: text("code_hash").primaryKey(), clientId: text("client_id") .notNull() .references(() => mcpOauthClients.clientId, { onDelete: "cascade" }), ...mcpOauthGrantColumns(), redirectUri: text("redirect_uri").notNull(), codeChallenge: text("code_challenge").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "mcp_oauth_authorization_codes_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), expires: index("mcp_oauth_authorization_codes_expires_idx").on(table.expiresAt), }), ); export const mcpOauthRefreshTokens = pgTable( "mcp_oauth_refresh_tokens", { tokenHash: text("token_hash").primaryKey(), familyId: uuid("family_id").notNull(), generation: integer("generation").notNull(), clientId: text("client_id") .notNull() .references(() => mcpOauthClients.clientId, { onDelete: "cascade" }), ...mcpOauthGrantColumns(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), connectedAt: timestamp("connected_at", { withTimezone: true }), revokedAt: timestamp("revoked_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), /** Auto-connected: the trusted issuer that vouched for the person, and its subject. */ trustedIssuerId: uuid("trusted_issuer_id"), assertionSubject: text("assertion_subject"), }, (table) => ({ workspaceAccount: foreignKey({ name: "mcp_oauth_refresh_tokens_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), familyGeneration: uniqueIndex("mcp_oauth_refresh_tokens_family_generation_uq").on( table.familyId, table.generation, ), expires: index("mcp_oauth_refresh_tokens_expires_idx").on(table.expiresAt), trustedIssuer: index("mcp_oauth_refresh_tokens_trusted_issuer_idx").on( table.trustedIssuerId, table.assertionSubject, table.clientId, ), }), ); export const mcpOauthAccessTokens = pgTable( "mcp_oauth_access_tokens", { tokenHash: text("token_hash").primaryKey(), refreshFamilyId: uuid("refresh_family_id").notNull(), refreshGeneration: integer("refresh_generation").notNull(), clientId: text("client_id") .notNull() .references(() => mcpOauthClients.clientId, { onDelete: "cascade" }), ...mcpOauthGrantColumns(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), revokedAt: timestamp("revoked_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "mcp_oauth_access_tokens_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), family: index("mcp_oauth_access_tokens_family_idx").on( table.refreshFamilyId, table.refreshGeneration, ), expires: index("mcp_oauth_access_tokens_expires_idx").on(table.expiresAt), }), ); export const toolGatewayApprovalCapabilities = pgTable( "tool_gateway_approval_capabilities", { tokenHash: text("token_hash").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), subjectId: text("subject_id").notNull(), operationId: uuid("operation_id").notNull(), bindingVersion: integer("binding_version").notNull().default(1), catalogDigest: text("catalog_digest"), targetBindingDigest: text("target_binding_digest"), serverId: text("server_id").notNull(), toolName: text("tool_name").notNull(), argumentsDigest: text("arguments_digest").notNull(), authorityDigest: text("authority_digest").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), consumedAt: timestamp("consumed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "tool_gateway_approval_capabilities_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), operation: uniqueIndex("tool_gateway_approval_capabilities_operation_uq").on( table.workspaceId, table.subjectId, table.operationId, ), expires: index("tool_gateway_approval_capabilities_expires_idx").on( table.expiresAt, table.tokenHash, ), liveSubjectExpiry: index("tool_gateway_approval_capabilities_live_subject_expiry_idx") .on(table.workspaceId, table.subjectId, table.expiresAt, table.tokenHash) .where(sql`${table.consumedAt} is null`), tokenHashValid: check( "tool_gateway_approval_capabilities_token_hash_chk", sql`${table.tokenHash} ~ '^[0-9a-f]{64}$'`, ), catalogDigestValid: check( "tool_gateway_approval_capabilities_catalog_digest_chk", sql`${table.catalogDigest} ~ '^[0-9a-f]{64}$'`, ), bindingValid: check( "tool_gateway_approval_capabilities_binding_chk", sql`(${table.bindingVersion} = 1 and ${table.catalogDigest} is not null and ${table.targetBindingDigest} is null) or (${table.bindingVersion} = 2 and ${table.catalogDigest} is null and ${table.targetBindingDigest} is not null and ${table.targetBindingDigest} ~ '^[0-9a-f]{64}$')`, ), argumentsDigestValid: check( "tool_gateway_approval_capabilities_arguments_digest_chk", sql`${table.argumentsDigest} ~ '^[0-9a-f]{64}$'`, ), authorityDigestValid: check( "tool_gateway_approval_capabilities_authority_digest_chk", sql`${table.authorityDigest} ~ '^[0-9a-f]{64}$'`, ), subjectValid: check( "tool_gateway_approval_capabilities_subject_chk", sql`length(btrim(${table.subjectId})) between 1 and 1024`, ), identityValid: check( "tool_gateway_approval_capabilities_identity_chk", sql`length(${table.serverId}) between 1 and 256 and length(${table.toolName}) between 1 and 512`, ), expiryValid: check( "tool_gateway_approval_capabilities_expiry_chk", sql`${table.expiresAt} > ${table.createdAt} and ${table.expiresAt} <= ${table.createdAt} + interval '10 minutes'`, ), }), ); // Per-workspace model/provider availability policy — the HARD blocker deciding // which providers/models may serve a turn in this workspace AT ALL. NULL columns // mean unrestricted (today's behavior for every workspace without a row). A // non-null allowed_providers is a strict allowlist over provider identities // (the same identities the model router resolves to, with the built-in // OpenAI/Azure client — including the legacy resolveTurnModel-null fallback — // mapped to one well-known id); a non-null allowed_models is an additional // exact-model-id allowlist. Enforced at the API model-choke points (422) and, // authoritatively, in the worker immediately after turn model resolution: a // blocked resolution NEVER reaches a model call and NEVER silently remaps. // This exists so a codex-subscription workspace can be fail-closed to codex — // a turn can wait/fail loud, but can never fall through to the paid built-in. export const workspaceModelPolicies = pgTable( "workspace_model_policies", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), allowedProviders: text("allowed_providers").array(), allowedModels: text("allowed_models").array(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspace: uniqueIndex("workspace_model_policies_workspace_idx").on(table.workspaceId), }), ); // Model defaults every workspace in the organization follows until it sets its // own: the default model for new work, the model allowlist for workspaces with // no policy row, and compaction triggers by exact model id. One row per // organization; absent reads as no defaults. export const organizationModelDefaults = pgTable("organization_model_defaults", { accountId: uuid("account_id") .primaryKey() .references(() => managedAccounts.id, { onDelete: "cascade" }), sessionDefaults: jsonb("session_defaults").$type<{ model: string; reasoningEffort: string; } | null>(), allowedProviders: text("allowed_providers").array(), allowedModels: text("allowed_models").array(), modelCompactionThresholds: jsonb("model_compaction_thresholds") .$type>() .notNull() .default({}), // Voice settings by realtime model id (0895); a workspace's own win. realtimeVoice: jsonb("realtime_voice").$type>().notNull().default({}), // Realtime voice model new voice conversations start with (0903); null is automatic. realtimeDefaultModel: text("realtime_default_model"), updatedBySubjectId: text("updated_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }); // Whether owners and admins may give an agent session admin access (0691). export const organizationAgentAdminAccess = pgTable("organization_agent_admin_access", { accountId: uuid("account_id") .primaryKey() .references(() => managedAccounts.id, { onDelete: "cascade" }), sessionAdminAccessAllowed: boolean("session_admin_access_allowed").notNull().default(false), // 0971: agents in a chat a person started may do app actions for them, each // change after they confirm it in the chat. On unless an owner or admin // turns it off. chatActionsAllowed: boolean("chat_actions_allowed").notNull().default(true), updatedBySubjectId: text("updated_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }); // An organization's privacy choices (0723): whether new chats and schedules // start as Workspace or Only me, and whether admins see that other people's // Only me schedules exist. No row means Workspace and on. export const organizationPrivacyPreferences = pgTable("organization_privacy_preferences", { accountId: uuid("account_id") .primaryKey() .references(() => managedAccounts.id, { onDelete: "cascade" }), defaultVisibility: text("default_visibility") .$type<"workspace_shared" | "user_private">() .notNull() .default("workspace_shared"), // Off: only owners and admins connect new machines of their own (1148). membersConnectOwnMachines: boolean("members_connect_own_machines").notNull().default(true), adminsSeePrivateSchedules: boolean("admins_see_private_schedules").notNull().default(true), personalWorkspacesEnabled: boolean("personal_workspaces_enabled").notNull().default(true), // The most each person spends from the organization's credits in their own // Personal workspace per calendar month, in USD micros (1147). Null: no limit. personalWorkspaceMonthlyCredits: bigint("personal_workspace_monthly_credits", { mode: "number", }), updatedBySubjectId: text("updated_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }); // An organization's EU-only inference setting (migration 1060). No row means // off. The runtime reads it; only update_organization_inference_residency_v1 writes it. export const organizationInferenceResidency = pgTable("organization_inference_residency", { accountId: uuid("account_id") .primaryKey() .references(() => managedAccounts.id, { onDelete: "cascade" }), euOnly: boolean("eu_only").notNull(), version: bigint("version", { mode: "number" }).notNull(), updatedBySubjectId: text("updated_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }); // Append-only history of EU-only inference changes (migration 1060). Each row // is also the stored result of its operation id. No runtime privileges. export const organizationInferenceResidencyEvents = pgTable( "organization_inference_residency_events", { accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), id: uuid("id").notNull(), actorSubjectId: text("actor_subject_id").notNull(), actorKind: text("actor_kind").$type<"browser_person" | "agent" | "api_key">().notNull(), requestedEuOnly: boolean("requested_eu_only").notNull(), expectedVersion: bigint("expected_version", { mode: "number" }).notNull(), previousEuOnly: boolean("previous_eu_only").notNull(), resultEuOnly: boolean("result_eu_only").notNull(), resultVersion: bigint("result_version", { mode: "number" }).notNull(), // Null only for an unchanged request before the first change. resultUpdatedAt: timestamp("result_updated_at", { withTimezone: true }), changed: boolean("changed").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => [ primaryKey({ name: "organization_inference_residency_events_pkey", columns: [table.accountId, table.id], }), // One version per change; unchanged requests repeat the current version. uniqueIndex("organization_inference_residency_events_version_key") .on(table.accountId, table.resultVersion) .where(sql`${table.changed}`), ], ); // A session an owner or admin gave admin access; the row ends when it is removed. export const sessionAdminAccess = pgTable( "session_admin_access", { sessionId: uuid("session_id") .primaryKey() .references(() => sessions.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), grantedBySubjectId: text("granted_by_subject_id").notNull(), grantedAt: timestamp("granted_at", { withTimezone: true }).notNull().defaultNow(), // When admin access ends by itself (0719); null means no time limit. expiresAt: timestamp("expires_at", { withTimezone: true }), }, (table) => [index("session_admin_access_account_idx").on(table.accountId)], ); // What one turn's message may do through app actions, frozen when the message // is accepted (0971): who sent it, whether they can confirm changes from where // they sent it, and at most their own access then. Written once; a turn // without a row runs no app actions. export const sessionTurnAppActionGrants = pgTable("session_turn_app_action_grants", { turnId: uuid("turn_id") .primaryKey() .references(() => sessionTurns.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), subjectId: text("subject_id").notNull(), changes: text("changes").$type<"confirm" | "none">().notNull(), permissions: text("permissions").array().notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }); // One allocation serialization row per organization, workspace, or exact user pool. // Workspace-shared channels organize root sessions ("workstreams") by work // type in the rail. Pure organizational metadata: filing a session into a // channel never affects execution, authority, memory, or history. export const channels = pgTable( "channels", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), name: text("name").notNull(), description: text("description"), // The project's avatar (1100), the same shape and bounds as a chat's. // Display metadata for people only. avatar: jsonb("avatar").$type(), pinned: boolean("pinned").notNull().default(false), // Explicit user order within the pinned and unpinned project groups. sortOrder: integer("sort_order").notNull().default(0), // Who sees it (1161): the workspace, or only its owner ("Only me"), like // a chat. An Only me project holds only its owner's Only me chats and // Sites; the migration owns the rule and the per-audience name indexes. visibility: text("visibility") .$type<"workspace_shared" | "user_private">() .notNull() .default("workspace_shared"), ownerSubjectId: text("owner_subject_id"), // Attribution string: 'user:' | 'session:' | 'system'. createdBy: text("created_by"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ // The migration owns the case-insensitive lower(name) uniqueness. workspaceIdentity: uniqueIndex("channels_workspace_id_uq").on(table.workspaceId, table.id), }), ); export const sessions = pgTable( "sessions", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), status: text("status").notNull().default("queued"), initialMessage: losslessText("initial_message").notNull(), initialMessageCodecVersion: losslessCodecVersion("initial_message_codec_version"), // Model-visible application context frozen with the winning create. The // initial turn copies it into the canonical user message so an idempotent // repair cannot adopt a retrying caller's different message context. initialModelContext: text("initial_model_context"), title: text("title"), titleSource: text("title_source"), // Display metadata shown with the title (1008): a one-line description and // an avatar. Never part of the model's context; copied by forks. description: text("description"), avatar: jsonb("avatar").$type(), // Who the chat waits on, as the agent said (1521). `turnId` is the turn // that said it: the wait shows only while that turn is the chat's latest // and the chat is idle, so a reply or a new turn clears it. waitingOn: jsonb("waiting_on").$type(), // The chat's Linked items (1521). NULL means none. Bounded by the contract. links: jsonb("links").$type(), // Per-session agent persona/system instructions supplied at create (the // per-agent-type prompt lever for embedding hosts). NULL ⇒ the session // carried none, so the composed agent instructions are byte-identical to a // workspace-only persona (no backfill, no behavior change for existing rows). // Composed system-level AFTER the workspace agentInstructions; never emitted // as a timeline event. instructions: text("instructions"), // Which vaults the agent may resolve secret references from (0739). The // effective policy is this intersected with the parent session's and the // agent config's; `{ mode: "all" }` adds no narrowing. vaultPolicy: jsonb("vault_policy").$type().notNull().default({ mode: "all" }), // Immutable normalized prompt-policy role. This is deliberately separate // from workspace membership roles and memory selectors. Existing rows keep // NULL and use the bounded metadata.role compatibility fallback at the // attempt-snapshot boundary. policyRole: text("policy_role"), admissionBlock: jsonb("admission_block").$type(), // Immutable timeline-only import identity, never inferred from metadata or // a user's mutable session archive preference. importedArchiveImportId: text("imported_archive_import_id"), importedArchiveImportedAt: timestamp("imported_archive_imported_at", { withTimezone: true }), importedArchiveRequestHash: text("imported_archive_request_hash"), importedArchiveSubjectId: text("imported_archive_subject_id"), importedArchiveNextOffset: integer("imported_archive_next_offset"), /** Never move this session's content to the idle-session archive. */ keepLive: boolean("keep_live").notNull().default(false), /** Changeable unattended setting (migration 1111); null defers to the create option. */ unattendedSetting: text("unattended_setting").$type< "unattended" | "attended" | "unattended_by_default" >(), /** * Set once at create when the setting starts the chat unattended * (migration 1111); never updated, so the instructions and tools follow * how the chat started. Null when it did not. */ startedUnattended: boolean("started_unattended"), /** Idle-session archive lifecycle: null (live), archiving, or archived (read-only). */ contentArchiveState: text("content_archive_state").$type<"archiving" | "archived">(), contentArchiveStartedAt: timestamp("content_archive_started_at", { withTimezone: true }), contentArchivedAt: timestamp("content_archived_at", { withTimezone: true }), /** Archive plan while archiving; verified manifest once archived. */ contentArchive: jsonb("content_archive").$type>(), contentArchivePurgedAt: timestamp("content_archive_purged_at", { withTimezone: true }), /** * When the chat was archived for everyone (migration 1213). Its content * moves to long-term storage once nothing runs in it; null while live, and * on chats the idle archiver stored before this column existed. */ archivedAt: timestamp("archived_at", { withTimezone: true }), /** Who archived the chat; null when the idle archiver did. */ archiveRequestedBy: text("archive_requested_by"), /** * When someone last asked to restore the chat's stored content (migration * 1261). A stored chat with this set is waiting to be restored; once live * again it marks the restore, which counts as activity for the idle period. */ contentRestoreRequestedAt: timestamp("content_restore_requested_at", { withTimezone: true }), resources: jsonb("resources").$type().notNull().default([]), // Repositories a person removed from the session (migration 1140); see // SessionRemovedRepository. Read with parseSessionRemovedRepositories. removedRepositories: jsonb("removed_repositories") .$type() .notNull() .default([]), // `skills` (the Skill folders the session carries itself) is deliberately // not part of this row model; see `sessionSkillSets` below. tools: jsonb("tools").$type().notNull().default([]), metadata: jsonb("metadata").$type>().notNull().default({}), // Frozen creator fact. This is used for creation attribution and for the // idempotent first-turn repair only; later turns capture their own actor. createdByKind: text("created_by_kind").notNull().default("service"), createdBySubjectId: text("created_by_subject_id").notNull().default("unattributed-legacy"), createdByContext: jsonb("created_by_context") .$type>() .notNull() .default({ backfill: true }), // Generic tenancy metadata is additive foundation only. Existing rows are // explicitly workspace-shared and have no owner membership, so absent // fields can never manufacture user authority. ownerOrganizationMembershipId: uuid("owner_organization_membership_id"), ownerSubjectId: text("owner_subject_id"), visibility: text("visibility").notNull().default("workspace_shared"), // Immutable server-derived Site audience. Independent of mutable metadata, // reservations, and native member ownership; descendants inherit the binding. siteId: uuid("site_id"), siteAccessRootId: uuid("site_access_root_id"), siteViewerPrincipal: text("site_viewer_principal"), siteOwnerSubjectId: text("site_owner_subject_id"), createRequestedVisibility: text("create_requested_visibility") .notNull() .default("workspace_shared"), authorityEpoch: integer("authority_epoch").notNull().default(1), // Old accepted epochs remain valid across sharing, never across revocation. executionAuthorityEpoch: integer("execution_authority_epoch").notNull().default(1), // Agent-access scope (migration 0427). Declares how far a live attempt on // this session may reach across the workspace and how far peers may reach // into it. 'workspace' is the pre-0426 behaviour; 'user' limits reach to // sessions carrying the same end-user label; 'session' limits it to the // own root tree. Enforced only in the core session-authorization seam. agentAccess: text("agent_access").notNull().default("workspace"), // Canonical authenticated user for the frozen cross-session agent scope. // Independent of per-turn initiating users and historical external labels. scopeSubjectId: text("scope_subject_id"), // Opaque end-user label (both set or both null). This is a product label // used for scoping and filtering, never a subject and never authority. endUserSource: text("end_user_source"), endUserId: text("end_user_id"), // Typed Workspace Memory selector this session's agent reads and writes: // 'workspace' | 'user' (end_user:v1:) | 'session' (root tree) | // 'off' (no Memory tools). Frozen at create like the columns above. memoryScope: text("memory_scope").notNull().default("workspace"), // Independent-copy provenance. A destination may use either visibility and // may live in another workspace in the same organization; no live process, // credential, grant, or delegation is represented by these facts. forkedFromSessionId: uuid("forked_from_session_id"), forkedFromAuthorityEpoch: integer("forked_from_authority_epoch"), forkedFromVisibility: text("forked_from_visibility"), forkedAt: timestamp("forked_at", { withTimezone: true }), forkedByOrganizationMembershipId: uuid("forked_by_organization_membership_id"), model: text("model").notNull(), // Immutable session-default execution policy. Follow-up composer drafts and // accepted turns are separate authorities and never mutate these columns. reasoningEffort: text("reasoning_effort").notNull(), latencyMode: text("latency_mode").notNull(), sandboxBackend: text("sandbox_backend").notNull(), // The OS this session's box runs. Defaults to 'linux' (today's only OS, so // every existing + new row is a behavior-preserving no-op). CHECK-constrained // to the SandboxOs enum (linux|macos|windows) in migration 0018. sandboxOs: text("sandbox_os").notNull().default("linux"), // The shared-sandbox group this session's box belongs to. Defaults to the // session's OWN id (a singleton group: group === session — today's 1:1 // behavior). When spawned shared via session_create, set to the PARENT's // sandboxGroupId so both run in ONE box. Immutable once set. NOT an FK (the // value is this row's id or an ancestor session's id in the same workspace; // the live lease row, not a sandbox_groups table, materializes the group). // The app generates the uuid and uses it for both id and sandbox_group_id in // one insert — it cannot SQL-default to id (id is defaultRandom()). sandboxGroupId: uuid("sandbox_group_id").notNull(), // The first-class swappable-sandbox POINTER (bring-your-own-compute M2). // NULL == "use the session's own group sandbox" (the // backward-compat default — every existing/new row is a behavior-preserving // no-op). The routing proxy re-reads (active_sandbox_id, active_epoch) PER // TOOL CALL to make a Modal<->selfhosted hot-swap seamless. The FK // (-> sandboxes(id) ON DELETE SET NULL — a deleted sandbox degrades the // pointer to the group default, never dangles) lives in migration 0024, NOT a // Drizzle .references() — exactly like parentSessionId below, so the const // ordering imposes no forward-reference. activeSandboxId: uuid("active_sandbox_id"), // The SECOND epoch ABOVE sandbox_leases.lease_epoch, bumped on every swap; an // in-flight op fenced by a stale active_epoch retries against the new active // sandbox. integer (NOT bigint) — the lease-epoch spike: int8 reads back as a // JS string and breaks the strict fence; int4 returns a number. activeEpoch: integer("active_epoch").notNull().default(0), // The session's effective absolute Connected Machine root. New attaches // resolve an optional relative request against the persisted Hello root and // write the result through the epoch-fenced setActiveSandbox CAS. Legacy // rows may still be null/relative and are resolved at establishment. workingDir: text("working_dir"), // The rig this session rides + the exact rig version frozen at create time // (migration 0047). NULL ⇒ the session rides no rig (today's behavior). FKs // (-> rigs(id)/rig_versions(id) ON DELETE SET NULL) live in migration 0047, // not Drizzle .references(), because those tables are declared later in this // file (forward-reference pattern, same as activeSandboxId). Consumed in M3. rigId: uuid("rig_id"), rigVersionId: uuid("rig_version_id"), // Workspace channel this session is filed under (rail organization only; // the rail groups a tree by its ROOT session's channel). Null = unfiled // (inbox). ON DELETE SET NULL detaches sessions when a channel is removed. channelId: uuid("channel_id").references(() => channels.id, { onDelete: "set null", }), // Non-default first-party MCP token permissions (manager-style sessions); // null means the fixed worker default set in @opengeni/runtime. firstPartyMcpPermissions: jsonb("first_party_mcp_permissions").$type(), // Exact model-visible first-party tool selection. All catalogued tools are // selected by default; [] intentionally selects no broad-server tools. firstPartyMcpTools: jsonb("first_party_mcp_tools").$type().notNull(), // Initial-command staging only. initializeSessionStartAtomically copies // this immutable snapshot onto the first turn so create repair survives a // crash between the session insert and first-turn transaction. Runtime // credential authority must never read this session field. initialPersonalConnectionDelegations: jsonb("initial_personal_connection_delegations") .$type() .notNull() .default([]), initialMcpAccountBindings: jsonb("initial_mcp_account_bindings").$type< McpConnectionAccountBinding[] | null >(), // Initial-command staging only, copied onto the first turn with the // bindings above: the creating person's account intent. Null is reserved // for writers that predate account intent. initialConnectionAccountIntent: jsonb( "initial_connection_account_intent", ).$type(), // Initial accepted-work staging only. The initializer consumes this inside // the same transaction that inserts the first logical turn and grant // snapshots; runtime never authorizes from the session field. initialPersonalResourceAttachmentIntent: jsonb( "initial_personal_resource_attachment_intent", ).$type(), initialXaiProviderAccountAuthoritySnapshot: jsonb( "initial_xai_provider_account_authority_snapshot", ) .$type() .notNull() .default(WORKSPACE_XAI_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1), initialClaudeProviderAccountAuthoritySnapshot: jsonb( "initial_claude_provider_account_authority_snapshot", ) .$type() .notNull() .default(WORKSPACE_CLAUDE_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1), // Durable tool-policy origin. Migration 0136 removes the old null/legacy // representation so every session has one explicit policy mode. toolPolicy: jsonb("tool_policy").$type().notNull(), // Optimistic-concurrency fence for durable session tool-policy writes. toolPolicyVersion: integer("tool_policy_version").notNull().default(1), mcpApprovalPolicies: jsonb("mcp_approval_policies") .$type>() .notNull() .default({}), // The manager session that spawned this one via session_create. Set only // when the creating grant carried a worker-signed sessionId claim (a session // spawning a worker); null for direct API creates and scheduled-task runs. // When set, this worker's terminal-for-now transitions wake the parent so a // manager can orchestrate workers without busy-polling. The migration-owned // self-reference uses ON DELETE CASCADE so the explicit quiescent root-tree // deletion lifecycle removes the complete hierarchy atomically. parentSessionId: uuid("parent_session_id"), // Exact parent turn whose worker-signed attempt created this child. This is // private immutable authority lineage: child completion copies personal MCP // authority from that turn, never from whichever parent turn ran most // recently. Null for top-level and legacy child sessions. parentTurnId: uuid("parent_turn_id"), // Workspace-scoped CREATE idempotency key. NULL means the create carried no // key (each such create is independent). When set, the partial unique index // below collapses concurrent/retried creates with the same key in the same // workspace to a single session row — the dedup that closes the // double-submit/double-dispatch stuck-queued bug. createIdempotencyKey: text("create_idempotency_key"), // Immutable creation-time hierarchy and policy snapshot. These values are // populated by the database admission boundary and never re-derived from // a live workspace setting for an existing session. rootSessionId: uuid("root_session_id").notNull(), nestedAgentDepth: integer("nested_agent_depth").notNull(), maxNestedAgentDepthOverride: integer("max_nested_agent_depth_override"), effectiveMaxNestedAgentDepth: integer("effective_max_nested_agent_depth").notNull(), nestedAgentDepthPolicySource: text("nested_agent_depth_policy_source").notNull(), nestedAgentDepthPolicySessionId: uuid("nested_agent_depth_policy_session_id"), temporalWorkflowId: text("temporal_workflow_id"), activeTurnId: uuid("active_turn_id"), // Server-owned accepted request governing informational agent input. // Advances when a new user/API turn starts, never when it queues. executionContextTurnId: uuid("execution_context_turn_id"), // Session-scoped out-of-turn wait (`wait_for_input`). The exact declaring // turn and absolute deadline are durable PostgreSQL authority; workflow // signals and timers only nudge reevaluation. A newer finished turn or a // terminal timeout input retires all four fields together. inputWaitTurnId: uuid("input_wait_turn_id"), inputWaitUntil: timestamp("input_wait_until", { withTimezone: true }), inputWaitReason: text("input_wait_reason"), inputWaitSetAt: timestamp("input_wait_set_at", { withTimezone: true }), // Open connection-card notices the agent waits on (migration 1546): their // keys and when the oldest was posted. Both null when none is open. // Maintained only by the session_events trigger. awaitingConnectionSince: timestamp("awaiting_connection_since", { withTimezone: true }), awaitingConnectionKeys: text("awaiting_connection_keys").array(), // Actual input tokens reported for the latest authoritative ordinary model // call. Compaction/context clearing invalidates it to null; local history // estimates must never be stored here. lastInputTokens: integer("last_input_tokens"), // Operator /compact request flag. The API sets // it true; the worker honors it BEFORE the next turn's model call by forcing // a compaction, then clears it. A durable flag (not a transient signal) so // the trigger survives a worker restart and converges before the next turn. compactRequested: boolean("compact_requested").notNull().default(false), // Who asked for the pending request (migration 1102): 'operator' for // /compact, 'proactive' for the worker's idle checkpoint after a turn that // reached the automatic threshold. NULL (older writers) reads as operator. // Meaningful only while compactRequested is true. compactRequestTrigger: text("compact_request_trigger").$type(), queueVersion: integer("queue_version").notNull().default(0), queueHeadPosition: bigint("queue_head_position", { mode: "number" }).notNull().default(0), queueTailPosition: bigint("queue_tail_position", { mode: "number" }).notNull().default(0), directControlState: text("direct_control_state").notNull().default("active"), directPauseRevision: bigint("direct_pause_revision", { mode: "number" }), subtreeRunOverrideRevision: bigint("subtree_run_override_revision", { mode: "number", }), controlVersion: bigint("control_version", { mode: "number" }).notNull().default(0), directControlReason: text("direct_control_reason"), directControlChangedBy: text("direct_control_changed_by"), directControlChangedAt: timestamp("direct_control_changed_at", { withTimezone: true, }), lastSequence: integer("last_sequence").notNull().default(0), // Frozen at create: remote_v2 (Codex remote compaction + Codex-only models) // or portable (plaintext compaction + free provider switching). Existing // rows backfill to portable. CHECK lives in the migration. codexCompactionMode: text("codex_compaction_mode").notNull().default("portable"), // Frozen at create (migration 0520): whether the optional Jev-backed // code_search tool is offered. NULL, as on every older row, means off. codeSearchEnabled: boolean("code_search_enabled"), // Frozen agent configuration (migration 0559); NULL means a legacy // session. Mid-session updates share the tool_policy_version CAS. agentConfig: jsonb("agent_config").$type(), // Migration 1244: the agent (agents.id) this chat was started for. No // foreign key; recheck the agent on use. Set once from NULL, never // changed (sessions_agent_id_immutable); forks copy it, child workers // never set it. Unrelated to agentConfig and agentAccess. agentId: uuid("agent_id"), // The agent revision whose Instructions are in this chat's system prompt. // NULL is a legacy chat (instructions already in `instructions`): never // add the agent layer to it. agentPromptRevision: integer("agent_prompt_revision"), // Migration 1505: the organization agent version this chat runs (with // agentId), the version whose Instructions are in its system prompt (NULL: // no agent layer, a worker without shared Instructions) and what the chat // changed from the version ({setting: {agent, chat}}). NULL for every // other chat. agentVersion: integer("agent_version"), agentPromptVersion: integer("agent_prompt_version"), agentOverrides: jsonb("agent_overrides").$type>(), // Migration 1124: hosted web-search records reach the model as runtime // input instead of assistant messages. Set once by a worker, never reset. searchRecordsAsInput: boolean("search_records_as_input").notNull().default(false), // Migration 1513: which base runtime tools every request carries // (CURRENT_FIRST_REQUEST_TOOLS_REVISION in @opengeni/contracts). Every // older row is 0. A new row starts NULL and its first turn attempt sets it // once, before any model request; forks copy their source's value. firstRequestToolsRevision: integer("first_request_tools_revision"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), // Top-level xid, assigned by a BEFORE trigger in the original row write. // Strings preserve all 64 bits; raw event-only writes do not stamp activity. activityXid: customType<{ data: string; driverData: string }>({ dataType: () => "xid8", })("activity_xid") .notNull() .default(sql`'0'::xid8`), }, (table) => ({ reasoningEffortValid: check( "sessions_reasoning_effort_check", sql`${table.reasoningEffort} in ('none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max')`, ), latencyModeValid: check( "sessions_latency_mode_check", sql`${table.latencyMode} in ('standard', 'priority', 'fast', 'ultrafast')`, ), accountIdentity: uniqueIndex("sessions_id_account_idx").on(table.id, table.accountId), workspaceIdentity: uniqueIndex("sessions_workspace_id_idx").on(table.workspaceId, table.id), workspaceImportedArchive: uniqueIndex("sessions_workspace_imported_archive_idx") .on(table.workspaceId, table.importedArchiveImportId) .where(sql`${table.importedArchiveImportId} is not null`), importedArchiveIdentity: check( "sessions_imported_archive_identity_check", sql` (${table.importedArchiveImportId} is null and ${table.importedArchiveImportedAt} is null and ${table.importedArchiveRequestHash} is null and ${table.importedArchiveSubjectId} is null and ${table.importedArchiveNextOffset} is null) or (${table.importedArchiveImportId} is not null and octet_length(${table.importedArchiveImportId}) between 1 and 800 and ${table.importedArchiveImportedAt} is not null and ${table.importedArchiveRequestHash} is not null and ${table.importedArchiveRequestHash} ~ '^[0-9a-f]{64}$' and ${table.importedArchiveSubjectId} is not null and ${table.importedArchiveNextOffset} is not null and ${table.importedArchiveNextOffset} >= 0)`, ), contentArchiveState: check( "sessions_content_archive_state_check", sql` (${table.contentArchiveState} is null and ${table.contentArchiveStartedAt} is null and ${table.contentArchivedAt} is null and ${table.contentArchive} is null and ${table.contentArchivePurgedAt} is null) or (${table.contentArchiveState} = 'archiving' and ${table.contentArchiveStartedAt} is not null and ${table.contentArchivedAt} is null and jsonb_typeof(${table.contentArchive}) = 'object' and ${table.contentArchivePurgedAt} is null) or (${table.contentArchiveState} = 'archived' and ${table.contentArchiveStartedAt} is not null and ${table.contentArchivedAt} is not null and jsonb_typeof(${table.contentArchive}) = 'object' and ${table.contentArchive} ? 'sha256')`, ), contentArchiveSize: check( "sessions_content_archive_size_check", sql`${table.contentArchive} is null or octet_length(${table.contentArchive}::text) <= 65536`, ), contentArchiveStateIndex: index("sessions_content_archive_state_idx") .on(table.contentArchiveState, table.contentArchiveStartedAt) .where(sql`${table.contentArchiveState} is not null`), importedArchiveInert: check( "sessions_imported_archive_inert_check", sql` ${table.importedArchiveImportId} is null or (${table.status} = 'idle' and ${table.activeTurnId} is null and ${table.temporalWorkflowId} is null and ${table.parentSessionId} is null)`, ), workspaceCreated: index("sessions_workspace_created_idx").on( table.workspaceId, table.createdAt, ), // Model-facing monitoring pages use exact (timestamp,id) keysets. Keep the // older prefix index during rolling deploys; these composites serve both // deterministic traversal and updatedAfter change scans. workspaceCreatedId: index("sessions_workspace_created_id_idx").on( table.workspaceId, table.createdAt.desc(), table.id.desc(), ), workspaceUpdatedId: index("sessions_workspace_updated_id_idx").on( table.workspaceId, table.updatedAt.desc(), table.id.desc(), ), workspaceCreatorUpdatedId: index("sessions_workspace_creator_updated_id_idx").on( table.workspaceId, table.createdByKind, table.createdBySubjectId, table.updatedAt.desc(), table.id.desc(), ), workspaceActivityXid: index("sessions_workspace_activity_xid_idx").on( table.workspaceId, table.activityXid.desc(), table.updatedAt.desc(), table.id.desc(), ), ownerOrganizationMembership: foreignKey({ name: "sessions_owner_organization_membership_fk", columns: [table.ownerOrganizationMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), forkedFromSession: foreignKey({ name: "sessions_forked_from_session_account_fk", columns: [table.forkedFromSessionId, table.accountId], foreignColumns: [table.id, table.accountId], }).onDelete("restrict"), forkedByOrganizationMembership: foreignKey({ name: "sessions_forked_by_organization_membership_fk", columns: [table.forkedByOrganizationMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), visibilityValid: check( "sessions_visibility_check", sql`${table.visibility} in ('user_private', 'workspace_shared')`, ), privateOwnerValid: check( "sessions_private_owner_check", sql`${table.visibility} <> 'user_private' or ${table.ownerOrganizationMembershipId} is not null`, ), authorityEpochValid: check("sessions_authority_epoch_check", sql`${table.authorityEpoch} > 0`), forkProvenanceValid: check( "sessions_fork_provenance_check", sql`( ${table.forkedFromSessionId} is null and ${table.forkedFromAuthorityEpoch} is null and ${table.forkedFromVisibility} is null and ${table.forkedAt} is null and ${table.forkedByOrganizationMembershipId} is null ) or ( ${table.forkedFromSessionId} is not null and ${table.forkedFromAuthorityEpoch} is not null and ${table.forkedFromAuthorityEpoch} > 0 and ${table.forkedFromVisibility} in ('user_private', 'workspace_shared') and ${table.forkedAt} is not null and ${table.forkedByOrganizationMembershipId} is not null )`, ), parent: index("sessions_parent_idx").on(table.workspaceId, table.parentSessionId), // Routing index: resolve session_id -> sandbox_group_id at every lease entry // point and enumerate all sessions in a group for attribution/disclosure. sandboxGroup: index("sessions_sandbox_group_idx").on(table.workspaceId, table.sandboxGroupId), // Partial unique index: one session per (workspace, create_idempotency_key) // when a key is present. The boundary trigger reserves the cross-outcome // winner before this source row commits; a losing source insert is // suppressed and the domain layer replays the durable winner. createIdempotency: uniqueIndex("sessions_workspace_create_idempotency_idx") .on(table.workspaceId, table.createIdempotencyKey) .where(sql`${table.createIdempotencyKey} is not null`), rootDepth: index("sessions_workspace_root_depth_idx").on( table.workspaceId, table.rootSessionId, table.nestedAgentDepth, ), // Migration 1245 (concurrent): an agent's chats, newest first. agent: index("sessions_agent_idx") .on(table.workspaceId, table.agentId, table.createdAt.desc()) .where(sql`${table.agentId} is not null`), // Migration 1244 (NOT VALID; enforced for new and changed rows). agentPromptRevisionValid: check( "sessions_agent_prompt_revision_check", sql`${table.agentPromptRevision} is null or (${table.agentPromptRevision} > 0 and ${table.agentId} is not null)`, ), initialModelContextValid: check( "sessions_initial_model_context_check", sql`${table.initialModelContext} is null or opengeni_private.model_context_value_valid(${table.initialModelContext})`, ), inputWaitValid: check( "sessions_input_wait_check", sql`( ${table.inputWaitTurnId} is null and ${table.inputWaitUntil} is null and ${table.inputWaitReason} is null and ${table.inputWaitSetAt} is null ) or ( ${table.inputWaitTurnId} is not null and ${table.inputWaitUntil} is not null and ${table.inputWaitReason} is not null and octet_length(btrim(${table.inputWaitReason})) between 1 and 2048 and ${table.inputWaitSetAt} is not null )`, ), }), ); /** * The `sessions.skills` column: the complete Skill folders a session carries * itself (every file's content), often hundreds of kilobytes per session and * copied to every child. It lives in the sessions table but is not part of the * `sessions` row model above, so ordinary row reads, `RETURNING` clauses and * the per-event session row locks never select it: selecting it makes * PostgreSQL fetch and decompress the whole TOASTed value and ship it to the * process on every hot path. Read it only where the Skill content is actually * used (see `sessionRowWithSkillsColumns` and `readSessionSkills`), and write * it only through this table. */ export const sessionSkillSets = pgTable("sessions", { id: uuid("id").primaryKey(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), skills: jsonb("skills").$type().notNull().default([]), }); export const organizationUserResourceGrants = pgTable( "organization_user_resource_grants", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), authorityId: uuid("authority_id").notNull(), ownerOrganizationMembershipId: uuid("owner_organization_membership_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id"), action: text("action").notNull(), mode: text("mode").notNull(), context: text("context").notNull(), authorityEpoch: integer("authority_epoch"), generation: bigint("generation", { mode: "number" }).notNull().default(1), status: text("status").notNull().default("active"), expiresAt: timestamp("expires_at", { withTimezone: true }), revokedAt: timestamp("revoked_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ accountIdentity: uniqueIndex("organization_user_resource_grants_id_account_idx").on( table.id, table.accountId, ), authorityWorkspace: index("organization_user_resource_grants_authority_workspace_idx").on( table.authorityId, table.workspaceId, table.status, ), activeIdentity: uniqueIndex("organization_user_resource_grants_active_identity_uq") .on( table.accountId, table.authorityId, table.workspaceId, table.action, table.mode, table.context, sql`coalesce(${table.sessionId}, '00000000-0000-0000-0000-000000000000'::uuid)`, sql`coalesce(${table.authorityEpoch}, 0)`, ) .where(sql`${table.status} = 'active'`), authority: foreignKey({ name: "organization_user_resource_grants_authority_fk", columns: [table.authorityId, table.accountId], foreignColumns: [ organizationUserResourceAuthorities.id, organizationUserResourceAuthorities.accountId, ], }).onDelete("restrict"), ownerMembership: foreignKey({ name: "organization_user_resource_grants_owner_membership_fk", columns: [table.ownerOrganizationMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), authorityOwner: foreignKey({ name: "organization_user_resource_grants_authority_owner_fk", columns: [table.authorityId, table.accountId, table.ownerOrganizationMembershipId], foreignColumns: [ organizationUserResourceAuthorities.id, organizationUserResourceAuthorities.accountId, organizationUserResourceAuthorities.organizationMembershipId, ], }).onDelete("restrict"), workspaceAccount: foreignKey({ name: "organization_user_resource_grants_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), sessionWorkspace: foreignKey({ name: "organization_user_resource_grants_session_workspace_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("restrict"), actionValid: check( "organization_user_resource_grants_action_check", sql`${table.action} = lower(btrim(${table.action})) and length(${table.action}) between 1 and 64 and ${table.action} ~ '^[a-z0-9](?:[a-z0-9._:-]*[a-z0-9])?$'`, ), modeValid: check( "organization_user_resource_grants_mode_check", sql`${table.mode} in ('once', 'session', 'always')`, ), contextValid: check( "organization_user_resource_grants_context_check", sql`${table.context} in ('user_private', 'workspace_shared')`, ), sessionFenceValid: check( "organization_user_resource_grants_session_fence_check", sql`( ${table.mode} = 'always' and ${table.sessionId} is null and ${table.authorityEpoch} is null ) or ( ${table.mode} in ('once', 'session') and ${table.sessionId} is not null and ${table.authorityEpoch} is not null and ${table.authorityEpoch} > 0 )`, ), generationValid: check( "organization_user_resource_grants_generation_check", sql`${table.generation} > 0`, ), statusValid: check( "organization_user_resource_grants_status_check", sql`${table.status} in ('active', 'consumed', 'revoked', 'expired')`, ), revocationValid: check( "organization_user_resource_grants_revocation_check", sql`(${table.status} = 'revoked' and ${table.revokedAt} is not null) or (${table.status} <> 'revoked' and ${table.revokedAt} is null)`, ), }), ); // One temporary realtime owner for an ordinary session. Terminal rows remain // as lifecycle evidence; the partial unique index admits only one active owner. export const sessionRealtimeModes = pgTable( "session_realtime_modes", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), operationId: uuid("operation_id").notNull(), ownerSubjectId: text("owner_subject_id").notNull(), browserInstanceId: text("browser_instance_id").notNull(), ownerKeyHash: text("owner_key_hash").notNull(), personalConnectionDelegations: jsonb("personal_connection_delegations") .$type() .notNull() .default([]), mcpAccountBindings: jsonb("mcp_account_bindings").$type(), model: text("model").notNull(), state: text("state").notNull().default("active"), // A non-active provider connection prepared for one ringing phone. incomingCallId: uuid("incoming_call_id"), incomingCallDevice: text("incoming_call_device"), // The voice owner's account intent, copied onto every turn this lease admits. connectionAccountIntent: jsonb( "connection_account_intent", ).$type(), version: integer("version").notNull().default(1), connectionEpoch: integer("connection_epoch").notNull().default(1), leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true, }).notNull(), lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true, }).notNull(), startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(), endedAt: timestamp("ended_at", { withTimezone: true }), endReason: text("end_reason"), // The rolling migration owns this forward reference. End commits at most // one canonical transcript-tail Steer and binds its audit projection here. contextProjectionId: uuid("context_projection_id"), contextProjectedAt: timestamp("context_projected_at", { withTimezone: true, }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "session_realtime_modes_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "session_realtime_modes_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), operation: uniqueIndex("session_realtime_modes_operation_uq").on( table.workspaceId, table.sessionId, table.operationId, ), oneActive: uniqueIndex("session_realtime_modes_one_active_uq") .on(table.workspaceId, table.sessionId) .where(sql`${table.state} = 'active'`), activeLease: index("session_realtime_modes_active_lease_idx") .on(table.leaseExpiresAt, table.workspaceId, table.sessionId) .where(sql`${table.state} = 'active'`), incomingCall: index("session_realtime_modes_incoming_call_idx") .on(table.incomingCallId) .where(sql`${table.incomingCallId} is not null`), incomingCallValid: check( "session_realtime_modes_incoming_call_check", sql`(${table.incomingCallId} is null and ${table.incomingCallDevice} is null and ${table.state} <> 'preparing') or (${table.incomingCallId} is not null and ${table.incomingCallDevice} is not null and length(${table.incomingCallDevice}) between 1 and 300)`, ), stateValid: check( "session_realtime_modes_state_check", sql`${table.state} in ('preparing', 'active', 'ended')`, ), modelValid: check( "session_realtime_modes_model_check", sql`${table.model} in ( 'opengeni-azure/gpt-live-1', 'gpt-live-1-boulder-alpha', 'supergrok/grok-voice-think-fast-2.0', 'opengeni-gateway/openai/gpt-realtime-2.1', 'opengeni-gateway/openai/gpt-realtime-mini', 'opengeni-gateway/xai/grok-voice-think-fast-2.0', 'workspace-gateway/openai/gpt-realtime-2.1', 'workspace-gateway/openai/gpt-realtime-mini', 'workspace-gateway/xai/grok-voice-think-fast-2.0', 'workspace-elevenlabs/eleven_realtime_v1_max', 'workspace-elevenlabs/eleven_realtime_v1_mini' )`, ), endReasonValid: check( "session_realtime_modes_end_reason_check", sql`${table.endReason} is null or ${table.endReason} in ('user_stop', 'browser_unload', 'lease_expired', 'authority_revoked')`, ), versionValid: check("session_realtime_modes_version_check", sql`${table.version} >= 1`), epochValid: check("session_realtime_modes_epoch_check", sql`${table.connectionEpoch} >= 1`), ownerSubjectValid: check( "session_realtime_modes_owner_subject_check", sql`octet_length(${table.ownerSubjectId}) between 1 and 1024`, ), browserInstanceValid: check( "session_realtime_modes_browser_instance_check", sql`octet_length(${table.browserInstanceId}) between 1 and 256`, ), ownerKeyHashValid: check( "session_realtime_modes_owner_key_hash_check", sql`${table.ownerKeyHash} ~ '^[0-9a-f]{64}$'`, ), leaseValid: check( "session_realtime_modes_lease_check", sql`${table.leaseExpiresAt} > ${table.lastHeartbeatAt}`, ), terminalValid: check( "session_realtime_modes_terminal_check", sql`(${table.state} in ('preparing', 'active') and ${table.endedAt} is null and ${table.endReason} is null) or (${table.state} = 'ended' and ${table.endedAt} is not null and ${table.endReason} is not null)`, ), }), ); export const sessionRealtimeConnections = pgTable( "session_realtime_connections", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), realtimeId: uuid("realtime_id") .notNull() .references(() => sessionRealtimeModes.id, { onDelete: "cascade" }), operationId: uuid("operation_id").notNull(), connectionEpoch: integer("connection_epoch").notNull(), startupFenceSequence: integer("startup_fence_sequence").notNull().default(0), promotionMode: text("promotion_mode").notNull().default("legacy"), state: text("state").notNull().default("negotiating"), sdpAnswer: text("sdp_answer"), failureCode: text("failure_code"), providerSessionId: text("provider_session_id"), startupEventId: text("startup_event_id"), startupAcknowledgedAt: timestamp("startup_acknowledged_at", { withTimezone: true, }), negotiatedAt: timestamp("negotiated_at", { withTimezone: true }), closedAt: timestamp("closed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "session_realtime_connections_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "session_realtime_connections_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), operation: uniqueIndex("session_realtime_connections_operation_uq").on( table.realtimeId, table.operationId, ), epoch: uniqueIndex("session_realtime_connections_epoch_uq").on( table.realtimeId, table.connectionEpoch, ), oneActive: uniqueIndex("session_realtime_connections_one_active_uq") .on(table.realtimeId) .where( sql`(${table.promotionMode} = 'legacy' and ${table.state} in ('negotiating', 'ready', 'active')) or (${table.promotionMode} = 'staged' and ${table.state} = 'active')`, ), onePreparing: uniqueIndex("session_realtime_connections_one_preparing_uq") .on(table.realtimeId) .where( sql`(${table.promotionMode} = 'legacy' and ${table.state} in ('negotiating', 'ready', 'active')) or (${table.promotionMode} = 'staged' and ${table.state} in ('negotiating', 'ready'))`, ), epochValid: check( "session_realtime_connections_epoch_check", sql`${table.connectionEpoch} >= 1`, ), startupFenceValid: check( "session_realtime_connections_startup_fence_check", sql`${table.startupFenceSequence} >= 0`, ), promotionModeValid: check( "session_realtime_connections_promotion_mode_check", sql`${table.promotionMode} in ('legacy', 'staged')`, ), stateValid: check( "session_realtime_connections_state_check", sql`${table.state} in ('negotiating', 'ready', 'active', 'failed', 'closed')`, ), sdpValid: check( "session_realtime_connections_sdp_check", sql`${table.sdpAnswer} is null or octet_length(${table.sdpAnswer}) between 1 and 1048576`, ), failureValid: check( "session_realtime_connections_failure_check", sql`${table.failureCode} is null or octet_length(${table.failureCode}) between 1 and 128`, ), providerSessionValid: check( "session_realtime_connections_provider_session_check", sql`${table.providerSessionId} is null or octet_length(${table.providerSessionId}) between 1 and 1024`, ), startupEventValid: check( "session_realtime_connections_startup_event_check", sql`${table.startupEventId} is null or octet_length(${table.startupEventId}) between 1 and 1024`, ), startupAckValid: check( "session_realtime_connections_startup_ack_check", sql`(${table.startupAcknowledgedAt} is null and ${table.providerSessionId} is null and ${table.startupEventId} is null) or (${table.startupAcknowledgedAt} is not null and ${table.providerSessionId} is not null)`, ), terminalValid: check( "session_realtime_connections_terminal_check", sql`(${table.state} = 'negotiating' and ${table.sdpAnswer} is null and ${table.failureCode} is null and ${table.negotiatedAt} is null and ${table.closedAt} is null) or (${table.state} = 'ready' and ${table.sdpAnswer} is not null and ${table.failureCode} is null and ${table.negotiatedAt} is not null and ${table.closedAt} is null) or (${table.state} = 'active' and ${table.sdpAnswer} is not null and ${table.failureCode} is null and ${table.negotiatedAt} is not null and ${table.closedAt} is null) or (${table.state} = 'failed' and ${table.sdpAnswer} is null and ${table.failureCode} is not null and ${table.closedAt} is not null) or (${table.state} = 'closed' and ${table.closedAt} is not null)`, ), }), ); export const sessionRealtimeEntries = pgTable( "session_realtime_entries", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), realtimeId: uuid("realtime_id") .notNull() .references(() => sessionRealtimeModes.id, { onDelete: "cascade" }), operationId: uuid("operation_id").notNull(), connectionEpoch: integer("connection_epoch").notNull(), sequence: integer("sequence").notNull(), direction: text("direction").notNull(), kind: text("kind").notNull(), role: text("role"), providerEventId: text("provider_event_id"), delegationItemId: text("delegation_item_id"), // The referenced tables are declared later in this schema module; the // rolling migration owns all three ON DELETE SET NULL foreign keys. sourceUpdateId: uuid("source_update_id"), historyItemId: uuid("history_item_id"), // The rolling migration owns this ON DELETE SET NULL foreign key because // sessionTurns is declared later in this schema module. A non-null value // links the accepted provider call and its one terminal outbound // result/error to the same ordinary turn. It never denotes a child/fork // session. turnId: uuid("turn_id"), text: losslessText("text"), textCodecVersion: losslessCodecVersion("text_codec_version"), payload: losslessJsonb("payload").$type>().notNull().default({}), payloadCodecVersion: losslessCodecVersion("payload_codec_version"), // Application context for an exact provider-in delegation or finalized // transcript. It is materialized as ordinary user-role message content. modelContext: text("model_context"), clientAckedAt: timestamp("client_acked_at", { withTimezone: true }), providerAckedAt: timestamp("provider_acked_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "session_realtime_entries_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "session_realtime_entries_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), operation: uniqueIndex("session_realtime_entries_operation_uq").on( table.realtimeId, table.operationId, ), sequence: uniqueIndex("session_realtime_entries_sequence_uq").on( table.realtimeId, table.sequence, ), sourceUpdate: uniqueIndex("session_realtime_entries_source_update_uq") .on(table.realtimeId, table.sourceUpdateId) .where(sql`${table.sourceUpdateId} is not null`), // Deleting a machine input (archive purge) sets this to null; that check // has only source_update_id, which the unique index above does not lead. sourceUpdateLookup: index("session_realtime_entries_source_update_idx") .on(table.sourceUpdateId) .where(sql`${table.sourceUpdateId} is not null`), // History deletion's ON DELETE SET NULL check has only history_item_id, // not a realtime_id. Avoid a full ledger scan for every archived item. historyItem: index("session_realtime_entries_history_item_idx") .on(table.historyItemId) .where(sql`${table.historyItemId} is not null`), delegationTurn: uniqueIndex("session_realtime_entries_delegation_turn_uq") .on(table.turnId) .where(sql`${table.kind} = 'delegation_call' and ${table.turnId} is not null`), delegationTerminal: uniqueIndex("session_realtime_entries_delegation_terminal_uq") .on(table.turnId) .where( sql`${table.direction} = 'provider_out' and ${table.kind} in ('delegation_result', 'error') and ${table.turnId} is not null`, ), delegationCall: uniqueIndex("session_realtime_entries_delegation_call_uq") .on(table.realtimeId, table.delegationItemId) .where(sql`${table.kind} = 'delegation_call' and ${table.delegationItemId} is not null`), outboundPending: index("session_realtime_entries_outbound_pending_idx") .on(table.realtimeId, table.sequence) .where(sql`${table.direction} = 'provider_out' and ${table.providerAckedAt} is null`), epochValid: check("session_realtime_entries_epoch_check", sql`${table.connectionEpoch} >= 1`), sequenceValid: check("session_realtime_entries_sequence_check", sql`${table.sequence} >= 1`), directionValid: check( "session_realtime_entries_direction_check", sql`${table.direction} in ('provider_in', 'provider_out')`, ), kindValid: check( "session_realtime_entries_kind_check", sql`${table.kind} in ('user_transcript', 'assistant_transcript', 'delegation_call', 'delegation_progress', 'delegation_result', 'interruption', 'session_update', 'error')`, ), roleValid: check( "session_realtime_entries_role_check", sql`${table.role} is null or ${table.role} in ('user', 'assistant')`, ), providerEventValid: check( "session_realtime_entries_provider_event_check", sql`${table.providerEventId} is null or octet_length(${table.providerEventId}) between 1 and 1024`, ), delegationItemValid: check( "session_realtime_entries_delegation_item_check", sql`${table.delegationItemId} is null or octet_length(${table.delegationItemId}) between 1 and 1024`, ), turnValid: check( "session_realtime_entries_turn_check", sql`${table.turnId} is null or (${table.kind} = 'delegation_call' and ${table.direction} = 'provider_in') or (${table.kind} in ('delegation_progress', 'delegation_result', 'error') and ${table.direction} = 'provider_out')`, ), transcriptValid: check( "session_realtime_entries_transcript_check", sql`(${table.kind} = 'user_transcript' and ${table.role} = 'user' and ${table.text} is not null) or (${table.kind} = 'assistant_transcript' and ${table.role} = 'assistant' and ${table.text} is not null) or (${table.kind} not in ('user_transcript', 'assistant_transcript') and ${table.role} is null)`, ), modelContextValid: check( "session_realtime_entries_model_context_check", sql`${table.modelContext} is null or ( ${table.direction} = 'provider_in' and ${table.kind} in ('delegation_call', 'user_transcript', 'assistant_transcript') and opengeni_private.model_context_value_valid(${table.modelContext}) )`, ), }), ); // A denied session create is durable evidence, not a mutable session/resource // artifact. It has its own workspace-scoped idempotency key so retries replay // the same denial without creating a session or billing/run rows. export const sessionSpawnDenials = pgTable( "session_spawn_denials", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), parentSessionId: uuid("parent_session_id"), rootSessionId: uuid("root_session_id"), currentDepth: integer("current_depth").notNull(), attemptedDepth: bigint("attempted_depth", { mode: "number" }).notNull(), effectiveMaxNestedAgentDepth: integer("effective_max_nested_agent_depth").notNull(), requestedMaxNestedAgentDepthOverride: integer("requested_max_nested_agent_depth_override"), policySource: text("policy_source").notNull(), policySessionId: uuid("policy_session_id"), subjectId: text("subject_id"), code: text("code").notNull(), idempotencyKey: text("idempotency_key"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceIdentity: uniqueIndex("session_spawn_denials_workspace_id_uq").on( table.workspaceId, table.id, ), workspaceCreated: index("session_spawn_denials_workspace_created_idx").on( table.workspaceId, table.createdAt, ), parent: index("session_spawn_denials_parent_idx").on( table.workspaceId, table.parentSessionId, table.createdAt, ), idempotency: uniqueIndex("session_spawn_denials_workspace_idempotency_idx") .on(table.workspaceId, table.idempotencyKey) .where(sql`${table.idempotencyKey} is not null`), workspaceAccount: foreignKey({ name: "session_spawn_denials_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); // Per-authenticated-subject session organization and follow-up state. This is // deliberately a relation instead of session columns: one member's pin, // acknowledgment, or actively-working label must never affect another member, // and a session's own activity timestamps must remain agent/runtime truth. // `subjectId` is the trusted AccessGrant // subject, which is text because configured/delegated principals are not always // UUIDs. The account/workspace pair carries the standard forced-RLS boundary. export const sessionPins = pgTable( "session_pins", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), subjectId: text("subject_id").notNull(), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), // Keep an unpinned tombstone (pinned=false, pinned_at=null) rather than // deleting it. That preserves a monotonic version and prevents an ABA race: // a stale client that saw pin version 1 cannot silently overwrite a later // unpin+re-pin that would otherwise recreate version 1. pinned: boolean("pinned").notNull().default(true), pinnedAt: timestamp("pinned_at", { withTimezone: true }).defaultNow(), version: integer("version").notNull().default(1), // Compare the meaningful event frontier, not the raw durable cursor. // Merely opening a route never changes this per-subject fence. acknowledgedSequence: integer("acknowledged_sequence").notNull().default(0), // A replay at/before this raw event position cannot consume explicit intent. // A genuinely newer proven read, or an explicit mark-read, removes it. manuallyUnreadThrough: integer("manually_unread_through"), activelyWorking: boolean("actively_working").notNull().default(false), attentionVersion: integer("attention_version").notNull().default(0), archived: boolean("archived").notNull().default(false), archivedAt: timestamp("archived_at", { withTimezone: true }), archiveVersion: integer("archive_version").notNull().default(0), }, (table) => ({ subjectNonempty: check( "session_pins_subject_nonempty", sql`length(btrim(${table.subjectId})) > 0`, ), versionNonnegative: check("session_pins_version_nonnegative", sql`${table.version} >= 0`), acknowledgedSequenceFloor: check( "session_pins_acknowledged_sequence_floor", sql`${table.acknowledgedSequence} >= -1`, ), attentionVersionNonnegative: check( "session_pins_attention_version_nonnegative", sql`${table.attentionVersion} >= 0`, ), archiveVersionNonnegative: check( "session_pins_archive_version_nonnegative", sql`${table.archiveVersion} >= 0`, ), archiveStateConsistent: check( "session_pins_archive_state_consistent", sql`((${table.archived}) and (${table.archivedAt}) is not null) or ((not ${table.archived}) and (${table.archivedAt}) is null)`, ), stateConsistent: check( "session_pins_state_consistent", sql`((${table.pinned}) and (${table.pinnedAt}) is not null) or ((not ${table.pinned}) and (${table.pinnedAt}) is null)`, ), workspaceAccount: foreignKey({ name: "session_pins_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "session_pins_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), subjectSession: uniqueIndex("session_pins_subject_workspace_session_idx").on( table.subjectId, table.workspaceId, table.sessionId, ), sessionSubject: index("session_pins_session_subject_idx").on(table.sessionId, table.subjectId), subjectPinned: index("session_pins_workspace_subject_pinned_idx").on( table.workspaceId, table.subjectId, table.pinned, table.pinnedAt.desc(), table.sessionId.desc(), ), subjectArchived: index("session_pins_workspace_subject_archived_idx").on( table.workspaceId, table.subjectId, table.archived, table.archivedAt.desc(), table.sessionId.desc(), ), }), ); // Rolling-compatibility storage for pre-keyset session-list cursors. New page // one reads freeze the committed workspace activity revision in an opaque // updated_at/id keyset and create no row here. Old API replicas and cursors may // retain an already-ordered id array for its short TTL, so current replicas keep // reading, visibility-stripping, member-cleaning, and reaping those rows until // the compatibility table is retired by a later migration. export const sessionListSnapshots = pgTable( "session_list_snapshots", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), subjectId: text("subject_id").notNull(), parentSessionFilter: text("parent_session_filter").notNull().default("all"), search: text("search"), archiveMode: text("archive_mode").$type<"active" | "archived">().notNull().default("active"), ordinarySessionIds: uuid("ordinary_session_ids") .array() .notNull() .default(sql`'{}'::uuid[]`), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "session_list_snapshots_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), subjectNonempty: check( "session_list_snapshots_subject_nonempty", sql`length(btrim(${table.subjectId})) > 0`, ), parentFilterValid: check( "session_list_snapshots_parent_filter_valid", sql`${table.parentSessionFilter} = 'all' or ${table.parentSessionFilter} = 'null' or ${table.parentSessionFilter} ~ '^[0-9a-fA-F-]{36}$'`, ), searchLength: check( "session_list_snapshots_search_length", sql`${table.search} is null or length(${table.search}) <= 200`, ), archiveModeValid: check( "session_list_snapshots_archive_mode_valid", sql`${table.archiveMode} in ('active', 'archived')`, ), workspaceExpiry: index("session_list_snapshots_workspace_expiry_idx").on( table.workspaceId, table.subjectId, table.expiresAt, ), expiryReaper: index("session_list_snapshots_expiry_reaper_idx").on(table.expiresAt, table.id), }), ); export const sessionMcpServers = pgTable( "session_mcp_servers", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), serverId: text("server_id").notNull(), name: text("name"), url: text("url").notNull(), allowedTools: jsonb("allowed_tools").$type(), timeoutMs: integer("timeout_ms"), cacheToolsList: boolean("cache_tools_list").notNull().default(false), // Human-approval policy: `true` = every tool requires approval, a string[] of // UNPREFIXED tool names = only those require it, null/absent = auto-run. requireApproval: jsonb("require_approval").$type(), // Non-secret pointer resolved at request time by the standalone broker or // an embedding host. Unlike headersEncrypted, this is safe to project. connectionRef: jsonb("connection_ref").$type(), // Map of header name -> AES-GCM ciphertext. Values are decrypted only by the // worker's run-preparation path and never returned by API helpers. headersEncrypted: jsonb("headers_encrypted") .$type>() .notNull() .default({}), credentialVersion: integer("credential_version").notNull().default(1), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ sessionServer: uniqueIndex("session_mcp_servers_session_server_idx").on( table.workspaceId, table.sessionId, table.serverId, ), session: index("session_mcp_servers_session_idx").on(table.workspaceId, table.sessionId), }), ); export const files = pgTable( "files", { privateOwnerSubjectIds: text("private_owner_subject_ids").array().default(sql`CASE WHEN nullif(current_setting('opengeni.private_file_owner',true),'') IS NULL THEN NULL ELSE ARRAY[current_setting('opengeni.private_file_owner',true)] END`), /** The person the file belongs to: only they can share or limit it. */ ownerSubjectId: text("owner_subject_id").default(sql`coalesce( nullif(current_setting('opengeni.private_file_owner',true),''), nullif(current_setting('opengeni.initiating_human_subject_id',true),''))`), // Migration 1186. An Only me file's other workspaces of the organization // where it also works, besides this one and its owner's Personal // workspace; null for every workspace (files from before 1186). reachWorkspaceIds: uuid("reach_workspace_ids") .array() .default(sql`'{}'::uuid[]`), id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), // Origin only for personal originals; SQL owns the generated retention FK. workspaceId: uuid("workspace_id").notNull(), status: text("status").notNull().default("pending_upload"), filename: text("filename").notNull(), safeFilename: text("safe_filename").notNull(), contentType: text("content_type").notNull(), sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(), sha256: text("sha256"), bucket: text("bucket").notNull(), objectKey: text("object_key").notNull(), /** An app-shot's capture (AppShotCapture); written with the upload, never changed. */ appShot: jsonb("app_shot"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceCreated: index("files_workspace_created_idx").on(table.workspaceId, table.createdAt), // File lists read one page newest first from each of these (migrations // 1409-1412): a workspace's shared files, a person's own files in one // workspace, and a person's own files that may reach other workspaces or // stay in their own. A private file has one owner (1431). sharedCreated: index("files_shared_created_idx") .on(table.workspaceId, table.status, table.createdAt, table.id) .where(sql`private_owner_subject_ids IS NULL`), privateWorkspaceCreated: index("files_private_workspace_created_idx") .on( table.workspaceId, sql`(private_owner_subject_ids[1])`, table.status, table.createdAt, table.id, ) .where(sql`private_owner_subject_ids IS NOT NULL`), privateRoamingCreated: index("files_private_roaming_created_idx") .on( table.accountId, sql`(private_owner_subject_ids[1])`, table.status, table.createdAt, table.id, ) .where( sql`private_owner_subject_ids IS NOT NULL AND (reach_workspace_ids IS NULL OR cardinality(reach_workspace_ids) > 0)`, ), privateLocalCreated: index("files_private_local_created_idx") .on( table.accountId, sql`(private_owner_subject_ids[1])`, table.status, table.createdAt, table.id, ) .where( sql`private_owner_subject_ids IS NOT NULL AND reach_workspace_ids IS NOT NULL AND cardinality(reach_workspace_ids) = 0`, ), objectKey: uniqueIndex("files_object_key_idx").on(table.objectKey), scopeIdentity: uniqueIndex("files_scope_id_uq").on( table.accountId, table.workspaceId, table.id, ), status: index("files_status_idx").on(table.status), }), ); /** Immutable publication receipt; content and ownership remain in files. */ export const sandboxFilePublications = opengeniPrivateSchema.table( "sandbox_file_publications", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), fileId: uuid("file_id").notNull(), sourceSessionId: uuid("source_session_id"), publishedAt: timestamp("published_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ name: "sandbox_file_publications_pk", columns: [table.accountId, table.workspaceId, table.fileId], }), file: foreignKey({ name: "sandbox_file_publications_file_fk", columns: [table.accountId, table.workspaceId, table.fileId], foreignColumns: [files.accountId, files.workspaceId, files.id], }).onDelete("cascade"), // SQL owns the composite session FK with column-specific SET NULL. session: index("sandbox_file_publications_session_idx").on( table.workspaceId, table.sourceSessionId, table.publishedAt, table.fileId, ), }), ); /** Shared discovery pins; no content or access authority. SQL owns target validation. */ export const artifactCatalogPins = opengeniPrivateSchema.table( "artifact_catalog_pins", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), kind: text("kind").notNull(), artifactId: text("artifact_id").notNull(), pinnedAt: timestamp("pinned_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ columns: [table.accountId, table.workspaceId, table.kind, table.artifactId] }), }), ); /** Source-session upload fence; never stores file bytes or expiring upload URLs. */ export const slackFileUploadOperations = opengeniPrivateSchema.table( "slack_file_upload_operations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), interactionId: uuid("interaction_id").notNull(), // Routed interactions may use an installation whose HOME is another workspace. connectionId: uuid("connection_id") .notNull() .references(() => connections.id, { onDelete: "cascade" }), fileId: uuid("file_id").notNull(), subjectId: text("subject_id").notNull(), operationId: uuid("operation_id").notNull(), requestDigest: text("request_digest").notNull(), phase: text("phase") .$type< "pending" | "uploading" | "uploaded" | "completing" | "outcome_unknown" | "completed" >() .notNull() .default("pending"), slackFileId: text("slack_file_id"), claimHolderId: uuid("claim_holder_id"), claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ operation: uniqueIndex("slack_file_upload_operations_workspace_operation_uq").on( table.workspaceId, table.operationId, ), session: foreignKey({ name: "slack_file_upload_operations_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), interaction: foreignKey({ name: "slack_file_upload_operations_interaction_fk", columns: [table.accountId, table.workspaceId, table.interactionId], foreignColumns: [ slackInteractions.accountId, slackInteractions.workspaceId, slackInteractions.id, ], }).onDelete("cascade"), file: foreignKey({ name: "slack_file_upload_operations_file_fk", columns: [table.accountId, table.workspaceId, table.fileId], foreignColumns: [files.accountId, files.workspaceId, files.id], }).onDelete("cascade"), sessionLookup: index("slack_file_upload_operations_session_idx").on( table.workspaceId, table.sessionId, ), bounds: check( "slack_file_upload_operations_bounds_check", sql`octet_length(${table.subjectId}) between 1 and 1024 and length(btrim(${table.subjectId})) > 0 and ${table.requestDigest} ~ '^[a-f0-9]{64}$' and (${table.slackFileId} is null or ( octet_length(${table.slackFileId}) between 1 and 128 and length(btrim(${table.slackFileId})) > 0 ))`, ), state: check( "slack_file_upload_operations_state_check", sql`${table.phase} in ('pending', 'uploading', 'uploaded', 'completing', 'outcome_unknown', 'completed') and ((${table.phase} = 'pending') = (${table.slackFileId} is null)) and ((${table.claimHolderId} is null) = (${table.claimExpiresAt} is null)) and (${table.phase} <> 'completed' or ${table.claimHolderId} is null)`, ), }), ); export const fileUploads = pgTable( "file_uploads", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), fileId: uuid("file_id") .notNull() .references(() => files.id, { onDelete: "cascade" }), privateFileOwnerSubjectId: text("private_file_owner_subject_id").default( sql`nullif(current_setting('opengeni.private_file_owner',true),'')`, ), status: text("status").notNull().default("pending"), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), completedAt: timestamp("completed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspace: index("file_uploads_workspace_idx").on(table.workspaceId), fileId: index("file_uploads_file_id_idx").on(table.fileId), status: index("file_uploads_status_idx").on(table.status), }), ); /** Permanent generated-image correlation; canonical bytes stay in `files`. */ export const generatedImageArtifacts = pgTable( "generated_image_artifacts", { artifactId: uuid("artifact_id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id").references(() => sessions.id, { onDelete: "set null", }), // Turn/attempt foreign keys are installed by the migration; those tables // are declared later in this monolithic schema module. turnId: uuid("turn_id"), attemptId: uuid("attempt_id"), uploadId: uuid("upload_id").references(() => fileUploads.id, { onDelete: "set null", }), settlementKey: text("settlement_key").notNull(), toolCallId: text("tool_call_id").notNull(), sourceStrategy: text("source_strategy").$type<"native_hosted" | "provider_adapter">().notNull(), providerId: text("provider_id").notNull(), providerBindingHash: text("provider_binding_hash").notNull(), providerItemId: text("provider_item_id"), status: text("status").$type<"pending" | "ready">().notNull().default("pending"), mediaType: text("media_type").notNull(), sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(), sha256: text("sha256").notNull(), width: integer("width").notNull(), height: integer("height").notNull(), sandboxPath: text("sandbox_path").notNull(), readyAt: timestamp("ready_at", { withTimezone: true }), lastError: text("last_error"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ settlementKey: uniqueIndex("generated_image_artifacts_settlement_key_uq").on( table.workspaceId, table.settlementKey, ), sessionCreated: index("generated_image_artifacts_session_created_idx").on( table.workspaceId, table.sessionId, table.createdAt, table.artifactId, ), providerItem: uniqueIndex("generated_image_artifacts_provider_item_uq") .on(table.workspaceId, table.providerId, table.providerBindingHash, table.providerItemId) .where(sql`${table.providerItemId} is not null`), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], name: "generated_image_artifacts_workspace_account_fk", }).onDelete("cascade"), workspaceFile: foreignKey({ columns: [table.workspaceId, table.artifactId], foreignColumns: [files.workspaceId, files.id], name: "generated_image_artifacts_workspace_file_fk", }).onDelete("cascade"), sourceStrategyValid: check( "generated_image_artifacts_source_strategy_chk", sql`${table.sourceStrategy} in ('native_hosted', 'provider_adapter')`, ), sourceShapeValid: check( "generated_image_artifacts_source_shape_chk", sql`(${table.sourceStrategy} = 'native_hosted' and ${table.providerItemId} is not null) or (${table.sourceStrategy} = 'provider_adapter' and ${table.providerItemId} is null)`, ), statusValid: check( "generated_image_artifacts_status_chk", sql`${table.status} in ('pending', 'ready')`, ), readyShapeValid: check( "generated_image_artifacts_ready_shape_chk", sql`(${table.status} = 'ready') = (${table.readyAt} is not null)`, ), mediaTypeValid: check( "generated_image_artifacts_media_type_chk", sql`${table.mediaType} in ('image/png', 'image/jpeg', 'image/webp')`, ), sizeValid: check( "generated_image_artifacts_size_chk", sql`${table.sizeBytes} > 0 and ${table.sizeBytes} <= 67108864`, ), sha256Valid: check( "generated_image_artifacts_sha256_chk", sql`${table.sha256} ~ '^[0-9a-f]{64}$'`, ), bindingHashValid: check( "generated_image_artifacts_binding_hash_chk", sql`${table.providerBindingHash} ~ '^[0-9a-f]{64}$'`, ), identityBoundsValid: check( "generated_image_artifacts_identity_bounds_chk", sql`${table.settlementKey} ~ '^[0-9a-f]{64}$' and octet_length(${table.toolCallId}) between 1 and 512 and octet_length(${table.providerId}) between 1 and 128 and (${table.providerItemId} is null or octet_length(${table.providerItemId}) between 1 and 512) and (${table.lastError} is null or octet_length(${table.lastError}) <= 16384)`, ), dimensionsValid: check( "generated_image_artifacts_dimensions_chk", sql`${table.width} between 1 and 16384 and ${table.height} between 1 and 16384 and (${table.width}::bigint * ${table.height}::bigint) <= 67108864`, ), sandboxPathValid: check( "generated_image_artifacts_sandbox_path_chk", sql`${table.sandboxPath} ~ '^/workspace/generated-images/generated-image-[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\\.(png|jpg|webp)$'`, ), }), ); /** Paid non-native generation admission; prevents ambiguous automatic replay. */ export const imageGenerationOperations = pgTable( "image_generation_operations", { id: uuid("id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id").references(() => sessions.id, { onDelete: "cascade", }), turnId: uuid("turn_id"), attemptId: uuid("attempt_id"), operationKey: text("operation_key").notNull(), toolCallId: text("tool_call_id").notNull(), providerId: text("provider_id").notNull(), providerBindingHash: text("provider_binding_hash").notNull(), modelId: text("model_id").notNull(), requestDigest: text("request_digest").notNull(), expectedArtifactId: uuid("expected_artifact_id").notNull(), status: text("status") .$type< "prepared" | "provider_started" | "completed" | "outcome_unknown" | "retention_failed" >() .notNull() .default("prepared"), /** Opengeni-credit price frozen at admission; zero when credits do not fund it. */ pricedCostMicros: bigint("priced_cost_micros", { mode: "number" }).notNull().default(0), /** A priced operation is debited exactly once, when its image is delivered. */ creditState: text("credit_state") .$type<"not_applicable" | "pending" | "debited">() .notNull() .default("not_applicable"), /** The turn's canonical chat model whose plan and trial grants may pay. */ creditUsageModelId: text("credit_usage_model_id"), providerStartedAt: timestamp("provider_started_at", { withTimezone: true }), completedAt: timestamp("completed_at", { withTimezone: true }), lastError: text("last_error"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ operationKey: uniqueIndex("image_generation_operations_operation_key_uq").on( table.workspaceId, table.operationKey, ), sessionCreated: index("image_generation_operations_session_created_idx").on( table.workspaceId, table.sessionId, table.createdAt, table.id, ), creditHold: index("image_generation_operations_credit_hold_idx") .on(table.workspaceId, table.providerStartedAt) .where(sql`${table.creditState} = 'pending' and ${table.status} = 'provider_started'`), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], name: "image_generation_operations_workspace_account_fk", }).onDelete("cascade"), statusValid: check( "image_generation_operations_status_chk", sql`${table.status} in ('prepared', 'provider_started', 'completed', 'outcome_unknown', 'retention_failed')`, ), digestValid: check( "image_generation_operations_digest_chk", sql`${table.operationKey} ~ '^[0-9a-f]{64}$' and ${table.providerBindingHash} ~ '^[0-9a-f]{64}$' and ${table.requestDigest} ~ '^[0-9a-f]{64}$'`, ), identityBoundsValid: check( "image_generation_operations_identity_bounds_chk", sql`octet_length(${table.toolCallId}) between 1 and 512 and octet_length(${table.providerId}) between 1 and 128 and octet_length(${table.modelId}) between 1 and 256 and (${table.lastError} is null or octet_length(${table.lastError}) <= 16384)`, ), stateValid: check( "image_generation_operations_state_chk", sql`(${table.status} = 'prepared' and ${table.providerStartedAt} is null and ${table.completedAt} is null) or (${table.status} in ('provider_started', 'outcome_unknown', 'retention_failed') and ${table.providerStartedAt} is not null and ${table.completedAt} is null) or (${table.status} = 'completed' and ${table.providerStartedAt} is not null and ${table.completedAt} is not null)`, ), creditValid: check( "image_generation_operations_credit_chk", sql`(${table.pricedCostMicros} = 0 and ${table.creditState} = 'not_applicable' and ${table.creditUsageModelId} is null) or (${table.pricedCostMicros} between 1 and 1000000000 and (${table.creditUsageModelId} is null or octet_length(${table.creditUsageModelId}) between 1 and 256) and ((${table.creditState} = 'pending' and ${table.status} <> 'completed') or (${table.creditState} = 'debited' and ${table.status} = 'completed')))`, ), }), ); /** * The maximum priced cost of a stateless Opengeni-credit model call that is * still in its provider request, reserved at admission and deleted when the * call settles or fails. An expired hold (its process stopped mid-call) no * longer counts. */ export const modelCallCreditHolds = pgTable( "model_call_credit_holds", { accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), /** The call's server-generated request id. */ requestId: uuid("request_id").notNull(), workspaceId: uuid("workspace_id").notNull(), amountMicros: bigint("amount_micros", { mode: "number" }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }) .notNull() .default(sql`statement_timestamp()`), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), }, (table) => ({ pk: primaryKey({ columns: [table.accountId, table.requestId] }), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], name: "model_call_credit_holds_workspace_account_fk", }).onDelete("cascade"), amountValid: check("model_call_credit_holds_amount_chk", sql`${table.amountMicros} > 0`), expiryValid: check( "model_call_credit_holds_expiry_chk", sql`${table.expiresAt} > ${table.createdAt}`, ), }), ); /** Workspace policy for provider-neutral video generation. Disabled by default. */ export const workspaceVideoGenerationPolicies = pgTable( "workspace_video_generation_policies", { workspaceId: uuid("workspace_id") .primaryKey() .references(() => workspaces.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), revision: bigint("revision", { mode: "number" }).notNull().default(0), fundingSource: text("funding_source").notNull().default("workspace_gateway"), enabledModelIds: jsonb("enabled_model_ids").$type().notNull().default([]), defaultModelId: text("default_model_id"), updatedBySubjectId: text("updated_by_subject_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "workspace_video_generation_policies_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), revisionValid: check( "workspace_video_generation_policies_revision_chk", sql`${table.revision} between 0 and 9007199254740991`, ), modelsValid: check( "workspace_video_generation_policies_models_chk", sql`jsonb_typeof(${table.enabledModelIds}) = 'array' and jsonb_array_length(${table.enabledModelIds}) <= 16 and (${table.defaultModelId} is null or ${table.enabledModelIds} ? ${table.defaultModelId})`, ), fundingSourceValid: check( "workspace_video_generation_policies_funding_source_chk", sql`${table.fundingSource} in ('opengeni_credits', 'workspace_gateway', 'supergrok_subscription')`, ), }), ); /** Exact pending/ready accounting for permanent generated-video files. */ export const workspaceVideoGenerationQuotas = pgTable( "workspace_video_generation_quotas", { workspaceId: uuid("workspace_id") .primaryKey() .references(() => workspaces.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), reservedBytes: bigint("reserved_bytes", { mode: "number" }).notNull().default(0), readyBytes: bigint("ready_bytes", { mode: "number" }).notNull().default(0), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "workspace_video_generation_quotas_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), nonnegative: check( "workspace_video_generation_quotas_nonnegative_chk", sql`${table.reservedBytes} >= 0 and ${table.readyBytes} >= 0`, ), }), ); /** * Paid asynchronous provider operation. This aggregate owns recovery; the * originating session is nullable provenance and never owns its lifecycle. */ export const videoGenerationOperations = pgTable( "video_generation_operations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), privateFileOwnerSubjectId: text("private_file_owner_subject_id").default( sql`nullif(current_setting('opengeni.private_file_owner',true),'')`, ), sessionId: uuid("session_id").references(() => sessions.id, { onDelete: "set null", }), turnId: uuid("turn_id"), attemptId: uuid("attempt_id"), toolCallId: text("tool_call_id").notNull(), admissionKey: text("admission_key").notNull(), requestDigest: text("request_digest").notNull(), promptDigest: text("prompt_digest").notNull(), requestEncrypted: text("request_encrypted"), modelId: text("model_id").notNull(), sourceMode: text("source_mode").notNull(), capabilityRevision: text("capability_revision").notNull(), fundingSource: text("funding_source").notNull().default("workspace_gateway"), pricedCostMicros: bigint("priced_cost_micros", { mode: "number" }).notNull().default(0), creditState: text("credit_state").notNull().default("not_applicable"), connectionId: uuid("connection_id"), credentialVersion: integer("credential_version").notNull(), credentialEncrypted: text("credential_encrypted"), providerIdempotencyKey: text("provider_idempotency_key").notNull(), providerJobId: text("provider_job_id"), /** Exact provider start body, encrypted before the first network byte. */ providerRequestEncrypted: text("provider_request_encrypted"), /** Bearer URLs inside the frozen body are unusable after this instant. */ providerRequestExpiresAt: timestamp("provider_request_expires_at", { withTimezone: true, }), expectedArtifactId: uuid("expected_artifact_id").notNull(), expectedFileId: uuid("expected_file_id").notNull(), reservedBytes: bigint("reserved_bytes", { mode: "number" }).notNull(), quotaState: text("quota_state").notNull().default("reserved"), status: text("status").notNull().default("preparing"), admissionOutputState: text("admission_output_state").notNull().default("pending"), terminalUpdateState: text("terminal_update_state").notNull().default("ineligible"), terminalUpdateId: uuid("terminal_update_id"), reconcileRevision: bigint("reconcile_revision", { mode: "number" }).notNull().default(0), reconcileLeaseOwner: text("reconcile_lease_owner"), reconcileLeaseExpiresAt: timestamp("reconcile_lease_expires_at", { withTimezone: true, }), nextReconcileAt: timestamp("next_reconcile_at", { withTimezone: true }), providerRequestSentAt: timestamp("provider_request_sent_at", { withTimezone: true, }), providerStartedAt: timestamp("provider_started_at", { withTimezone: true }), recoveryDeadlineAt: timestamp("recovery_deadline_at", { withTimezone: true, }).notNull(), terminalAt: timestamp("terminal_at", { withTimezone: true }), privateDataEraseAfter: timestamp("private_data_erase_after", { withTimezone: true, }), boundedPublicReason: text("bounded_public_reason"), lastError: text("last_error"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ admission: uniqueIndex("video_generation_operations_admission_uq").on( table.workspaceId, table.admissionKey, ), expectedArtifact: uniqueIndex("video_generation_operations_expected_artifact_uq").on( table.workspaceId, table.expectedArtifactId, ), expectedFile: uniqueIndex("video_generation_operations_expected_file_uq").on( table.workspaceId, table.expectedFileId, ), due: index("video_generation_operations_due_idx").on( table.status, table.nextReconcileAt, table.id, ), workspaceCreated: index("video_generation_operations_workspace_created_idx").on( table.workspaceId, table.createdAt, table.id, ), workspaceAccount: foreignKey({ name: "video_generation_operations_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), hashesValid: check( "video_generation_operations_hashes_chk", sql`${table.admissionKey} ~ '^[0-9a-f]{64}$' and ${table.requestDigest} ~ '^[0-9a-f]{64}$' and ${table.promptDigest} ~ '^[0-9a-f]{64}$' and ${table.capabilityRevision} ~ '^[0-9a-f]{64}$'`, ), shapeValid: check( "video_generation_operations_shape_chk", sql`octet_length(${table.toolCallId}) between 1 and 512 and octet_length(${table.modelId}) between 1 and 256 and octet_length(${table.providerIdempotencyKey}) between 1 and 128 and ${table.sourceMode} in ('text','first_frame','first_and_last_frames','image_reference','video_reference') and ${table.reservedBytes} > 0 and ${table.reservedBytes} <= 536870912 and (${table.boundedPublicReason} is null or octet_length(${table.boundedPublicReason}) <= 4000) and (${table.lastError} is null or octet_length(${table.lastError}) <= 16384)`, ), stateValid: check( "video_generation_operations_state_chk", sql`${table.status} in ('preparing','prepared','accepted','submission_uncertain','provider_started','retaining','completed','provider_failed','cancelled_before_submit','outcome_unknown','retention_failed') and ${table.admissionOutputState} in ('pending','recorded') and ${table.terminalUpdateState} in ('ineligible','pending','leased','delivered','suppressed') and ${table.quotaState} in ('reserved','ready','released') and ((${table.terminalAt} is not null) = (${table.status} in ('completed','provider_failed','cancelled_before_submit','outcome_unknown','retention_failed'))) and (${table.status} <> 'submission_uncertain' or (${table.providerRequestEncrypted} is not null and ${table.providerRequestExpiresAt} is not null)) and (${table.providerRequestEncrypted} is null or ${table.status} = 'submission_uncertain') and (${table.status} not in ('provider_started','retaining','completed','retention_failed') or ${table.providerJobId} is not null) and (${table.providerJobId} is null or ${table.status} in ('provider_started','retaining','completed','provider_failed','retention_failed'))`, ), fundingStateValid: check( "video_generation_operations_funding_state_chk", sql`(${table.fundingSource} = 'workspace_gateway' and ${table.connectionId} is not null and ${table.pricedCostMicros} = 0 and ${table.creditState} = 'not_applicable') or (${table.fundingSource} = 'opengeni_credits' and ${table.connectionId} is null and ((${table.pricedCostMicros} = 0 and ${table.creditState} = 'not_applicable') or (${table.pricedCostMicros} > 0 and ((${table.status} in ('provider_failed','cancelled_before_submit','outcome_unknown','retention_failed') and ${table.creditState} = 'refunded') or (${table.status} not in ('provider_failed','cancelled_before_submit','outcome_unknown','retention_failed') and ${table.creditState} = 'debited')))) or (${table.fundingSource} = 'supergrok_subscription' and ${table.connectionId} is null and ${table.pricedCostMicros} = 0 and ${table.creditState} = 'not_applicable'))`, ), fundingValuesValid: check( "video_generation_operations_funding_values_chk", sql`${table.fundingSource} in ('opengeni_credits','workspace_gateway','supergrok_subscription') and ${table.pricedCostMicros} between 0 and 1000000000 and ${table.creditState} in ('not_applicable','debited','refunded')`, ), }), ); /** Immutable operation reference snapshots; provider-facing URLs never persist here. */ export const videoGenerationReferences = pgTable( "video_generation_references", { operationId: uuid("operation_id") .notNull() .references(() => videoGenerationOperations.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), ordinal: integer("ordinal").notNull(), role: text("role").notNull(), contentType: text("content_type").notNull(), sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(), sha256: text("sha256").notNull(), stagingObjectKey: text("staging_object_key"), grantExpiresAt: timestamp("grant_expires_at", { withTimezone: true }), cleanupAfter: timestamp("cleanup_after", { withTimezone: true }), cleanedAt: timestamp("cleaned_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ name: "video_generation_references_pk", columns: [table.operationId, table.ordinal], }), workspaceAccount: foreignKey({ name: "video_generation_references_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), hashValid: check( "video_generation_references_hash_chk", sql`${table.sha256} ~ '^[0-9a-f]{64}$'`, ), boundsValid: check( "video_generation_references_bounds_chk", sql`${table.ordinal} between 0 and 1 and ${table.role} in ('first_frame','last_frame','image_reference','video_reference') and octet_length(${table.contentType}) between 3 and 128 and ${table.sizeBytes} > 0 and ${table.sizeBytes} <= 209715200`, ), }), ); /** Permanent generated-video product; canonical bytes remain a separate File. */ export const generatedVideoArtifacts = pgTable( "generated_video_artifacts", { id: uuid("id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), primaryFileId: uuid("primary_file_id") .notNull() .references(() => files.id, { onDelete: "restrict" }), operationId: uuid("operation_id") .notNull() .references(() => videoGenerationOperations.id, { onDelete: "restrict" }), sessionId: uuid("session_id").references(() => sessions.id, { onDelete: "set null", }), turnId: uuid("turn_id"), attemptId: uuid("attempt_id"), modelId: text("model_id").notNull(), sourceMode: text("source_mode").notNull(), promptDigest: text("prompt_digest").notNull(), contentType: text("content_type").notNull(), sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(), sha256: text("sha256").notNull(), durationMillis: integer("duration_millis").notNull(), width: integer("width").notNull(), height: integer("height").notNull(), fpsMilli: integer("fps_milli").notNull(), videoCodec: text("video_codec").notNull(), audioCodec: text("audio_codec"), hasAudio: boolean("has_audio").notNull(), sandboxFilename: text("sandbox_filename").notNull(), deletedAt: timestamp("deleted_at", { withTimezone: true }), readyAt: timestamp("ready_at", { withTimezone: true }).notNull().defaultNow(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceFile: uniqueIndex("generated_video_artifacts_workspace_file_uq").on( table.workspaceId, table.primaryFileId, ), workspaceOperation: uniqueIndex("generated_video_artifacts_workspace_operation_uq").on( table.workspaceId, table.operationId, ), sessionCreated: index("generated_video_artifacts_session_created_idx").on( table.workspaceId, table.sessionId, table.createdAt, table.id, ), workspaceAccount: foreignKey({ name: "generated_video_artifacts_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceFileScope: foreignKey({ name: "generated_video_artifacts_workspace_file_scope_fk", columns: [table.accountId, table.workspaceId, table.primaryFileId], foreignColumns: [files.accountId, files.workspaceId, files.id], }).onDelete("restrict"), valuesValid: check( "generated_video_artifacts_values_chk", sql`${table.contentType} = 'video/mp4' and ${table.sizeBytes} > 0 and ${table.sizeBytes} <= 536870912 and ${table.sha256} ~ '^[0-9a-f]{64}$' and ${table.promptDigest} ~ '^[0-9a-f]{64}$' and ${table.durationMillis} between 1 and 120000 and ${table.width} between 1 and 8192 and ${table.height} between 1 and 8192 and ${table.fpsMilli} between 1 and 120000 and ${table.videoCodec} = 'h264' and ((${table.hasAudio} and ${table.audioCodec} = 'aac') or (not ${table.hasAudio} and ${table.audioCodec} is null)) and ${table.sandboxFilename} = 'generated-video-' || ${table.id}::text || '.mp4'`, ), }), ); /** Exact pending/ready byte accounting for retained computer screenshots. */ export const workspaceScreenshotQuotas = pgTable( "workspace_screenshot_quotas", { workspaceId: uuid("workspace_id") .primaryKey() .references(() => workspaces.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), reservedBytes: bigint("reserved_bytes", { mode: "number" }).notNull().default(0), readyBytes: bigint("ready_bytes", { mode: "number" }).notNull().default(0), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], name: "workspace_screenshot_quotas_workspace_account_fk", }).onDelete("cascade"), nonnegative: check( "workspace_screenshot_quotas_nonnegative_chk", sql`${table.reservedBytes} >= 0 and ${table.readyBytes} >= 0`, ), }), ); /** Provider-neutral screenshot lifecycle; canonical bytes stay in `files` storage. */ export const retainedScreenshotArtifacts = pgTable( "retained_screenshot_artifacts", { // The composite file FK is RESTRICT in migration 0176: only the retained // screenshot lifecycle may remove its backing file after provider cleanup. artifactId: uuid("artifact_id").primaryKey(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), privateFileOwnerSubjectId: text("private_file_owner_subject_id").default( sql`nullif(current_setting('opengeni.private_file_owner',true),'')`, ), sessionId: uuid("session_id").references(() => sessions.id, { onDelete: "set null", }), // Turn/attempt foreign keys are installed by migrations 0140/0176. // Those tables are declared later in this monolithic schema module, so // referencing them here would create an eager initialization cycle. turnId: uuid("turn_id"), attemptId: uuid("attempt_id"), settlementKey: text("settlement_key").notNull(), toolCallId: text("tool_call_id").notNull(), toolOutputId: text("tool_output_id").notNull(), status: text("status") .$type< | "pending" | "reconciling" | "ready" | "cleanup_queued" | "cleanup_pending" | "failed" | "expired" | "deleted" >() .notNull() .default("pending"), quotaState: text("quota_state") .$type<"reserved" | "ready" | "released">() .notNull() .default("reserved"), mediaType: text("media_type").notNull(), sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(), sha256: text("sha256").notNull(), width: integer("width").notNull(), height: integer("height").notNull(), retentionExpiresAt: timestamp("retention_expires_at", { withTimezone: true, }).notNull(), readyAt: timestamp("ready_at", { withTimezone: true }), cleanupReason: text("cleanup_reason"), lastError: text("last_error"), maintenanceClaimId: uuid("maintenance_claim_id"), maintenanceClaimedAt: timestamp("maintenance_claimed_at", { withTimezone: true, }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ settlementKey: uniqueIndex("retained_screenshot_artifacts_settlement_key_uq").on( table.settlementKey, ), sessionCreated: index("retained_screenshot_artifacts_session_created_idx").on( table.workspaceId, table.sessionId, table.createdAt, table.artifactId, ), readyExpiry: index("retained_screenshot_artifacts_ready_expiry_idx") .on(table.retentionExpiresAt, table.artifactId) .where(sql`${table.status} = 'ready'`), pendingReconcile: index("retained_screenshot_artifacts_pending_reconcile_idx") .on(table.updatedAt, table.artifactId) .where( sql`${table.status} in ('pending', 'reconciling', 'cleanup_queued', 'cleanup_pending')`, ), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], name: "retained_screenshot_artifacts_workspace_account_fk", }).onDelete("cascade"), workspaceFile: foreignKey({ columns: [table.workspaceId, table.artifactId], foreignColumns: [files.workspaceId, files.id], name: "retained_screenshot_artifacts_workspace_file_fk", }).onDelete("restrict"), statusValid: check( "retained_screenshot_artifacts_status_chk", sql`${table.status} in ('pending', 'reconciling', 'ready', 'cleanup_queued', 'cleanup_pending', 'failed', 'expired', 'deleted')`, ), quotaStateValid: check( "retained_screenshot_artifacts_quota_state_chk", sql`${table.quotaState} in ('reserved', 'ready', 'released')`, ), statusQuotaValid: check( "retained_screenshot_artifacts_status_quota_chk", sql`(${table.status} in ('pending', 'reconciling') and ${table.quotaState} = 'reserved') or (${table.status} = 'ready' and ${table.quotaState} = 'ready') or (${table.status} in ('cleanup_queued', 'cleanup_pending') and ${table.quotaState} in ('reserved', 'ready')) or (${table.status} in ('failed', 'expired', 'deleted') and ${table.quotaState} = 'released')`, ), claimShapeValid: check( "retained_screenshot_artifacts_claim_shape_chk", sql`(${table.status} in ('reconciling', 'cleanup_pending') and ${table.maintenanceClaimId} is not null and ${table.maintenanceClaimedAt} is not null) or (${table.status} not in ('reconciling', 'cleanup_pending') and ${table.maintenanceClaimId} is null and ${table.maintenanceClaimedAt} is null)`, ), dimensionsValid: check( "retained_screenshot_artifacts_dimensions_chk", sql`${table.width} between 1 and 16384 and ${table.height} between 1 and 16384 and (${table.width}::bigint * ${table.height}::bigint) <= 67108864`, ), mediaTypeValid: check( "retained_screenshot_artifacts_media_type_v2_chk", sql`${table.mediaType} in ('image/png', 'image/jpeg', 'image/webp')`, ), }), ); export const documentBases = pgTable( "document_bases", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), name: text("name").notNull(), description: text("description"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceCreated: index("document_bases_workspace_created_idx").on( table.workspaceId, table.createdAt, ), defaultName: uniqueIndex("document_bases_workspace_default_name_uq") .on(table.workspaceId) .where(sql`lower(btrim(${table.name})) = 'default'`), }), ); export const documents = pgTable( "documents", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), baseId: uuid("base_id") .notNull() .references(() => documentBases.id, { onDelete: "cascade" }), fileId: uuid("file_id") .notNull() .references(() => files.id, { onDelete: "restrict" }), status: text("status").notNull().default("queued"), title: text("title").notNull(), parser: text("parser").notNull().default("liteparse"), chunkCount: integer("chunk_count").notNull().default(0), error: text("error"), sourceKind: text("source_kind").notNull().default("manual_upload"), sourceUri: text("source_uri"), sourceExternalId: text("source_external_id"), sourceTitle: text("source_title"), sourceAuthor: text("source_author"), sourceCreatedAt: timestamp("source_created_at", { withTimezone: true }), sourceUpdatedAt: timestamp("source_updated_at", { withTimezone: true }), sourceVersion: text("source_version"), // Connector imports keep immutable source-object/version identity separate // from the content-addressed file row so equal bytes never collapse two // independently authorized provider objects into one Document. knowledgeSourceIdentity: text("knowledge_source_identity"), aclTags: jsonb("acl_tags").$type().notNull().default([]), // Durable authorization tuple. The workspace_id above remains ingestion // provenance; organization authority deliberately has no workspace owner. authorityKind: text("authority_kind").notNull().default("workspace"), authorityWorkspaceId: uuid("authority_workspace_id"), authoritySubjectId: text("authority_subject_id"), // Activated personal documents follow their organization membership across // workspaces. Legacy personal rows retain a null authority id and their // original workspace anchor; originWorkspaceId is provenance only. authorityId: uuid("authority_id"), ownerOrganizationMembershipId: uuid("owner_organization_membership_id"), originWorkspaceId: uuid("origin_workspace_id").notNull(), // Per-document access controls. visibility 'private' restricts human reads to // created_by (a grant subject id, not a uuid); agent_access=false hides the // document from agent retrieval surfaces (docs MCP) while humans keep REST. visibility: text("visibility").notNull().default("workspace"), createdBy: text("created_by"), // Trusted ingestion causality, frozen before async source preparation. // createdBy/authority ownership is not verified initiating-human evidence. billingAttribution: jsonb("billing_attribution") .$type() .notNull() .default({ kind: "unknown" }), agentAccess: boolean("agent_access").notNull().default(true), // Auto-curation output (knowledge drops). summary: text("summary"), topics: jsonb("topics").$type().notNull().default([]), curationStatus: text("curation_status").notNull().default("none"), curation: jsonb("curation").$type>(), // Assigned only by the database whenever indexing transitions to ready. // Unlike updated_at, metadata refreshes and base moves cannot advance this // checkpoint order. indexSequence: bigint("index_sequence", { mode: "bigint" }), indexedAt: timestamp("indexed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ baseFile: uniqueIndex("documents_workspace_base_file_idx") .on(table.workspaceId, table.baseId, table.fileId) .where(sql`${table.knowledgeSourceIdentity} is null`), knowledgeSourceIdentity: uniqueIndex("documents_workspace_knowledge_source_identity_uq") .on(table.workspaceId, table.knowledgeSourceIdentity) .where(sql`${table.knowledgeSourceIdentity} is not null`), baseStatus: index("documents_workspace_base_status_idx").on( table.workspaceId, table.baseId, table.status, ), sourceKind: index("documents_workspace_source_kind_idx").on( table.workspaceId, table.sourceKind, ), sourceExternalId: index("documents_workspace_source_external_id_idx").on( table.workspaceId, table.sourceExternalId, ), curationStatus: index("documents_workspace_curation_status_idx").on( table.workspaceId, table.curationStatus, ), accountIndexSequence: index("documents_account_index_sequence_idx") .on(table.accountId, table.indexSequence) .where(sql`${table.status} = 'ready' and ${table.indexSequence} is not null`), authority: index("documents_authority_idx").on( table.accountId, table.authorityKind, table.authorityWorkspaceId, table.authoritySubjectId, table.status, ), authorityWorkspaceAccount: foreignKey({ name: "documents_authority_workspace_fk", columns: [table.authorityWorkspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("restrict"), userAuthority: foreignKey({ name: "documents_user_authority_fk", columns: [table.authorityId, table.accountId, table.ownerOrganizationMembershipId], foreignColumns: [ organizationUserResourceAuthorities.id, organizationUserResourceAuthorities.accountId, organizationUserResourceAuthorities.organizationMembershipId, ], }).onDelete("restrict"), authorityState: check( "documents_authority_chk", sql`(${table.authorityKind} = 'organization' and ${table.authorityWorkspaceId} is null and ${table.authoritySubjectId} is null and ${table.authorityId} is null and ${table.ownerOrganizationMembershipId} is null) or (${table.authorityKind} = 'workspace' and ${table.authorityWorkspaceId} = ${table.workspaceId} and ${table.authoritySubjectId} is null and ${table.authorityId} is null and ${table.ownerOrganizationMembershipId} is null) or (${table.authorityKind} = 'personal' and nullif(btrim(${table.authoritySubjectId}), '') is not null and octet_length(convert_to(${table.authoritySubjectId}, 'UTF8')) <= 1024 and ${table.authoritySubjectId} = ${table.createdBy} and ((${table.authorityWorkspaceId} = ${table.workspaceId} and ${table.authorityId} is null and ${table.ownerOrganizationMembershipId} is null) or (${table.authorityWorkspaceId} is null and ${table.authorityId} is not null and ${table.ownerOrganizationMembershipId} is not null)))`, ), authorityVisibility: check( "documents_authority_visibility_chk", sql`(${table.authorityKind} = 'personal') = (${table.visibility} = 'private')`, ), originWorkspace: check( "documents_origin_workspace_chk", sql`${table.originWorkspaceId} = ${table.workspaceId}`, ), visibilityState: check( "documents_visibility_chk", sql`${table.visibility} in ('workspace', 'private')`, ), curationState: check( "documents_curation_status_chk", sql`${table.curationStatus} in ('none', 'pending', 'suggested', 'auto_filed', 'failed')`, ), privateCreator: check( "documents_private_creator_chk", sql`${table.visibility} <> 'private' or nullif(btrim(${table.createdBy}), '') is not null`, ), knowledgeSourceIdentityBounds: check( "documents_knowledge_source_identity_chk", sql`${table.knowledgeSourceIdentity} is null or length(btrim(${table.knowledgeSourceIdentity})) between 1 and 512`, ), topicsArray: check("documents_topics_array_chk", sql`jsonb_typeof(${table.topics}) = 'array'`), curationObject: check( "documents_curation_object_chk", sql`${table.curation} is null or jsonb_typeof(${table.curation}) = 'object'`, ), indexSequenceState: check( "documents_index_sequence_chk", sql`(${table.indexSequence} is null or ${table.indexSequence} > 0) and (${table.status} <> 'ready' or (${table.indexSequence} is not null and ${table.indexedAt} is not null))`, ), }), ); export const documentChunks = pgTable( "document_chunks", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), documentId: uuid("document_id") .notNull() .references(() => documents.id, { onDelete: "cascade" }), baseId: uuid("base_id") .notNull() .references(() => documentBases.id, { onDelete: "cascade" }), fileId: uuid("file_id") .notNull() .references(() => files.id, { onDelete: "restrict" }), chunkIndex: integer("chunk_index").notNull(), text: text("text").notNull(), metadata: jsonb("metadata").$type>().notNull().default({}), authorityKind: text("authority_kind").notNull().default("workspace"), authorityWorkspaceId: uuid("authority_workspace_id"), authoritySubjectId: text("authority_subject_id"), authorityId: uuid("authority_id"), ownerOrganizationMembershipId: uuid("owner_organization_membership_id"), embedding: vector("embedding").notNull(), embeddingModel: text("embedding_model").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ documentIndex: uniqueIndex("document_chunks_workspace_document_index_idx").on( table.workspaceId, table.documentId, table.chunkIndex, ), base: index("document_chunks_workspace_base_idx").on(table.workspaceId, table.baseId), authority: index("document_chunks_authority_idx").on( table.accountId, table.authorityKind, table.authorityWorkspaceId, table.authoritySubjectId, ), authorityWorkspaceAccount: foreignKey({ name: "document_chunks_authority_workspace_fk", columns: [table.authorityWorkspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("restrict"), userAuthority: foreignKey({ name: "document_chunks_user_authority_fk", columns: [table.authorityId, table.accountId, table.ownerOrganizationMembershipId], foreignColumns: [ organizationUserResourceAuthorities.id, organizationUserResourceAuthorities.accountId, organizationUserResourceAuthorities.organizationMembershipId, ], }).onDelete("restrict"), authorityState: check( "document_chunks_authority_chk", sql`(${table.authorityKind} = 'organization' and ${table.authorityWorkspaceId} is null and ${table.authoritySubjectId} is null and ${table.authorityId} is null and ${table.ownerOrganizationMembershipId} is null) or (${table.authorityKind} = 'workspace' and ${table.authorityWorkspaceId} = ${table.workspaceId} and ${table.authoritySubjectId} is null and ${table.authorityId} is null and ${table.ownerOrganizationMembershipId} is null) or (${table.authorityKind} = 'personal' and nullif(btrim(${table.authoritySubjectId}), '') is not null and octet_length(convert_to(${table.authoritySubjectId}, 'UTF8')) <= 1024 and ((${table.authorityWorkspaceId} = ${table.workspaceId} and ${table.authorityId} is null and ${table.ownerOrganizationMembershipId} is null) or (${table.authorityWorkspaceId} is null and ${table.authorityId} is not null and ${table.ownerOrganizationMembershipId} is not null)))`, ), }), ); export const knowledgeMemories = pgTable( "knowledge_memories", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), status: text("status").notNull().default("proposed"), kind: text("kind").notNull().default("semantic"), scope: text("scope").notNull().default("workspace"), text: losslessText("text").notNull(), textCodecVersion: losslessCodecVersion("text_codec_version"), sourceRefs: jsonb("source_refs").$type().notNull().default([]), confidence: integer("confidence").notNull().default(50), metadata: jsonb("metadata").$type>().notNull().default({}), createdBySessionId: uuid("created_by_session_id").references(() => sessions.id, { onDelete: "set null", }), reviewedBy: text("reviewed_by"), reviewedAt: timestamp("reviewed_at", { withTimezone: true }), // Workspace Memory V1 (migration 0045). Embedding is nullable: fail-soft writes // (embedder unavailable) persist keyword-searchable rows without a vector. embedding: vector("embedding"), embeddingModel: text("embedding_model"), pinned: boolean("pinned").notNull().default(false), usageCount: integer("usage_count").notNull().default(0), lastUsedAt: timestamp("last_used_at", { withTimezone: true }), // Self-referential supersession chain. FKs live in migration 0045 (ON DELETE SET // NULL); declared here as plain columns like the migration-only composite FK. supersedesId: uuid("supersedes_id"), supersededById: uuid("superseded_by_id"), validFrom: timestamp("valid_from", { withTimezone: true }).notNull().defaultNow(), validUntil: timestamp("valid_until", { withTimezone: true }), // Hierarchical memory foundation (migration 0152). `scope` remains the V1 // compatibility projection; typed selectors are the fail-closed authority. scopeType: text("scope_type").notNull().default("workspace"), scopeSubjectId: text("scope_subject_id"), scopeRoleKey: text("scope_role_key"), scopeSessionId: uuid("scope_session_id"), namespace: text("namespace_key").notNull().default("general"), labels: text("labels").array().notNull().default([]), memoryVersion: integer("memory_version").notNull().default(1), createdByKind: text("created_by_kind").notNull().default("service"), createdBySubjectId: text("created_by_subject_id").notNull().default("unattributed-legacy"), createdByContext: jsonb("created_by_context") .$type>() .notNull() .default({ backfill: true }), // sha256(normalizeMemoryText(text)) — exact-dedup key; see memory-domain. textHash: text("text_hash"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceStatus: index("knowledge_memories_workspace_status_idx").on( table.workspaceId, table.status, table.updatedAt, ), workspaceKind: index("knowledge_memories_workspace_kind_idx").on(table.workspaceId, table.kind), workspaceScope: index("knowledge_memories_workspace_scope_idx").on( table.workspaceId, table.scope, ), workspaceTypedScope: index("knowledge_memories_workspace_typed_scope_idx").on( table.workspaceId, table.scopeType, table.scopeSubjectId, table.scopeRoleKey, table.scopeSessionId, ), workspaceNamespace: index("knowledge_memories_workspace_namespace_idx").on( table.workspaceId, table.namespace, ), labelsGin: index("knowledge_memories_labels_idx").using("gin", table.labels), createdBySession: index("knowledge_memories_workspace_created_by_session_idx").on( table.workspaceId, table.createdBySessionId, ), // Working-set selection (partial index mirrors migration 0045). workspaceVisible: index("knowledge_memories_workspace_visible_idx") .on(table.workspaceId, table.pinned, table.updatedAt) .where(sql`${table.status} in ('active', 'approved')`), workspaceTextHash: index("knowledge_memories_workspace_text_hash_idx").on( table.workspaceId, table.textHash, ), // Drizzle 0.45 cannot encode PostgreSQL `NULLS NOT DISTINCT`; migration // 0152 owns that option so nullable scope selectors remain one identity. scopeVisibleTextHashUnique: uniqueIndex("knowledge_memories_scope_visible_text_hash_uq") .on( table.workspaceId, table.scopeType, table.scopeSubjectId, table.scopeRoleKey, table.scopeSessionId, table.namespace, table.textHash, ) .where(sql`${table.status} in ('active', 'approved') and ${table.textHash} is not null`), }), ); export const sessionTurns = pgTable( "session_turns", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), triggerEventId: uuid("trigger_event_id").notNull(), temporalWorkflowId: text("temporal_workflow_id").notNull(), status: text("status").notNull(), source: text("source").notNull().default("user"), // Immutable, content-free product surface the request entered through // (`SessionTurnSurface`). Analytics only, never an authorization input. // Null is reserved for rolling/legacy writers (migration 0533). surface: text("surface"), // Immutable funding origin (`BillingOrigin`: app or api), frozen when the // turn is accepted and inherited by agent and machine work. Unlike // `surface` it decides which credit pays; it never grants access. Null is // legacy and billed as app (migration 1128). billingOrigin: text("billing_origin"), // Immutable user-facing admission intent. Physical execution still uses // status=queued until a worker claims the row; this field keeps that // implementation queue distinct from prompts genuinely waiting behind // other work. Null is reserved for rolling/legacy writers and non-human // turns, and is projected conservatively as visible queue work. promptRouting: text("prompt_routing"), position: bigint("position", { mode: "number" }).notNull(), prompt: losslessText("prompt").notNull(), promptCodecVersion: losslessCodecVersion("prompt_codec_version"), annotations: jsonb("annotations").$type().notNull().default([]), // Application context for this exact user message. It is copied into the // canonical user-role history item at claim and omitted from public queue // projections; full event/audit data retains it. modelContext: text("model_context"), resources: jsonb("resources").$type().notNull().default([]), tools: jsonb("tools").$type().notNull().default([]), // false = inherit the durable session policy; true = this turn explicitly // replaces it with `tools` after the core subset fence. toolsProvided: boolean("tools_provided").notNull().default(false), model: text("model").notNull(), reasoningEffort: text("reasoning_effort").notNull(), // Peer of model + reasoning_effort for Fast/priority inheritance. latencyMode: text("latency_mode").notNull().default("standard"), sandboxBackend: text("sandbox_backend").notNull(), // Per-turn OS override. NULL = inherit the session's sandbox_os. CHECK- // constrained to the SandboxOs enum (or NULL) in migration 0018. sandboxOs: text("sandbox_os"), metadata: jsonb("metadata").$type>().notNull().default({}), version: integer("version").notNull().default(1), executionGeneration: integer("execution_generation").notNull().default(0), // Composite FK to session_turn_attempts is installed by migration 0063. // It lives in SQL because attempts carry the reciprocal turn FK and because // the claim transaction preallocates this ID before inserting the attempt; // the SQL constraint is therefore DEFERRABLE INITIALLY DEFERRED. activeAttemptId: uuid("active_attempt_id"), lineage: jsonb("lineage").$type>().notNull().default({}), // Required immutable authority captured when the turn is accepted. These // columns are deliberately outside mutable metadata/lineage. initiatorKind: text("initiator_kind").notNull().default("service"), initiatorSubjectId: text("initiator_subject_id").notNull().default("unattributed-legacy"), initiatorContext: jsonb("initiator_context") .$type>() .notNull() .default({ backfill: true }), // Bounded, immutable causal-human selector for named attempt-bound // capabilities. Human turns bind their own subject; trusted continuations // and compactions may inherit the causal turn's value while retaining a // service initiator. It never authorizes by itself. Null means pure service // work has no human-bound authority. initiatingHumanSubjectId: text("initiating_human_subject_id"), // Exact receiving-session authority copied by an informational inbox turn. // Immutable and checked against the session pointer by the database. executionContextTurnId: uuid("execution_context_turn_id"), // Exact goal authority frozen when the logical turn is accepted. The // migration trigger fills this for old and rolling writers; claim only // reconstructs legacy nulls from events as-of created_at. goalSnapshot: jsonb("goal_snapshot").$type(), // Immutable exact personal MCP authority for this logical turn. Recovery, // approval, retries, and Codemode reuse this row; no runtime may infer // broader authority from the session creator or mutable session state. personalConnectionDelegations: jsonb("personal_connection_delegations") .$type() .notNull() .default([]), mcpAccountBindings: jsonb("mcp_account_bindings").$type(), // Immutable account intent of this logical turn: whose personal accounts // it may use and which accounts a person explicitly picked. Autonomous // turns that continue it copy this intent and resolve it again for the // same person instead of copying `mcp_account_bindings`. Null marks turns // accepted before account intent existed; their continuations copy the // exact bindings as before. connectionAccountIntent: jsonb( "connection_account_intent", ).$type(), // Credential-free public summary of a turn-bound personal Variable // Set/Rig attachment. Exact resource and grant identity lives only in the // immutable accepted-work snapshot tables. personalResourceAttachmentSummary: jsonb( "personal_resource_attachment_summary", ).$type(), // 0 = legacy attempt-selected authority; 1 = immutable logical-turn // snapshots. Drained migration 0306 makes every new atomic attachment v1. personalResourceProtocolVersion: integer("personal_resource_protocol_version") .notNull() .default(0), // Immutable scheduled occurrence that accepted this logical turn. Null for // ordinary human, goal, child, and unrelated internal work. scheduledTaskRunId: uuid("scheduled_task_run_id"), xaiProviderAccountAuthoritySnapshot: jsonb("xai_provider_account_authority_snapshot") .$type() .notNull() .default(WORKSPACE_XAI_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1), claudeProviderAccountAuthoritySnapshot: jsonb("claude_provider_account_authority_snapshot") .$type() .notNull() .default(WORKSPACE_CLAUDE_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1), // Additive M3 v2 slot. v1 remains the authority source until the drained // Codex cutover migration backfills and activates this value. subscriptionAuthority: jsonb( "subscription_authority", ).$type(), cancelledBy: text("cancelled_by"), cancelReason: text("cancel_reason"), // Leftover unused counter from the removed per-turn Codemode call cap // (migrations 0043/0205). New writers do not increment it; do not enforce. codemodeCallCount: integer("codemode_call_count").notNull().default(0), startedAt: timestamp("started_at", { withTimezone: true }), finishedAt: timestamp("finished_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceIdentity: uniqueIndex("session_turns_workspace_id_idx").on( table.workspaceId, table.id, ), queue: index("session_turns_workspace_queue_idx").on( table.workspaceId, table.sessionId, table.status, table.position, ), // Next turn position, max(position) + 1, as one backward probe instead of // a row-security check of every earlier turn (migration 1355). sessionPosition: index("session_turns_session_position_idx").on( table.workspaceId, table.sessionId, table.position, ), oneCurrentInference: uniqueIndex("session_turns_one_current_inference_uq") .on(table.workspaceId, table.sessionId) .where(sql`${table.status} in ('running','requires_action','recovering','waiting_capacity')`), // Agent-monitoring "was this prompt's turn ever claimed" probe // (`excludeUnclaimedHumanPromptEventFilter`), migration 0322. unclaimedPromptTrigger: index("session_turns_unclaimed_prompt_trigger_idx") .on(table.workspaceId, table.sessionId, table.triggerEventId) .where(sql`${table.startedAt} is null`), // Newest-finished-first walk for the session input-wait deciding turn, so // the lateral LIMIT 1 stops at the first match instead of sorting the whole // session history (migration 0786). finishedOrder: index("session_turns_finished_order_idx") .on( table.workspaceId, table.sessionId, table.finishedAt.desc(), table.position.desc(), table.createdAt.desc(), ) .where(sql`${table.finishedAt} is not null`), // Finished turns of a workspace by finish time, for the turn timing // profile sweep's recent window (migration 1352). workspaceFinished: index("session_turns_workspace_finished_idx") .on(table.workspaceId, table.finishedAt) .where(sql`${table.finishedAt} is not null`), // "Mine" session-list filter (migration 0799): prompts a person sent // directly, by sender, so a workstream probe is one index lookup per tree // session. Agent-relayed and service turns are excluded by the predicate. humanPromptSubject: index("session_turns_human_prompt_subject_idx") .on(table.workspaceId, table.initiatorSubjectId, table.sessionId) .where( sql`${table.initiatorKind} = 'subject' and ${table.source} in ('user', 'api') and ${table.surface} is distinct from 'agent'`, ), latencyModeValid: check( "session_turns_latency_mode_check", sql`${table.latencyMode} in ('standard', 'priority', 'fast', 'ultrafast')`, ), modelContextValid: check( "session_turns_model_context_check", sql`${table.modelContext} is null or opengeni_private.model_context_value_valid(${table.modelContext})`, ), surfaceValid: check( "session_turns_surface_check", sql`${table.surface} is null or ${table.surface} in ( 'web', 'slack', 'api_key', 'embedded', 'scheduled', 'agent', 'voice', 'site', 'automation', 'mcp', 'system' )`, ), }), ); /** Immutable logical-turn receipt for atomic personal-resource issuance. */ export const turnPersonalResourceAttachmentReceipts = pgTable( "turn_personal_resource_attachment_receipts", { turnId: uuid("turn_id") .primaryKey() .references(() => sessionTurns.id, { onDelete: "cascade" }), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), initiatingHumanSubjectId: text("initiating_human_subject_id").notNull(), ownerOrganizationMembershipId: uuid("owner_organization_membership_id").notNull(), membershipAuthorizationRevision: bigint("membership_authorization_revision", { mode: "number", }).notNull(), sessionVisibility: text("session_visibility").notNull(), sessionAuthorityEpoch: integer("session_authority_epoch").notNull(), grantMode: text("grant_mode").notNull(), sharedOutputWarningVersion: integer("shared_output_warning_version").notNull(), sharedOutputAcknowledged: boolean("shared_output_acknowledged").notNull(), requestDigest: bytea("request_digest").notNull(), resourceCount: integer("resource_count").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceTurn: foreignKey({ name: "turn_personal_resource_attachment_receipts_workspace_turn_fk", columns: [table.workspaceId, table.turnId], foreignColumns: [sessionTurns.workspaceId, sessionTurns.id], }).onDelete("cascade"), identity: check( "turn_personal_resource_attachment_receipts_identity_chk", sql`${table.sessionAuthorityEpoch} > 0 and octet_length(${table.initiatingHumanSubjectId}) between 1 and 512 and ${table.membershipAuthorizationRevision} > 0 and ${table.resourceCount} between 1 and 52 and ${table.grantMode} in ('once', 'session', 'always') and ${table.sessionVisibility} in ('user_private', 'workspace_shared') and ${table.sharedOutputWarningVersion} = 1 and (${table.sessionVisibility} <> 'workspace_shared' or ${table.sharedOutputAcknowledged})`, ), }), ); /** Exact resource/grant authority frozen on one accepted logical turn. */ export const turnPersonalResourceSnapshots = pgTable( "turn_personal_resource_snapshots", { turnId: uuid("turn_id").notNull(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), resourceKind: text("resource_kind").notNull(), resourceId: uuid("resource_id").notNull(), resourceVersionId: uuid("resource_version_id"), selectionSources: text("selection_sources").array().notNull(), action: text("action").notNull(), originWorkspaceId: uuid("origin_workspace_id").notNull(), ownerOrganizationMembershipId: uuid("owner_organization_membership_id").notNull(), membershipAuthorizationRevision: bigint("membership_authorization_revision", { mode: "number", }).notNull(), authorityId: uuid("authority_id").notNull(), authorityGeneration: bigint("authority_generation", { mode: "number", }).notNull(), grantId: uuid("grant_id").notNull(), grantGeneration: bigint("grant_generation", { mode: "number" }).notNull(), grantMode: text("grant_mode").notNull(), grantContext: text("grant_context").notNull(), grantSessionId: uuid("grant_session_id"), grantAuthorityEpoch: integer("grant_authority_epoch"), canonicalDelegation: jsonb("canonical_delegation").$type().notNull(), snapshotDigest: bytea("snapshot_digest").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ columns: [table.turnId, table.resourceKind, table.resourceId], }), receipt: foreignKey({ name: "turn_personal_resource_snapshots_receipt_fk", columns: [table.turnId], foreignColumns: [turnPersonalResourceAttachmentReceipts.turnId], }).onDelete("cascade"), authority: index("turn_personal_resource_snapshots_authority_idx").on(table.authorityId), grant: index("turn_personal_resource_snapshots_grant_idx").on(table.grantId), kind: check( "turn_personal_resource_snapshots_kind_chk", sql`(${table.resourceKind} = 'variable_set' and ${table.action} = 'variable_set.use' and ${table.resourceVersionId} is null) or (${table.resourceKind} = 'rig' and ${table.action} = 'rig.use' and ${table.resourceVersionId} is not null) or (${table.resourceKind} = 'connected_machine' and ${table.action} = 'connected_machine.use' and ${table.resourceVersionId} is null)`, ), generations: check( "turn_personal_resource_snapshots_generation_chk", sql`${table.membershipAuthorizationRevision} > 0 and ${table.authorityGeneration} > 0 and ${table.grantGeneration} > 0 and cardinality(${table.selectionSources}) between 1 and 50`, ), grantShape: check( "turn_personal_resource_snapshots_grant_chk", sql`${table.grantMode} in ('once', 'session', 'always') and ${table.grantContext} in ('user_private', 'workspace_shared') and ((${table.grantMode} = 'always' and ${table.grantSessionId} is null and ${table.grantAuthorityEpoch} is null) or (${table.grantMode} in ('once', 'session') and ${table.grantSessionId} = ${table.sessionId} and ${table.grantAuthorityEpoch} > 0))`, ), }), ); /** One once grant may belong to one accepted logical turn only. */ export const turnPersonalResourceOnceReceipts = pgTable( "turn_personal_resource_once_receipts", { grantId: uuid("grant_id").primaryKey(), turnId: uuid("turn_id").notNull(), accountId: uuid("account_id").notNull(), authorityId: uuid("authority_id").notNull(), authorityGeneration: bigint("authority_generation", { mode: "number", }).notNull(), grantGeneration: bigint("grant_generation", { mode: "number" }).notNull(), consumedAt: timestamp("consumed_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ receipt: foreignKey({ name: "turn_personal_resource_once_receipts_turn_fk", columns: [table.turnId], foreignColumns: [turnPersonalResourceAttachmentReceipts.turnId], }).onDelete("cascade"), generations: check( "turn_personal_resource_once_receipts_generation_chk", sql`${table.authorityGeneration} > 0 and ${table.grantGeneration} > 0`, ), }), ); // One bounded audit/idempotency projection of an ended mode's transcript-tail // wrapper, bound to the exact ordinary Steer turn that durably carries it. export const sessionRealtimeContextProjections = pgTable( "session_realtime_context_projections", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), context: text("context"), sourceModeCount: integer("source_mode_count").notNull(), sourceEntryCount: integer("source_entry_count").notNull(), includedEntryCount: integer("included_entry_count").notNull(), omittedEntryCount: integer("omitted_entry_count").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "session_realtime_context_projections_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "session_realtime_context_projections_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), workspaceTurn: foreignKey({ name: "session_realtime_context_projections_workspace_turn_fk", columns: [table.workspaceId, table.turnId], foreignColumns: [sessionTurns.workspaceId, sessionTurns.id], }).onDelete("cascade"), turn: uniqueIndex("session_realtime_context_projections_turn_uq").on( table.workspaceId, table.sessionId, table.turnId, ), contextValid: check( "session_realtime_context_projections_context_check", sql`${table.context} is null or octet_length(${table.context}) between 1 and 65536`, ), countsValid: check( "session_realtime_context_projections_counts_check", sql`${table.sourceModeCount} >= 1 and ${table.sourceEntryCount} >= 0 and ${table.includedEntryCount} >= 0 and ${table.omittedEntryCount} >= 0 and ${table.includedEntryCount} + ${table.omittedEntryCount} = ${table.sourceEntryCount} and ((${table.sourceEntryCount} = 0 and ${table.context} is null) or (${table.sourceEntryCount} > 0 and ${table.context} is not null))`, ), }), ); // First-class ownership for one accepted execution attempt. A workflow may // preallocate id, but this row is inserted only by the activity transaction // that actually claims the logical turn and registers its exact dispatch. // Protected EXECUTE-only ledger. SQL owns live-attempt/principal derivation, // immutable settlement, bounds, RLS and source ownership constraints. export const mcpOperations = pgTable( "mcp_operations", { operationId: uuid("operation_id").primaryKey(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), sourceTurnId: uuid("source_turn_id").notNull(), sourceAttemptId: uuid("source_attempt_id").notNull(), sourceExecutionGeneration: integer("source_execution_generation").notNull(), sourceCallId: text("source_call_id"), principalKind: text("principal_kind").notNull(), principalId: text("principal_id").notNull(), principalMembershipId: uuid("principal_membership_id"), principalMembershipRevision: bigint("principal_membership_revision", { mode: "number" }), serverId: text("server_id").notNull(), originalTool: text("original_tool").notNull(), observerTool: text("observer_tool").notNull(), argumentDigest: text("argument_digest").notNull(), destinationDigest: text("destination_digest").notNull(), authorityDigest: text("authority_digest").notNull(), originalOutcome: text("original_outcome").notNull().default("captured"), originalResult: jsonb("original_result"), originalResultCodecVersion: integer("original_result_codec_version"), observationResult: jsonb("observation_result"), observationResultCodecVersion: integer("observation_result_codec_version"), receiptRevision: text("receipt_revision"), receiptDigest: text("receipt_digest"), observationClaimId: uuid("observation_claim_id"), observationClaimAttemptId: uuid("observation_claim_attempt_id"), observationClaimExpiresAt: timestamp("observation_claim_expires_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), observedAt: timestamp("observed_at", { withTimezone: true }), }, (table) => ({ source: index("mcp_operations_source_idx").on( table.workspaceId, table.sessionId, table.sourceTurnId, table.sourceCallId, ), }), ); export const sessionTurnAttempts = pgTable( "session_turn_attempts", { id: uuid("id").primaryKey(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), executionGeneration: integer("execution_generation").notNull(), state: text("state").notNull().default("claimed"), outcome: text("outcome"), temporalWorkflowId: text("temporal_workflow_id").notNull(), temporalWorkflowRunId: text("temporal_workflow_run_id").notNull(), temporalActivityId: text("temporal_activity_id").notNull(), workerId: text("worker_id"), leaseId: text("lease_id"), leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }), verifiedControlRevision: bigint("verified_control_revision", { mode: "number", }).notNull(), // Immutable generic session-tenancy authority admitted with this exact // attempt. A later visibility/ownership epoch change fences the attempt; // these are snapshots, never live lookups or mutable metadata. // Pre-0222 SQL writers may omit these columns; the migration-owned BEFORE // INSERT trigger fills them from the exact session row. Current claim // writers pass both explicitly, so no client-side default may bypass the // trigger and manufacture stale authority. authorityEpoch: integer("authority_epoch").notNull(), authorityVisibility: text("authority_visibility").notNull(), authorityOwnerOrganizationMembershipId: uuid("authority_owner_organization_membership_id"), personalResourceProtocolVersion: integer("personal_resource_protocol_version") .notNull() .default(0), // Immutable policy snapshot captured under the session lock at claim. mcpApprovalPolicies: jsonb("mcp_approval_policies") .$type>() .notNull(), connectorActionPolicies: jsonb("connector_action_policies") .$type() .notNull() .default([]), startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), closedAt: timestamp("closed_at", { withTimezone: true }), // The cancelled activity writes this after losing inference, user-visible // output, and workspace-persistence authority. Fenced/idempotent cleanup // and telemetry may still finish. Temporal activity cancellation or // terminalization is transport state only; queue admission and clients use // this durable receipt as the physical-quiescence authority. quiescedAt: timestamp("quiesced_at", { withTimezone: true }), }, (table) => ({ workspaceAccount: foreignKey({ name: "session_turn_attempts_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "session_turn_attempts_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), workspaceTurn: foreignKey({ name: "session_turn_attempts_workspace_turn_fk", columns: [table.workspaceId, table.turnId], foreignColumns: [sessionTurns.workspaceId, sessionTurns.id], }).onDelete("restrict"), workspaceIdentity: uniqueIndex("session_turn_attempts_workspace_id_uq").on( table.workspaceId, table.id, ), ownershipIdentity: uniqueIndex("session_turn_attempts_human_input_owner_uq").on( table.accountId, table.workspaceId, table.sessionId, table.turnId, table.id, ), liveTurn: uniqueIndex("session_turn_attempts_live_turn_uq") .on(table.workspaceId, table.turnId) .where(sql`${table.state} in ('claimed', 'running')`), liveSession: uniqueIndex("session_turn_attempts_live_session_uq") .on(table.workspaceId, table.sessionId) .where(sql`${table.state} in ('claimed', 'running')`), latestSessionAttempt: index("session_turn_attempts_latest_session_idx").on( table.workspaceId, table.sessionId, table.startedAt.desc(), table.id.desc(), ), authorityEpoch: index("session_turn_attempts_authority_epoch_idx").on( table.workspaceId, table.sessionId, table.authorityEpoch, ), dispatch: uniqueIndex("session_turn_attempts_dispatch_uq").on( table.workspaceId, table.temporalWorkflowRunId, table.temporalActivityId, ), leaseExpiry: index("session_turn_attempts_lease_expiry_idx") .on(table.leaseExpiresAt, table.workspaceId, table.sessionId) .where(sql`${table.state} in ('claimed', 'running')`), stateValid: check( "session_turn_attempts_state_check", sql`${table.state} in ('claimed', 'running', 'closed')`, ), outcomeValid: check( "session_turn_attempts_outcome_check", sql`${table.outcome} is null or ${table.outcome} in ( 'completed', 'failed', 'cancelled', 'superseded', 'requires_action', 'waiting_capacity', 'interrupted_recoverable', 'lease_lost_recoverable', 'pre_cutover_closed' )`, ), closedConsistent: check( "session_turn_attempts_closed_check", sql`(${table.state} = 'closed' and ${table.outcome} is not null and ${table.closedAt} is not null) or (${table.state} <> 'closed' and ${table.outcome} is null and ${table.closedAt} is null)`, ), authorityEpochValid: check( "session_turn_attempts_authority_epoch_check", sql`${table.authorityEpoch} is not null and ${table.authorityVisibility} is not null and ${table.authorityEpoch} > 0`, ), authorityVisibilityValid: check( "session_turn_attempts_authority_visibility_check", sql`${table.authorityEpoch} is not null and ${table.authorityVisibility} is not null and ${table.authorityVisibility} in ('user_private', 'workspace_shared')`, ), authorityOwnerShape: check( "session_turn_attempts_authority_owner_shape_check", sql`${table.authorityVisibility} <> 'user_private' or ${table.authorityOwnerOrganizationMembershipId} is not null`, ), authorityOwner: foreignKey({ name: "session_turn_attempts_authority_owner_fk", columns: [table.authorityOwnerOrganizationMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), }), ); // Per-turn startup SLO checkpoint ledger (migration 0318). One row per // (turn, milestone, outcome); the transaction whose // `insert ... on conflict do nothing returning` returns the row is the // canonical inserter and the sole metric receipt, so recovery and replay // conflict without re-reading the turn's session_events. `pre_ledger_history` // rows seal a turn whose startup predates the ledger. export const sessionTurnStartupMilestones = pgTable( "session_turn_startup_milestones", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), milestone: text("milestone").notNull(), outcome: text("outcome").notNull(), canonicalSource: text("canonical_source").notNull(), eventId: uuid("event_id"), occurredAt: timestamp("occurred_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ name: "session_turn_startup_milestones_pkey", columns: [table.workspaceId, table.turnId, table.milestone, table.outcome], }), workspaceAccount: foreignKey({ name: "session_turn_startup_milestones_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "session_turn_startup_milestones_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), workspaceTurn: foreignKey({ name: "session_turn_startup_milestones_workspace_turn_fk", columns: [table.workspaceId, table.turnId], foreignColumns: [sessionTurns.workspaceId, sessionTurns.id], }).onDelete("cascade"), workspaceSessionIndex: index("session_turn_startup_milestones_workspace_session_idx").on( table.workspaceId, table.sessionId, ), milestoneCheck: check( "session_turn_startup_milestones_milestone_chk", sql`${table.milestone} in ('queue', 'provider_dispatch', 'first_byte')`, ), outcomeCheck: check( "session_turn_startup_milestones_outcome_chk", sql`${table.outcome} in ('completed', 'failed')`, ), checkpointCheck: check( "session_turn_startup_milestones_checkpoint_chk", sql`${table.outcome} = 'completed' or ${table.milestone} = 'first_byte'`, ), canonicalSourceCheck: check( "session_turn_startup_milestones_canonical_source_chk", sql`(${table.canonicalSource} = 'inserted_event' and ${table.eventId} is not null and ${table.occurredAt} is not null) or (${table.canonicalSource} = 'pre_ledger_history' and ${table.outcome} = 'completed' and ${table.eventId} is null and ${table.occurredAt} is null)`, ), }), ); // Credential-free authority captured with the accepted logical turn. Runtime // credential resolution loads this canonical row by exact turn + tool surface; // a caller-provided snapshot is never authority. export const turnConnectionAuthoritySnapshots = pgTable( "turn_connection_authority_snapshots", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), serverId: text("server_id").notNull(), connectionId: uuid("connection_id").notNull(), connectionGeneration: bigint("connection_generation", { mode: "number", }).notNull(), originWorkspaceId: uuid("origin_workspace_id").notNull(), providerDomain: text("provider_domain").notNull(), connectionKind: text("connection_kind").notNull(), authorityScope: text("authority_scope").notNull(), authoritySource: text("authority_source").notNull(), ownerSubjectId: text("owner_subject_id"), ownerOrganizationMembershipId: uuid("owner_organization_membership_id"), membershipAuthorizationRevision: bigint("membership_authorization_revision", { mode: "number", }), authorityId: uuid("authority_id"), authorityGeneration: bigint("authority_generation", { mode: "number" }), grantId: uuid("grant_id"), grantGeneration: bigint("grant_generation", { mode: "number" }), grantMode: text("grant_mode"), grantContext: text("grant_context"), grantSessionId: uuid("grant_session_id"), grantAuthorityEpoch: integer("grant_authority_epoch"), sessionVisibility: text("session_visibility").notNull(), sessionAuthorityEpoch: integer("session_authority_epoch").notNull(), canonicalSnapshot: jsonb("canonical_snapshot").$type>().notNull(), snapshotDigest: bytea("snapshot_digest").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ identity: primaryKey({ columns: [table.turnId, table.serverId] }), turn: foreignKey({ name: "turn_connection_authority_turn_fk", columns: [table.workspaceId, table.turnId], foreignColumns: [sessionTurns.workspaceId, sessionTurns.id], }).onDelete("cascade"), connection: foreignKey({ name: "turn_connection_authority_connection_fk", columns: [table.connectionId], foreignColumns: [connections.id], }).onDelete("restrict"), membership: foreignKey({ name: "turn_connection_authority_membership_fk", columns: [table.ownerOrganizationMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), authority: foreignKey({ name: "turn_connection_authority_authority_fk", columns: [table.authorityId, table.accountId], foreignColumns: [ organizationUserResourceAuthorities.id, organizationUserResourceAuthorities.accountId, ], }).onDelete("restrict"), grant: foreignKey({ name: "turn_connection_authority_grant_fk", columns: [table.grantId, table.accountId], foreignColumns: [organizationUserResourceGrants.id, organizationUserResourceGrants.accountId], }).onDelete("restrict"), connectionLookup: index("turn_connection_authority_connection_idx").on( table.accountId, table.connectionId, table.turnId, table.serverId, ), serverValid: check( "turn_connection_authority_server_check", sql`octet_length(${table.serverId}) between 1 and 256`, ), generationValid: check( "turn_connection_authority_generation_check", sql`${table.connectionGeneration} > 0 and ${table.sessionAuthorityEpoch} > 0`, ), }), ); // One metadata-only authorization fact per caller-preallocated physical // provider request. No credential, header, body, provider response, or content // is retained in this table. export const connectionUseAuditFacts = pgTable( "connection_use_audit_facts", { physicalRequestId: uuid("physical_request_id").primaryKey(), usePhase: text("use_phase").notNull(), requestDigest: bytea("request_digest").notNull(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), attemptId: uuid("attempt_id").notNull(), executionGeneration: integer("execution_generation").notNull(), serverId: text("server_id").notNull(), connectionId: uuid("connection_id"), connectionGeneration: bigint("connection_generation", { mode: "number" }), authorityScope: text("authority_scope"), ownerSubjectId: text("owner_subject_id"), authorityId: uuid("authority_id"), grantId: uuid("grant_id"), initiatorKind: text("initiator_kind"), initiatorSubjectId: text("initiator_subject_id"), initiatingHumanSubjectId: text("initiating_human_subject_id"), authorityEpoch: integer("authority_epoch"), authorityVisibility: text("authority_visibility"), authorityOwnerOrganizationMembershipId: uuid("authority_owner_organization_membership_id"), outcome: text("outcome").notNull(), denialReason: text("denial_reason"), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ attempt: index("connection_use_audit_attempt_idx").on( table.workspaceId, table.attemptId, table.occurredAt, ), shapeValid: check( "connection_use_audit_shape_check", sql`octet_length(${table.serverId}) between 1 and 256 and octet_length(${table.requestDigest}) = 32 and ${table.executionGeneration} > 0 and ${table.usePhase} in ('credential_resolution', 'provider_request') and ${table.outcome} in ('authorized', 'denied')`, ), }), ); // Immutable executable tool universe admitted to one exact attempt. Model MCP // and sandbox Codemode use the same digest and opaque identities from this row. export const sessionAttemptToolCatalogs = pgTable( "session_attempt_tool_catalogs", { attemptId: uuid("attempt_id").primaryKey(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), executionGeneration: integer("execution_generation").notNull(), catalogVersion: integer("catalog_version").notNull(), generation: integer("generation").notNull(), digest: text("digest").notNull(), catalog: jsonb("catalog").$type().notNull(), /** Session content-blob digests for `catalog.entries`; NULL means inline legacy form. */ contentRefs: jsonb("content_refs").$type<{ v: 1; entries: string[] }>(), createdAt: timestamp("created_at", { withTimezone: true }).notNull(), }, (table) => ({ attemptOwner: foreignKey({ name: "session_attempt_tool_catalogs_attempt_owner_fk", columns: [table.accountId, table.workspaceId, table.sessionId, table.turnId, table.attemptId], foreignColumns: [ sessionTurnAttempts.accountId, sessionTurnAttempts.workspaceId, sessionTurnAttempts.sessionId, sessionTurnAttempts.turnId, sessionTurnAttempts.id, ], }).onDelete("cascade"), sessionTurn: index("session_attempt_tool_catalogs_session_turn_idx").on( table.workspaceId, table.sessionId, table.turnId, ), exactAuthorityDigest: uniqueIndex( "session_attempt_tool_catalogs_exact_authority_digest_uidx", ).on( table.accountId, table.workspaceId, table.sessionId, table.turnId, table.attemptId, table.executionGeneration, table.digest, ), versionValid: check( "session_attempt_tool_catalogs_version_check", sql`${table.catalogVersion} = 1 and ${table.generation} > 0 and ${table.executionGeneration} > 0`, ), digestValid: check( "session_attempt_tool_catalogs_digest_check", sql`${table.digest} ~ '^[0-9a-f]{64}$'`, ), catalogSize: check( "session_attempt_tool_catalogs_size_check", sql`octet_length(${table.catalog}::text) between 2 and 16777216`, ), catalogIdentity: check( "session_attempt_tool_catalogs_catalog_identity_check", sql`jsonb_typeof(${table.catalog}) = 'object' and ${table.catalog} ?& array[ 'version', 'accountId', 'workspaceId', 'sessionId', 'turnId', 'attemptId', 'executionGeneration', 'generation', 'createdAt', 'digest', 'entries' ]::text[] and ${table.catalog}->>'accountId' = ${table.accountId}::text and ${table.catalog}->>'workspaceId' = ${table.workspaceId}::text and ${table.catalog}->>'sessionId' = ${table.sessionId}::text and ${table.catalog}->>'turnId' = ${table.turnId}::text and ${table.catalog}->>'attemptId' = ${table.attemptId}::text and (${table.catalog}->>'executionGeneration')::integer = ${table.executionGeneration} and (${table.catalog}->>'version')::integer = ${table.catalogVersion} and (${table.catalog}->>'generation')::integer = ${table.generation} and ${table.catalog}->>'digest' = ${table.digest} and jsonb_typeof(${table.catalog}->'entries') = 'array' and jsonb_array_length(${table.catalog}->'entries') <= 4096`, ), }), ); export const sessionAttemptModelContextSnapshots = pgTable( "session_attempt_model_context_snapshots", { attemptId: uuid("attempt_id").primaryKey(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), executionGeneration: integer("execution_generation").notNull(), requestIndex: integer("request_index").notNull(), capturedAt: timestamp("captured_at", { withTimezone: true }).notNull(), snapshot: jsonb("snapshot").$type().notNull(), /** Session content-blob digests for externalized snapshot values; NULL means inline. */ contentRefs: jsonb("content_refs").$type<{ v: 1; instructions: string; layers: string; tools: string; skills: string; body: string[] | null; }>(), createdAt: timestamp("created_at", { withTimezone: true }).notNull(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull(), }, (table) => ({ attemptOwner: foreignKey({ name: "session_attempt_model_context_snapshots_attempt_owner_fk", columns: [table.accountId, table.workspaceId, table.sessionId, table.turnId, table.attemptId], foreignColumns: [ sessionTurnAttempts.accountId, sessionTurnAttempts.workspaceId, sessionTurnAttempts.sessionId, sessionTurnAttempts.turnId, sessionTurnAttempts.id, ], }).onDelete("cascade"), sessionLatest: index("session_attempt_model_context_snapshots_session_idx").on( table.workspaceId, table.sessionId, table.capturedAt.desc(), ), requestIndexValid: check( "session_attempt_model_context_snapshots_request_index_check", sql`${table.requestIndex} > 0 and ${table.executionGeneration} > 0`, ), snapshotSize: check( "session_attempt_model_context_snapshots_size_check", sql`octet_length(${table.snapshot}::text) between 2 and 16777216`, ), snapshotIdentity: check( "session_attempt_model_context_snapshots_identity_check", sql`jsonb_typeof(${table.snapshot}) = 'object' and ${table.snapshot} ?& array['version', 'capturedAt', 'source', 'requestIndex', 'instructions', 'layers', 'tools', 'skills', 'tokens']::text[] and (${table.snapshot}->>'version')::integer = 1 and ${table.snapshot}->>'source' = 'model_request' and jsonb_typeof(${table.snapshot}->'layers') = 'array' and jsonb_typeof(${table.snapshot}->'tools') = 'array' and jsonb_typeof(${table.snapshot}->'skills') = 'array'`, ), }), ); /** Session-owned content-addressed JSON values (see `session-content-blobs.ts`). */ export const sessionContentBlobs = pgTable( "session_content_blobs", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), digest: text("digest").notNull(), value: jsonb("value").$type().notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ name: "session_content_blobs_pkey", columns: [table.workspaceId, table.sessionId, table.digest], }), sessionOwner: foreignKey({ name: "session_content_blobs_session_fk", columns: [table.sessionId], foreignColumns: [sessions.id], }).onDelete("cascade"), workspaceAccount: foreignKey({ name: "session_content_blobs_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), session: index("session_content_blobs_session_idx").on(table.sessionId), digestValid: check( "session_content_blobs_digest_check", sql`${table.digest} ~ '^[0-9a-f]{64}$'`, ), }), ); // Durable idempotency and outcome journal for calls made programmatically from // an attempt's sandbox. The active worker executes these through the exact same // in-memory AttemptToolEnvironment as model MCP calls. export const sessionAttemptCodemodeCalls = pgTable( "session_attempt_codemode_calls", { operationId: uuid("operation_id").primaryKey(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), attemptId: uuid("attempt_id").notNull(), executionGeneration: integer("execution_generation").notNull(), catalogDigest: text("catalog_digest").notNull(), requestDigest: text("request_digest").notNull(), durableApproval: boolean("durable_approval").notNull().default(false), approvalRequestId: uuid("approval_request_id").references(() => connectorActionRequests.id), effectDigest: text("effect_digest"), executionAttemptId: uuid("execution_attempt_id"), executionAttemptGeneration: integer("execution_attempt_generation"), executionCatalogDigest: text("execution_catalog_digest"), serverId: text("server_id").notNull(), toolName: text("tool_name").notNull(), arguments: jsonb("arguments").$type>().notNull(), callerSubjectId: text("caller_subject_id").notNull(), /** 1108: the machine the calling code ran on, when it was not the session's * active sandbox (a `run_on` exec). Paths in the call resolve there. */ callerExecutionSandboxId: uuid("caller_execution_sandbox_id"), state: text("state", { enum: [ "queued", "waiting_for_approval", "running", "completed", "failed", "outcome_unknown", "cancelled", ], }) .notNull() .default("queued"), claimId: uuid("claim_id"), result: jsonb("result").$type(), errorCode: text("error_code"), errorMessage: text("error_message"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), claimedAt: timestamp("claimed_at", { withTimezone: true }), executionStartedAt: timestamp("execution_started_at", { withTimezone: true, }), claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true }), completedAt: timestamp("completed_at", { withTimezone: true }), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ catalog: foreignKey({ name: "session_attempt_codemode_calls_catalog_fk", columns: [ table.accountId, table.workspaceId, table.sessionId, table.turnId, table.attemptId, table.executionGeneration, table.catalogDigest, ], foreignColumns: [ sessionAttemptToolCatalogs.accountId, sessionAttemptToolCatalogs.workspaceId, sessionAttemptToolCatalogs.sessionId, sessionAttemptToolCatalogs.turnId, sessionAttemptToolCatalogs.attemptId, sessionAttemptToolCatalogs.executionGeneration, sessionAttemptToolCatalogs.digest, ], }).onDelete("cascade"), executionCatalog: foreignKey({ name: "session_codemode_execution_catalog_fk", columns: [ table.accountId, table.workspaceId, table.sessionId, table.turnId, table.executionAttemptId, table.executionAttemptGeneration, table.executionCatalogDigest, ], foreignColumns: [ sessionAttemptToolCatalogs.accountId, sessionAttemptToolCatalogs.workspaceId, sessionAttemptToolCatalogs.sessionId, sessionAttemptToolCatalogs.turnId, sessionAttemptToolCatalogs.attemptId, sessionAttemptToolCatalogs.executionGeneration, sessionAttemptToolCatalogs.digest, ], }).onDelete("cascade"), continuationValid: check( "session_codemode_continuation_check", sql`( (${table.executionAttemptId} is null and ${table.executionAttemptGeneration} is null and ${table.executionCatalogDigest} is null) or (${table.executionAttemptId} is not null and ${table.executionAttemptGeneration} is not null and ${table.executionAttemptGeneration} > 0 and ${table.executionCatalogDigest} is not null and ${table.executionCatalogDigest} ~ '^[0-9a-f]{64}$') ) and (${table.approvalRequestId} is null or (${table.durableApproval} and ${table.effectDigest} is not null and ${table.effectDigest} ~ '^[0-9a-f]{64}$'))`, ), sessionTurn: index("session_attempt_codemode_calls_session_turn_idx").on( table.workspaceId, table.sessionId, table.turnId, table.createdAt, ), activeAttempt: index("session_attempt_codemode_calls_active_attempt_idx") .on(table.workspaceId, table.attemptId, table.state) .where(sql`${table.state} in ('queued', 'running')`), generationsValid: check( "session_attempt_codemode_calls_generation_check", sql`${table.executionGeneration} > 0`, ), digestsValid: check( "session_attempt_codemode_calls_digests_check", sql`${table.catalogDigest} ~ '^[0-9a-f]{64}$' and ${table.requestDigest} ~ '^[0-9a-f]{64}$'`, ), identityValid: check( "session_attempt_codemode_calls_identity_check", sql`octet_length(${table.serverId}) between 1 and 256 and octet_length(${table.toolName}) between 1 and 512 and octet_length(${table.callerSubjectId}) between 1 and 1024`, ), argumentsSize: check( "session_attempt_codemode_calls_arguments_size_check", sql`jsonb_typeof(${table.arguments}) = 'object' and octet_length(${table.arguments}::text) between 2 and 4194304`, ), resultSize: check( "session_attempt_codemode_calls_result_size_check", sql`${table.result} is null or ( jsonb_typeof(${table.result}) = 'object' and octet_length(${table.result}::text) between 2 and 16777216 )`, ), lifecycleValid: check( "session_attempt_codemode_calls_lifecycle_check", sql`( ${table.state} in ('queued', 'waiting_for_approval') and (${table.state} <> 'waiting_for_approval' or ${table.approvalRequestId} is not null) and ${table.claimId} is null and ${table.claimedAt} is null and ${table.executionStartedAt} is null and ${table.claimExpiresAt} is null and ${table.completedAt} is null and ${table.result} is null and ${table.errorCode} is null and ${table.errorMessage} is null ) or ( ${table.state} = 'running' and ${table.claimId} is not null and ${table.claimedAt} is not null and ${table.claimExpiresAt} is not null and ${table.completedAt} is null and ${table.result} is null and ${table.errorCode} is null and ${table.errorMessage} is null ) or ( ${table.state} = 'completed' and ${table.claimId} is not null and ${table.claimedAt} is not null and ${table.executionStartedAt} is not null and ${table.claimExpiresAt} is not null and ${table.completedAt} is not null and ${table.result} is not null and ${table.errorCode} is null and ${table.errorMessage} is null ) or ( ${table.state} = 'failed' and ${table.claimId} is not null and ${table.claimedAt} is not null and ${table.claimExpiresAt} is not null and ${table.completedAt} is not null and ${table.result} is null and ${table.errorCode} is not null and ${table.errorMessage} is not null ) or ( ${table.state} = 'outcome_unknown' and ${table.claimId} is not null and ${table.claimedAt} is not null and ${table.executionStartedAt} is not null and ${table.claimExpiresAt} is not null and ${table.completedAt} is not null and ${table.result} is null and ${table.errorCode} is not null and ${table.errorMessage} is not null ) or ( ${table.state} = 'cancelled' and ${table.claimId} is null and ${table.claimedAt} is null and ${table.executionStartedAt} is null and ${table.claimExpiresAt} is null and ${table.completedAt} is not null and ${table.result} is null and ${table.errorCode} is not null and ${table.errorMessage} is not null )`, ), }), ); export const connectorActionRequests = pgTable( "connector_action_requests", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), creationAttemptId: uuid("creation_attempt_id").notNull(), creationExecutionGeneration: integer("creation_execution_generation").notNull(), executionAttemptId: uuid("execution_attempt_id"), executionAttemptGeneration: integer("execution_attempt_generation"), approvalId: text("approval_id").notNull(), initiatorKind: text("initiator_kind").$type<"subject" | "service">().notNull(), initiatorSubjectId: text("initiator_subject_id").notNull(), connectionId: text("connection_id").notNull(), connectionVersion: integer("connection_version"), serverId: text("server_id").notNull(), toolName: text("tool_name").notNull(), actionName: text("action_name").notNull(), // Attempt-frozen provenance intentionally survives policy deletion. policyId: uuid("policy_id"), policyVersion: integer("policy_version"), policySource: text("policy_source").$type<"explicit" | "default" | "ambiguous">().notNull(), policyDecision: text("policy_decision").$type().notNull(), /** * The agent and Can use rule that made the call ask or blocked it; null * when the connection's own settings decided (`policy_source` stays * `default` for an agent rule, as before this column). */ agentRule: jsonb("agent_rule").$type(), actionFingerprint: text("action_fingerprint").notNull(), reviewArguments: text("review_arguments"), reviewContext: jsonb("review_context").$type(), status: text("status") .$type< | "pending" | "approved" | "rejected" | "blocked" | "executing" | "completed" | "failed" | "uncertain" >() .notNull(), decision: text("decision").$type<"approve" | "reject">(), decisionBySubjectId: text("decision_by_subject_id"), // 0971: how the decider reached the card, and whether they were signed in // where an app-action change may be confirmed: the app itself, or an embed // the deployment opted in (never a key, chat integration or other token). decisionByKind: text("decision_by_kind").$type<"human" | "api" | "agent_attempt" | "system">(), decisionBySignedInPerson: boolean("decision_by_signed_in_person").notNull().default(false), decisionEventId: uuid("decision_event_id"), decidedAt: timestamp("decided_at", { withTimezone: true }), executionStartedAt: timestamp("execution_started_at", { withTimezone: true, }), executionFinishedAt: timestamp("execution_finished_at", { withTimezone: true, }), outcome: text("outcome"), // 1114: times the provider stopped this call to ask the person (MCP // elicitation). Each round has its own decision and single execution. inputRound: integer("input_round").notNull().default(0), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ creationAttempt: foreignKey({ name: "connector_action_requests_creation_attempt_fk", columns: [ table.accountId, table.workspaceId, table.sessionId, table.turnId, table.creationAttemptId, ], foreignColumns: [ sessionTurnAttempts.accountId, sessionTurnAttempts.workspaceId, sessionTurnAttempts.sessionId, sessionTurnAttempts.turnId, sessionTurnAttempts.id, ], }).onDelete("cascade"), executionAttempt: foreignKey({ name: "connector_action_requests_execution_attempt_fk", columns: [ table.accountId, table.workspaceId, table.sessionId, table.turnId, table.executionAttemptId, ], foreignColumns: [ sessionTurnAttempts.accountId, sessionTurnAttempts.workspaceId, sessionTurnAttempts.sessionId, sessionTurnAttempts.turnId, sessionTurnAttempts.id, ], }).onDelete("cascade"), identity: uniqueIndex("connector_action_requests_identity_uq").on( table.workspaceId, table.sessionId, table.turnId, table.approvalId, ), attemptStatus: index("connector_action_requests_attempt_status_idx").on( table.workspaceId, table.creationAttemptId, table.status, ), sessionCreated: index("connector_action_requests_session_created_idx").on( table.workspaceId, table.sessionId, table.createdAt.desc(), table.id.desc(), ), policyDecisionValid: check( "connector_action_requests_policy_decision_chk", sql`${table.policyDecision} in ('allow', 'ask', 'block')`, ), reviewArgumentsBound: check( "connector_review_arguments_bound", sql`${table.reviewArguments} is null or octet_length(${table.reviewArguments}) <= 4194304`, ), reviewContextBound: check( "connector_review_context_bound", sql`${table.reviewContext} is null or octet_length(${table.reviewContext}::text) <= 4194304`, ), statusValid: check( "connector_action_requests_status_chk", sql`${table.status} in ( 'pending', 'approved', 'rejected', 'blocked', 'executing', 'completed', 'failed', 'uncertain' )`, ), }), ); // One durable idempotency/operation record for every queue, control, // foreground Send/Steer, and Agent MCP mutation. The database migration owns // the NULLS NOT DISTINCT uniqueness form because Drizzle does not model it. export const sessionCommandReceipts = pgTable( "session_command_receipts", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), actorType: text("actor_type").notNull(), actorSubjectId: text("actor_subject_id"), actorAttemptId: uuid("actor_attempt_id"), action: text("action").notNull(), targetSessionId: uuid("target_session_id"), targetTurnId: uuid("target_turn_id"), operationKey: text("operation_key").notNull(), canonicalRequestHash: text("canonical_request_hash").notNull(), appliedControlRevision: bigint("applied_control_revision", { mode: "number", }), appliedQueueVersion: integer("applied_queue_version"), appliedTurnVersion: integer("applied_turn_version"), appliedDraftRevision: bigint("applied_draft_revision", { mode: "number" }), result: jsonb("result").$type>().notNull().default({}), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "session_command_receipts_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), actorAttempt: foreignKey({ name: "session_command_receipts_actor_attempt_fk", columns: [table.workspaceId, table.actorAttemptId], foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id], }).onDelete("restrict"), targetSession: foreignKey({ name: "session_command_receipts_target_session_fk", columns: [table.workspaceId, table.targetSessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), targetTurn: foreignKey({ name: "session_command_receipts_target_turn_fk", columns: [table.workspaceId, table.targetTurnId], foreignColumns: [sessionTurns.workspaceId, sessionTurns.id], }).onDelete("restrict"), workspaceIdentity: uniqueIndex("session_command_receipts_workspace_id_uq").on( table.workspaceId, table.id, ), targetCreated: index("session_command_receipts_target_created_idx").on( table.workspaceId, table.targetSessionId, table.createdAt, ), // Attempt-claim recovery-warning guards probe one action of one session // (migration 1356). targetAction: index("session_command_receipts_target_action_idx").on( table.workspaceId, table.targetSessionId, table.action, ), promptActorOperation: index("session_command_receipts_prompt_actor_operation_idx") .on( table.workspaceId, table.actorType, table.actorSubjectId, table.actorAttemptId, table.operationKey, ) .where(sql`${table.action} in ('prompt.send', 'prompt.steer')`), goalUpdateOperation: uniqueIndex("session_command_receipts_goal_update_operation_uq") .on(table.workspaceId, table.action, table.targetSessionId, table.operationKey) .where(sql`${table.action} = 'goal.update'`), waitForInputOperation: uniqueIndex("session_command_receipts_wait_for_input_operation_uq") .on(table.workspaceId, table.action, table.targetSessionId, table.operationKey) .where(sql`${table.action} = 'session.wait_for_input'`), actorValid: check( "session_command_receipts_actor_check", sql`( ${table.actorType} = 'agent_attempt' and ${table.actorAttemptId} is not null and ${table.actorSubjectId} is null ) or ( ${table.actorType} in ('human', 'operator', 'service') and ${table.actorSubjectId} is not null and ${table.actorAttemptId} is null )`, ), }), ); // One workspace-scoped durable invalidation per committed control revision. // This is deliberately separate from conversation/session events: a parent or // workspace Pause can change thousands of effective projections without // manufacturing one event (or queue row) per descendant. export const workspaceControlEvents = pgTable( "workspace_control_events", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), revision: bigint("revision", { mode: "number" }).notNull(), scope: text("scope").notNull(), rootSessionId: uuid("root_session_id"), action: text("action").notNull(), automatic: boolean("automatic").notNull().default(false), reason: text("reason"), reasonOriginalBytes: integer("reason_original_bytes"), actor: text("actor").notNull(), // Null is the rolling-upgrade shape for untouched, already-bounded legacy // rows. New writes and rewritten poison rows carry exact source byte facts. actorOriginalBytes: integer("actor_original_bytes"), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "workspace_control_events_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), rootSession: foreignKey({ name: "workspace_control_events_root_session_fk", columns: [table.workspaceId, table.rootSessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), workspaceRevision: uniqueIndex("workspace_control_events_workspace_revision_uq").on( table.workspaceId, table.revision, ), revisionValid: check("workspace_control_events_revision_check", sql`${table.revision} > 0`), shapeValid: check( "workspace_control_events_shape_check", sql`(${table.scope} = 'workspace' and ${table.rootSessionId} is null) or (${table.scope} = 'session' and ${table.rootSessionId} is not null)`, ), actionValid: check( "workspace_control_events_action_check", sql`${table.action} in ('pause', 'resume', 'timer_set', 'timer_cancelled')`, ), }), ); // An interruption is an independently durable request against an exact live // attempt. Multiple Pause/Steer causes coexist; no scalar session field owns // delivery or settlement. export const sessionAttemptInterruptions = pgTable( "session_attempt_interruptions", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), operationId: uuid("operation_id").notNull(), attemptId: uuid("attempt_id").notNull(), kind: text("kind").notNull(), controlRevision: bigint("control_revision", { mode: "number" }).notNull(), state: text("state").notNull().default("pending"), requestedAt: timestamp("requested_at", { withTimezone: true }).notNull().defaultNow(), deliveredAt: timestamp("delivered_at", { withTimezone: true }), acknowledgedAt: timestamp("acknowledged_at", { withTimezone: true }), settledAt: timestamp("settled_at", { withTimezone: true }), // Monotonic hint maintained by triggers from the attempt's quiesced_at. // Indexes the open settlement set only; readers still check the attempt. attemptQuiesced: boolean("attempt_quiesced").notNull().default(false), }, (table) => ({ workspaceAccount: foreignKey({ name: "session_attempt_interruptions_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "session_attempt_interruptions_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), operation: foreignKey({ name: "session_attempt_interruptions_operation_fk", columns: [table.workspaceId, table.operationId], foreignColumns: [sessionCommandReceipts.workspaceId, sessionCommandReceipts.id], }).onDelete("restrict"), attempt: foreignKey({ name: "session_attempt_interruptions_attempt_fk", columns: [table.workspaceId, table.attemptId], foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id], }).onDelete("restrict"), operationAttempt: uniqueIndex("session_attempt_interruptions_operation_attempt_uq").on( table.operationId, table.attemptId, ), unsettled: index("session_attempt_interruptions_unsettled_idx") .on(table.workspaceId, table.sessionId, table.requestedAt) .where(sql`${table.state} in ('pending', 'delivered', 'acknowledged')`), openSettlement: index("session_attempt_interruptions_open_settlement_idx") .on(table.workspaceId, table.sessionId) .where( sql`${table.state} in ('pending', 'delivered', 'acknowledged') or not ${table.attemptQuiesced}`, ), kindValid: check( "session_attempt_interruptions_kind_check", sql`${table.kind} in ('session_pause', 'workspace_pause', 'steer', 'maintenance', 'authority_change', 'organization_membership_revoked')`, ), stateValid: check( "session_attempt_interruptions_state_check", sql`${table.state} in ('pending', 'delivered', 'acknowledged', 'settled', 'rejected_stale')`, ), }), ); // Private, authenticated-subject composer truth. Editing a queued prompt and // restoring it here is one transaction; human drafts are never agent-visible. export const composerDrafts = pgTable( "composer_drafts", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), subjectId: text("subject_id").notNull(), revision: bigint("revision", { mode: "number" }).notNull().default(1), text: text("text").notNull().default(""), annotations: jsonb("annotations").$type().notNull().default([]), resources: jsonb("resources").$type().notNull().default([]), tools: jsonb("tools").$type().notNull().default([]), toolsProvided: boolean("tools_provided").notNull().default(false), model: text("model").notNull(), reasoningEffort: text("reasoning_effort").notNull(), latencyMode: text("latency_mode").notNull().default("standard"), /** * True while the person has not picked a model in this composer: reads * then return the chat's current settings, so a change made elsewhere * (for example by the agent) is what the next Send uses. The three * columns above keep the settings the draft was last saved with. */ policyFollowsSession: boolean("policy_follows_session").notNull().default(true), sourceTurnId: uuid("source_turn_id"), sourceTurnVersion: integer("source_turn_version"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "composer_drafts_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "composer_drafts_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), sourceTurn: foreignKey({ name: "composer_drafts_source_turn_fk", columns: [table.workspaceId, table.sourceTurnId], foreignColumns: [sessionTurns.workspaceId, sessionTurns.id], }).onDelete("restrict"), subjectSession: uniqueIndex("composer_drafts_subject_session_uq").on( table.workspaceId, table.sessionId, table.subjectId, ), subjectValid: check( "composer_drafts_subject_check", sql`length(btrim(${table.subjectId})) > 0`, ), revisionValid: check("composer_drafts_revision_check", sql`${table.revision} >= 1`), latencyModeValid: check( "composer_drafts_latency_mode_check", sql`${table.latencyMode} in ('standard', 'priority', 'fast', 'ultrafast')`, ), }), ); // Private pre-session composer truth. It is separate from composerDrafts so // the established-session table keeps its mandatory session foreign key. export const newSessionDrafts = pgTable( "new_session_drafts", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), subjectId: text("subject_id").notNull(), revision: bigint("revision", { mode: "number" }).notNull().default(1), text: text("text").notNull().default(""), resources: jsonb("resources").$type().notNull().default([]), tools: jsonb("tools").$type().notNull().default([]), model: text("model").notNull(), reasoningEffort: text("reasoning_effort").notNull(), latencyMode: text("latency_mode").notNull().default("standard"), sessionOptions: jsonb("session_options").$type>().notNull().default({}), // Project provenance is schema-owned so rolling old Drizzle binaries do // not select or overwrite it while updating the public draft columns. // A null snapshot means absent/unknown; a non-null snapshot plus a null // channel means explicit Default provenance. selectedProjectChannelId: uuid("selected_project_channel_id"), selectedProjectComputeSnapshot: jsonb("selected_project_compute_snapshot").$type< Record >(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "new_session_drafts_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), subjectWorkspace: uniqueIndex("new_session_drafts_subject_workspace_uq").on( table.workspaceId, table.subjectId, ), subjectValid: check( "new_session_drafts_subject_check", sql`length(btrim(${table.subjectId})) > 0`, ), revisionValid: check("new_session_drafts_revision_check", sql`${table.revision} >= 1`), latencyModeValid: check( "new_session_drafts_latency_mode_check", sql`${table.latencyMode} in ('standard', 'priority', 'fast', 'ultrafast')`, ), projectProvenanceValid: check( "new_session_drafts_project_provenance_check", sql`(${table.selectedProjectComputeSnapshot} is null and ${table.selectedProjectChannelId} is null) or jsonb_typeof(${table.selectedProjectComputeSnapshot}) = 'object'`, ), }), ); export const sessionSystemUpdates = pgTable( "session_system_updates", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), kind: text("kind").notNull(), classification: text("classification").notNull().default("info"), sourceId: text("source_id").notNull(), dedupeKey: text("dedupe_key").notNull(), summary: losslessText("summary").notNull(), summaryCodecVersion: losslessCodecVersion("summary_codec_version"), payload: losslessJsonb("payload").$type>().notNull().default({}), payloadCodecVersion: losslessCodecVersion("payload_codec_version"), lineage: jsonb("lineage").$type>().notNull().default({}), // Private immutable authority frozen when this machine input is accepted. // Public projections intentionally omit connection ids and owner subjects. personalConnectionDelegations: jsonb("personal_connection_delegations") .$type() .notNull() .default([]), mcpAccountBindings: jsonb("mcp_account_bindings").$type(), xaiProviderAccountAuthoritySnapshot: jsonb("xai_provider_account_authority_snapshot") .$type() .notNull() .default(WORKSPACE_XAI_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1), claudeProviderAccountAuthoritySnapshot: jsonb("claude_provider_account_authority_snapshot") .$type() .notNull() .default(WORKSPACE_CLAUDE_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1), // M3 v2 slot (0688): the Codex entry frozen with the update; copied, never // recomputed, by the turn that delivers it. NULL before the cutover. subscriptionAuthority: jsonb( "subscription_authority", ).$type(), // Private scheduled-occurrence authority linkage. Public update/event // projections intentionally omit this producer identifier. scheduledTaskRunId: uuid("scheduled_task_run_id"), // pending is visible queue truth; delivered means its exact model-memory // batch was durably claimed. Terminal cancellation/supersession is explicit. state: text("state").notNull().default("pending"), deliveredTurnId: uuid("delivered_turn_id").references(() => sessionTurns.id, { onDelete: "set null", }), // Migration owns the forward FK to session_history_items, declared later. // Every member of one claimed batch points at the exact model-memory row. deliveredHistoryItemId: uuid("delivered_history_item_id"), deliveredAt: timestamp("delivered_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), // The personal machine's owner let this informational update from someone // else's work continue under the owner's receiving context (0916). Set // only by continue_session_waiting_work; the producer receipt is unchanged. continuedBySubjectId: text("continued_by_subject_id"), continuedAt: timestamp("continued_at", { withTimezone: true }), }, (table) => ({ kindValid: check( "system_updates_kind_check", sql`${table.kind} in ('scheduled_occurrence', 'goal_continuation', 'agent_message', 'agent_steer_instruction', 'session_wait_timeout', 'background_command_result', 'child_terminal_result', 'media_generation_result', 'child_requires_action', 'child_requires_action_resolved', 'child_paused', 'child_waiting_capacity', 'child_progress', 'secret_use_approval_decided', 'capability_setup_completed')`, ), payloadKindValid: check( "system_updates_payload_kind_check", sql`${table.payload} ->> 'type' = ${table.kind}`, ), stateValid: check( "system_updates_state_check", sql`${table.state} in ('pending', 'delivered', 'cancelled', 'superseded', 'failed')`, ), dedupe: uniqueIndex("session_system_updates_dedupe_uq").on( table.workspaceId, table.sessionId, table.dedupeKey, ), pending: index("session_system_updates_pending_idx").on( table.workspaceId, table.sessionId, table.state, table.createdAt, ), // Producer-side supersession / resolution of one child's pending notices // of one kind on the parent (migration 0325). pendingKindSource: index("session_system_updates_pending_kind_source_idx") .on(table.workspaceId, table.sessionId, table.kind, table.sourceId) .where(sql`${table.state} = 'pending'`), pendingTerminalRepair: index("session_system_updates_pending_terminal_repair_idx") .on(table.workspaceId, table.sessionId, table.sourceId, table.dedupeKey) .where(sql`${table.state} = 'pending' and ${table.kind} = 'child_terminal_result'`), // "Did this turn consume awaited machine input?" in the session input-wait // deciding-turn predicate, probed once per candidate turn (migration 0787). deliveredTurn: index("session_system_updates_delivered_turn_idx") .on(table.workspaceId, table.deliveredTurnId) .where(sql`${table.deliveredTurnId} is not null`), // Deleting a history item (archive purge, session deletion) checks the // deferred session_system_updates_history_item_fk by delivered_history_item_id // alone; without its own index that check scans every workspace's entries. deliveredHistoryItem: index("session_system_updates_delivered_history_item_idx") .on(table.deliveredHistoryItemId) .where(sql`${table.deliveredHistoryItemId} is not null`), onePendingSteer: uniqueIndex("session_system_updates_one_pending_steer_idx") .on(table.workspaceId, table.sessionId) .where(sql`${table.kind} = 'agent_steer_instruction' and ${table.state} = 'pending'`), deliveryHistoryValid: check( "session_system_updates_delivery_history_check", sql`( (${table.state} = 'delivered' and ${table.deliveredHistoryItemId} is not null) or (${table.state} <> 'delivered' and ${table.deliveredHistoryItemId} is null) )`, ), }), ); /** * Durable child-terminal producer outbox. The source terminal transaction * inserts this row; fan-in delivery marks it delivered inside * addSessionSystemUpdateWithSourceMutation. A bounded reconciler may retry a * committed row after any worker/process death without duplicating a member. */ export const sessionSystemUpdateOutbox = pgTable( "session_system_update_outbox", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sourceSessionId: uuid("source_session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), targetSessionId: uuid("target_session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), dedupeKey: text("dedupe_key").notNull(), kind: text("kind").notNull(), classification: text("classification").notNull(), sourceId: text("source_id").notNull(), summary: losslessText("summary").notNull(), summaryCodecVersion: losslessCodecVersion("summary_codec_version"), payload: losslessJsonb("payload").$type>().notNull().default({}), payloadCodecVersion: losslessCodecVersion("payload_codec_version"), lineage: jsonb("lineage").$type>().notNull().default({}), // Exact private authority copied from the causal parent turn in the source // terminal transaction. Delivery retries cannot replace this snapshot. personalConnectionDelegations: jsonb("personal_connection_delegations") .$type() .notNull() .default([]), mcpAccountBindings: jsonb("mcp_account_bindings").$type(), xaiProviderAccountAuthoritySnapshot: jsonb("xai_provider_account_authority_snapshot") .$type() .notNull() .default(WORKSPACE_XAI_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1), claudeProviderAccountAuthoritySnapshot: jsonb("claude_provider_account_authority_snapshot") .$type() .notNull() .default(WORKSPACE_CLAUDE_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1), // M3 v2 slot (0688), copied onto the update the outbox row delivers. subscriptionAuthority: jsonb( "subscription_authority", ).$type(), status: text("status").notNull().default("pending"), attempts: integer("attempts").notNull().default(0), updateId: uuid("update_id"), lastError: text("last_error"), deliveredAt: timestamp("delivered_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ kindValid: check( "system_update_outbox_kind_check", sql`${table.kind} in ('child_terminal_result', 'child_requires_action', 'child_requires_action_resolved', 'child_paused', 'child_waiting_capacity', 'child_progress')`, ), payloadKindValid: check( "system_update_outbox_payload_kind_check", sql`${table.payload} ->> 'type' = ${table.kind}`, ), dedupe: uniqueIndex("session_system_update_outbox_dedupe_uq").on( table.workspaceId, table.dedupeKey, ), pending: index("session_system_update_outbox_pending_idx").on(table.status, table.createdAt), // The newest terminal notice a child wrote for its parent, which decides // whether that child's failure is already the parent agent's (migration 1360). childTerminalSource: index("session_system_update_outbox_child_terminal_source_idx") .on( table.workspaceId, table.sourceSessionId, table.targetSessionId, table.createdAt, table.id, ) .where(sql`${table.kind} = 'child_terminal_result'`), }), ); /** * Transactional delivery ledger for session-workflow wakeups. Postgres owns * work eligibility; Temporal signals are only nudges. One coalescing row per * session makes a committed mutation repairable without periodically scanning * every session that happens to look runnable. */ export const sessionWorkflowWakeOutbox = pgTable( "session_workflow_wake_outbox", { sessionId: uuid("session_id").primaryKey(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), temporalWorkflowId: text("temporal_workflow_id").notNull(), wakeRevision: bigint("wake_revision", { mode: "number" }).notNull().default(1), deliveredRevision: bigint("delivered_revision", { mode: "number" }).notNull().default(0), controlRevision: bigint("control_revision", { mode: "number" }).notNull().default(0), reason: text("reason").notNull(), attempts: integer("attempts").notNull().default(0), nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(), lastError: text("last_error"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ revisionValid: check( "session_workflow_wake_outbox_revision_check", sql`${table.wakeRevision} > 0 and ${table.deliveredRevision} >= 0 and ${table.deliveredRevision} <= ${table.wakeRevision}`, ), revisionSafe: check( "session_workflow_wake_outbox_revision_safe_check", sql`${table.wakeRevision} <= 9007199254740991 and ${table.deliveredRevision} <= 9007199254740991`, ), controlRevisionValid: check( "session_workflow_wake_outbox_control_revision_check", sql`${table.controlRevision} >= 0 and ${table.controlRevision} <= ${table.wakeRevision} and ${table.controlRevision} <= 9007199254740991`, ), workspaceAccount: foreignKey({ name: "session_workflow_wake_outbox_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSessionFk: foreignKey({ name: "session_workflow_wake_outbox_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), workspaceSession: uniqueIndex("session_workflow_wake_outbox_workspace_session_uq").on( table.workspaceId, table.sessionId, ), pending: index("session_workflow_wake_outbox_pending_idx") .on(table.nextAttemptAt, table.updatedAt, table.sessionId) .where(sql`${table.wakeRevision} > ${table.deliveredRevision}`), }), ); export const sessionGoals = pgTable( "session_goals", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), status: text("status").notNull().default("active"), // active | paused | completed text: text("text").notNull(), successCriteria: text("success_criteria"), rootConstraints: jsonb("root_constraints").$type().notNull().default([]), evidence: text("evidence"), // set by goal_complete rationale: text("rationale"), // set by goal_pause pausedReason: text("paused_reason"), // agent | user_pause | api | no_progress | max_auto_continuations | limits createdBy: text("created_by").notNull().default("api"), // api | agent | scheduled_task version: integer("version").notNull().default(1), // bumped on every set/update; progress signal // Semantic objective changes use a separate fence. `version` remains the // established lifecycle/wake identity for continuation compatibility. objectiveRevision: integer("objective_revision").notNull().default(1), mutationPolicy: text("mutation_policy") .$type() .notNull() .default("preserve_intent"), autoContinuations: integer("auto_continuations").notNull().default(0), noProgressStreak: integer("no_progress_streak").notNull().default(0), maxAutoContinuations: integer("max_auto_continuations"), // per-goal override; a configured settings cap (if any) remains the hard ceiling lastContinuationTurnId: uuid("last_continuation_turn_id"), versionAtLastContinuation: integer("version_at_last_continuation"), // Postgres owns the continuation obligation. Terminal settlement advances // wakeRevision in the same transaction that makes the session idle; // materialization advances observedRevision only alongside the one typed // update, timeline events, usage row, and workflow-wake outbox row. // Temporal signals and workflow history are replaceable nudges over these // monotonic revisions. continuationWakeRevision: bigint("continuation_wake_revision", { mode: "number", }) .notNull() .default(0), continuationObservedRevision: bigint("continuation_observed_revision", { mode: "number", }) .notNull() .default(0), // A terminal condition can keep the goal active while making unchanged // autonomous input unsafe. The fence is honored only while this remains // the newest finished turn; newer work or a goal mutation clears it. continuationSuppressedTurnId: uuid("continuation_suppressed_turn_id"), metadata: jsonb("metadata").$type>().notNull().default({}), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceIdentity: uniqueIndex("session_goals_workspace_id_idx").on( table.workspaceId, table.id, ), workspaceSession: uniqueIndex("session_goals_workspace_session_idx").on( table.workspaceId, table.sessionId, ), status: index("session_goals_workspace_status_idx").on(table.workspaceId, table.status), continuationRevisionValid: check( "session_goals_continuation_revision_check", sql`${table.continuationWakeRevision} >= 0 and ${table.continuationObservedRevision} >= 0 and ${table.continuationObservedRevision} <= ${table.continuationWakeRevision} and ${table.continuationWakeRevision} <= 9007199254740991 and ${table.continuationObservedRevision} <= 9007199254740991`, ), }), ); /** * Immutable semantic goal history. A proposal is never model-visible until a * later applied row references it; rejection is another immutable decision * row rather than mutation of the original proposal. */ export const sessionGoalRevisions = pgTable( "session_goal_revisions", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), goalId: uuid("goal_id").notNull(), disposition: text("disposition").$type<"applied" | "proposed" | "rejected">().notNull(), changeKind: text("change_kind").$type().notNull(), baseObjectiveRevision: integer("base_objective_revision").notNull(), resultObjectiveRevision: integer("result_objective_revision"), text: text("text").notNull(), successCriteria: text("success_criteria"), rootConstraints: jsonb("root_constraints").$type().notNull().default([]), mutationPolicy: text("mutation_policy").$type().notNull(), rationale: text("rationale").notNull(), actor: text("actor").$type<"agent" | "api" | "scheduled_task">().notNull(), actorTurnId: uuid("actor_turn_id"), actorAttemptId: uuid("actor_attempt_id"), proposalId: uuid("proposal_id"), rollbackOfRevisionId: uuid("rollback_of_revision_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "session_goal_revisions_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "session_goal_revisions_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), actorTurn: foreignKey({ name: "session_goal_revisions_actor_turn_fk", columns: [table.workspaceId, table.actorTurnId], foreignColumns: [sessionTurns.workspaceId, sessionTurns.id], }).onDelete("restrict"), actorAttempt: foreignKey({ name: "session_goal_revisions_actor_attempt_fk", columns: [table.workspaceId, table.actorAttemptId], foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id], }).onDelete("restrict"), proposal: foreignKey({ name: "session_goal_revisions_proposal_fk", columns: [table.workspaceId, table.proposalId], foreignColumns: [table.workspaceId, table.id], }).onDelete("restrict"), rollbackOfRevision: foreignKey({ name: "session_goal_revisions_rollback_of_revision_fk", columns: [table.workspaceId, table.rollbackOfRevisionId], foreignColumns: [table.workspaceId, table.id], }).onDelete("restrict"), appliedRevision: uniqueIndex("session_goal_revisions_applied_revision_uq") .on(table.workspaceId, table.goalId, table.resultObjectiveRevision) .where(sql`${table.disposition} = 'applied'`), goalTimeline: index("session_goal_revisions_goal_timeline_idx").on( table.workspaceId, table.goalId, table.createdAt, table.id, ), proposalDecision: uniqueIndex("session_goal_revisions_proposal_decision_uq") .on(table.workspaceId, table.proposalId) .where( sql`${table.proposalId} is not null and ${table.disposition} in ('applied', 'rejected')`, ), rollbackRequest: uniqueIndex("session_goal_revisions_rollback_request_uq") .on(table.workspaceId, table.goalId, table.rollbackOfRevisionId, table.baseObjectiveRevision) .where(sql`${table.disposition} = 'applied' and ${table.rollbackOfRevisionId} is not null`), dispositionValid: check( "session_goal_revisions_disposition_chk", sql`${table.disposition} in ('applied', 'proposed', 'rejected')`, ), changeKindValid: check( "session_goal_revisions_change_kind_chk", sql`${table.changeKind} in ('refinement', 'adaptation', 'replacement')`, ), policyValid: check( "session_goal_revisions_policy_chk", sql`${table.mutationPolicy} in ('review_changes', 'preserve_intent', 'autonomous_adaptation')`, ), revisionShape: check( "session_goal_revisions_revision_shape_chk", sql`(${table.disposition} = 'applied' and ${table.resultObjectiveRevision} = ${table.baseObjectiveRevision} + 1) or (${table.disposition} in ('proposed', 'rejected') and ${table.resultObjectiveRevision} is null)`, ), lineageShape: check( "session_goal_revisions_lineage_shape_chk", sql`(${table.disposition} = 'proposed' and ${table.proposalId} is null and ${table.rollbackOfRevisionId} is null) or (${table.disposition} = 'rejected' and ${table.proposalId} is not null and ${table.rollbackOfRevisionId} is null) or (${table.disposition} = 'applied' and not (${table.proposalId} is not null and ${table.rollbackOfRevisionId} is not null))`, ), }), ); export const sessionEventCursors = pgTable( "session_event_cursors", { sessionId: uuid("session_id") .primaryKey() .references(() => sessions.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), lastSequence: integer("last_sequence").notNull().default(0), lastMeaningfulSequence: integer("last_meaningful_sequence").notNull().default(0), revision: bigint("revision", { mode: "number" }).notNull().default(0), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "session_event_cursors_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "session_event_cursors_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), workspaceIdentity: uniqueIndex("session_event_cursors_workspace_session_idx").on( table.workspaceId, table.sessionId, ), sequenceValid: check("session_event_cursors_sequence_check", sql`${table.lastSequence} >= 0`), meaningfulSequenceValid: check( "session_event_cursors_meaningful_sequence_check", sql`${table.lastMeaningfulSequence} >= 0 and ${table.lastMeaningfulSequence} <= ${table.lastSequence}`, ), revisionValid: check("session_event_cursors_revision_check", sql`${table.revision} >= 0`), }), ); export const sessionImportBatches = opengeniPrivateSchema.table( "session_import_batches", { accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), batchId: text("batch_id").notNull(), subjectId: text("subject_id").notNull(), requestHash: text("request_hash").notNull(), eventOffset: integer("event_offset").notNull(), eventCount: integer("event_count").notNull(), nextOffset: integer("next_offset").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ columns: [table.workspaceId, table.sessionId, table.batchId] }), workspaceAccountFk: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSessionFk: foreignKey({ columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), batchIdValid: check( "session_import_batches_batch_id_check", sql`octet_length(${table.batchId}) between 1 and 800`, ), requestHashValid: check( "session_import_batches_request_hash_check", sql`${table.requestHash} ~ '^[0-9a-f]{64}$'`, ), eventOffsetValid: check( "session_import_batches_event_offset_check", sql`${table.eventOffset} >= 0`, ), eventCountValid: check( "session_import_batches_event_count_check", sql`${table.eventCount} between 1 and 100`, ), nextOffsetValid: check( "session_import_batches_next_offset_check", sql`${table.nextOffset} = ${table.eventOffset} + ${table.eventCount}`, ), }), ); export const sessionEvents = pgTable( "session_events", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), turnId: uuid("turn_id"), turnGeneration: integer("turn_generation"), turnAttemptId: uuid("turn_attempt_id"), turnAssociation: text("turn_association"), duplicateOfEventId: uuid("duplicate_of_event_id"), duplicateReason: text("duplicate_reason"), sequence: integer("sequence").notNull(), type: text("type").notNull(), payload: losslessJsonb("payload").$type().notNull().default({}), payloadCodecVersion: losslessCodecVersion("payload_codec_version"), clientEventId: text("client_event_id"), producerId: text("producer_id"), producerSeq: integer("producer_seq"), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), // Filled by a BEFORE INSERT trigger from payload ->> 'sourceKey' for // agent.model.usage rows (migration 0810). Never written by application // code; a plain column keeps the usage idempotency lookup indexable under // row-level security, where the payload expression index cannot be used. usageSourceKey: text("usage_source_key"), // Filled by a BEFORE INSERT OR UPDATE OF payload trigger from // payload ->> 'name' for agent.toolCall.created rows (migration 0889). // Never written by application code. Rows written before 0889 keep NULL; // readers fall back to the payload only then, so the presented-tool filter // does not detoast every excluded call's arguments. toolName: text("tool_name"), // The shared metadata trigger also extracts the exact coalesced call ID // for created/output rows (0913). NULL retains the legacy payload fallback. toolCallId: text("tool_call_id"), }, (table) => ({ workspaceAttempt: foreignKey({ name: "session_events_workspace_attempt_fk", columns: [table.workspaceId, table.turnAttemptId], foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id], }).onDelete("restrict"), // A deleted attempt's FK probe has no session_id. Avoid scanning every // event in its workspace once for each attempt in the deleted chat. attemptReference: index("session_events_workspace_attempt_idx") .on(table.workspaceId, table.turnAttemptId) .where(sql`${table.turnAttemptId} is not null`), sessionSequence: uniqueIndex("session_events_workspace_session_sequence_idx").on( table.workspaceId, table.sessionId, table.sequence, ), clientEvent: uniqueIndex("session_events_workspace_client_event_idx") .on(table.workspaceId, table.sessionId, table.clientEventId) .where(sql`${table.clientEventId} is not null`), producer: uniqueIndex("session_events_workspace_producer_idx") .on(table.workspaceId, table.sessionId, table.producerId, table.producerSeq) .where(sql`${table.producerId} is not null and ${table.producerSeq} is not null`), sessionCreated: index("session_events_workspace_session_created_idx").on( table.workspaceId, table.sessionId, table.createdAt, ), sessionTypeSequence: index("session_events_workspace_session_type_sequence_idx").on( table.workspaceId, table.sessionId, table.type, table.sequence, ), toolNamePage: index("session_events_tool_name_page_idx") .on(table.workspaceId, table.sessionId, table.toolName, table.sequence) .where( sql`${table.type} = 'agent.toolCall.created' and ${table.toolName} is not null and octet_length(${table.toolName}) <= 2048`, ), toolNameFallbackPage: index("session_events_tool_name_fallback_page_idx") .on(table.workspaceId, table.sessionId, table.sequence) .where( sql`${table.type} = 'agent.toolCall.created' and (${table.toolName} is null or octet_length(${table.toolName}) > 2048)`, ), toolCallPage: index("session_events_tool_call_page_idx") .on(table.workspaceId, table.sessionId, table.toolCallId, table.sequence) .where( sql`${table.type} in ('agent.toolCall.created', 'agent.toolCall.output') and ${table.toolCallId} is not null and octet_length(${table.toolCallId}) <= 2048`, ), toolCallFallbackPage: index("session_events_tool_call_fallback_page_idx") .on(table.workspaceId, table.sessionId, table.sequence) .where( sql`${table.type} in ('agent.toolCall.created', 'agent.toolCall.output') and (${table.toolCallId} is null or octet_length(${table.toolCallId}) > 2048)`, ), // Pre-0527 attention probes (which still counted commentary) during a rolling // deploy. Drop it in a later rolling migration once no pre-0527 API can run. meaningfulAttention: index("session_events_meaningful_attention_idx") .on(table.workspaceId, table.sessionId, table.sequence) .where(commentaryInclusiveMeaningfulSessionEventSql("session_events")), // Pre-0774 attention probes (task usage-limit stops not yet meaningful) // during a rolling deploy. Drop it in a later rolling migration once no // pre-0774 API can run. meaningfulAttentionWithoutCommentary: index("session_events_meaningful_attention_v2_idx") .on(table.workspaceId, table.sessionId, table.sequence) .where(commentaryExclusiveMeaningfulSessionEventSql("session_events")), meaningfulAttentionWithUsageLimitStops: index("session_events_meaningful_attention_v3_idx") .on(table.workspaceId, table.sessionId, table.sequence) .where(meaningfulAttentionIndexPredicateSql("session_events")), workspaceTurnType: index("session_events_workspace_turn_type_idx") .on(table.workspaceId, table.turnId, table.type) .where(sql`${table.turnId} is not null`), usageSourceKey: index("session_events_usage_source_key_idx") .on(table.workspaceId, table.turnId, table.usageSourceKey) .where(sql`${table.usageSourceKey} is not null`), modelFactPage: index("session_events_model_fact_page_idx") .on(table.workspaceId, table.sessionId, table.turnId, table.occurredAt, table.id) .where(sql`${table.type} = 'agent.model.usage'`), commandOutputPage: index("session_events_command_output_page_idx") .on( table.workspaceId, table.sessionId, sql`(${table.payload} ->> 'commandId')`, table.sequence, ) .where(sql`${table.type} = 'sandbox.command.output.delta'`), // Command output paging under row-level security (migration 0788). Every // output chunk's client event id starts with `command-output::`; // byte-order text comparisons are leakproof, so a policy-bound reader can // bound the scan to one command and the cursor. The JSON key above cannot: // `->>` is not leakproof, so policies demote it to a per-row filter. commandOutputClient: index("session_events_command_output_client_idx") .on( table.workspaceId, table.sessionId, sql`${table.clientEventId} collate "C"`, table.sequence, ) .where(sql`${table.type} = 'sandbox.command.output.delta'`), monitoringTail: index("session_events_workspace_session_monitoring_tail_idx") .on(table.workspaceId, table.sessionId, table.sequence) .where( sql`${table.type} not in ('agent.message.delta', 'agent.reasoning.delta', 'sandbox.command.output.delta', 'terminal.pty.output.delta')`, ), duplicateOfEvent: index("session_events_duplicate_of_event_idx").on(table.duplicateOfEventId), typeBytes: check( "session_events_type_bytes_check", sql`octet_length(${table.type}) <= 256 and position(E'\n' in ${table.type}) = 0 and position(E'\r' in ${table.type}) = 0`, ), clientEventIdBytes: check( "session_events_client_event_id_bytes_check", sql`${table.clientEventId} is null or octet_length(${table.clientEventId}) <= 1024`, ), producerIdBytes: check( "session_events_producer_id_bytes_check", sql`${table.producerId} is null or octet_length(${table.producerId}) <= 1024`, ), turnAssociationBytes: check( "session_events_turn_association_bytes_check", sql`${table.turnAssociation} is null or octet_length(${table.turnAssociation}) <= 64`, ), duplicateReasonBytes: check( "session_events_duplicate_reason_bytes_check", sql`${table.duplicateReason} is null or octet_length(${table.duplicateReason}) <= 4096`, ), }), ); /** * Where the wall time of one finished logical turn went (migration 1351). * Computed from the session event log by a control maintenance sweep after * the turn settles, never on the turn's own path. The `*_ms` segments are * exclusive and add up to `wall_ms`; `steps` lists model requests, tool * calls, sandbox operations and waits with their start, end and duration. * Dimensions are frozen copies of the turn row. Rows outlive the turn's raw * events (which an idle archive may purge) and go with the turn. */ export const turnTimingProfiles = pgTable( "turn_timing_profiles", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), version: integer("version").notNull(), status: text("status").notNull(), model: text("model").notNull(), provider: text("provider"), reasoningEffort: text("reasoning_effort").notNull(), latencyMode: text("latency_mode").notNull(), surface: text("surface"), source: text("source").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull(), startedAt: timestamp("started_at", { withTimezone: true }), finishedAt: timestamp("finished_at", { withTimezone: true }).notNull(), wallMs: bigint("wall_ms", { mode: "number" }).notNull(), queueMs: bigint("queue_ms", { mode: "number" }).notNull(), turnStartMs: bigint("turn_start_ms", { mode: "number" }).notNull(), dispatchMs: bigint("dispatch_ms", { mode: "number" }).notNull(), modelInferenceMs: bigint("model_inference_ms", { mode: "number" }).notNull(), modelProviderOtherMs: bigint("model_provider_other_ms", { mode: "number" }).notNull(), modelNetworkMs: bigint("model_network_ms", { mode: "number" }).notNull(), modelUnsplitMs: bigint("model_unsplit_ms", { mode: "number" }).notNull(), modelStalledMs: bigint("model_stalled_ms", { mode: "number" }).notNull(), compactionMs: bigint("compaction_ms", { mode: "number" }).notNull().default(0), webSearchMs: bigint("web_search_ms", { mode: "number" }).notNull(), mcpToolMs: bigint("mcp_tool_ms", { mode: "number" }).notNull(), sandboxToolMs: bigint("sandbox_tool_ms", { mode: "number" }).notNull(), ownToolMs: bigint("own_tool_ms", { mode: "number" }).notNull(), sandboxSetupMs: bigint("sandbox_setup_ms", { mode: "number" }).notNull(), humanWaitMs: bigint("human_wait_ms", { mode: "number" }).notNull(), capacityWaitMs: bigint("capacity_wait_ms", { mode: "number" }).notNull(), afterModelMs: bigint("after_model_ms", { mode: "number" }).notNull(), afterToolMs: bigint("after_tool_ms", { mode: "number" }).notNull(), recoveryMs: bigint("recovery_ms", { mode: "number" }).notNull(), turnEndMs: bigint("turn_end_ms", { mode: "number" }).notNull(), attempts: integer("attempts").notNull(), modelRequests: integer("model_requests").notNull(), toolCalls: integer("tool_calls").notNull(), steps: jsonb("steps").$type().notNull(), computedAt: timestamp("computed_at", { withTimezone: true }) .notNull() .default(sql`statement_timestamp()`), }, (table) => ({ pk: primaryKey({ columns: [table.workspaceId, table.turnId] }), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], name: "turn_timing_profiles_workspace_account_fk", }).onDelete("cascade"), workspaceTurn: foreignKey({ columns: [table.workspaceId, table.turnId], foreignColumns: [sessionTurns.workspaceId, sessionTurns.id], name: "turn_timing_profiles_workspace_turn_fk", }).onDelete("cascade"), workspaceFinished: index("turn_timing_profiles_workspace_finished_idx").on( table.workspaceId, table.finishedAt, ), finished: index("turn_timing_profiles_finished_idx").on(table.finishedAt), stepsArray: check( "turn_timing_profiles_steps_array_chk", sql`jsonb_typeof(${table.steps}) = 'array'`, ), }), ); /** * Durable fanout obligation for the migration-owned automatic-title * quarantine event. The deployment-wide workflow-wake dispatcher publishes * these exact committed events and marks them delivered; duplicate publication * after a process crash is safe because consumers sequence-fence every event. */ export const automaticSessionTitleFanoutOutboxV1 = opengeniPrivateSchema.table( "automatic_session_title_fanout_outbox_v1", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), eventId: uuid("event_id").notNull(), attempts: integer("attempts").notNull().default(0), lastError: text("last_error"), deliveredAt: timestamp("delivered_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ attemptsValid: check("automatic_title_fanout_attempts_chk", sql`${table.attempts} >= 0`), workspaceAccount: foreignKey({ name: "automatic_title_fanout_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "automatic_title_fanout_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), workspaceEvent: foreignKey({ name: "automatic_title_fanout_workspace_event_fk", columns: [table.workspaceId, table.eventId], foreignColumns: [sessionEvents.workspaceId, sessionEvents.id], }).onDelete("cascade"), event: uniqueIndex("automatic_title_fanout_event_uq").on(table.eventId), pending: index("automatic_title_fanout_pending_idx") .on(table.createdAt, table.id) .where(sql`${table.deliveredAt} is null`), }), ); /** * Searchable text of each user and completed assistant message, written only * by the invoker-rights AFTER INSERT trigger on session_events (admitted as an * exact mirror of a visible message event). Its * row-security policies are the search: rows are visible only while the * transaction's `opengeni.session_message_search_pattern` matches them (or the * text is losslessly encoded), so the trigram index can serve the pattern * under FORCE RLS. See docs/session-message-search.md. */ export const sessionMessageSearchTexts = pgTable( "session_message_search_texts", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), sequence: integer("sequence").notNull(), encoded: boolean("encoded").notNull(), text: text("text").notNull(), }, (table) => ({ pk: primaryKey({ name: "session_message_search_texts_pkey", columns: [table.workspaceId, table.sessionId, table.sequence], }), workspaceEvent: foreignKey({ name: "session_message_search_texts_event_fk", columns: [table.workspaceId, table.sessionId, table.sequence], foreignColumns: [sessionEvents.workspaceId, sessionEvents.sessionId, sessionEvents.sequence], }).onDelete("cascade"), encodedText: index("session_message_search_texts_encoded_idx") .on(table.workspaceId) .where(sql`${table.encoded}`), }), ); export const agentRunStates = pgTable("agent_run_states", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null", }), stateVersion: integer("state_version").notNull(), serializedRunState: losslessText("serialized_run_state").notNull(), serializedRunStateCodecVersion: losslessCodecVersion("serialized_run_state_codec_version"), pendingApprovals: losslessJsonb("pending_approvals").$type().notNull().default([]), pendingApprovalsCodecVersion: losslessCodecVersion("pending_approvals_codec_version"), // Exact provider rejection marks the latest current-turn receipt only when it // was part of the rejected request. The serialized receipt remains durable; // recovery builds a temporary view without unusable opaque artifacts. providerArtifactInvalidatedAt: timestamp("provider_artifact_invalidated_at", { withTimezone: true, }), providerArtifactInvalidationReason: text("provider_artifact_invalidation_reason"), providerArtifactInvalidatedByAttemptId: uuid("provider_artifact_invalidated_by_attempt_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }); // Durable structured human-input requests. The creation attempt is immutable // provenance; legitimate resume attempts are newer owners of the SAME logical // turn. Settlement therefore fences on the active session/turn plus the // request's turn generation, never on creationAttemptId. export const sessionHumanInputRequests = pgTable( "session_human_input_requests", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), turnGeneration: integer("turn_generation").notNull(), creationAttemptId: uuid("creation_attempt_id").notNull(), toolCallId: text("tool_call_id").notNull(), /** * `tool_call`: asked by the agent's `request_human_input`; its turn waits * and ends with it. `secret_use_approval` (0961): Opengeni's own card for * a blocked secret use (`tool_call_id` is `secret-approval:`); * the turn does not wait, and the card outlives the turn until answered. */ origin: text("origin").notNull().default("tool_call"), status: text("status").notNull().default("pending"), questions: jsonb("questions").$type().notNull(), allowSkip: boolean("allow_skip").notNull().default(false), response: jsonb("response").$type(), respondedBy: text("responded_by"), skillReviewHumanAuthorized: boolean("skill_review_human_authorized").notNull().default(false), /** With the agent that started this sub-agent, not yet the person (1553). */ heldForAgent: boolean("held_for_agent").notNull().default(false), respondedAt: timestamp("responded_at", { withTimezone: true }), expiresAt: timestamp("expires_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ creationAttemptOwner: foreignKey({ name: "session_human_input_requests_creation_attempt_fk", columns: [ table.accountId, table.workspaceId, table.sessionId, table.turnId, table.creationAttemptId, ], foreignColumns: [ sessionTurnAttempts.accountId, sessionTurnAttempts.workspaceId, sessionTurnAttempts.sessionId, sessionTurnAttempts.turnId, sessionTurnAttempts.id, ], }).onDelete("cascade"), toolCall: uniqueIndex("session_human_input_requests_tool_call_uq").on( table.workspaceId, table.sessionId, table.turnId, table.toolCallId, ), pendingSession: index("session_human_input_requests_pending_session_idx") .on(table.workspaceId, table.sessionId, table.createdAt, table.id) .where(sql`${table.status} = 'pending'`), pendingExpiry: index("session_human_input_requests_pending_expiry_idx") .on(table.expiresAt, table.id) .where(sql`${table.status} = 'pending' and ${table.expiresAt} is not null`), status: check( "session_human_input_requests_status_check", sql`${table.status} in ('pending','answered','skipped','expired','cancelled')`, ), origin: check( "session_human_input_requests_origin_check", sql`${table.origin} in ('tool_call','secret_use_approval')`, ), generation: check( "session_human_input_requests_generation_check", sql`${table.turnGeneration} > 0`, ), toolCallBytes: check( "session_human_input_requests_tool_call_bytes_check", sql`octet_length(${table.toolCallId}) between 1 and 1024`, ), questionsBytes: check( "session_human_input_requests_questions_bytes_check", sql`octet_length(${table.questions}::text) <= 49152`, ), responseBytes: check( "session_human_input_requests_response_bytes_check", sql`${table.response} is null or octet_length(${table.response}::text) <= 49152`, ), actorBytes: check( "session_human_input_requests_actor_bytes_check", sql`${table.respondedBy} is null or octet_length(${table.respondedBy}) <= 1024`, ), }), ); // Conversation truth: ordered, verbatim SDK input items (issue #35). The // model-facing memory store — exact and replay-ready. session_events is also // exact canonical Opengeni data; transport projections must not rewrite it. export const sessionHistoryItems = pgTable( "session_history_items", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null", }), // Numeric (not integer) so the synthetic compaction-summary row can be // inserted at a FRACTIONAL position (boundaryPosition - 0.5) that sorts ahead // of the kept tail without colliding with — and thus overwriting — the real // prefix row at boundaryPosition - 1. Normally-appended rows keep whole-number // positions; only the summary uses the half-step. `mode: "number"` maps the // postgres.js string back to a JS number so every reader stays numeric. position: numeric("position", { mode: "number" }).notNull(), item: losslessOrderedJson("item_ordered").$type>().notNull(), itemCodecVersion: losslessCodecVersion("item_codec_version"), // Live-row flag for client-side context compaction. The read path selects // only active rows; a compaction supersedes the summarized prefix (sets this // false — never deletes, so the full transcript stays as an audit trail) and // inserts ONE synthetic active summary row at the boundary. Defaults true so // every existing and normally-appended row is live. active: boolean("active").notNull().default(true), // An exact provider 400 can prove that the request's active opaque artifact // set is no longer usable. Keep each canonical item immutable, but record the // attempt-fenced rejection on the exact candidate row IDs so later model // reads build a temporary projection. No FK: the receipt must outlive // operational attempt retention. providerArtifactInvalidatedAt: timestamp("provider_artifact_invalidated_at", { withTimezone: true, }), providerArtifactInvalidationReason: text("provider_artifact_invalidation_reason"), providerArtifactInvalidatedByAttemptId: uuid("provider_artifact_invalidated_by_attempt_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ positionIdx: uniqueIndex("session_history_items_position_idx").on( table.workspaceId, table.sessionId, table.position, ), // Receipt proofs page newest-first within one turn, not the whole session. turnPositionIdx: index("session_history_items_turn_position_idx") .on(table.turnId, table.position) .where(sql`${table.turnId} IS NOT NULL`), scopeTurnPositionIdx: index("session_history_items_scope_turn_position_idx") .on(table.workspaceId, table.sessionId, table.turnId, table.position) .where(sql`${table.turnId} IS NOT NULL`), }), ); // Turn-lineage ledger for a tool call that the SDK emitted but has not yet // produced a durably reconciled result. The raw call item is model-facing truth // (not a transport projection). The attempt/generation identify // where the call originated, but the receipt survives an approval resume into a // newer attempt of the same logical turn. Turn-ending transactions // consume these rows atomically and append a valid interrupted result so a // recovered model sees an explicit unknown outcome instead of a silently // dropped call. export const sessionPendingToolCalls = pgTable( "session_pending_tool_calls", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), turnId: uuid("turn_id") .notNull() .references(() => sessionTurns.id, { onDelete: "cascade" }), executionGeneration: integer("execution_generation").notNull(), attemptId: uuid("attempt_id").notNull(), callId: text("call_id").notNull(), callType: text("call_type").notNull(), callItem: losslessOrderedJson("call_item_ordered").$type>().notNull(), callItemCodecVersion: losslessCodecVersion("call_item_codec_version"), interruptionKind: text("interruption_kind"), tiedReasoningItems: losslessOrderedJson("tied_reasoning_items_ordered") .$type>>() .notNull() .default([]), tiedReasoningItemsCodecVersion: losslessCodecVersion("tied_reasoning_items_codec_version"), modelToolOutputTruncationTokens: integer("model_tool_output_truncation_tokens"), resultItem: losslessOrderedJson("result_item_ordered").$type>(), resultItemCodecVersion: losslessCodecVersion("result_item_codec_version"), eventOutput: losslessJsonb("event_output").$type(), eventOutputCodecVersion: losslessCodecVersion("event_output_codec_version"), resultRecordedAt: timestamp("result_recorded_at", { withTimezone: true }), /** Private state of an MCP server question that paused this call; never in events. */ mcpInputRequest: jsonb("mcp_input_request").$type>(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAttempt: foreignKey({ name: "pending_tool_calls_workspace_attempt_fk", columns: [table.workspaceId, table.attemptId], foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id], }).onDelete("restrict"), turnCall: uniqueIndex("session_pending_tool_calls_turn_call_idx").on( table.workspaceId, table.turnId, table.callId, ), sessionTurn: index("session_pending_tool_calls_session_turn_idx").on( table.workspaceId, table.sessionId, table.turnId, ), interruptionKindValid: check( "session_pending_tool_calls_interruption_kind_chk", sql`${table.interruptionKind} is null or ${table.interruptionKind} in ('human_input', 'approval', 'interaction_intervention')`, ), tiedReasoningItemsArray: check( "session_pending_tool_calls_tied_reasoning_items_chk", sql`jsonb_typeof(${table.tiedReasoningItems}) = 'array'`, ), }), ); // Sandbox recovery descriptor, decoupled from the RunState blob: the small // versioned envelope (provider handle / snapshot ref / manifest) needed to // reattach, restore, or rebuild the session's sandbox on its next turn. export const sandboxSessionEnvelopes = pgTable( "sandbox_session_envelopes", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), envelope: losslessJsonb("envelope").$type>().notNull(), envelopeCodecVersion: losslessCodecVersion("envelope_codec_version"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ sessionIdx: uniqueIndex("sandbox_session_envelopes_session_idx").on( table.workspaceId, table.sessionId, ), }), ); export const sandboxCheckpointArtifactStateValues = [ "candidate", "current", "previous", "delete_pending", "deleting", "delete_failed", "deleted", ] as const; /** * Durable ownership ledger for provider-native workspace checkpoints. These * rows intentionally have no cascading parent FK: a workspace/lease can vanish * before the provider object is deleted, and global GC still needs the exact * non-secret provider binding and object id after that deletion. */ export const sandboxCheckpointArtifacts = pgTable( "sandbox_checkpoint_artifacts", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sandboxGroupId: uuid("sandbox_group_id").notNull(), sourceLeaseId: uuid("source_lease_id").notNull(), sourceLeaseEpoch: integer("source_lease_epoch").notNull(), sourceInstanceId: text("source_instance_id"), sourceWorkspaceGeneration: integer("source_workspace_generation"), provenance: text("provenance", { enum: ["native_capture", "legacy_provider_adopted"], }).notNull(), providerBackend: text("provider_backend").notNull(), providerBindingKey: text("provider_binding_key").notNull(), providerBinding: jsonb("provider_binding").$type>().notNull(), objectKind: text("object_kind", { enum: ["modal_filesystem_snapshot", "modal_directory_snapshot"], }).notNull(), objectId: text("object_id").notNull(), archiveBase64: text("archive_base64").notNull(), archiveSha256: text("archive_sha256").notNull(), archiveBytes: integer("archive_bytes").notNull(), descriptor: jsonb("descriptor").$type>().notNull(), descriptorRevision: text("descriptor_revision").notNull(), state: text("state", { enum: sandboxCheckpointArtifactStateValues }) .notNull() .default("candidate"), deleteAfter: timestamp("delete_after", { withTimezone: true }), deleteAttempts: integer("delete_attempts").notNull().default(0), deleteClaimId: uuid("delete_claim_id"), deleteClaimedAt: timestamp("delete_claimed_at", { withTimezone: true }), lastDeleteError: text("last_delete_error"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), publishedAt: timestamp("published_at", { withTimezone: true }), deletedAt: timestamp("deleted_at", { withTimezone: true }), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ providerObject: uniqueIndex("sandbox_checkpoint_artifacts_provider_object_uq").on( table.providerBackend, table.providerBindingKey, table.objectId, ), gc: index("sandbox_checkpoint_artifacts_gc_idx") .on(table.deleteAfter, table.createdAt, table.id) .where( sql`${table.state} in ( 'candidate', 'current', 'previous', 'delete_pending', 'delete_failed', 'deleting' )`, ), source: index("sandbox_checkpoint_artifacts_source_idx").on( table.workspaceId, table.sandboxGroupId, table.sourceLeaseId, ), sourceValid: check( "sandbox_checkpoint_artifacts_source_check", sql`${table.sourceLeaseEpoch} >= 0 and ( ( ${table.provenance} = 'native_capture' and ${table.sourceWorkspaceGeneration} is not null and ${table.sourceWorkspaceGeneration} >= 0 and ${table.sourceInstanceId} is not null and octet_length(${table.sourceInstanceId}) between 1 and 512 ) or ( ${table.provenance} = 'legacy_provider_adopted' and ${table.sourceWorkspaceGeneration} is null and ${table.sourceInstanceId} is null ) )`, ), providerValid: check( "sandbox_checkpoint_artifacts_provider_check", sql`${table.providerBackend} = 'modal' and octet_length(${table.providerBindingKey}) between 1 and 1024 and jsonb_typeof(${table.providerBinding}) = 'object' and ${table.providerBindingKey}::jsonb = ${table.providerBinding} and ${table.objectKind} in ('modal_filesystem_snapshot', 'modal_directory_snapshot') and octet_length(${table.objectId}) between 1 and 1024`, ), archiveValid: check( "sandbox_checkpoint_artifacts_archive_check", sql`${table.archiveBytes} > 0 and octet_length(${table.archiveBase64}) > 0 and ${table.archiveSha256} ~ '^[0-9a-f]{64}$' and jsonb_typeof(${table.descriptor}) = 'object' and octet_length(${table.descriptorRevision}) between 1 and 256`, ), stateValid: check( "sandbox_checkpoint_artifacts_state_check", sql`${table.state} in ( 'candidate', 'current', 'previous', 'delete_pending', 'deleting', 'delete_failed', 'deleted' )`, ), deleteClaimValid: check( "sandbox_checkpoint_artifacts_delete_claim_check", sql`(${table.state} = 'deleting' and ${table.deleteClaimId} is not null and ${table.deleteClaimedAt} is not null) or (${table.state} <> 'deleting' and ${table.deleteClaimId} is null and ${table.deleteClaimedAt} is null)`, ), }), ); // The 4 liveness states of the singleton lease. Exported so the query layer and // the stateless resume-by-id path share one source of truth for the domain. export const sandboxLeaseLivenessValues = ["cold", "warming", "warm", "draining"] as const; // One row per GROUP: the SOLE enforcer of the strict-singleton-box invariant. // uniqueIndex(workspaceId, sandboxGroupId) + SELECT…FOR UPDATE + cold->warming // CAS + integer lease_epoch fence. Re-keyed to sandboxGroupId from the start // (addendum B.2) so today's 1:1 world (sandboxGroupId == session id, set in // 0018) is a behavior-preserving no-op. Mirrors the account/workspace FK chain // of sandboxSessionEnvelopes; sandboxGroupId is a BARE uuid (NOT an FK — the // value is a session id or an ancestor's, and an FK would let a founder's // deletion cascade-kill a box still in use by a spawned session). export const sandboxLeases = pgTable( "sandbox_leases", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sandboxGroupId: uuid("sandbox_group_id").notNull(), publicRecovery: jsonb("public_recovery").$type>(), providerCreateAttempt: jsonb("provider_create_attempt").$type>(), providerCreateRecoveryAfter: timestamp("provider_create_recovery_after", { withTimezone: true, }), unobservableCommandDrainIds: uuid("unobservable_command_drain_ids").array(), unobservableCommandCheckedAt: timestamp("unobservable_command_checked_at", { withTimezone: true, }), // Stamped by a database trigger (0547) whenever the holder counters change, // for every writer generation. Idle command containment measures holder // release from this durable fact. holdersChangedAt: timestamp("holders_changed_at", { withTimezone: true }) .notNull() .defaultNow(), // Why an enrolled drain contains its commands (0547); cleared with the // enrollment. Null for a pre-0547 enrollment: settle with neutral wording. commandContainmentReason: text("command_containment_reason", { enum: ["idle_containment", "provider_deadline_containment", "quiescence_containment"], }), liveness: text("liveness", { enum: sandboxLeaseLivenessValues }).notNull().default("cold"), refcount: integer("refcount").notNull().default(0), turnHolders: integer("turn_holders").notNull().default(0), viewerHolders: integer("viewer_holders").notNull().default(0), // Admission elected this box for an unpaid organization (unpaid tier, no // paid history): it counts toward the fleet limits (1486). computeUnpaid: boolean("compute_unpaid"), instanceId: text("instance_id"), backend: text("backend").notNull(), os: text("os").notNull().default("linux"), // The container IMAGE the group box runs (Modal image ref / docker image). A shared // box is SHARED STATE: all its sessions run the SAME filesystem, so they must run the // same image. This column stamps the image the live box was created with; a resume // whose resolved image DIFFERS is a conflict (B3): a solo holder requests a // capture-and-drain rotation; N-holders are rejected (SandboxImageConflictError). Nullable — a // legacy/cold row reads NULL = "image unknown", which never conflicts. image: text("image"), // The frozen rig version the live box was created under (M3). Like `image`, // this is SHARED STATE: all the box's sessions run the same rig-baked setup, // so a resume resolving a DIFFERENT rig_version_id conflicts (a solo holder // requests capture-and-drain rotation; N-holders throw SandboxRigConflictError). // Nullable — a legacy/cold row or a rig-less session reads NULL = "rig // unknown", which never conflicts. No FK (symmetric with sandbox_group_id's // bare-uuid rationale: this lease outlives no single rig_versions row's RLS). rigVersionId: uuid("rig_version_id"), dataPlaneUrl: text("data_plane_url"), // The REAL PTY terminal (ttyd pty-ws) rides a SEPARATE provider tunnel (7681) // from the desktop noVNC (6080), so its resolved URL is cached independently. // Recorded under the epoch fence by recordLeaseTerminalDataPlaneUrl; reset to // null on every box re-key (warm-commit / fail / drain), symmetric with // data_plane_url. terminalDataPlaneUrl: text("terminal_data_plane_url"), // Cached browserd HTTP/WebSocket tunnel (7682). Controller requests use // this epoch-fenced endpoint directly after the first provider resolution; // provider-handle coordination remains limited to lifecycle/provisioning. controllerDataPlaneUrl: text("controller_data_plane_url"), // integer (NOT bigint): the lease-epoch spike proved a raw int8 read returns a // JS STRING from postgres-js, breaking the strict epoch-fence comparison (it // was always-true → every turn fenced); int4 returns a JS number, the fix. // Epochs never approach 2^31, so the narrower type loses nothing. leaseEpoch: integer("lease_epoch").notNull().default(0), // Monotonic mutation intent for the live workspace. Every acknowledged // filesystem-writing operation advances this under the exact lease epoch + // provider-instance fence BEFORE it reaches the provider. A verified // archive fold copies the exact captured value into archive_generation in // the same row update; equality is the only durable completeness proof. workspaceGeneration: integer("workspace_generation").notNull().default(0), archiveGeneration: integer("archive_generation"), // Provider-native capture may pause the live box. The exact claim is // acquired before provider I/O and cleared only after that capture settles; // new holders and workspace mutations fence on it. operation_id is the // stable logical request across Temporal retries, while capture_id + attempt // identify the one callback currently allowed to publish/terminate. The SQL // constraint also requires the claimed generation to remain current, so an // unaware writer cannot advance generation through an active capture. archiveCaptureId: uuid("archive_capture_id"), archiveCaptureOperationId: uuid("archive_capture_operation_id"), archiveCaptureProviderRequestId: uuid("archive_capture_provider_request_id"), // True only when the provider contract guarantees that reusing // archiveCaptureProviderRequestId resumes the same physical capture. This is // deliberately explicit rather than inferred from backend/id equality so a // rolling old worker can never be mistaken for an idempotent caller. archiveCaptureProviderReplaySafe: boolean("archive_capture_provider_replay_safe") .notNull() .default(false), // Provider-neutral takeover proof. True means the registered adapter has // proven either same-request idempotency or an independently repeatable, // read-only capture. It is distinct from providerReplaySafe so portable tar // can recover immediately without pretending it resumes one provider RPC. archiveCaptureTakeoverSafe: boolean("archive_capture_takeover_safe").notNull().default(false), archiveCaptureAttempt: integer("archive_capture_attempt"), // Periodic capture cadence survives a failed claim's release and worker // restarts. This is not evidence that a recovery archive was published. archiveCaptureLastAttemptAt: timestamp("archive_capture_last_attempt_at", { withTimezone: true, }), // Consecutive settled drain snapshot failures of one lease epoch (migration // 1253). Valid only while drain_capture_failure_epoch equals lease_epoch, // so a new box starts from zero without every epoch writer resetting it. // Drives the drain retry backoff and the snapshot-failure alerts. drainCaptureFailures: integer("drain_capture_failures").notNull().default(0), drainCaptureFailureEpoch: integer("drain_capture_failure_epoch"), drainCaptureFirstFailedAt: timestamp("drain_capture_first_failed_at", { withTimezone: true, }), drainCaptureLastFailedAt: timestamp("drain_capture_last_failed_at", { withTimezone: true, }), // The reaper's idle checkpoint sweep last tried this box, whatever the // outcome, so refused or failing boxes yield the batch to others. idleCheckpointAttemptedAt: timestamp("idle_checkpoint_attempted_at", { withTimezone: true, }), // Earliest attach of a viewer or interaction (writers that bypass // generation admissions) not yet covered by a capture claimed with none // attached. Cleared by such a capture and when the lease epoch changes. untrackedWriterSince: timestamp("untracked_writer_since", { withTimezone: true, }), archiveCaptureGeneration: integer("archive_capture_generation"), archiveCaptureStartedAt: timestamp("archive_capture_started_at", { withTimezone: true, }), archiveCaptureDeadlineAt: timestamp("archive_capture_deadline_at", { withTimezone: true, }), // Set atomically with a verified draining archive publication. Once set, // the exact claim is an irreversible teardown receipt: a recovered worker // skips recapture and resumes provider termination. Warm capture clears its // claim in the publication write and therefore never retains this marker. archiveCapturePublishedAt: timestamp("archive_capture_published_at", { withTimezone: true, }), // The exact warm capture claim that ran around active background commands // (migration 0659). Equal to archive_capture_id only for that claim. archiveCaptureConcurrentCaptureId: uuid("archive_capture_concurrent_capture_id"), // Exact admissions a mandatory pre-deadline save may capture around and // settle after termination (migration 0676). deadlineForcedAdmissionIds: uuid("deadline_forced_admission_ids").array(), // Bounded operator preservation gate. Unlike rotation/capture, this blocks // only reaper teardown: a user may still re-arm a resumable draining lease. // The exact id makes renewal/release ownership explicit and race-safe. reaperHoldId: uuid("reaper_hold_id"), reaperHoldUntil: timestamp("reaper_hold_until", { withTimezone: true }), reaperHoldReason: text("reaper_hold_reason"), // The group box-envelope (the "envelope split" Critical): the small recovery // descriptor to resume()-by-id the group's box without a per-session join. resumeBackendId: text("resume_backend_id"), resumeState: jsonb("resume_state").$type>(), // Warm-time billing cursor: last_meter_at = accrual cursor; last_meter_tick = // idempotency tick (warm_seconds accrued idempotent on // (sandbox_group_id, lease_epoch, last_meter_tick) in P2.1). lastMeterAt: timestamp("last_meter_at", { withTimezone: true }), lastMeterTick: integer("last_meter_tick").notNull().default(0), providerCreatedAt: timestamp("provider_created_at", { withTimezone: true }), providerDeadlineAt: timestamp("provider_deadline_at", { withTimezone: true, }), rotationRequestedAt: timestamp("rotation_requested_at", { withTimezone: true, }), rotationReason: text("rotation_reason", { enum: ["provider_deadline", "operator", "teardown_claim"], }), // The reaper released this box's viewers because nobody used the page for // the viewer idle window (1477). A viewer attach that reports no newer // interaction is refused until a person or a turn uses the session again. viewerIdleDrainedAt: timestamp("viewer_idle_drained_at", { withTimezone: true }), // A chat or workspace deletion ended this compute lease's group: its // sandbox is deleted without a workspace capture (0861). groupEndRequestedAt: timestamp("group_end_requested_at", { withTimezone: true }), // The agent gateway reported the current compute sandbox asleep since then; // warm time does not accrue while it sleeps (0861). computeAsleepSince: timestamp("compute_asleep_since", { withTimezone: true }), // The agent gateway reported the current compute sandbox's host handing // it off since then; it may refuse wakes for a short while (1281). computeHandingOffSince: timestamp("compute_handing_off_since", { withTimezone: true }), // The SQL migration owns the two DEFERRABLE foreign keys and deferred // scope/state constraint triggers. Drizzle does not model deferrability, so // these remain bare UUIDs here rather than generating a stricter wrong FK. currentCheckpointArtifactId: uuid("current_checkpoint_artifact_id"), previousCheckpointArtifactId: uuid("previous_checkpoint_artifact_id"), // Durable single-flight for immutable machine setup (currently exact rig // setup only). Per-turn credentials, repositories, files, and cloud login // deliberately remain outside this lease-scoped receipt. sharedPreparationLeaseEpoch: integer("shared_preparation_lease_epoch"), sharedPreparationInstanceId: text("shared_preparation_instance_id"), sharedPreparationSpecHash: text("shared_preparation_spec_hash"), sharedPreparationStatus: text("shared_preparation_status", { enum: ["running", "completed", "failed"], }), sharedPreparationClaimId: uuid("shared_preparation_claim_id"), sharedPreparationOwnerAttemptId: uuid("shared_preparation_owner_attempt_id"), sharedPreparationAttempt: integer("shared_preparation_attempt"), sharedPreparationRevision: integer("shared_preparation_revision").notNull().default(0), sharedPreparationStartedAt: timestamp("shared_preparation_started_at", { withTimezone: true, }), sharedPreparationDeadlineAt: timestamp("shared_preparation_deadline_at", { withTimezone: true, }), sharedPreparationSettledAt: timestamp("shared_preparation_settled_at", { withTimezone: true, }), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ groupIdx: uniqueIndex("sandbox_leases_group_idx").on(table.workspaceId, table.sandboxGroupId), scopedId: uniqueIndex("sandbox_leases_scoped_id_uq").on( table.accountId, table.workspaceId, table.sandboxGroupId, table.id, ), accountWorkspaceId: uniqueIndex("sandbox_leases_account_workspace_id_uq").on( table.accountId, table.workspaceId, table.id, ), reaperIdx: index("sandbox_leases_reaper_idx") .on(table.expiresAt) .where(sql`${table.liveness} in ('warming','warm','draining')`), expiredDrainingInventory: index("sandbox_leases_expired_draining_inventory_idx") .on(table.expiresAt, table.backend) .where(sql`${table.liveness} = 'draining'`), providerDeadline: index("sandbox_leases_provider_deadline_idx") .on(table.providerDeadlineAt, table.id) .where( sql`${table.backend} = 'modal' and ${table.liveness} in ('warming', 'warm') and ${table.rotationRequestedAt} is null`, ), workspaceGenerationValid: check( "sandbox_leases_workspace_generation_check", sql`${table.workspaceGeneration} >= 0`, ), archiveGenerationValid: check( "sandbox_leases_archive_generation_check", sql`${table.archiveGeneration} is null or (${table.archiveGeneration} >= 0 and ${table.archiveGeneration} <= ${table.workspaceGeneration})`, ), archiveCaptureValid: check( "sandbox_leases_archive_capture_check", sql`( ${table.archiveCaptureId} is null and ${table.archiveCaptureOperationId} is null and ${table.archiveCaptureProviderRequestId} is null and ${table.archiveCaptureProviderReplaySafe} = false and ${table.archiveCaptureTakeoverSafe} = false and ${table.archiveCaptureAttempt} is null and ${table.archiveCaptureGeneration} is null and ${table.archiveCaptureStartedAt} is null and ${table.archiveCaptureDeadlineAt} is null and ${table.archiveCapturePublishedAt} is null ) or ( ${table.archiveCaptureId} is not null and ${table.archiveCaptureOperationId} is not null and ${table.archiveCaptureProviderRequestId} is not null and ( ${table.archiveCaptureProviderReplaySafe} = false or ${table.archiveCaptureTakeoverSafe} = true ) and ${table.archiveCaptureAttempt} is not null and ${table.archiveCaptureAttempt} > 0 and ${table.archiveCaptureGeneration} is not null and ${table.archiveCaptureGeneration} = ${table.workspaceGeneration} and ${table.archiveCaptureStartedAt} is not null and ${table.archiveCaptureDeadlineAt} is not null and ${table.archiveCaptureDeadlineAt} > ${table.archiveCaptureStartedAt} and ( ${table.archiveCapturePublishedAt} is null or ${table.liveness} = 'draining' ) )`, ), archiveCaptureDeadline: index("sandbox_leases_archive_capture_deadline_idx") .on(table.archiveCaptureDeadlineAt, table.id) .where(sql`${table.archiveCaptureId} is not null`), reaperHoldValid: check( "sandbox_leases_reaper_hold_check", sql`( ${table.reaperHoldId} is null and ${table.reaperHoldUntil} is null and ${table.reaperHoldReason} is null ) or ( ${table.reaperHoldId} is not null and ${table.reaperHoldUntil} is not null and ${table.reaperHoldReason} is not null and length(${table.reaperHoldReason}) between 1 and 500 )`, ), providerDeadlineValid: check( "sandbox_leases_provider_deadline_check", sql`(${table.providerCreatedAt} is null and ${table.providerDeadlineAt} is null) or (${table.providerCreatedAt} is not null and ${table.providerDeadlineAt} is not null and ${table.providerDeadlineAt} > ${table.providerCreatedAt})`, ), rotationValid: check( "sandbox_leases_rotation_check", sql`(${table.rotationRequestedAt} is null and ${table.rotationReason} is null) or (${table.rotationRequestedAt} is not null and ${table.rotationReason} is not null and ${table.rotationReason} in ('provider_deadline', 'operator', 'teardown_claim'))`, ), checkpointDistinct: check( "sandbox_leases_checkpoint_distinct_check", sql`${table.currentCheckpointArtifactId} is null or ${table.previousCheckpointArtifactId} is null or ${table.currentCheckpointArtifactId} <> ${table.previousCheckpointArtifactId}`, ), }), ); // N rows per group: one per live holder. Makes release idempotent // (delete-my-row, never blind decrement) and lets the reaper recompute refcount. export const sandboxLeaseHolders = pgTable( "sandbox_lease_holders", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), leaseId: uuid("lease_id") .notNull() .references(() => sandboxLeases.id, { onDelete: "cascade" }), kind: text("kind", { enum: ["turn", "viewer", "direct", "process", "interaction"], }).notNull(), holderId: text("holder_id").notNull(), // The attributing session within the (possibly shared) group. subjectId: uuid("subject_id"), // Viewer holders only (0281): the authenticated viewer subject and the // session authority epoch observed at attach - identities and epochs // only, mirrored into the scoped stream token's claims. viewerSubjectId: text("viewer_subject_id"), viewerAuthorityEpoch: integer("viewer_authority_epoch"), lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true }).notNull().defaultNow(), // Viewer holders only (1476): the last real user interaction the viewer // reported on a heartbeat. Null when never reported (older clients). lastInteractionAt: timestamp("last_interaction_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ leaseScope: foreignKey({ name: "sandbox_lease_holders_lease_scope_fk", columns: [table.accountId, table.workspaceId, table.leaseId], foreignColumns: [sandboxLeases.accountId, sandboxLeases.workspaceId, sandboxLeases.id], }).onDelete("cascade"), holderIdx: uniqueIndex("sandbox_lease_holders_holder_idx").on( table.leaseId, table.kind, table.holderId, ), staleIdx: index("sandbox_lease_holders_stale_idx").on(table.kind, table.lastHeartbeatAt), leaseIdx: index("sandbox_lease_holders_lease_idx").on(table.leaseId), }), ); export const sandboxWorkspaceMutationActorKindValues = ["turn", "direct", "process"] as const; export const sandboxWorkspaceMutationHolderKindValues = ["turn", "direct", "process"] as const; // The causal principal behind an admitted workspace writer. `subject`/`service` // are the canonical `session_turns` initiator vocabulary; `legacy_unattributed` // exists only for rows written before migration 0277 recorded any authority. export const sandboxWorkspaceMutationInitiatorKindValues = [ "subject", "service", "legacy_unattributed", ] as const; // Durable admission ledger for every provider operation that may mutate a // persistable /workspace. The row is inserted atomically with the lease's // workspace_generation increment before the provider is invoked, then marked // physically settled after the provider promise resolves OR rejects. Capture // remains blocked by an unsettled direct/process row. A turn row may cease // blocking only after its exact attempt carries the authoritative quiesced_at // receipt. Yielded provider processes remain retained/unsettled until exact // exit or loss proof settles their parent admission. export const sandboxWorkspaceMutationAdmissions = pgTable( "sandbox_workspace_mutation_admissions", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), leaseId: uuid("lease_id") .notNull() .references(() => sandboxLeases.id, { onDelete: "cascade" }), sandboxGroupId: uuid("sandbox_group_id").notNull(), sessionId: uuid("session_id").notNull(), actorKind: text("actor_kind", { enum: sandboxWorkspaceMutationActorKindValues, }).notNull(), actorId: uuid("actor_id").notNull(), // Exact turn authority is present only for actor_kind='turn'. Direct HTTP // requests and retained processes never invent a turn or quiescence owner. turnId: uuid("turn_id"), attemptId: uuid("attempt_id"), executionGeneration: integer("execution_generation"), holderKind: text("holder_kind", { enum: sandboxWorkspaceMutationHolderKindValues, }).notNull(), holderId: text("holder_id").notNull(), leaseEpoch: integer("lease_epoch").notNull(), providerBackend: text("provider_backend").notNull(), providerInstanceId: text("provider_instance_id").notNull(), routeKind: text("route_kind", { enum: ["home", "active"] }).notNull(), // null route target means the persistable home/group provider. A non-null // target is pinned together with the active pointer epoch observed when the // operation was admitted. routeTargetId: uuid("route_target_id"), routeEpoch: integer("route_epoch").notNull(), workspaceGeneration: integer("workspace_generation").notNull(), operation: text("operation").notNull(), // Exact authority admitted with this operation (migration 0277). Identities // and epochs only, never a secret value. `legacy_unattributed` marks a // pre-0277 `direct`/`process` row whose authority was never recorded; a // post-0277 writer never produces it and new admission refuses it. initiatorKind: text("initiator_kind", { enum: sandboxWorkspaceMutationInitiatorKindValues, }) .notNull() .default("legacy_unattributed"), initiatorSubjectId: text("initiator_subject_id").notNull().default("unattributed-legacy"), initiatingHumanSubjectId: text("initiating_human_subject_id"), // The grant identity that authorized the causal human, plus the // authorization revision observed at admission. The revision is audit // evidence: a role change is not a revocation and must not fence a writer. initiatorOrganizationMembershipId: uuid("initiator_organization_membership_id"), initiatorAuthorizationRevision: bigint("initiator_authorization_revision", { mode: "number", }), // Session tenancy authority observed when the operation was admitted; the // same triple `session_turn_attempts` freezes for a turn. authorityEpoch: integer("authority_epoch"), authorityVisibility: text("authority_visibility", { enum: ["user_private", "workspace_shared"], }), authorityOwnerOrganizationMembershipId: uuid("authority_owner_organization_membership_id"), providerOutcome: text("provider_outcome", { enum: ["resolved", "rejected", "retained"], }), admittedAt: timestamp("admitted_at", { withTimezone: true }).notNull().defaultNow(), settledAt: timestamp("settled_at", { withTimezone: true }), }, (table) => ({ workspaceAccount: foreignKey({ name: "sandbox_workspace_mutation_admissions_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "sandbox_workspace_mutation_admissions_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("restrict"), workspaceTurn: foreignKey({ name: "sandbox_workspace_mutation_admissions_workspace_turn_fk", columns: [table.workspaceId, table.turnId], foreignColumns: [sessionTurns.workspaceId, sessionTurns.id], }).onDelete("restrict"), workspaceAttempt: foreignKey({ name: "sandbox_workspace_mutation_admissions_workspace_attempt_fk", columns: [table.workspaceId, table.attemptId], foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id], }).onDelete("restrict"), leaseGeneration: uniqueIndex("sandbox_workspace_mutation_admissions_lease_generation_uq").on( table.leaseId, table.workspaceGeneration, ), scopedId: uniqueIndex("sandbox_workspace_mutation_admissions_scoped_id_uq").on( table.accountId, table.workspaceId, table.sessionId, table.leaseId, table.id, ), blocking: index("sandbox_workspace_mutation_admissions_blocking_idx") .on(table.leaseId, table.workspaceGeneration) .where(sql`${table.settledAt} is null`), // Session-wide pending-writer checks start from this (normally empty) set // instead of probing every attempt the session ever ran (migration 0879). unsettledSession: index("sandbox_workspace_mutation_admissions_unsettled_session_idx") .on(table.workspaceId, table.sessionId) .where(sql`${table.settledAt} is null`), attempt: index("sandbox_workspace_mutation_admissions_attempt_idx").on( table.workspaceId, table.attemptId, ), actor: index("sandbox_workspace_mutation_admissions_actor_idx").on( table.workspaceId, table.actorKind, table.actorId, ), initiatorMembership: foreignKey({ name: "sandbox_workspace_mutation_admissions_initiator_membership_fk", columns: [table.initiatorOrganizationMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), authorityOwnerMembership: foreignKey({ name: "sandbox_workspace_mutation_admissions_authority_owner_fk", columns: [table.authorityOwnerOrganizationMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), initiator: index("sandbox_workspace_mutation_admissions_initiator_idx") .on(table.accountId, table.initiatorOrganizationMembershipId) .where(sql`${table.settledAt} is null`), initiatorValid: check( "sandbox_workspace_mutation_admissions_initiator_check", sql`( ${table.initiatorKind} = 'legacy_unattributed' and ${table.initiatorSubjectId} = 'unattributed-legacy' and ${table.initiatingHumanSubjectId} is null and ${table.initiatorOrganizationMembershipId} is null and ${table.initiatorAuthorizationRevision} is null ) or ( ${table.initiatorKind} in ('subject', 'service') and length(btrim(${table.initiatorSubjectId})) between 1 and 1024 and ${table.initiatorSubjectId} <> 'unattributed-legacy' and ( ${table.initiatingHumanSubjectId} is null or length(btrim(${table.initiatingHumanSubjectId})) between 1 and 1024 ) and ( ${table.initiatorOrganizationMembershipId} is null or ${table.initiatingHumanSubjectId} is not null ) and ( ${table.initiatorAuthorizationRevision} is null or ( ${table.initiatorAuthorizationRevision} > 0 and ${table.initiatorOrganizationMembershipId} is not null ) ) )`, ), tenancyValid: check( "sandbox_workspace_mutation_admissions_tenancy_check", sql`( ${table.authorityEpoch} is null and ${table.authorityVisibility} is null and ${table.authorityOwnerOrganizationMembershipId} is null ) or ( ${table.authorityEpoch} is not null and ${table.authorityVisibility} is not null and ${table.authorityEpoch} > 0 and ${table.authorityVisibility} in ('user_private', 'workspace_shared') and ( ${table.authorityVisibility} <> 'user_private' or ${table.authorityOwnerOrganizationMembershipId} is not null ) )`, ), generationValid: check( "sandbox_workspace_mutation_admissions_generation_check", sql`${table.workspaceGeneration} > 0 and ${table.leaseEpoch} >= 0 and ${table.routeEpoch} >= 0 and (${table.executionGeneration} is null or ${table.executionGeneration} > 0)`, ), actorValid: check( "sandbox_workspace_mutation_admissions_actor_check", sql`( ${table.actorKind} = 'turn' and ${table.actorId} = ${table.attemptId} and ${table.turnId} is not null and ${table.attemptId} is not null and ${table.executionGeneration} is not null and ${table.holderKind} = 'turn' ) or ( ${table.actorKind} = 'direct' and ${table.turnId} is null and ${table.attemptId} is null and ${table.executionGeneration} is null and ${table.holderKind} = 'direct' ) or ( ${table.actorKind} = 'process' and ${table.turnId} is null and ${table.attemptId} is null and ${table.executionGeneration} is null and ${table.holderKind} = 'process' )`, ), routeValid: check( "sandbox_workspace_mutation_admissions_route_check", sql`${table.actorKind} in ('turn', 'direct', 'process') and ${table.holderKind} in ('turn', 'direct', 'process') and octet_length(${table.holderId}) between 1 and 256 and octet_length(${table.providerBackend}) between 1 and 64 and octet_length(${table.providerInstanceId}) between 1 and 512 and ${table.routeKind} in ('home', 'active') and (${table.routeKind} = 'active' or ${table.routeTargetId} is null)`, ), operationValid: check( "sandbox_workspace_mutation_admissions_operation_check", sql`octet_length(${table.operation}) between 1 and 128`, ), outcomeValid: check( "sandbox_workspace_mutation_admissions_outcome_check", sql`${table.providerOutcome} is null or ${table.providerOutcome} in ('resolved', 'rejected', 'retained')`, ), settlementConsistent: check( "sandbox_workspace_mutation_admissions_settlement_check", sql`(${table.providerOutcome} is null and ${table.settledAt} is null) or (${table.providerOutcome} = 'retained' and ${table.settledAt} is null) or (${table.providerOutcome} in ('resolved', 'rejected') and ${table.settledAt} is not null)`, ), }), ); export const sandboxRetainedProcessStateValues = ["active", "exited", "lost"] as const; // A yielded exec is not merely a numeric provider session id: it is a durable // continuation of the exact admitted mutation and owns a non-TTL process lease // holder until exit/loss is proven. Every later model-facing stdin write gets a // distinct actor_kind='process' admission tied back to this identity. Control // polling may use the pinned provider route without creating a new generation. export const sandboxRetainedProcesses = pgTable( "sandbox_retained_processes", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), leaseId: uuid("lease_id").notNull(), sandboxGroupId: uuid("sandbox_group_id").notNull(), parentAdmissionId: uuid("parent_admission_id").notNull(), holderId: text("holder_id").notNull(), ownerActorKind: text("owner_actor_kind", { enum: ["turn", "direct"], }).notNull(), ownerActorId: uuid("owner_actor_id").notNull(), ownerTurnId: uuid("owner_turn_id"), ownerAttemptId: uuid("owner_attempt_id"), ownerExecutionGeneration: integer("owner_execution_generation"), leaseEpoch: integer("lease_epoch").notNull(), providerBackend: text("provider_backend").notNull(), providerInstanceId: text("provider_instance_id").notNull(), // Provider object ids are namespace-scoped. New Modal processes bind the // exact authenticated workspace before execution; legacy rows remain null // until a positive lookup proves which namespace owns the historical box. providerBindingKey: text("provider_binding_key"), providerBinding: jsonb("provider_binding").$type>(), routeKind: text("route_kind", { enum: ["home", "active"] }).notNull(), routeTargetId: uuid("route_target_id"), routeEpoch: integer("route_epoch").notNull(), providerSessionId: integer("provider_session_id").notNull(), providerCommand: jsonb("provider_command").$type(), supervisionRetentionXid: customType<{ data: string }>({ dataType: () => "xid8", })("supervision_retention_xid").default(sql`pg_current_xact_id()`), supervisionReceipt: jsonb("supervision_receipt").$type(), supervisionOutputCaptured: boolean("supervision_output_captured").notNull().default(false), cancellationRequestedAt: timestamp("cancellation_requested_at", { withTimezone: true }), cancellationReason: text("cancellation_reason"), deadlineCancellationRequestedAt: timestamp("deadline_cancellation_requested_at", { withTimezone: true, }), providerCommandInputIndex: bigint("provider_command_input_index", { mode: "number" }) .notNull() .default(0), // Authority frozen when the process was retained (migration 0277). A // `legacy_unattributed` process keeps running; only its next workspace // mutation is refused, because nothing may invent an owner for it. initiatorKind: text("initiator_kind", { enum: sandboxWorkspaceMutationInitiatorKindValues, }) .notNull() .default("legacy_unattributed"), initiatorSubjectId: text("initiator_subject_id").notNull().default("unattributed-legacy"), initiatingHumanSubjectId: text("initiating_human_subject_id"), initiatorOrganizationMembershipId: uuid("initiator_organization_membership_id"), initiatorAuthorizationRevision: bigint("initiator_authorization_revision", { mode: "number", }), authorityEpoch: integer("authority_epoch"), authorityVisibility: text("authority_visibility", { enum: ["user_private", "workspace_shared"], }), authorityOwnerOrganizationMembershipId: uuid("authority_owner_organization_membership_id"), state: text("state", { enum: sandboxRetainedProcessStateValues }).notNull().default("active"), exitCode: integer("exit_code"), settlementReason: text("settlement_reason"), startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(), settledAt: timestamp("settled_at", { withTimezone: true }), // Coordination state for bounded terminal-owner reconciliation. While a // claim is live, reconcileAfter is its expiry; otherwise it is the next // retry time. Becoming due only licenses an exact provider probe and is // never exit/loss proof. reconcileAfter: timestamp("reconcile_after", { withTimezone: true }).notNull().defaultNow(), reconcileClaimId: uuid("reconcile_claim_id"), reconcileClaimedAt: timestamp("reconcile_claimed_at", { withTimezone: true, }), reconcileAttempts: integer("reconcile_attempts").notNull().default(0), lastReconcileOutcome: text("last_reconcile_outcome"), reconcileProofOutcome: text("reconcile_proof_outcome", { enum: ["exited", "lost"], }), reconcileProofExitCode: integer("reconcile_proof_exit_code"), reconcileProofReason: text("reconcile_proof_reason"), reconcileProofObservedAt: timestamp("reconcile_proof_observed_at", { withTimezone: true, }), // The oldest reconciler that can reach this process (migration 0840). // Docker and local commands under the in-sandbox supervisor are 2: a // worker built before that supervisor would look for them in its own // memory and settle a live command as lost, so its claim skips them. reconcilerVersion: smallint("reconciler_version").notNull().default(1), }, (table) => ({ workspaceAccount: foreignKey({ name: "sandbox_retained_processes_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceSession: foreignKey({ name: "sandbox_retained_processes_workspace_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("restrict"), parentAdmissionScope: foreignKey({ name: "sandbox_retained_processes_parent_admission_scope_fk", columns: [ table.accountId, table.workspaceId, table.sessionId, table.leaseId, table.parentAdmissionId, ], foreignColumns: [ sandboxWorkspaceMutationAdmissions.accountId, sandboxWorkspaceMutationAdmissions.workspaceId, sandboxWorkspaceMutationAdmissions.sessionId, sandboxWorkspaceMutationAdmissions.leaseId, sandboxWorkspaceMutationAdmissions.id, ], }).onDelete("restrict"), scopedId: uniqueIndex("sandbox_retained_processes_scoped_id_uq").on( table.accountId, table.workspaceId, table.sessionId, table.leaseId, table.id, ), parentAdmission: uniqueIndex("sandbox_retained_processes_parent_admission_uq").on( table.parentAdmissionId, ), liveProviderSession: uniqueIndex("sandbox_retained_processes_live_provider_session_uq") .on( table.leaseId, table.leaseEpoch, table.providerInstanceId, table.routeEpoch, table.providerSessionId, ) .where(sql`${table.state} = 'active'`), providerCommandValid: check( "sandbox_retained_processes_provider_command_chk", sql`${table.providerCommand} IS NULL OR (( ${table.providerBackend} = 'modal' AND jsonb_typeof(${table.providerCommand}) = 'object' AND ${table.providerCommand}->>'kind' IN ('modal-control-v1', 'modal-router-v1') AND ${table.providerCommand}->>'sandboxId' = ${table.providerInstanceId} AND length(${table.providerCommand}->>'taskId') > 0 AND length(${table.providerCommand}->>'execId') > 0 ) IS TRUE)`, ), providerInputIndexValid: check( "sandbox_retained_processes_provider_input_index_chk", sql`${table.providerCommandInputIndex} BETWEEN 0 AND 9007199254740991`, ), holder: uniqueIndex("sandbox_retained_processes_holder_uq").on(table.leaseId, table.holderId), active: index("sandbox_retained_processes_active_idx") .on(table.workspaceId, table.sessionId, table.startedAt) .where(sql`${table.state} = 'active'`), reconcileDue: index("sandbox_retained_processes_reconcile_due_idx") .on(table.reconcileAfter, table.startedAt, table.id) .where(sql`${table.state} = 'active'`), activeInventory: index("sandbox_retained_processes_active_inventory_idx") .on(table.ownerActorKind, table.workspaceId, table.ownerTurnId, table.ownerAttemptId) .where(sql`${table.state} = 'active'`), initiatorMembership: foreignKey({ name: "sandbox_retained_processes_initiator_membership_fk", columns: [table.initiatorOrganizationMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), authorityOwnerMembership: foreignKey({ name: "sandbox_retained_processes_authority_owner_fk", columns: [table.authorityOwnerOrganizationMembershipId, table.accountId], foreignColumns: [organizationMemberships.id, organizationMemberships.accountId], }).onDelete("restrict"), initiator: index("sandbox_retained_processes_initiator_idx") .on(table.accountId, table.initiatorOrganizationMembershipId) .where(sql`${table.state} = 'active'`), initiatingHuman: index("sandbox_retained_processes_initiating_human_idx") .on(table.accountId, table.initiatingHumanSubjectId) .where(sql`${table.state} = 'active'`), initiatorValid: check( "sandbox_retained_processes_initiator_check", sql`( ${table.initiatorKind} = 'legacy_unattributed' and ${table.initiatorSubjectId} = 'unattributed-legacy' and ${table.initiatingHumanSubjectId} is null and ${table.initiatorOrganizationMembershipId} is null and ${table.initiatorAuthorizationRevision} is null ) or ( ${table.initiatorKind} in ('subject', 'service') and length(btrim(${table.initiatorSubjectId})) between 1 and 1024 and ${table.initiatorSubjectId} <> 'unattributed-legacy' and ( ${table.initiatingHumanSubjectId} is null or length(btrim(${table.initiatingHumanSubjectId})) between 1 and 1024 ) and ( ${table.initiatorOrganizationMembershipId} is null or ${table.initiatingHumanSubjectId} is not null ) and ( ${table.initiatorAuthorizationRevision} is null or ( ${table.initiatorAuthorizationRevision} > 0 and ${table.initiatorOrganizationMembershipId} is not null ) ) )`, ), tenancyValid: check( "sandbox_retained_processes_tenancy_check", sql`( ${table.authorityEpoch} is null and ${table.authorityVisibility} is null and ${table.authorityOwnerOrganizationMembershipId} is null ) or ( ${table.authorityEpoch} is not null and ${table.authorityVisibility} is not null and ${table.authorityEpoch} > 0 and ${table.authorityVisibility} in ('user_private', 'workspace_shared') and ( ${table.authorityVisibility} <> 'user_private' or ${table.authorityOwnerOrganizationMembershipId} is not null ) )`, ), identityValid: check( "sandbox_retained_processes_identity_check", sql`${table.leaseEpoch} >= 0 and ${table.routeEpoch} >= 0 and ${table.providerSessionId} > 0 and octet_length(${table.holderId}) between 1 and 256 and octet_length(${table.providerBackend}) between 1 and 64 and octet_length(${table.providerInstanceId}) between 1 and 512 and (${table.routeKind} = 'active' or ${table.routeTargetId} is null)`, ), ownerValid: check( "sandbox_retained_processes_owner_check", sql`( ${table.ownerActorKind} = 'turn' and ${table.ownerActorId} = ${table.ownerAttemptId} and ${table.ownerTurnId} is not null and ${table.ownerAttemptId} is not null and ${table.ownerExecutionGeneration} > 0 ) or ( ${table.ownerActorKind} = 'direct' and ${table.ownerTurnId} is null and ${table.ownerAttemptId} is null and ${table.ownerExecutionGeneration} is null )`, ), settlementValid: check( "sandbox_retained_processes_settlement_check", sql`(${table.state} = 'active' and ${table.settledAt} is null and ${table.exitCode} is null) or (${table.state} = 'exited' and ${table.settledAt} is not null) or (${table.state} = 'lost' and ${table.settledAt} is not null and ${table.exitCode} is null)`, ), reasonValid: check( "sandbox_retained_processes_reason_check", sql`${table.settlementReason} is null or octet_length(${table.settlementReason}) between 1 and 512`, ), providerBindingValid: check( "sandbox_retained_processes_provider_binding_check", sql`( ${table.providerBindingKey} is null and ${table.providerBinding} is null ) or ( ${table.providerBackend} = 'modal' and octet_length(${table.providerBindingKey}) between 1 and 1024 and jsonb_typeof(${table.providerBinding}) = 'object' and ${table.providerBindingKey}::jsonb = ${table.providerBinding} and ${table.providerBindingKey} = format( '{"version":1,"serverUrl":%s,"workspaceName":%s,"environment":%s}', to_jsonb(${table.providerBinding} ->> 'serverUrl')::text, to_jsonb(${table.providerBinding} ->> 'workspaceName')::text, to_jsonb(${table.providerBinding} ->> 'environment')::text ) and ${table.providerBinding} = jsonb_build_object( 'version', 1, 'serverUrl', ${table.providerBinding} ->> 'serverUrl', 'workspaceName', ${table.providerBinding} ->> 'workspaceName', 'environment', ${table.providerBinding} ->> 'environment' ) and coalesce(octet_length(${table.providerBinding} ->> 'serverUrl'), 0) > 0 and coalesce(octet_length(${table.providerBinding} ->> 'workspaceName'), 0) > 0 and ${table.providerBinding} ->> 'environment' is not null )`, ), reconcileClaimValid: check( "sandbox_retained_processes_reconcile_claim_check", sql`(${table.reconcileClaimId} is null and ${table.reconcileClaimedAt} is null) or (${table.reconcileClaimId} is not null and ${table.reconcileClaimedAt} is not null)`, ), reconcileAttemptsValid: check( "sandbox_retained_processes_reconcile_attempts_check", sql`${table.reconcileAttempts} >= 0`, ), reconcileOutcomeValid: check( "sandbox_retained_processes_reconcile_outcome_check", sql`${table.lastReconcileOutcome} is null or octet_length(${table.lastReconcileOutcome}) between 1 and 64`, ), reconcileProofValid: check( "sandbox_retained_processes_reconcile_proof_check", sql`( ${table.reconcileProofOutcome} is null and ${table.reconcileProofExitCode} is null and ${table.reconcileProofReason} is null and ${table.reconcileProofObservedAt} is null ) or ( ${table.reconcileProofOutcome} = 'exited' and ${table.reconcileProofExitCode} is not null and ${table.reconcileProofReason} = 'provider_exit_banner' and ${table.reconcileProofObservedAt} is not null ) or ( ${table.reconcileProofOutcome} = 'lost' and ${table.reconcileProofExitCode} is null and ${table.reconcileProofReason} in ( 'provider_session_lost_banner', 'provider_instance_not_found', 'provider_instance_terminated' ) and ${table.reconcileProofObservedAt} is not null )`, ), }), ); export const sessionBackgroundCommands = pgTable( "session_background_commands", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id").notNull(), provider: text("provider", { enum: ["managed", "connected_machine"], }).notNull(), state: text("state", { enum: ["running", "stopping", "exited", "lost"] }) .notNull() .default("running"), retainedProcessId: uuid("retained_process_id"), // Exact launch receipt, never inferred from a later turn or session owner. launchTurnId: uuid("launch_turn_id"), launchAttemptId: uuid("launch_attempt_id"), launchExecutionGeneration: integer("launch_execution_generation"), controlWorkspaceId: uuid("control_workspace_id"), enrollmentId: uuid("enrollment_id"), connectionInstanceId: text("connection_instance_id"), opId: text("op_id"), commandPreview: text("command_preview").notNull().default(""), commandText: text("command_text"), cancelRequestedAt: timestamp("cancel_requested_at", { withTimezone: true }), cancelRequestedBy: text("cancel_requested_by"), exitCode: integer("exit_code"), settlementReason: text("settlement_reason"), runnerFailure: jsonb("runner_failure").$type(), backgroundChildrenStopped: boolean("background_children_stopped").notNull().default(false), startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(), settledAt: timestamp("settled_at", { withTimezone: true }), completionObservedAt: timestamp("completion_observed_at", { withTimezone: true }), completionNotifiedAt: timestamp("completion_notified_at", { withTimezone: true }), reconcileAfter: timestamp("reconcile_after", { withTimezone: true }).notNull().defaultNow(), reconcileClaimId: uuid("reconcile_claim_id"), reconcileClaimedAt: timestamp("reconcile_claimed_at", { withTimezone: true, }), reconcileAttempts: integer("reconcile_attempts").notNull().default(0), lastReconcileOutcome: text("last_reconcile_outcome"), reconcileProofOutcome: text("reconcile_proof_outcome", { enum: ["exited", "lost"], }), reconcileProofExitCode: integer("reconcile_proof_exit_code"), reconcileProofReason: text("reconcile_proof_reason"), reconcileProofObservedAt: timestamp("reconcile_proof_observed_at", { withTimezone: true, }), // Independent output custody. Neither terminal state nor model observation // licenses native output collection. Pending releases survive worker loss. outputExitSeq: text("output_exit_seq"), outputAttachGeneration: text("output_attach_generation"), outputConsumedAt: timestamp("output_consumed_at", { withTimezone: true }), outputReleaseObservedAt: timestamp("output_release_observed_at", { withTimezone: true }), outputUnavailableAt: timestamp("output_unavailable_at", { withTimezone: true }), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "session_background_commands_workspace_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), runnerFailureCheck: check( "session_background_commands_runner_failure_check", sql` ${table.runnerFailure} IS NULL OR ( ${table.provider} = 'connected_machine' AND jsonb_typeof(${table.runnerFailure}) = 'object' AND octet_length(${table.runnerFailure}::text) <= 8192 AND ${table.runnerFailure} ?& ARRAY['code', 'retryable'] AND jsonb_typeof(${table.runnerFailure} -> 'code') = 'string' AND (${table.runnerFailure} ->> 'code') ~ '^[A-Za-z0-9_-]{1,128}$' AND ${table.runnerFailure} -> 'retryable' = 'false'::jsonb AND (NOT (${table.runnerFailure} ? 'detail') OR jsonb_typeof(${table.runnerFailure} -> 'detail') = 'object') )`, ), workspaceSession: foreignKey({ name: "session_background_commands_session_fk", columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), controlWorkspaceAccount: foreignKey({ name: "session_background_commands_control_workspace_fk", columns: [table.controlWorkspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("restrict"), retainedProcess: foreignKey({ name: "session_background_commands_process_fk", columns: [table.retainedProcessId], foreignColumns: [sandboxRetainedProcesses.id], }).onDelete("restrict"), managedProcess: uniqueIndex("session_background_commands_process_uq") .on(table.retainedProcessId) .where(sql`${table.retainedProcessId} is not null`), connectedOp: uniqueIndex("session_background_commands_connected_op_uq") .on(table.controlWorkspaceId, table.enrollmentId, table.connectionInstanceId, table.opId) .where(sql`${table.provider} = 'connected_machine'`), outputReleasePending: index("session_background_commands_output_release_idx").on( table.reconcileAfter, table.startedAt, table.id, ).where(sql`${table.provider} = 'connected_machine' and ${table.state} = 'exited' and ${table.outputReleaseObservedAt} is null and ${table.outputUnavailableAt} is null`), outputCustodyValid: check( "session_background_commands_output_custody_check", sql`( ${table.outputExitSeq} is null and ${table.outputAttachGeneration} is null and ${table.outputConsumedAt} is null and ${table.outputReleaseObservedAt} is null and (${table.outputUnavailableAt} is null or (${table.provider} = 'connected_machine' and ${table.state} = 'exited')) ) or ( ${table.provider} = 'connected_machine' and ${table.state} = 'exited' and ${table.outputExitSeq} is not null and ${table.outputAttachGeneration} is not null and ${table.outputConsumedAt} is not null and ${table.outputUnavailableAt} is null and ${table.outputExitSeq} ~ '^[1-9][0-9]{0,19}$' and ${table.outputAttachGeneration} ~ '^[1-9][0-9]{0,19}$' and ${table.outputExitSeq}::numeric <= 18446744073709551615 and ${table.outputAttachGeneration}::numeric <= 18446744073709551615 )`, ), activeSession: index("session_background_commands_active_session_idx") .on(table.workspaceId, table.sessionId, table.state, table.startedAt, table.id) .where(sql`${table.state} in ('running', 'stopping')`), stopping: index("session_background_commands_stopping_idx") .on(table.reconcileAfter, table.cancelRequestedAt, table.id) .where(sql`${table.state} in ('running', 'stopping')`), launchIdentityValid: check( "session_background_commands_launch_identity_check", sql`(${table.launchTurnId} is null and ${table.launchAttemptId} is null and ${table.launchExecutionGeneration} is null) or (${table.launchTurnId} is not null and ${table.launchAttemptId} is not null and ${table.launchExecutionGeneration} is not null and ${table.launchExecutionGeneration} > 0)`, ), providerValid: check( "session_background_commands_provider_check", sql`${table.provider} in ('managed', 'connected_machine')`, ), stateValid: check( "session_background_commands_state_check", sql`${table.state} in ('running', 'stopping', 'exited', 'lost')`, ), observationValid: check( "session_background_commands_observation_check", sql`${table.completionObservedAt} is null or ${table.state} in ('exited', 'lost')`, ), providerIdentityValid: check( "session_background_commands_provider_identity_check", sql`( ${table.provider} = 'managed' and ${table.retainedProcessId} is not null and ${table.controlWorkspaceId} is null and ${table.enrollmentId} is null and ${table.connectionInstanceId} is null and ${table.opId} is null ) or ( ${table.provider} = 'connected_machine' and ${table.retainedProcessId} is null and ${table.controlWorkspaceId} is not null and ${table.enrollmentId} is not null and ${table.connectionInstanceId} is not null and octet_length(${table.connectionInstanceId}) between 1 and 128 and ${table.opId} is not null and octet_length(${table.opId}) between 1 and 256 )`, ), lifecycleValid: check( "session_background_commands_lifecycle_check", sql`( ${table.state} = 'running' and ${table.cancelRequestedAt} is null and ${table.cancelRequestedBy} is null and ${table.exitCode} is null and ${table.settlementReason} is null and ${table.settledAt} is null ) or ( ${table.state} = 'stopping' and ${table.cancelRequestedAt} is not null and ${table.cancelRequestedBy} is not null and octet_length(btrim(${table.cancelRequestedBy})) between 1 and 1024 and ${table.exitCode} is null and ${table.settlementReason} is null and ${table.settledAt} is null ) or ( ${table.state} = 'exited' and ${table.settledAt} is not null and octet_length(btrim(${table.settlementReason})) between 1 and 512 ) or ( ${table.state} = 'lost' and ${table.exitCode} is null and ${table.settledAt} is not null and octet_length(btrim(${table.settlementReason})) between 1 and 512 )`, ), previewValid: check( "session_background_commands_preview_check", sql`octet_length(${table.commandPreview}) <= 2048`, ), reconcileValid: check( "session_background_commands_reconcile_check", sql`${table.reconcileAttempts} >= 0 and ( (${table.reconcileClaimId} is null and ${table.reconcileClaimedAt} is null) or (${table.reconcileClaimId} is not null and ${table.reconcileClaimedAt} is not null) ) and ( ${table.lastReconcileOutcome} is null or octet_length(${table.lastReconcileOutcome}) between 1 and 64 ) and ( ( ${table.reconcileProofOutcome} is null and ${table.reconcileProofExitCode} is null and ${table.reconcileProofReason} is null and ${table.reconcileProofObservedAt} is null ) or ( ${table.reconcileProofOutcome} = 'exited' and ${table.reconcileProofExitCode} is not null and octet_length(btrim(${table.reconcileProofReason})) between 1 and 512 and ${table.reconcileProofObservedAt} is not null ) or ( ${table.reconcileProofOutcome} = 'lost' and ${table.reconcileProofExitCode} is null and octet_length(btrim(${table.reconcileProofReason})) between 1 and 512 and ${table.reconcileProofObservedAt} is not null ) )`, ), }), ); // The recording lifecycle states (P4.3). Exported so the activity + the query // layer share one source of truth for the §3.1 state machine. export const sessionRecordingStateValues = [ "recording", "finalizing", "available", "failed", ] as const; export const sessionRecordingModeValues = ["manual", "on-turn", "on-verify"] as const; export const sessionRecordingCodecValues = ["h264-mp4", "vp9-webm"] as const; // One row per recording — the durable index for the "agent films itself proving // the fix" loop. ffmpeg x11grab of the SAME :0 humans watch, finalized by // reading the bytes off the box and PUTting them to @opengeni/storage in the // process that holds the resumed-by-id handle (never a Temporal payload, F10). // Mirrors the account/workspace/session FK chain of sandboxSessionEnvelopes; // turnId is ON DELETE SET NULL (a deleted turn must not kill the artifact row). export const sessionRecordings = pgTable( "session_recordings", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null", }), state: text("state", { enum: sessionRecordingStateValues }).notNull(), mode: text("mode", { enum: sessionRecordingModeValues }).notNull(), codec: text("codec", { enum: sessionRecordingCodecValues }).notNull(), storageKey: text("storage_key"), sizeBytes: bigint("size_bytes", { mode: "number" }), durationSeconds: numeric("duration_seconds").$type(), width: integer("width").notNull(), height: integer("height").notNull(), reason: losslessText("reason"), reasonCodecVersion: losslessCodecVersion("reason_codec_version"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), finalizedAt: timestamp("finalized_at", { withTimezone: true }), }, (table) => ({ sessionIdx: index("session_recordings_session_idx").on( table.workspaceId, table.sessionId, table.createdAt, ), }), ); // Workbench v2 turn-end workspace capture (model: sessionRecordings). // One row per capture revision — a point-in-time snapshot of a session's changed // files, probed off the live box at turn end. The manifest (tree index + per-repo // status/diff + file index) and each after-image blob live in @opengeni/storage; // this row is the durable index the read routes serve from. `revision` is // monotonic per session (unique (session_id, revision)); `blob_keys` records the // content-addressed after-image keys this revision references so the keep-latest-10 // GC can delete only blobs no surviving revision shares (set-difference GC without // a storage read). `lease_epoch` fences a write: an insert whose lease was // superseded writes zero rows (see insertWorkspaceCapture). export const workspaceCaptures = pgTable( "workspace_captures", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null", }), revision: bigint("revision", { mode: "number" }).notNull(), leaseEpoch: integer("lease_epoch").notNull(), // 'available' on a committed capture. 'failed' reserved for a future two-phase // write; the current synchronous capture only ever inserts 'available'. state: text("state", { enum: ["available", "failed"] }) .notNull() .default("available"), // Single JSON manifest blob (tree index + repos + file refs) — the cold-paint payload. manifestKey: text("manifest_key"), // The fs tree index blob, kept separate from the manifest so the API can inline // or sign it independently of the (usually small) manifest metadata. treeIndexKey: text("tree_index_key"), // Content-addressed after-image blob keys this revision references (GC input). blobKeys: jsonb("blob_keys").$type().notNull().default([]), sizeBytes: bigint("size_bytes", { mode: "number" }), stats: jsonb("stats").$type>().notNull().default({}), capturedAt: timestamp("captured_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ sessionRevision: uniqueIndex("workspace_captures_session_revision_idx").on( table.sessionId, table.revision, ), latest: index("workspace_captures_latest_idx").on( table.workspaceId, table.sessionId, table.revision, ), }), ); // Interactive PTY sessions. An OPEN PTY adopts one exact retained process; the // provider's numeric exec-session id is only a copied locator and never authority // on its own. Provider/lease/route/admission identity is copied onto the row so a // stale pointer or box epoch cannot redirect control to a rival process. Legacy // numeric-only rows are closed by the maintenance cutover and may retain null // identity columns only in that terminal state. export const sandboxPtySessions = pgTable( "sandbox_pty_sessions", { id: uuid("id").primaryKey().defaultRandom(), // == ptyId on the wire accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), leaseId: uuid("lease_id"), sandboxGroupId: uuid("sandbox_group_id"), retainedProcessId: uuid("retained_process_id"), openAdmissionId: uuid("open_admission_id"), // Copied provider locator for the adopted retained process. execSessionId: integer("exec_session_id"), leaseEpoch: integer("lease_epoch").notNull(), providerBackend: text("provider_backend"), providerInstanceId: text("provider_instance_id"), routeKind: text("route_kind", { enum: ["home", "active"] }), routeTargetId: uuid("route_target_id"), routeEpoch: integer("route_epoch"), cols: integer("cols").notNull(), rows: integer("rows").notNull(), shell: text("shell").notNull(), cwd: text("cwd").notNull(), status: text("status").notNull().default("open"), // 'open' | 'closed' // The viewer grant/subject that opened it (free-text — access subjects are not // always UUIDs, M5; so a text column, never a uuid NOT NULL). openedBy: text("opened_by").notNull(), lastInputAt: timestamp("last_input_at", { withTimezone: true }).notNull().defaultNow(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), closedAt: timestamp("closed_at", { withTimezone: true }), }, (table) => ({ retainedProcessScope: foreignKey({ name: "sandbox_pty_sessions_retained_process_scope_fk", columns: [ table.accountId, table.workspaceId, table.sessionId, table.leaseId, table.retainedProcessId, ], foreignColumns: [ sandboxRetainedProcesses.accountId, sandboxRetainedProcesses.workspaceId, sandboxRetainedProcesses.sessionId, sandboxRetainedProcesses.leaseId, sandboxRetainedProcesses.id, ], }).onDelete("restrict"), openIdx: index("sandbox_pty_sessions_session_idx") .on(table.workspaceId, table.sessionId) .where(sql`${table.status} = 'open'`), processIdx: uniqueIndex("sandbox_pty_sessions_open_process_uq") .on(table.retainedProcessId) .where(sql`${table.status} = 'open'`), openIdentityValid: check( "sandbox_pty_sessions_open_identity_check", sql`${table.status} <> 'open' or ( ${table.leaseId} is not null and ${table.sandboxGroupId} is not null and ${table.retainedProcessId} is not null and ${table.openAdmissionId} is not null and ${table.execSessionId} > 0 and octet_length(${table.providerBackend}) between 1 and 64 and octet_length(${table.providerInstanceId}) between 1 and 512 and ${table.routeKind} in ('home', 'active') and (${table.routeKind} = 'active' or ${table.routeTargetId} is null) and ${table.routeEpoch} is not null and ${table.leaseEpoch} >= 0 and ${table.routeEpoch} >= 0 )`, ), }), ); // ============================================================================ // Bring-your-own-compute (M2): first-class swappable sandboxes + enrollment + // metrics (migration 0024). The session→box // binding becomes a per-session mutable, epoch-fenced active_sandbox_id pointer // (declared on sessions above) that the routing proxy resolves PER TOOL CALL. // The lifecycle/enum domains, exported so the query layer + the migration share // ONE source of truth for each CHECK. export const enrollmentExposureValues = ["whole-machine"] as const; export const enrollmentStatusValues = ["active", "revoked"] as const; export const enrollmentKindValues = ["machine", "sandbox"] as const; export const enrollmentOsValues = ["linux", "macos", "windows"] as const; export const sandboxKindValues = ["modal", "selfhosted"] as const; export const agentUpdateStatusValues = [ "requested", "accepted", "waiting_for_idle", "downloading", "verifying", "applying", "restarting", "succeeded", "failed", ] as const; // One row per registered machine. The agent's ed25519 PUBLIC key IS the machine // identity (the NATS control-plane subject the agent subscribes to maps to it). // exposure is the loudly-consented access mode; has_display/allow_screen_control // are the desktop/computer-use consent bits (default false — opt-in). status is // the active|revoked lifecycle; last_seen_at the heartbeat liveness cursor the // Machines dashboard renders online/reconnecting/offline from. export const enrollments = pgTable( "enrollments", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), authorityScope: text("authority_scope").notNull().default("workspace"), authorityId: uuid("authority_id"), ownerOrganizationMembershipId: uuid("owner_organization_membership_id"), originWorkspaceId: uuid("origin_workspace_id"), generation: bigint("generation", { mode: "number" }).notNull().default(1), // Where an organization machine works besides the workspace it was // connected from (migration 1190): every shared workspace (null) or the // listed ones, and members' Personal workspaces when the switch is on. // Unused for workspace and personal machines. allowedWorkspaceIds: uuid("allowed_workspace_ids").array(), allowPersonalWorkspaces: boolean("allow_personal_workspaces").notNull().default(true), allowManagedWorkspaces: boolean("allow_managed_workspaces").notNull().default(false), // 'machine' is a Connected Machine. 'sandbox' is the agent inside one // Opengeni compute sandbox (migration 0858): bound to its sandbox group, // reached through the agent gateway, with no key or bearer, and never // listed, offered, attached or granted as a machine. kind: text("kind", { enum: enrollmentKindValues }).notNull().default("machine"), sandboxGroupId: uuid("sandbox_group_id"), // The highest owner epoch the agent gateway accepted for a sandbox // enrollment; null for machines. linkEpoch: bigint("link_epoch", { mode: "number" }), // The agent's ed25519 public key (the machine identity). Null exactly for // sandbox enrollments, which hold no credential. pubkey: text("pubkey"), exposure: text("exposure", { enum: enrollmentExposureValues }) .notNull() .default("whole-machine"), hasDisplay: boolean("has_display").notNull().default(false), // Refreshed from every connect Hello (Capabilities.op_stream); false for // agents predating the op-stream engine. opStream: boolean("op_stream").notNull().default(false), // When the machine has a display it CANNOT capture (macOS Screen Recording / TCC // not granted), the agent reports has_display=false AND a human, actionable reason // here (e.g. "grant Screen Recording in System Settings"). NULL means capture is // permitted (has_display=true) or the machine is genuinely headless — the reason // distinguishes "display present but capture not granted" from plain "no display" // so the Machines dashboard / VM picker can surface the specific hint. Refreshed // from every connect Hello alongside has_display. desktopUnavailableReason: text("desktop_unavailable_reason"), allowScreenControl: boolean("allow_screen_control").notNull().default(false), // Optional per-connection command policy. NULL is the unrestricted default. // Values remain within JavaScript's exact-integer wire range; local runner and // ancestor host policy may only tighten them at execution. operationMemoryMaxBytes: bigint("operation_memory_max_bytes", { mode: "number", }), operationMemoryHighBytes: bigint("operation_memory_high_bytes", { mode: "number", }), operationCpuMaxMillicores: bigint("operation_cpu_max_millicores", { mode: "number", }), operationPolicyRevision: integer("operation_policy_revision").notNull().default(0), operationPolicyUpdatedAt: timestamp("operation_policy_updated_at", { withTimezone: true, }), status: text("status", { enum: enrollmentStatusValues }).notNull().default("active"), // Credential-family fence. Existing rows/migration-era bearers are generation // 1; every successful re-enrollment increments this atomically before a new // bearer is signed. Auth and self-revoke require an exact row/claim match. credentialGeneration: integer("credential_generation").notNull().default(1), // One live runner instance owns this enrollment's data-plane address at a // time. Auth-callout claims/renews the lease before NATS grants a connection; // every operational subject includes the instance id, so an older still-open // socket cannot receive work after a successor claims authority. connectionInstanceId: text("connection_instance_id"), connectionGeneration: integer("connection_generation").notNull().default(0), connectionLeaseExpiresAt: timestamp("connection_lease_expires_at", { withTimezone: true, }), // Durable diagnostics for valid cloned credentials / duplicate daemons that // were blocked while another process held the live authority lease. connectionDuplicateDeniedCount: integer("connection_duplicate_denied_count") .notNull() .default(0), connectionDuplicateDeniedAt: timestamp("connection_duplicate_denied_at", { withTimezone: true, }), os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"), arch: text("arch").notNull().default("x86_64"), // Exact absolute launch root reported by the authoritative runner Hello. // Null means no current runner has supplied a usable root yet. workspaceRoot: text("workspace_root"), // Heartbeat liveness cursor. Null until the first connect. lastSeenAt: timestamp("last_seen_at", { withTimezone: true }), // Clean going-offline marker (migration 0049). Set when the machine announces a // typed GoingOffline (user-stop / self-update / host-shutdown); the liveness // derivation reads an un-cleared marker as OFFLINE immediately, regardless of a // still-fresh last_seen. Any newer liveness signal (a reconnect Hello or a // fresher heartbeat via touchEnrollmentLastSeen) clears BOTH back to NULL. NULL // (the default) ⇒ no goodbye pending — today's last_seen-aging behavior. wentOfflineAt: timestamp("went_offline_at", { withTimezone: true }), wentOfflineReason: text("went_offline_reason"), // Exact running build + negotiated capability truth, refreshed from the // authoritative process Hello. Null means an older agent has not reported it. agentVersion: text("agent_version"), agentBinarySha256: text("agent_binary_sha256"), agentUpdateChannel: text("agent_update_channel", { enum: ["stable", "beta"] as const, }), agentCapabilities: jsonb("agent_capabilities") .$type>() .notNull() .default({}), // One current/most-recent self-update. The accepting connection coordinates // fence every progress write; a successor Hello is the only success signal. agentUpdateOperationId: uuid("agent_update_operation_id"), agentUpdateStatus: text("agent_update_status", { enum: agentUpdateStatusValues, }), agentUpdateTargetVersion: text("agent_update_target_version"), agentUpdateExpectedBinarySha256: text("agent_update_expected_binary_sha256"), agentUpdateErrorCode: text("agent_update_error_code"), agentUpdateBlockers: jsonb("agent_update_blockers") .$type>() .notNull() .default([]), agentUpdateRetryable: boolean("agent_update_retryable").notNull().default(false), agentUpdateRolledBack: boolean("agent_update_rolled_back").notNull().default(false), agentUpdateConnectionInstanceId: text("agent_update_connection_instance_id"), agentUpdateConnectionGeneration: integer("agent_update_connection_generation"), agentUpdateRequestedAt: timestamp("agent_update_requested_at", { withTimezone: true, }), agentUpdateUpdatedAt: timestamp("agent_update_updated_at", { withTimezone: true, }), agentUpdateCompletedAt: timestamp("agent_update_completed_at", { withTimezone: true, }), /** When the current run of unsuccessful updates first postponed the * update for managed browsers in use; bounds that wait (migration 1270). */ agentUpdateBrowsersWaitSince: timestamp("agent_update_browsers_wait_since", { withTimezone: true, }), /** Attempts of the current run for the current target that failed for a * reason other than a busy machine, before the current operation. * Automatic retries back off from it (migration 1270). */ agentUpdateFailedAttempts: integer("agent_update_failed_attempts").notNull().default(0), /** The announced time at which an automatic update closes an older * agent's managed browsers; kept through busy refusals (migration 1270). */ agentUpdateBrowsersCloseAt: timestamp("agent_update_browsers_close_at", { withTimezone: true, }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), revokedAt: timestamp("revoked_at", { withTimezone: true }), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ // One enrollment identity per authority boundary and pubkey. Revocation keeps // the identity so a re-enroll can reactivate the same durable row. workspacePubkey: uniqueIndex("enrollments_workspace_pubkey_idx") .on(table.workspaceId, table.pubkey) .where(sql`${table.authorityScope} = 'workspace'`), organizationPubkey: uniqueIndex("enrollments_organization_pubkey_idx") .on(table.accountId, table.pubkey) .where(sql`${table.authorityScope} = 'organization'`), // A person's machine: one enrollment per workspace it was connected from, // and at most one of them live (0996). userWorkspacePubkey: uniqueIndex("enrollments_user_workspace_pubkey_idx") .on(table.accountId, table.ownerOrganizationMembershipId, table.pubkey, table.workspaceId) .where(sql`${table.authorityScope} = 'user'`), userActivePubkey: uniqueIndex("enrollments_user_active_pubkey_idx") .on(table.accountId, table.ownerOrganizationMembershipId, table.pubkey) .where(sql`${table.authorityScope} = 'user' and ${table.status} = 'active'`), // List a workspace's ACTIVE machines without scanning revoked rows. workspaceStatus: index("enrollments_workspace_status_idx").on(table.workspaceId, table.status), sandboxGroup: index("enrollments_sandbox_group_idx") .on(table.workspaceId, table.sandboxGroupId) .where(sql`${table.kind} = 'sandbox'`), kindValid: check("enrollments_kind_check", sql`${table.kind} in ('machine', 'sandbox')`), sandboxBinding: check( "enrollments_sandbox_binding_check", sql`(${table.kind} = 'machine' and ${table.sandboxGroupId} is null and ${table.pubkey} is not null and ${table.linkEpoch} is null) or (${table.kind} = 'sandbox' and ${table.sandboxGroupId} is not null and ${table.pubkey} is null and ${table.authorityScope} = 'workspace')`, ), authorityShape: check( "enrollments_authority_shape_check", sql`( ${table.authorityScope} in ('organization', 'workspace') and ${table.authorityId} is null and ${table.ownerOrganizationMembershipId} is null ) or ( ${table.authorityScope} = 'user' and ${table.authorityId} is not null and ${table.ownerOrganizationMembershipId} is not null )`, ), authorityScopeValid: check( "enrollments_authority_scope_check", sql`${table.authorityScope} in ('organization', 'workspace', 'user')`, ), generationPositive: check("enrollments_generation_check", sql`${table.generation} > 0`), authority: foreignKey({ name: "enrollments_authority_fk", columns: [table.authorityId, table.accountId, table.ownerOrganizationMembershipId], foreignColumns: [ organizationUserResourceAuthorities.id, organizationUserResourceAuthorities.accountId, organizationUserResourceAuthorities.organizationMembershipId, ], }).onDelete("restrict"), connectionAuthorityShape: check( "enrollments_connection_authority_shape_chk", sql`(${table.connectionInstanceId} is null and ${table.connectionLeaseExpiresAt} is null) or (${table.connectionInstanceId} is not null and length(${table.connectionInstanceId}) between 1 and 128 and ${table.connectionLeaseExpiresAt} is not null)`, ), connectionGenerationNonnegative: check( "enrollments_connection_generation_chk", sql`${table.connectionGeneration} >= 0`, ), operationMemoryMaxShape: check( "enrollments_operation_memory_max_shape_chk", sql`${table.operationMemoryMaxBytes} is null or (${table.operationMemoryMaxBytes} > 0 and ${table.operationMemoryMaxBytes} <= 9007199254740991)`, ), operationMemoryHighShape: check( "enrollments_operation_memory_high_shape_chk", sql`${table.operationMemoryHighBytes} is null or (${table.operationMemoryHighBytes} > 0 and ${table.operationMemoryHighBytes} <= 9007199254740991)`, ), operationMemoryOrder: check( "enrollments_operation_memory_order_chk", sql`${table.operationMemoryMaxBytes} is null or ${table.operationMemoryHighBytes} is null or ${table.operationMemoryHighBytes} <= ${table.operationMemoryMaxBytes}`, ), operationCpuShape: check( "enrollments_operation_cpu_shape_chk", sql`${table.operationCpuMaxMillicores} is null or ${table.operationCpuMaxMillicores} between 1 and 4294967295`, ), operationPolicyRevisionNonnegative: check( "enrollments_operation_policy_revision_chk", sql`${table.operationPolicyRevision} >= 0`, ), agentBinarySha256Shape: check( "enrollments_agent_binary_sha256_chk", sql`${table.agentBinarySha256} is null or ${table.agentBinarySha256} ~ '^[0-9a-f]{64}$'`, ), agentUpdateChannelShape: check( "enrollments_agent_update_channel_chk", sql`${table.agentUpdateChannel} is null or ${table.agentUpdateChannel} in ('stable', 'beta')`, ), agentUpdateExpectedBinarySha256Shape: check( "enrollments_agent_update_expected_binary_sha256_chk", sql`${table.agentUpdateExpectedBinarySha256} is null or ${table.agentUpdateExpectedBinarySha256} ~ '^[0-9a-f]{64}$'`, ), agentUpdateStateShape: check( "enrollments_agent_update_state_shape_chk", sql`( (${table.agentUpdateOperationId} is null and ${table.agentUpdateStatus} is null and ${table.agentUpdateTargetVersion} is null and ${table.agentUpdateConnectionInstanceId} is null and ${table.agentUpdateConnectionGeneration} is null and ${table.agentUpdateRequestedAt} is null and ${table.agentUpdateUpdatedAt} is null) or (${table.agentUpdateOperationId} is not null and ${table.agentUpdateStatus} in ( 'requested', 'accepted', 'waiting_for_idle', 'downloading', 'verifying', 'applying', 'restarting', 'succeeded', 'failed' ) and ${table.agentUpdateTargetVersion} is not null and ${table.agentUpdateConnectionInstanceId} is not null and ${table.agentUpdateConnectionGeneration} is not null and ${table.agentUpdateConnectionGeneration} >= 0 and ${table.agentUpdateRequestedAt} is not null and ${table.agentUpdateUpdatedAt} is not null) )`, ), connectionDuplicateDeniedCountNonnegative: check( "enrollments_connection_duplicate_denied_count_chk", sql`${table.connectionDuplicateDeniedCount} >= 0`, ), }), ); // One durable receipt per workspace-authorized connected-machine removal // request. The enrollment row remains the lifecycle truth; this table preserves // the exact idempotency key, request fingerprint, and terminal result so a lost // response can be replayed without re-running dependency checks or mutating a // different enrollment that happens to share the same display name. export const machineRemovalOperationOutcomeValues = [ "removed", "already_removed", "blocked", ] as const; export const machineRemovalOperations = pgTable( "machine_removal_operations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), enrollmentId: uuid("enrollment_id") .notNull() .references(() => enrollments.id, { onDelete: "restrict" }), operationKey: text("operation_key").notNull(), requestFingerprint: text("request_fingerprint").notNull(), outcome: text("outcome", { enum: machineRemovalOperationOutcomeValues, }).notNull(), result: jsonb("result").$type>().notNull().default({}), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccount: foreignKey({ name: "machine_removal_operations_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceOperation: uniqueIndex("machine_removal_operations_workspace_operation_uq").on( table.workspaceId, table.operationKey, ), workspaceIdentity: uniqueIndex("machine_removal_operations_workspace_id_uq").on( table.workspaceId, table.id, ), enrollmentTimeline: index("machine_removal_operations_enrollment_created_idx").on( table.workspaceId, table.enrollmentId, table.createdAt, ), requestFingerprintValid: check( "machine_removal_operations_request_fingerprint_chk", sql`${table.requestFingerprint} ~ '^[0-9a-f]{64}$'`, ), operationKeyValid: check( "machine_removal_operations_operation_key_chk", sql`length(btrim(${table.operationKey})) between 1 and 200 and ${table.operationKey} = btrim(${table.operationKey})`, ), }), ); // The OAuth 2.0 device-authorization (RFC 8628) PENDING request (M5, migration // 0025 / enrollment + §18 LOUD consent). An agent's `enroll` starts // a flow (POST /enrollments/device/start) → one short-TTL, single-use row keyed by // an opaque `device_code` (the agent polls with) + a short `user_code` (the user // types at the approve page). The user (workspace-membership / workspace:admin // gated) approves it (POST /enrollments/device/approve), which records WHO // (subject + label) consented WHEN (approved_at) to WHAT (whole-machine mandatory + // screen-control per allow_screen_control) and stamps the resulting enrollment_id / // sandbox_id. The agent then polls (POST /enrollments/device/poll) and the approved // row yields the EnrollmentCredentials. State machine: pending → approved | denied; // a pending row past expires_at is EXPIRED; once the agent has polled an approved // row its credentials, the row flips to consumed (single-use). NOT a long-lived // record — a retention sweep prunes terminal rows; the durable identity is the // `enrollments` row the approve produced. export const deviceEnrollmentStatusValues = ["pending", "approved", "denied", "consumed"] as const; export const deviceEnrollmentRequests = pgTable( "device_enrollment_requests", { id: uuid("id").primaryKey().defaultRandom(), // The opaque code the agent polls with (unguessable, single-use). Unique. deviceCode: text("device_code").notNull(), // The short human-typed code (e.g. "WDJB-MJHT"). Unique among LIVE (pending) // rows via a partial unique index so a recycled code never collides with a // terminal row. userCode: text("user_code").notNull(), // The workspace this request was started for (resolved from the deployment-edge // request context — the agent presents the access key, the flow binds to the // single managed workspace OR a workspace hint). account_id rides along for RLS. accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), // The agent's ed25519 public key (the machine identity the enrollment binds to). pubkey: text("pubkey").notNull(), os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"), arch: text("arch").notNull().default("x86_64"), machineName: text("machine_name"), // The exposure the agent REQUESTED (whole-machine in v1; loudly consented at // approve). Mirrors the enrollment column domain. requestedExposure: text("requested_exposure", { enum: enrollmentExposureValues, }) .notNull() .default("whole-machine"), // The agent CAN offer a display (a real screen / Xvfb is available) — gates // whether screen-control consent is even meaningful. has_display on the // resulting enrollment is derived from this. canOfferDisplay: boolean("can_offer_display").notNull().default(false), // The agent REQUESTS screen control (computer-use). The user's allow_screen_control // at approve is the AUTHORITATIVE consent; this is only the agent's request. requestsScreenControl: boolean("requests_screen_control").notNull().default(false), status: text("status", { enum: deviceEnrollmentStatusValues }).notNull().default("pending"), // ── LOUD CONSENT capture (who/when/what), stamped at approve ────────────── approvedBySubjectId: text("approved_by_subject_id"), approvedBySubjectLabel: text("approved_by_subject_label"), // The user's screen-control consent decision (whole-machine is mandatory at // approve; screen-control is opt-in per this flag). allowScreenControl: boolean("allow_screen_control").notNull().default(false), approvedAt: timestamp("approved_at", { withTimezone: true }), // The enrollment + sandbox the approve produced (acceptance #2: an enrollment // row AND a sandbox row appear). Null until approved. enrollmentId: uuid("enrollment_id").references(() => enrollments.id, { onDelete: "set null", }), sandboxId: uuid("sandbox_id").references(() => sandboxes.id, { onDelete: "set null", }), // The short-TTL expiry; a pending row past this is EXPIRED on poll. expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ // The device_code is the agent's poll key — globally unique + indexed. deviceCode: uniqueIndex("device_enrollment_requests_device_code_idx").on(table.deviceCode), // The user_code must be unique among LIVE (pending) rows so the approve lookup // is unambiguous; a terminal row's code may be recycled. userCodePending: uniqueIndex("device_enrollment_requests_user_code_pending_idx") .on(table.userCode) .where(sql`${table.status} = 'pending'`), workspaceCreated: index("device_enrollment_requests_workspace_created_idx").on( table.workspaceId, table.createdAt, ), expires: index("device_enrollment_requests_expires_idx").on(table.expiresAt), }), ); // The first-class NAMED sandbox a session's active_sandbox_id points AT. kind // discriminates the backend the routing proxy resolves to: 'modal' (cloud box, // NULL enrollment_id) or 'selfhosted' (a user's machine, enrollment_id -> the // enrollment it lives on). The selfhosted-needs-enrollment invariant is pinned by // the sandboxes_selfhosted_enrollment_chk CHECK in migration 0024. enrollment_id // is ON DELETE SET NULL so deleting an enrollment never cascade-kills a sandbox a // session might still point at (the routing layer surfaces agent_offline instead). export const sandboxes = pgTable( "sandboxes", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), kind: text("kind", { enum: sandboxKindValues }).notNull(), name: text("name").notNull(), enrollmentId: uuid("enrollment_id").references(() => enrollments.id, { onDelete: "set null", }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceCreated: index("sandboxes_workspace_created_idx").on( table.workspaceId, table.createdAt, ), enrollment: index("sandboxes_enrollment_idx") .on(table.enrollmentId) .where(sql`${table.enrollmentId} is not null`), }), ); // Last-sample upsert: ONE row per enrollment, overwritten on every sample (the // PK on enrollment_id is the ON CONFLICT target). The §10.7 signals; nullable // where a platform/sample may not provide it (no GPU, headless). export const machineMetricsLatest = pgTable( "machine_metrics_latest", { enrollmentId: uuid("enrollment_id") .primaryKey() .references(() => enrollments.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), cpuPercent: numeric("cpu_percent").$type(), load1: numeric("load1").$type(), load5: numeric("load5").$type(), load15: numeric("load15").$type(), memUsedBytes: bigint("mem_used_bytes", { mode: "number" }), memTotalBytes: bigint("mem_total_bytes", { mode: "number" }), diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }), diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }), gpuUtilPercent: numeric("gpu_util_percent").$type(), gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }), gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }), contention: numeric("contention").$type(), sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspace: index("machine_metrics_latest_workspace_idx").on(table.workspaceId), }), ); // Append-only downsampled history (~1/min per enrollment, retained N days). Same // signal columns as _latest. The (enrollment_id, sampled_at) index serves the // dashboard time-range read AND the (later) retention sweep. export const machineMetricsSeries = pgTable( "machine_metrics_series", { id: uuid("id").primaryKey().defaultRandom(), enrollmentId: uuid("enrollment_id") .notNull() .references(() => enrollments.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), cpuPercent: numeric("cpu_percent").$type(), load1: numeric("load1").$type(), load5: numeric("load5").$type(), load15: numeric("load15").$type(), memUsedBytes: bigint("mem_used_bytes", { mode: "number" }), memTotalBytes: bigint("mem_total_bytes", { mode: "number" }), diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }), diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }), gpuUtilPercent: numeric("gpu_util_percent").$type(), gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }), gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }), contention: numeric("contention").$type(), sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ enrollmentSampled: index("machine_metrics_series_enrollment_sampled_idx").on( table.enrollmentId, table.sampledAt, ), sampled: index("machine_metrics_series_sampled_idx").on(table.sampledAt), }), ); export const scheduledTasks = pgTable( "scheduled_tasks", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), name: text("name").notNull(), ownerSubjectId: text("owner_subject_id"), // Who can read the schedule (migration 0720): everyone in the workspace, or // only its owner. Not execution configuration; excluded from the digest. visibility: text("visibility").notNull().default("workspace_shared"), status: text("status").notNull().default("active"), schedule: jsonb("schedule").$type().notNull(), temporalScheduleId: text("temporal_schedule_id").notNull(), runMode: text("run_mode").notNull().default("new_session_per_run"), overlapPolicy: text("overlap_policy").notNull().default("allow_concurrent"), action: jsonb("action").$type().notNull().default({ kind: "agent_turn" }), agentConfig: jsonb("agent_config").$type().notNull(), // Vault narrowing for every run (0739), applied when the run resolves // secret references; `{ mode: "all" }` adds no narrowing. vaultPolicy: jsonb("vault_policy").$type().notNull().default({ mode: "all" }), createdByKind: text("created_by_kind").notNull().default("service"), createdBySubjectId: text("created_by_subject_id").notNull().default("unattributed-legacy"), createdByContext: jsonb("created_by_context") .$type>() .notNull() .default({ backfill: true }), // Funding origin of whoever set the task up (`BillingOrigin`), frozen at // creation and inherited by every run. Null is legacy and billed as app. billingOrigin: text("billing_origin"), personalConnectionDelegations: jsonb("personal_connection_delegations") .$type() .notNull() .default([]), xaiProviderAccountAuthoritySnapshot: jsonb("xai_provider_account_authority_snapshot") .$type() .notNull() .default(WORKSPACE_XAI_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1), claudeProviderAccountAuthoritySnapshot: jsonb("claude_provider_account_authority_snapshot") .$type() .notNull() .default(WORKSPACE_CLAUDE_PROVIDER_ACCOUNT_AUTHORITY_SNAPSHOT_V1), // M3 v2 slot (0688): frozen at task creation; a firing copies it (or its // current revision authority's value), never recomputes it. subscriptionAuthority: jsonb( "subscription_authority", ).$type(), authorityRevision: bigint("authority_revision", { mode: "number" }).notNull().default(1), // The migration-owned BEFORE INSERT/UPDATE trigger replaces this client // placeholder with the canonical whole-row execution digest. executionDigest: text("execution_digest") .notNull() .$defaultFn(() => ""), reusableSessionId: uuid("reusable_session_id").references(() => sessions.id, { onDelete: "set null", }), // The rig this task's runs ride; the active version is resolved per fire // (migration 0047). NULL ⇒ no rig. FK (-> rigs(id) ON DELETE SET NULL) lives // in migration 0047 (forward-reference pattern). Consumed in M3. rigId: uuid("rig_id"), metadata: jsonb("metadata").$type>().notNull().default({}), // Frozen creator boundary for tasks created by a live agent attempt // (migration 0428): generated sessions inherit these instead of the // deployment default. NULL for human/API creates. creatorFirstPartyMcpTools: jsonb("creator_first_party_mcp_tools").$type< FirstPartyMcpToolName[] >(), creatorFirstPartyMcpPermissions: jsonb("creator_first_party_mcp_permissions").$type< Permission[] >(), creatorSessionPolicy: jsonb("creator_session_policy").$type<{ agentAccess: string | null; scopeSubjectId: string | null; memoryScope: string | null; }>(), // Opt-in at creation (migration 1100): only the frozen creator principal // may change, run, resume or delete the task; agent attempts never may. // Mutation authority, not execution configuration: excluded from the digest. creatorLocked: boolean("creator_locked").notNull().default(false), deletedAt: timestamp("deleted_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ temporalScheduleId: uniqueIndex("scheduled_tasks_workspace_temporal_schedule_id_idx").on( table.workspaceId, table.temporalScheduleId, ), sessionTarget: index("scheduled_tasks_workspace_session_target_idx") .on(table.workspaceId, table.reusableSessionId) .where(sql`${table.deletedAt} is null`), status: index("scheduled_tasks_workspace_status_idx").on(table.workspaceId, table.status), }), ); /** Durable latest-state synchronization after schedule retirement. */ export const scheduledTaskScheduleOutbox = pgTable( "scheduled_task_schedule_outbox", { id: uuid("id").primaryKey().defaultRandom(), taskId: uuid("task_id").notNull().unique(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), temporalScheduleId: text("temporal_schedule_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ due: index("scheduled_task_schedule_outbox_due_idx").on(table.nextAttemptAt, table.id), }), ); /** * Migration 0792: one review per schedule of its newest settled scheduled run. * A blocked schedule tells its owner once (`notified`) or pauses itself when * no later run can start until a person acts (`paused`). Owner-run lifecycle * code writes it under the task lock; see `scheduled-task-blockers.ts`. */ export const scheduledTaskBlockerReviews = pgTable( "scheduled_task_blocker_reviews", { taskId: uuid("task_id") .primaryKey() .references(() => scheduledTasks.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), reviewedRunId: uuid("reviewed_run_id"), state: text("state").notNull().default("clear"), reason: text("reason"), message: text("message"), blockedRunId: uuid("blocked_run_id"), blockedSince: timestamp("blocked_since", { withTimezone: true }), noticeSessionId: uuid("notice_session_id"), noticeKey: text("notice_key"), noticePending: text("notice_pending"), noticePayload: jsonb("notice_payload"), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspace: index("scheduled_task_blocker_reviews_workspace_idx").on( table.workspaceId, table.taskId, ), }), ); /** * Durable ownership of Temporal schedules whose database owner was deleted. * No workspace/account foreign key: deletion cleanup survives the cascade. * Cross-workspace claim/settlement uses migration-owned lifecycle functions. */ export const temporalScheduleCleanupOutbox = pgTable( "temporal_schedule_cleanup_outbox", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), temporalScheduleId: text("temporal_schedule_id").notNull(), scheduledTaskId: uuid("scheduled_task_id"), connectorCleanupSubjectId: text("connector_cleanup_subject_id"), connectorCleanupSnapshot: jsonb("connector_cleanup_snapshot"), connectorCleanupCompletedAt: timestamp("connector_cleanup_completed_at", { withTimezone: true, }), claimId: uuid("claim_id"), claimUntil: timestamp("claim_until", { withTimezone: true }), attemptCount: integer("attempt_count").notNull().default(0), nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(), lastError: text("last_error"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ schedule: uniqueIndex("temporal_schedule_cleanup_outbox_schedule_uq").on( table.temporalScheduleId, ), due: index("temporal_schedule_cleanup_outbox_due_idx").on( table.nextAttemptAt, table.claimUntil, table.id, ), valid: check( "temporal_schedule_cleanup_outbox_valid_chk", sql`length(${table.temporalScheduleId}) between 1 and 512 and ${table.attemptCount} >= 0 and ((${table.claimId} is null and ${table.claimUntil} is null) or (${table.claimId} is not null and ${table.claimUntil} is not null)) and ((${table.scheduledTaskId} is null and ${table.connectorCleanupSubjectId} is null and ${table.connectorCleanupSnapshot} is null) or (${table.scheduledTaskId} is not null and ${table.connectorCleanupSubjectId} is not null and ${table.connectorCleanupSnapshot} is not null)) and (${table.connectorCleanupSnapshot} is not null or ${table.connectorCleanupCompletedAt} is null) and (${table.connectorCleanupSubjectId} is null or octet_length(${table.connectorCleanupSubjectId}) between 1 and 4096) and (${table.connectorCleanupSnapshot} is null or ( jsonb_typeof(${table.connectorCleanupSnapshot}) = 'object' and ${table.connectorCleanupSnapshot} ?& array[ 'version','taskId','accountId','workspaceId','connectorKind','connectionId', 'connectionVersion','sourceId','sourceLifecycleGeneration', 'sourceConfigGeneration','externalSourceId','subjectId' ] and ${table.connectorCleanupSnapshot} - array[ 'version','taskId','accountId','workspaceId','connectorKind','connectionId', 'connectionVersion','sourceId','sourceLifecycleGeneration', 'sourceConfigGeneration','externalSourceId','subjectId' ]::text[] = '{}'::jsonb and jsonb_typeof(${table.connectorCleanupSnapshot}->'version') = 'number' and jsonb_typeof(${table.connectorCleanupSnapshot}->'taskId') = 'string' and jsonb_typeof(${table.connectorCleanupSnapshot}->'accountId') = 'string' and jsonb_typeof(${table.connectorCleanupSnapshot}->'workspaceId') = 'string' and jsonb_typeof(${table.connectorCleanupSnapshot}->'connectorKind') = 'string' and jsonb_typeof(${table.connectorCleanupSnapshot}->'connectionId') = 'string' and jsonb_typeof(${table.connectorCleanupSnapshot}->'connectionVersion') = 'number' and jsonb_typeof(${table.connectorCleanupSnapshot}->'sourceId') = 'string' and jsonb_typeof(${table.connectorCleanupSnapshot}->'sourceLifecycleGeneration') = 'number' and jsonb_typeof(${table.connectorCleanupSnapshot}->'sourceConfigGeneration') = 'number' and jsonb_typeof(${table.connectorCleanupSnapshot}->'externalSourceId') = 'string' and jsonb_typeof(${table.connectorCleanupSnapshot}->'subjectId') = 'string' and ${table.connectorCleanupSnapshot}->>'version' = '1' and ${table.connectorCleanupSnapshot}->>'connectorKind' in ('google_drive','atlassian') and ${table.connectorCleanupSnapshot}->>'subjectId' = ${table.connectorCleanupSubjectId} and ${table.connectorCleanupSnapshot}->>'taskId' = ${table.scheduledTaskId}::text and ${table.connectorCleanupSnapshot}->>'accountId' = ${table.accountId}::text and ${table.connectorCleanupSnapshot}->>'workspaceId' = ${table.workspaceId}::text and octet_length(${table.connectorCleanupSnapshot}->>'externalSourceId') between 1 and 2048 and octet_length(${table.connectorCleanupSnapshot}->>'subjectId') between 1 and 4096 and ${table.connectorCleanupSnapshot}->>'taskId' ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' and ${table.connectorCleanupSnapshot}->>'accountId' ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' and ${table.connectorCleanupSnapshot}->>'workspaceId' ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' and ${table.connectorCleanupSnapshot}->>'connectionId' ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' and ${table.connectorCleanupSnapshot}->>'sourceId' ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' and ${table.connectorCleanupSnapshot}->>'connectionVersion' ~ '^[1-9][0-9]*$' and ${table.connectorCleanupSnapshot}->>'sourceLifecycleGeneration' ~ '^[1-9][0-9]*$' and ${table.connectorCleanupSnapshot}->>'sourceConfigGeneration' ~ '^[1-9][0-9]*$' and (${table.connectorCleanupSnapshot}->>'connectionVersion')::numeric <= 9007199254740991 and (${table.connectorCleanupSnapshot}->>'sourceLifecycleGeneration')::numeric <= 9007199254740991 and (${table.connectorCleanupSnapshot}->>'sourceConfigGeneration')::numeric <= 9007199254740991 )) and (${table.lastError} is null or length(${table.lastError}) <= 2000)`, ), }), ); export const scheduledTaskRuns = pgTable( "scheduled_task_runs", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), taskId: uuid("task_id") .notNull() .references(() => scheduledTasks.id), taskAuthorityRevision: bigint("task_authority_revision", { mode: "number", }), taskExecutionDigest: text("task_execution_digest"), status: text("status").notNull().default("queued"), triggerType: text("trigger_type").notNull(), scheduledAt: timestamp("scheduled_at", { withTimezone: true }), firedAt: timestamp("fired_at", { withTimezone: true }).notNull().defaultNow(), sessionId: uuid("session_id").references(() => sessions.id), triggerEventId: uuid("trigger_event_id"), actionKind: text("action_kind").notNull().default("agent_turn"), knowledgeSyncRunId: uuid("knowledge_sync_run_id"), knowledgeSummary: jsonb("knowledge_summary").$type>(), // App data sync runs: what the run read and wrote (1520). syncSummary: jsonb("sync_summary").$type>(), completedAt: timestamp("completed_at", { withTimezone: true }), // Stable Temporal producer identity. Activity replay/re-dispatch returns // the exact run instead of allocating a second schedule source row. producerKey: text("producer_key"), // Complete credential-free accepted execution truth. It is private worker // authority and never appears in public scheduled-run projections. acceptedExecutionSnapshot: jsonb("accepted_execution_snapshot").$type(), acceptedExecutionDigest: text("accepted_execution_digest"), admissionDiagnostic: jsonb("admission_diagnostic").$type(), admissionRefusal: jsonb("admission_refusal").$type(), error: text("error"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ taskCreated: index("scheduled_task_runs_workspace_task_created_idx").on( table.workspaceId, table.taskId, table.createdAt, ), session: index("scheduled_task_runs_workspace_session_idx").on( table.workspaceId, table.sessionId, ), producer: uniqueIndex("scheduled_task_runs_producer_key_uq") .on(table.workspaceId, table.producerKey) .where(sql`${table.producerKey} is not null`), }), ); export const githubInstallations = pgTable( "github_installations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), installationId: integer("installation_id").notNull(), githubAccountId: bigint("github_account_id", { mode: "number" }), accountLogin: text("account_login"), accountType: text("account_type"), repositoryScope: text("repository_scope").notNull().default("all"), linkedBySubjectId: text("linked_by_subject_id"), githubActorId: bigint("github_actor_id", { mode: "number" }), githubActorLogin: text("github_actor_login"), authorityKind: text("authority_kind"), authorityCheckedAt: timestamp("authority_checked_at", { withTimezone: true, }), authorityExpiresAt: timestamp("authority_expires_at", { withTimezone: true, }), authorityNonce: text("authority_nonce"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceInstallation: uniqueIndex("github_installations_workspace_installation_idx").on( table.workspaceId, table.installationId, ), installation: index("github_installations_installation_idx").on(table.installationId), workspace: index("github_installations_workspace_idx").on(table.workspaceId), repositoryScopeCheck: check( "github_installations_repository_scope_check", sql`${table.repositoryScope} in ('all', 'selected')`, ), authorityKindCheck: check( "github_installations_authority_kind_check", sql` ( ${table.githubAccountId} is null and ${table.githubActorId} is null and ${table.githubActorLogin} is null and ${table.authorityKind} is null and ${table.authorityCheckedAt} is null and ${table.authorityExpiresAt} is null and ${table.authorityNonce} is null ) or ( ${table.githubAccountId} is not null and ${table.githubAccountId} > 0 and ${table.githubActorId} is not null and ${table.githubActorId} > 0 and ${table.githubActorLogin} is not null and length(${table.githubActorLogin}) > 0 and ${table.accountLogin} is not null and length(${table.accountLogin}) > 0 and ${table.accountType} is not null and ${table.linkedBySubjectId} is not null and length(${table.linkedBySubjectId}) > 0 and ${table.authorityKind} is not null and ${table.authorityCheckedAt} is not null and ${table.authorityExpiresAt} is not null and ${table.authorityCheckedAt} < ${table.authorityExpiresAt} and ${table.authorityExpiresAt} <= ${table.authorityCheckedAt} + interval '10 minutes' and ${table.authorityNonce} is not null and length(${table.authorityNonce}) > 0 and ${table.repositoryScope} = 'selected' and ( ( ${table.authorityKind} = 'personal_owner' and ${table.accountType} = 'User' and ${table.githubActorId} = ${table.githubAccountId} ) or ( ${table.authorityKind} = 'organization_owner' and ${table.accountType} = 'Organization' ) ) ) `, ), authorityNonce: uniqueIndex("github_installations_authority_nonce_uq") .on(table.authorityNonce) .where(sql`${table.authorityNonce} is not null`), }), ); export const githubInstallationRepositories = pgTable( "github_installation_repositories", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), installationId: integer("installation_id").notNull(), repositoryId: bigint("repository_id", { mode: "number" }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ installationRepository: uniqueIndex("github_install_repo_workspace_installation_repo_idx").on( table.workspaceId, table.installationId, table.repositoryId, ), workspaceInstallation: index("github_install_repo_workspace_installation_idx").on( table.workspaceId, table.installationId, ), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], name: "github_installation_repositories_workspace_account_fk", }).onDelete("cascade"), installationBinding: foreignKey({ columns: [table.workspaceId, table.installationId], foreignColumns: [githubInstallations.workspaceId, githubInstallations.installationId], name: "github_installation_repositories_installation_fk", }).onDelete("cascade"), }), ); /** * Repositories GitHub recently reported removed from a bound installation. * GitHub's list can lag its webhook: a list read within the hold window never * adds such a repository back (migration 1293). */ export const githubInstallationRepositoryRemovals = pgTable( "github_installation_repository_removals", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), installationId: integer("installation_id").notNull(), repositoryId: bigint("repository_id", { mode: "number" }).notNull(), removedAt: timestamp("removed_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ repository: uniqueIndex("github_installation_repository_removals_repo_uq").on( table.workspaceId, table.installationId, table.repositoryId, ), account: index("github_installation_repository_removals_account_idx").on(table.accountId), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], name: "github_installation_repository_removals_workspace_account_fk", }).onDelete("cascade"), installationBinding: foreignKey({ columns: [table.workspaceId, table.installationId], foreignColumns: [githubInstallations.workspaceId, githubInstallations.installationId], name: "github_installation_repository_removals_installation_fk", }).onDelete("cascade"), ids: check( "github_installation_repository_removals_ids_check", sql`${table.installationId} > 0 AND ${table.repositoryId} > 0`, ), }), ); export const usageEvents = pgTable( "usage_events", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), subjectId: text("subject_id"), eventType: text("event_type").notNull(), quantity: bigint("quantity", { mode: "number" }).notNull(), unit: text("unit").notNull(), sourceResourceType: text("source_resource_type"), sourceResourceId: text("source_resource_id"), // Exact execution source for host usage export. These are deliberately // validated soft references rather than cascading foreign keys: usage is // an immutable billing/audit fact and must retain its source identity after // a session or turn is deleted. sessionId: uuid("session_id"), turnId: uuid("turn_id"), turnAttemptId: uuid("turn_attempt_id"), initiatorKind: text("initiator_kind"), initiatorSubjectId: text("initiator_subject_id"), initiatorContext: jsonb("initiator_context") .$type>() .notNull() .default({}), origin: text("origin"), idempotencyKey: text("idempotency_key").notNull(), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(), recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull().defaultNow(), exportedToBillingAt: timestamp("exported_to_billing_at", { withTimezone: true, }), billingProviderEventId: text("billing_provider_event_id"), // Where a model-backed side feature processed this call (geography, // deployment type, regions of its route's residency record; never // evidence). Null before 1072 and for events that are not such calls. processingResidency: jsonb("processing_residency").$type<{ geography: string; deploymentType: string; regions: string[]; }>(), }, (table) => ({ idempotency: uniqueIndex("usage_events_idempotency_idx").on(table.idempotencyKey), workspaceMetric: index("usage_events_workspace_metric_idx").on( table.workspaceId, table.eventType, table.occurredAt, ), workspaceMetricPage: index("usage_events_workspace_metric_page_idx").on( table.workspaceId, table.eventType, table.occurredAt, table.id, ), workspaceMetricSource: index("usage_events_workspace_metric_source_idx").on( table.workspaceId, table.eventType, table.sourceResourceId, ), accountMetric: index("usage_events_account_metric_idx").on( table.accountId, table.eventType, table.occurredAt, ), accountRecent: index("usage_events_account_recent_idx").on( table.accountId, table.occurredAt.desc(), table.recordedAt.desc(), ), workspaceRecent: index("usage_events_workspace_recent_idx").on( table.accountId, table.workspaceId, table.occurredAt.desc(), table.recordedAt.desc(), ), workspaceSession: index("usage_events_workspace_session_idx").on( table.workspaceId, table.sessionId, table.occurredAt, ), // A turn's charges, summed onto its terminal event (migrations 1496, 1497). workspaceTurn: index("usage_events_workspace_turn_idx") .on(table.workspaceId, table.turnId) .where(sql`${table.turnId} is not null`), contextHierarchy: check( "usage_events_context_hierarchy_check", sql`(${table.turnId} is null or ${table.sessionId} is not null) and (${table.turnAttemptId} is null or ${table.turnId} is not null)`, ), initiatorConsistent: check( "usage_events_initiator_check", sql`(${table.initiatorKind} is null and ${table.initiatorSubjectId} is null) or (${table.initiatorKind} in ('subject', 'service') and ${table.initiatorSubjectId} is not null and octet_length(${table.initiatorSubjectId}) between 1 and 1024)`, ), attributionContextBytes: check( "usage_events_initiator_context_bytes_check", sql`octet_length(${table.initiatorContext}::text) <= 4096`, ), originValid: check( "usage_events_origin_check", sql`${table.origin} is null or ${table.origin} in ( 'user', 'scheduled_task', 'api', 'goal', 'system', 'compaction' )`, ), }), ); /** * Per model-call Insights facts. Additive observability only — never the billing * ledger. Written after an authoritative `agent.model.usage` emit. */ export const modelCallFactReconciliationProgress = pgTable( "model_call_fact_reconciliation_progress", { workspaceId: uuid("workspace_id").primaryKey(), accountId: uuid("account_id").notNull(), checkpoint: jsonb("checkpoint").$type(), }, (table) => ({ workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), checkpointObject: check( "model_call_fact_reconciliation_progress_checkpoint_check", sql`${table.checkpoint} is null or jsonb_typeof(${table.checkpoint}) = 'object'`, ), }), ); export const modelCallFactReconciliationCandidates = pgTable( "model_call_fact_reconciliation_candidates", { workspaceId: uuid("workspace_id").notNull(), accountId: uuid("account_id").notNull(), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), sourceKey: text("source_key").notNull(), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(), batchId: uuid("batch_id"), }, (table) => ({ pk: primaryKey({ columns: [table.workspaceId, table.turnId, table.sourceKey] }), ready: index("model_fact_reconciliation_ready_idx") .on(table.workspaceId, table.occurredAt, table.turnId, table.sourceKey) .where(sql`${table.batchId} is null`), batch: index("model_fact_reconciliation_batch_idx").on(table.workspaceId, table.batchId), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); export const modelCallFacts = pgTable( "model_call_facts", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), connectionId: uuid("connection_id").references(() => subscriptionConnections.id, { onDelete: "set null", }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), sessionId: uuid("session_id").notNull(), turnId: uuid("turn_id").notNull(), turnAttemptId: uuid("turn_attempt_id"), sourceKey: text("source_key").notNull(), provider: text("provider").notNull(), providerApi: text("provider_api").notNull(), model: text("model").notNull(), billingPath: text("billing_path").notNull(), turnSource: text("turn_source"), initiatorKind: text("initiator_kind"), initiatorSubjectId: text("initiator_subject_id"), scheduledTaskId: uuid("scheduled_task_id"), // Source-stamped attribution survives session/Site deletion. Not a foreign key. siteId: uuid("site_id"), inputTokens: bigint("input_tokens", { mode: "number" }), outputTokens: bigint("output_tokens", { mode: "number" }), cachedTokens: bigint("cached_tokens", { mode: "number" }), cacheWriteTokens: bigint("cache_write_tokens", { mode: "number" }), reasoningTokens: bigint("reasoning_tokens", { mode: "number" }), totalTokens: bigint("total_tokens", { mode: "number" }), pricedCostMicros: bigint("priced_cost_micros", { mode: "number" }).notNull().default(0), estimatedProviderCostMicros: bigint("estimated_provider_cost_micros", { mode: "number", }), equivalentCreditCostMicros: bigint("equivalent_credit_cost_micros", { mode: "number", }), pricingSource: text("pricing_source"), listUncachedInputCostMicros: bigint("list_uncached_input_cost_micros", { mode: "number" }), listCacheReadCostMicros: bigint("list_cache_read_cost_micros", { mode: "number" }), listCacheWriteCostMicros: bigint("list_cache_write_cost_micros", { mode: "number" }), listOutputCostMicros: bigint("list_output_cost_micros", { mode: "number" }), listCostIsApprox: boolean("list_cost_is_approx"), contextContributions: jsonb("context_contributions").$type(), // Worker-measured call timing in milliseconds (see ModelCallTiming); null // for calls before 0802 and calls the worker did not stream. preDispatchMs: integer("pre_dispatch_ms"), timeToFirstTokenMs: integer("time_to_first_token_ms"), timeToFirstTextMs: integer("time_to_first_text_ms"), durationMs: integer("duration_ms"), // Prompt-cache observation and warm-miss classification (see // PromptCacheDiagnostics); null before 0979 and for repaired facts. promptCacheDiagnostics: jsonb("prompt_cache_diagnostics").$type(), // Processing residency claim of the route that served the call (see // ModelCallProcessingResidencyV1), never evidence; null before 1030. processingResidency: jsonb("processing_residency").$type(), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(), recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceTurnSource: uniqueIndex("model_call_facts_workspace_turn_source_uq").on( table.workspaceId, table.turnId, table.sourceKey, ), workspaceOccurred: index("model_call_facts_workspace_occurred_idx").on( table.workspaceId, table.occurredAt, ), workspaceProviderModelOccurred: index( "model_call_facts_workspace_provider_model_occurred_idx", ).on(table.workspaceId, table.provider, table.model, table.occurredAt), workspaceSessionOccurred: index("model_call_facts_workspace_session_occurred_idx").on( table.workspaceId, table.sessionId, table.occurredAt, ), subscriptionConnectionOccurred: index("model_call_facts_connection_occurred_idx") .on(table.accountId, table.connectionId, table.occurredAt) .where(sql`${table.connectionId} is not null`), workspaceScheduledTaskOccurred: index("model_call_facts_workspace_scheduled_task_occurred_idx") .on(table.workspaceId, table.scheduledTaskId, table.occurredAt) .where(sql`${table.scheduledTaskId} is not null`), workspaceAccount: foreignKey({ name: "model_call_facts_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), billingPathValid: check( "model_call_facts_billing_path_check", sql`${table.billingPath} in ('opengeni_credits', 'external')`, ), pricedCostNonNegative: check( "model_call_facts_priced_cost_check", sql`${table.pricedCostMicros} >= 0`, ), estimatedProviderCostValid: check( "model_call_facts_estimated_provider_cost_check", sql`${table.estimatedProviderCostMicros} is null or ${table.estimatedProviderCostMicros} >= 0`, ), equivalentCreditCostValid: check( "model_call_facts_equivalent_credit_cost_check", sql`${table.equivalentCreditCostMicros} is null or (${table.equivalentCreditCostMicros} >= 0 and ${table.estimatedProviderCostMicros} is not null)`, ), pricingSourceValid: check( "model_call_facts_pricing_source_check", sql`(${table.estimatedProviderCostMicros} is null and ${table.pricingSource} is null) or (${table.estimatedProviderCostMicros} is not null and ${table.pricingSource} in ('configured_list_price', 'gateway_reported'))`, ), listUncachedInputCostValid: check( "model_call_facts_list_uncached_input_cost_micros_check", sql`${table.listUncachedInputCostMicros} >= 0`, ), listCacheReadCostValid: check( "model_call_facts_list_cache_read_cost_micros_check", sql`${table.listCacheReadCostMicros} >= 0`, ), listCacheWriteCostValid: check( "model_call_facts_list_cache_write_cost_micros_check", sql`${table.listCacheWriteCostMicros} >= 0`, ), listOutputCostValid: check( "model_call_facts_list_output_cost_micros_check", sql`${table.listOutputCostMicros} >= 0`, ), listClassesValid: check( "model_call_facts_list_classes_check", sql` (${table.listUncachedInputCostMicros} is null and ${table.listCacheReadCostMicros} is null and ${table.listCacheWriteCostMicros} is null and ${table.listOutputCostMicros} is null) or (${table.estimatedProviderCostMicros} is not null and ${table.listCostIsApprox} is not null and ${table.listUncachedInputCostMicros} is not null and ${table.listCacheReadCostMicros} is not null and ${table.listCacheWriteCostMicros} is not null and ${table.listOutputCostMicros} is not null and ${table.estimatedProviderCostMicros}::numeric = ${table.listUncachedInputCostMicros}::numeric + ${table.listCacheReadCostMicros}::numeric + ${table.listCacheWriteCostMicros}::numeric + ${table.listOutputCostMicros}::numeric)`, ), initiatorConsistent: check( "model_call_facts_initiator_check", sql`(${table.initiatorKind} is null and ${table.initiatorSubjectId} is null) or (${table.initiatorKind} in ('subject', 'service') and ${table.initiatorSubjectId} is not null and octet_length(${table.initiatorSubjectId}) between 1 and 1024)`, ), sourceKeyBytes: check( "model_call_facts_source_key_bytes_check", sql`octet_length(${table.sourceKey}) between 1 and 1024`, ), providerBytes: check( "model_call_facts_provider_bytes_check", sql`octet_length(${table.provider}) between 1 and 256`, ), providerApiBytes: check( "model_call_facts_provider_api_bytes_check", sql`octet_length(${table.providerApi}) between 1 and 256`, ), modelBytes: check( "model_call_facts_model_bytes_check", sql`octet_length(${table.model}) between 1 and 512`, ), contextContributionsValid: check( "model_call_facts_context_contributions_check", sql`opengeni_private.model_context_contributions_valid(${table.contextContributions})`, ), }), ); /** Singleton, migration-installed gate. Standalone defaults keep every kind off. */ export const hostExportConfig = pgTable( "host_export_config", { id: integer("id").primaryKey().default(1), sessionEventsEnabled: boolean("session_events_enabled").notNull().default(false), usageEventsEnabled: boolean("usage_events_enabled").notNull().default(false), lifecycleFactsEnabled: boolean("lifecycle_facts_enabled").notNull().default(false), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ singleton: check("host_export_config_singleton_check", sql`${table.id} = 1`), }), ); /** * Transactional delivery buffer. It intentionally has no tenant/source FKs: * a workspace deletion must not erase an already-committed, unacknowledged * host fact. Session-event rows retain exact storage bytes while they fit the * bounded host wire; larger canonical events carry an explicit content-free * projection plus literal-JSON codec truth. Usage payloads remain ordinary JSON. */ export const hostExportOutbox = pgTable( "host_export_outbox", { id: uuid("id").primaryKey().defaultRandom(), exportKind: text("export_kind").notNull(), exportCursor: bigint("export_cursor", { mode: "bigint" }), sourceId: uuid("source_id").notNull(), // Null only for `lifecycle_fact` rows (see host_export_outbox_scope_check). accountId: uuid("account_id"), workspaceId: uuid("workspace_id"), sessionId: uuid("session_id"), rootSessionId: uuid("root_session_id"), turnId: uuid("turn_id"), turnGeneration: integer("turn_generation"), turnAttemptId: uuid("turn_attempt_id"), sessionSequence: integer("session_sequence"), clientEventId: text("client_event_id"), turnAssociation: text("turn_association"), duplicateOfEventId: uuid("duplicate_of_event_id"), duplicateReason: text("duplicate_reason"), eventType: text("event_type").notNull(), idempotencyKey: text("idempotency_key").notNull(), initiator: jsonb("initiator").$type | null>(), initiatorContext: jsonb("initiator_context") .$type>() .notNull() .default({}), origin: text("origin"), // Content-free analytics dimensions captured with the row (migration 0533). surface: text("surface"), modelProvider: text("model_provider"), toolFamily: text("tool_family"), payload: jsonb("payload").$type().notNull(), payloadCodecVersion: losslessCodecVersion("payload_codec_version"), envelopeBytes: integer("envelope_bytes").notNull(), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(), sourceRecordedAt: timestamp("source_recorded_at", { withTimezone: true, }).notNull(), enqueuedAt: timestamp("enqueued_at", { withTimezone: true }).notNull(), }, (table) => ({ kindValid: check( "host_export_outbox_kind_check", sql`${table.exportKind} in ('session_event', 'usage_event', 'lifecycle_fact')`, ), scopeValid: check( "host_export_outbox_scope_check", sql`(${table.exportKind} <> 'lifecycle_fact' and ${table.accountId} is not null and ${table.workspaceId} is not null) or (${table.exportKind} = 'lifecycle_fact' and (${table.workspaceId} is null or ${table.accountId} is not null) and ${table.sessionId} is null)`, ), rootSessionCaptured: check( "host_export_outbox_root_session_check", sql`${table.sessionId} is null or ${table.rootSessionId} is not null`, ), sourceUnique: uniqueIndex("host_export_outbox_source_uq").on(table.exportKind, table.sourceId), cursorUnique: uniqueIndex("host_export_outbox_cursor_uq") .on(table.exportKind, table.exportCursor) .where(sql`${table.exportCursor} is not null`), unassigned: index("host_export_outbox_unassigned_idx") .on(table.exportKind, table.enqueuedAt, table.id) .where(sql`${table.exportCursor} is null`), unassignedSession: index("host_export_outbox_unassigned_session_idx") .on(table.exportKind, table.sessionId, table.sessionSequence) .where(sql`${table.exportCursor} is null and ${table.sessionId} is not null`), contextBytes: check( "host_export_outbox_context_bytes_check", sql`octet_length(${table.initiatorContext}::text) <= 4096`, ), originValid: check( "host_export_outbox_origin_check", sql`${table.origin} is null or ${table.origin} in ( 'user', 'scheduled_task', 'api', 'goal', 'system', 'compaction' )`, ), analyticsValid: check( "host_export_outbox_analytics_check", sql`(${table.surface} is null or ${table.surface} in ( 'web', 'slack', 'api_key', 'embedded', 'scheduled', 'agent', 'voice', 'site', 'automation', 'mcp', 'system' )) and (${table.modelProvider} is null or ${table.modelProvider} in ( 'openai', 'azure', 'codex-subscription', 'supergrok-subscription', 'opengeni-gateway', 'workspace-gateway', 'organization-gateway', 'openrouter', 'workspace-openrouter', 'organization-openrouter', 'opper', 'workspace-opper', 'organization-opper', 'organization-openai', 'organization-azure-openai', 'registry' )) and (${table.toolFamily} is null or ${table.toolFamily} ~ '^(custom|integration:[a-z0-9]([a-z0-9.-]{0,150}[a-z0-9])?|[a-z][a-z0-9_]{0,63})$')`, ), }), ); export const hostExportCursorState = pgTable( "host_export_cursor_state", { exportKind: text("export_kind").primaryKey(), nextCursor: bigint("next_cursor", { mode: "bigint" }).notNull().default(1n), prunedThrough: bigint("pruned_through", { mode: "bigint" }).notNull().default(0n), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ kindValid: check( "host_export_cursor_state_kind_check", sql`${table.exportKind} in ('session_event', 'usage_event', 'lifecycle_fact')`, ), cursorValid: check( "host_export_cursor_state_next_check", sql`${table.nextCursor} > 0 and ${table.prunedThrough} >= 0 and ${table.prunedThrough} < ${table.nextCursor}`, ), }), ); /** Named at-least-once consumer checkpoint and one-batch lease. */ export const hostExportConsumers = pgTable( "host_export_consumers", { id: uuid("id").primaryKey().defaultRandom(), consumerId: text("consumer_id").notNull(), exportKind: text("export_kind").notNull(), checkpoint: bigint("checkpoint", { mode: "bigint" }).notNull().default(0n), enabled: boolean("enabled").notNull().default(true), leaseToken: uuid("lease_token"), leaseHolderId: text("lease_holder_id"), leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }), leaseFrom: bigint("lease_from", { mode: "bigint" }), leaseThrough: bigint("lease_through", { mode: "bigint" }), consecutiveFailures: integer("consecutive_failures").notNull().default(0), nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(), lastError: text("last_error"), lastErrorCodecVersion: losslessCodecVersion("last_error_codec_version"), lastErrorAt: timestamp("last_error_at", { withTimezone: true }), blockedAt: timestamp("blocked_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ consumerKind: uniqueIndex("host_export_consumers_kind_id_uq").on( table.exportKind, table.consumerId, ), kindValid: check( "host_export_consumers_kind_check", sql`${table.exportKind} in ('session_event', 'usage_event', 'lifecycle_fact')`, ), checkpointValid: check("host_export_consumers_checkpoint_check", sql`${table.checkpoint} >= 0`), due: index("host_export_consumers_due_idx").on( table.enabled, table.blockedAt, table.nextAttemptAt, ), }), ); /** Explicit poison-row disposition; transient failures never write here. */ export const hostExportDeadLetters = pgTable( "host_export_dead_letters", { id: uuid("id").primaryKey().defaultRandom(), consumerId: text("consumer_id").notNull(), exportKind: text("export_kind").notNull(), exportCursor: bigint("export_cursor", { mode: "bigint" }).notNull(), sourceId: uuid("source_id").notNull(), reason: text("reason").notNull(), envelope: losslessJsonb("envelope").$type>().notNull(), envelopeCodecVersion: losslessCodecVersion("envelope_codec_version"), eventPayloadCodecVersion: losslessCodecVersion("event_payload_codec_version"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ consumerCursor: uniqueIndex("host_export_dead_letters_consumer_cursor_uq").on( table.exportKind, table.consumerId, table.exportCursor, ), kindValid: check( "host_export_dead_letters_kind_check", sql`${table.exportKind} in ('session_event', 'usage_event', 'lifecycle_fact')`, ), reasonValid: check( "host_export_dead_letters_reason_check", sql`length(${table.reason}) between 1 and 500`, ), envelopeBytes: check( "host_export_dead_letters_envelope_bytes_check", sql`pg_column_size(${table.envelope}) <= 114688`, ), }), ); export const creditLedgerEntries = pgTable( "credit_ledger_entries", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "set null", }), type: text("type").notNull(), amountMicros: bigint("amount_micros", { mode: "number" }).notNull(), /** Null preserves the unrestricted terms of legacy credits. */ eligibleModelIds: text("eligible_model_ids").array(), currency: text("currency").notNull().default("usd"), sourceType: text("source_type"), sourceId: text("source_id"), // Immutable execution-origin attribution, not an allocated platform charge. siteId: uuid("site_id"), // Funding origin of a usage debit (`BillingOrigin`). API debits never // count against the monthly plan allowance (plan_period_usage). Null is // legacy or non-usage and treated as app. usageOrigin: text("usage_origin"), idempotencyKey: text("idempotency_key").notNull(), metadata: jsonb("metadata").$type>().notNull().default({}), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ idempotency: uniqueIndex("credit_ledger_entries_idempotency_idx").on(table.idempotencyKey), idAccount: uniqueIndex("credit_ledger_entries_id_account_idx").on(table.id, table.accountId), scopedGrants: index("credit_ledger_scoped_grants_idx") .on(table.accountId, table.createdAt, table.id) .where(sql`${table.eligibleModelIds} is not null`), // Rows that can carry a paid-credit receipt (credit-balances.ts reads // paid credit and own-key fee debt from these alone). receiptRows: index("credit_ledger_receipt_rows_idx") .on(table.accountId, table.createdAt) .where( sql`${table.amountMicros} > 0 or ${table.type} in ('credit_refund', 'credit_dispute_hold', 'byok_platform_fee')`, ), scopeValid: check( "credit_ledger_scope_valid", sql`${table.eligibleModelIds} is null or ( ${table.type} = 'grant' and ${table.amountMicros} > 0 and cardinality(${table.eligibleModelIds}) between 1 and 40 and array_position(${table.eligibleModelIds}, null) is null and array_position(${table.eligibleModelIds}, '') is null )`, ), modelDebitPeriod: index("credit_ledger_entries_model_debit_period_idx") .on(table.accountId, table.occurredAt, table.workspaceId) .where( sql`${table.type}='model_usage_debit' and ${table.sourceType}='model_response' and ${table.amountMicros}<0`, ), accountCreated: index("credit_ledger_entries_account_created_idx").on( table.accountId, table.createdAt, ), }), ); export const subscriptionPlanCatalogRevisions = opengeniPrivateSchema.table( "subscription_plan_catalog_revisions", { revision: bigint("revision", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(), catalog: jsonb("catalog") .$type() .notNull(), operator: text("operator").notNull(), reason: text("reason").notNull(), databaseRole: text("database_role") .notNull() .default(sql`session_user`), changedAt: timestamp("changed_at", { withTimezone: true }) .notNull() .default(sql`clock_timestamp()`), }, ); export const billingSubscriptionOperations = pgTable( "billing_subscription_operations", { accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), operationKey: uuid("operation_key").notNull(), kind: text("kind").notNull(), request: jsonb("request").$type>().notNull(), intent: jsonb("intent").$type>().notNull(), result: jsonb("result").$type>(), createdAt: timestamp("created_at", { withTimezone: true }) .notNull() .default(sql`clock_timestamp()`), completedAt: timestamp("completed_at", { withTimezone: true }), }, (table) => ({ pk: primaryKey({ columns: [table.accountId, table.operationKey] }), pending: uniqueIndex("billing_subscription_operations_pending_idx") .on(table.accountId) .where(sql`${table.completedAt} is null`), }), ); export const billingAutoTopUpSettings = pgTable("billing_auto_top_up_settings", { accountId: uuid("account_id") .primaryKey() .references(() => managedAccounts.id, { onDelete: "cascade" }), enabled: boolean("enabled").notNull().default(false), thresholdMicros: bigint("threshold_micros", { mode: "number" }).notNull().default(10000000), amountMicros: bigint("amount_micros", { mode: "number" }).notNull().default(25000000), monthlyCapMicros: bigint("monthly_cap_micros", { mode: "number" }).notNull().default(100000000), consentSubject: text("consent_subject"), consentVersion: text("consent_version"), consentAt: timestamp("consent_at", { withTimezone: true }), provider: text("provider"), customerId: text("customer_id"), paymentMethodId: text("payment_method_id"), paymentMethodBrand: text("payment_method_brand"), paymentMethodLast4: text("payment_method_last4"), setupKey: uuid("setup_key"), setupSubject: text("setup_subject"), failureReason: text("failure_reason"), capRequiredMicros: bigint("cap_required_micros", { mode: "number" }), revision: uuid("revision").notNull(), updatedAt: timestamp("updated_at", { withTimezone: true }) .notNull() .default(sql`clock_timestamp()`), }); export const billingAutoTopUpMutations = pgTable( "billing_auto_top_up_mutations", { accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), operationKey: uuid("operation_key").notNull(), actorSubject: text("actor_subject").notNull(), request: jsonb("request").$type>().notNull(), createdAt: timestamp("created_at", { withTimezone: true }) .notNull() .default(sql`clock_timestamp()`), }, (table) => ({ pk: primaryKey({ columns: [table.accountId, table.operationKey] }) }), ); export const billingAutoTopUpOperations = pgTable( "billing_auto_top_up_operations", { accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), operationKey: uuid("operation_key").notNull(), state: text("state").notNull().default("pending"), reservationMonth: date("reservation_month").notNull(), creditMicros: bigint("credit_micros", { mode: "number" }).notNull(), chargeMicros: bigint("charge_micros", { mode: "number" }).notNull(), intent: jsonb("intent").$type().notNull(), paymentIntentId: text("payment_intent_id").unique(), confirmationStartedAt: timestamp("confirmation_started_at", { withTimezone: true }), chargedAt: timestamp("charged_at", { withTimezone: true }), failureReason: text("failure_reason"), notificationDeliveredAt: timestamp("notification_delivered_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }) .notNull() .default(sql`clock_timestamp()`), completedAt: timestamp("completed_at", { withTimezone: true }), }, (table) => ({ pk: primaryKey({ columns: [table.accountId, table.operationKey] }), pending: uniqueIndex("billing_auto_top_up_one_pending") .on(table.accountId) .where(sql`${table.state} = 'pending'`), month: index("billing_auto_top_up_month").on(table.accountId, table.reservationMonth), }), ); export const organizationPlans = pgTable("organization_plans", { accountId: uuid("account_id") .primaryKey() .references(() => managedAccounts.id, { onDelete: "cascade" }), planKey: text("plan_key").notNull(), status: text("status").notNull(), stripeSubscriptionId: text("stripe_subscription_id").unique(), currentPeriodStart: timestamp("current_period_start", { withTimezone: true }), currentPeriodEnd: timestamp("current_period_end", { withTimezone: true }), cancelAtPeriodEnd: boolean("cancel_at_period_end").notNull().default(false), createdAt: timestamp("created_at", { withTimezone: true }) .notNull() .default(sql`clock_timestamp()`), updatedAt: timestamp("updated_at", { withTimezone: true }) .notNull() .default(sql`clock_timestamp()`), }); export const planCreditPeriods = pgTable( "plan_credit_periods", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), planKey: text("plan_key").notNull(), catalogRevision: bigint("catalog_revision", { mode: "number" }) .notNull() .references(() => subscriptionPlanCatalogRevisions.revision), stripeSubscriptionId: text("stripe_subscription_id"), periodStart: timestamp("period_start", { withTimezone: true }).notNull(), periodEnd: timestamp("period_end", { withTimezone: true }).notNull(), grantedMicros: bigint("granted_micros", { mode: "number" }).notNull(), openingDebtMicros: bigint("opening_debt_micros", { mode: "number" }).notNull(), grantEntryId: uuid("grant_entry_id").notNull().unique(), idempotencyKey: text("idempotency_key").notNull().unique(), grantedAt: timestamp("granted_at", { withTimezone: true }) .notNull() .default(sql`clock_timestamp()`), expiredAt: timestamp("expired_at", { withTimezone: true }), expiryEntryId: uuid("expiry_entry_id").unique(), usageAtExpiryMicros: bigint("usage_at_expiry_micros", { mode: "number" }), }, (table) => ({ openingDebt: check( "plan_credit_periods_opening_debt_check", sql`${table.openingDebtMicros} between 0 and ${table.grantedMicros}`, ), grant: foreignKey({ columns: [table.grantEntryId, table.accountId], foreignColumns: [creditLedgerEntries.id, creditLedgerEntries.accountId], }), expiry: foreignKey({ columns: [table.expiryEntryId, table.accountId], foreignColumns: [creditLedgerEntries.id, creditLedgerEntries.accountId], }), open: uniqueIndex("plan_credit_periods_open_idx") .on(table.accountId) .where(sql`${table.expiredAt} is null`), due: index("plan_credit_periods_due_idx") .on(table.periodEnd, table.accountId) .where(sql`${table.expiredAt} is null`), }), ); /** One debit can consume several grants; the remainder is paid by general credits. */ export const creditDebitAllocations = pgTable( "credit_debit_allocations", { accountId: uuid("account_id").notNull(), debitEntryId: uuid("debit_entry_id").notNull(), grantEntryId: uuid("grant_entry_id").notNull(), amountMicros: bigint("amount_micros", { mode: "number" }).notNull(), }, (table) => ({ pk: primaryKey({ columns: [table.debitEntryId, table.grantEntryId] }), debit: foreignKey({ columns: [table.debitEntryId, table.accountId], foreignColumns: [creditLedgerEntries.id, creditLedgerEntries.accountId], }).onDelete("cascade"), grant: foreignKey({ columns: [table.grantEntryId, table.accountId], foreignColumns: [creditLedgerEntries.id, creditLedgerEntries.accountId], }).onDelete("cascade"), grantIndex: index("credit_debit_allocations_grant_idx").on(table.accountId, table.grantEntryId), positive: check("credit_debit_allocations_positive", sql`${table.amountMicros} > 0`), }), ); /** Content-free immutable accepted billing facts; no runtime table privileges. */ export const usageAllowanceAttributionReceipts = opengeniPrivateSchema.table( "usage_allowance_attribution_receipts", { accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sourceKind: text("source_kind") .$type<"turn" | "schedule" | "knowledge_query" | "voice_transcription" | "voice_realtime">() .notNull(), sourceId: text("source_id").notNull(), sessionId: uuid("session_id"), attribution: jsonb("attribution") .$type() .notNull(), quantity: bigint("quantity", { mode: "number" }), idempotencyKey: text("idempotency_key"), }, (table) => ({ pk: primaryKey({ columns: [table.accountId, table.workspaceId, table.sourceKind, table.sourceId], }), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); /** EXECUTE-only lifecycle/counter storage; migration 0547 owns FORCE-RLS policy. */ export const workspaceAllowanceClearReceipts = opengeniPrivateSchema.table( "workspace_allowance_clear_receipts", { workspaceId: uuid("workspace_id").notNull(), accountId: uuid("account_id").notNull(), operationId: text("operation_id").notNull(), request: jsonb("request").$type>().notNull(), result: jsonb("result").$type<{ version: number }>().notNull(), }, (table) => ({ pk: primaryKey({ columns: [table.workspaceId, table.operationId] }), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); export const workspaceUsageAllowances = opengeniPrivateSchema.table( "workspace_usage_allowances", { workspaceId: uuid("workspace_id").primaryKey(), accountId: uuid("account_id").notNull(), config: jsonb("config").$type(), version: bigint("version", { mode: "number" }).notNull().default(1), actorSubjectId: text("actor_subject_id").notNull(), actorType: text("actor_type").notNull(), activePeriodKey: text("active_period_key"), activeStartAt: timestamp("active_start_at", { withTimezone: true }), activeEndAt: timestamp("active_end_at", { withTimezone: true }), maintenanceNextAt: timestamp("maintenance_next_at", { withTimezone: true }) .notNull() .defaultNow(), maintenanceCursor: text("maintenance_cursor"), maintenanceError: text("maintenance_error"), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ maintenanceDue: index("workspace_usage_allowances_maintenance_due") .on(table.maintenanceNextAt, table.workspaceId) .where(sql`${table.config} is not null`), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); export const workspaceMemberAllowances = opengeniPrivateSchema.table( "workspace_member_allowances", { workspaceId: uuid("workspace_id").notNull(), accountId: uuid("account_id").notNull(), subjectId: text("subject_id").notNull(), rule: jsonb("rule").$type(), version: bigint("version", { mode: "number" }).notNull().default(1), actorSubjectId: text("actor_subject_id").notNull(), actorType: text("actor_type").notNull(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ columns: [table.workspaceId, table.subjectId] }), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); export const workspaceAllowanceGrants = opengeniPrivateSchema.table( "workspace_allowance_grants", { workspaceId: uuid("workspace_id").notNull(), accountId: uuid("account_id").notNull(), operationId: text("operation_id").notNull(), credits: bigint("credits", { mode: "number" }).notNull(), remaining: bigint("remaining", { mode: "number" }).notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }), actorSubjectId: text("actor_subject_id").notNull(), actorType: text("actor_type").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ columns: [table.workspaceId, table.operationId] }), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), fefo: index("workspace_allowance_grants_fefo") .on(table.workspaceId, table.expiresAt, table.createdAt, table.operationId) .where(sql`${table.remaining} > 0`), }), ); export const workspaceAllowanceCounters = opengeniPrivateSchema.table( "workspace_allowance_counters", { workspaceId: uuid("workspace_id").notNull(), accountId: uuid("account_id").notNull(), periodKey: text("period_key").notNull(), subjectId: text("subject_id").notNull().default(""), used: bigint("used", { mode: "number" }).notNull().default(0), includedUsed: bigint("included_used", { mode: "number" }).notNull().default(0), grantsUsed: bigint("grants_used", { mode: "number" }).notNull().default(0), }, (table) => ({ pk: primaryKey({ columns: [table.workspaceId, table.periodKey, table.subjectId] }), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); export const workspaceAllowanceNotifications = opengeniPrivateSchema.table( "workspace_allowance_notifications", { id: uuid("id").primaryKey().defaultRandom(), workspaceId: uuid("workspace_id").notNull(), accountId: uuid("account_id").notNull(), periodKey: text("period_key").notNull(), subjectId: text("subject_id").notNull(), threshold: numeric("threshold").notNull(), payload: jsonb("payload").$type>().notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ crossing: uniqueIndex("workspace_allowance_notifications_crossing").on( table.workspaceId, table.periodKey, table.subjectId, table.threshold, ), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); export const workspaceAllowancePeriods = opengeniPrivateSchema.table( "workspace_allowance_periods", { workspaceId: uuid("workspace_id").notNull(), accountId: uuid("account_id").notNull(), periodKey: text("period_key").notNull(), config: jsonb("config").$type(), startAt: timestamp("start_at", { withTimezone: true }), endAt: timestamp("end_at", { withTimezone: true }), grantsRemaining: bigint("grants_remaining", { mode: "number" }).notNull().default(0), grantsSnapshot: jsonb("grants_snapshot").$type().notNull().default([]), memberRules: jsonb("member_rules").$type>().notNull().default({}), memberCount: integer("member_count").notNull().default(0), closedAt: timestamp("closed_at", { withTimezone: true }), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ columns: [table.workspaceId, table.periodKey] }), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); export const workspaceVideoAllowanceAllocations = opengeniPrivateSchema.table( "workspace_video_allowance_allocations", { ledgerId: uuid("ledger_id") .primaryKey() .references(() => creditLedgerEntries.id, { onDelete: "cascade" }), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), operationId: uuid("operation_id").notNull(), periodKey: text("period_key").notNull(), humanSubjectId: text("human_subject_id"), amount: bigint("amount", { mode: "number" }).notNull(), includedUsed: bigint("included_used", { mode: "number" }).notNull(), grantsUsed: bigint("grants_used", { mode: "number" }).notNull(), grantAllocations: jsonb("grant_allocations") .$type>() .notNull(), reversedByLedgerId: uuid("reversed_by_ledger_id").references(() => creditLedgerEntries.id), }, (table) => ({ operation: uniqueIndex("workspace_video_allowance_allocations_operation_idx").on( table.accountId, table.workspaceId, table.operationId, ), refund: uniqueIndex("workspace_video_allowance_allocations_refund_idx") .on(table.reversedByLedgerId) .where(sql`${table.reversedByLedgerId} is not null`), workspaceAccount: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), }), ); export const billingCustomers = pgTable( "billing_customers", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), provider: text("provider").notNull().default("stripe"), providerCustomerId: text("provider_customer_id").notNull(), email: text("email"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ accountProvider: uniqueIndex("billing_customers_account_provider_idx").on( table.accountId, table.provider, ), providerCustomer: uniqueIndex("billing_customers_provider_customer_idx").on( table.provider, table.providerCustomerId, ), }), ); export const stripeWebhookEvents = pgTable("stripe_webhook_events", { id: text("id").primaryKey(), type: text("type").notNull(), livemode: text("livemode").notNull().default("false"), payload: jsonb("payload").$type().notNull(), processedAt: timestamp("processed_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }); export const auditEvents = pgTable( "audit_events", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").references(() => managedAccounts.id, { onDelete: "set null", }), workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "set null", }), subjectId: text("subject_id"), action: text("action").notNull(), targetType: text("target_type"), targetId: text("target_id"), metadata: losslessJsonb("metadata").$type>().notNull().default({}), metadataCodecVersion: losslessCodecVersion("metadata_codec_version"), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ accountCreated: index("audit_events_account_created_idx").on(table.accountId, table.occurredAt), workspaceCreated: index("audit_events_workspace_created_idx").on( table.workspaceId, table.occurredAt, ), }), ); export const importBatches = pgTable( "import_batches", { id: uuid("id").primaryKey().defaultRandom(), source: text("source").notNull(), snapshotDate: timestamp("snapshot_date", { withTimezone: true }).notNull(), snapshotRef: text("snapshot_ref"), attributionNote: text("attribution_note").notNull(), importedCount: integer("imported_count").notNull().default(0), skippedCount: integer("skipped_count").notNull().default(0), quarantinedCount: integer("quarantined_count").notNull().default(0), logoFailureCount: integer("logo_failure_count").notNull().default(0), staleCount: integer("stale_count").notNull().default(0), details: jsonb("details").$type>().notNull().default({}), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ sourceSnapshot: index("import_batches_source_snapshot_idx").on( table.source, table.snapshotDate, ), createdAt: index("import_batches_created_at_idx").on(table.createdAt), }), ); export const capabilityCatalogItems = pgTable( "capability_catalog_items", { id: text("id").notNull(), accountId: uuid("account_id").references(() => managedAccounts.id, { onDelete: "cascade", }), workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade", }), kind: text("kind").notNull(), source: text("source").notNull().default("manual"), name: text("name").notNull(), description: text("description"), category: text("category").notNull().default("custom"), tags: jsonb("tags").$type().notNull().default([]), homepageUrl: text("homepage_url"), endpointUrl: text("endpoint_url"), installUrl: text("install_url"), authModel: text("auth_model"), providerDomain: text("provider_domain"), surfaceType: text("surface_type"), transport: text("transport"), mcpUrl: text("mcp_url"), authKind: text("auth_kind"), credentialFacts: jsonb("credential_facts") .$type>>() .notNull() .default([]), tier: text("tier"), provenance: text("provenance"), logoAssetPath: text("logo_asset_path"), importBatchId: uuid("import_batch_id").references(() => importBatches.id, { onDelete: "set null", }), stale: boolean("stale").notNull().default(false), staleAt: timestamp("stale_at", { withTimezone: true }), metadata: jsonb("metadata").$type>().notNull().default({}), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ kindAuthority: check("capability_catalog_items_kind_authority_chk", sql`${table.kind} = 'mcp'`), workspaceCapability: uniqueIndex("capability_catalog_items_workspace_capability_idx").on( table.workspaceId, table.id, ), registrySurface: uniqueIndex("capability_catalog_items_registry_surface_idx").on( table.source, table.providerDomain, table.mcpUrl, ), globalCapability: uniqueIndex("capability_catalog_items_global_capability_idx") .on(table.id) .where(sql`${table.workspaceId} is null`), kind: index("capability_catalog_items_workspace_kind_idx").on(table.workspaceId, table.kind), category: index("capability_catalog_items_workspace_category_idx").on( table.workspaceId, table.category, ), source: index("capability_catalog_items_workspace_source_idx").on( table.workspaceId, table.source, ), providerDomain: index("capability_catalog_items_provider_domain_idx").on(table.providerDomain), importBatch: index("capability_catalog_items_import_batch_idx").on(table.importBatchId), stale: index("capability_catalog_items_source_stale_idx").on(table.source, table.stale), }), ); export const capabilityInstallations = pgTable( "capability_installations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), capabilityId: text("capability_id").notNull(), kind: text("kind").notNull(), status: text("status").notNull().default("active"), config: jsonb("config").$type>().notNull().default({}), metadata: jsonb("metadata").$type>().notNull().default({}), enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), /** Who turned it on or last changed it; null (every row from before 1228) * counts as installed by an admin. A member removes only their own. */ installedBySubjectId: text("installed_by_subject_id"), }, (table) => ({ kindAuthority: check("capability_installations_kind_authority_chk", sql`${table.kind} = 'mcp'`), workspaceCapability: uniqueIndex("capability_installations_workspace_capability_idx").on( table.workspaceId, table.capabilityId, ), kind: index("capability_installations_workspace_kind_idx").on(table.workspaceId, table.kind), status: index("capability_installations_workspace_status_idx").on( table.workspaceId, table.status, ), }), ); /** * An organization's connector, added once by an organization owner or admin * and served to the workspaces its reach selects: every shared workspace * (`allowedWorkspaceIds` null) or the listed ones, plus members' Personal * workspaces when `allowPersonalWorkspaces` is on. A workspace's own setup of * the same capability, on or off, wins (resolved by readers). * * `kind` "mcp": a remote MCP server. `config` has the shape of a workspace * installation's config; `customDefinition` holds a custom server's name and * endpoint and is null for a catalog connector. * `kind` "api": an API integration. `customDefinition` is the reviewed, * compiled definition every reached workspace runs; `config` holds how turns * sign in and the tools that are on. */ export type OrganizationMcpServerDefinition = { name: string; description?: string | null; endpointUrl: string; }; /** What an organization admin reviewed when adding an API integration. */ export type OrganizationApiIntegrationDefinition = { kind: "api"; name: string; description: string | null; definitionId: string; definitionProvenance: "curated" | "workspace"; protocol: "openapi" | "graphql"; pluginKey: string; /** The base server id a workspace installation of it would use. */ serverId: string; provider: string | null; providerDomain: string; baseUrl: string; sourceUrl: string | null; /** The source it was compiled from, as a preview echoes it (never an inline document's text). */ source: Record; requiredScopes: string[]; /** How the API authenticates, as the preview showed it: what each person or the key provides. */ auth: ApiIntegrationAuthPreview; authScheme: Record; revision: StoredApiIntegrationRevision; }; export const organizationConnectors = pgTable( "organization_connectors", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), capabilityId: text("capability_id").notNull(), kind: text("kind").$type<"mcp" | "api">().notNull().default("mcp"), customDefinition: jsonb("custom_definition").$type< OrganizationMcpServerDefinition | OrganizationApiIntegrationDefinition >(), config: jsonb("config").$type>().notNull().default({}), metadata: jsonb("metadata").$type>().notNull().default({}), status: text("status").$type<"active" | "disabled">().notNull().default("active"), allowedWorkspaceIds: uuid("allowed_workspace_ids").array(), allowPersonalWorkspaces: boolean("allow_personal_workspaces").notNull().default(false), generation: integer("generation").notNull().default(1), createdBySubjectId: text("created_by_subject_id").notNull(), updatedBySubjectId: text("updated_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ capability: unique("organization_connectors_capability_key").on( table.accountId, table.capabilityId, ), statusCheck: check( "organization_connectors_status_chk", sql`${table.status} in ('active', 'disabled')`, ), kindCheck: check( "organization_connectors_kind_chk", sql`${table.kind} in ('mcp', 'api') and (${table.kind} = 'mcp' or ${table.customDefinition} is not null)`, ), }), ); // --- MCP auto-connect (1263) ------------------------------------------------- // Inbound: issuers an organization trusts to vouch for its members (ID-JAG). export const organizationMcpTrustedIssuers = pgTable( "organization_mcp_trusted_issuers", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), name: text("name").notNull(), provider: text("provider").$type<"claude" | "okta" | "other">().notNull(), issuer: text("issuer").notNull(), jwksUri: text("jwks_uri"), allowedClientIds: jsonb("allowed_client_ids").$type(), organizationAccess: jsonb("organization_access").$type().notNull(), status: text("status").$type<"active" | "disabled">().notNull().default("active"), createdBySubjectId: text("created_by_subject_id").notNull(), updatedBySubjectId: text("updated_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ issuerKey: unique("organization_mcp_trusted_issuers_issuer_key").on( table.accountId, table.issuer, ), issuerLookup: index("organization_mcp_trusted_issuers_issuer_idx").on(table.issuer), }), ); export const organizationMcpTrustedIssuerSubjects = pgTable( "organization_mcp_trusted_issuer_subjects", { trustedIssuerId: uuid("trusted_issuer_id") .notNull() .references(() => organizationMcpTrustedIssuers.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), assertionSubject: text("assertion_subject").notNull(), subjectId: text("subject_id").notNull(), email: text("email"), firstConnectedAt: timestamp("first_connected_at", { withTimezone: true }) .notNull() .defaultNow(), lastConnectedAt: timestamp("last_connected_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pk: primaryKey({ columns: [table.trustedIssuerId, table.assertionSubject] }), account: index("organization_mcp_trusted_issuer_subjects_account_idx").on( table.accountId, table.trustedIssuerId, ), }), ); export const organizationMcpTrustedIssuerEvents = pgTable( "organization_mcp_trusted_issuer_events", { id: uuid("id").primaryKey().defaultRandom(), trustedIssuerId: uuid("trusted_issuer_id") .notNull() .references(() => organizationMcpTrustedIssuers.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), outcome: text("outcome").$type<"connected" | "refused">().notNull(), reason: text("reason"), subjectId: text("subject_id"), email: text("email"), clientId: text("client_id"), clientName: text("client_name"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ recent: index("organization_mcp_trusted_issuer_events_recent_idx").on( table.trustedIssuerId, table.createdAt, ), }), ); export const organizationMcpAssertionReplays = pgTable( "organization_mcp_assertion_replays", { trustedIssuerId: uuid("trusted_issuer_id") .notNull() .references(() => organizationMcpTrustedIssuers.id, { onDelete: "cascade" }), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), jtiHash: text("jti_hash").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), }, (table) => ({ pk: primaryKey({ columns: [table.trustedIssuerId, table.jtiHash] }), expires: index("organization_mcp_assertion_replays_expires_idx").on( table.accountId, table.expiresAt, ), }), ); // Outbound: the organization's own ID-JAG signing key (Opengeni as the issuer). export const organizationIdentityIssuers = pgTable("organization_identity_issuers", { accountId: uuid("account_id") .primaryKey() .references(() => managedAccounts.id, { onDelete: "cascade" }), keyId: text("key_id").notNull(), algorithm: text("algorithm").$type<"RS256" | "ES256">().notNull(), publicJwk: jsonb("public_jwk").$type>().notNull(), privateKeyEncrypted: text("private_key_encrypted").notNull(), createdBySubjectId: text("created_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }); // --- Capabilities platform --------------------------------------------------- // Authoritative Plugin, immutable Version, Facet, installation, and ownership // state. The generic catalog/installations ledger is reserved for MCP. export const capabilityPlugins = pgTable( "capability_plugins", { id: uuid("id").primaryKey().defaultRandom(), pluginKey: text("plugin_key").notNull(), accountId: uuid("account_id").references(() => managedAccounts.id, { onDelete: "cascade", }), workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade", }), name: text("name").notNull(), description: text("description"), category: text("category").notNull(), tags: jsonb("tags").$type().notNull().default([]), provenance: text("provenance").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ globalKey: uniqueIndex("capability_plugins_global_key_idx") .on(table.pluginKey) .where(sql`${table.workspaceId} is null`), workspaceKey: uniqueIndex("capability_plugins_workspace_key_idx").on( table.workspaceId, table.pluginKey, ), scope: index("capability_plugins_scope_idx").on(table.workspaceId, table.category), }), ); export const capabilityPluginVersions = pgTable( "capability_plugin_versions", { id: uuid("id").primaryKey().defaultRandom(), pluginId: uuid("plugin_id") .notNull() .references(() => capabilityPlugins.id, { onDelete: "cascade" }), version: text("version").notNull(), manifestDigest: text("manifest_digest").notNull(), manifest: jsonb("manifest").$type>().notNull().default({}), status: text("status").notNull().default("published"), importBatchId: uuid("import_batch_id").references(() => importBatches.id, { onDelete: "set null", }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pluginVersion: uniqueIndex("capability_plugin_versions_plugin_version_idx").on( table.pluginId, table.version, ), pluginDigest: uniqueIndex("capability_plugin_versions_plugin_digest_idx").on( table.pluginId, table.manifestDigest, ), pluginIdentity: uniqueIndex("capability_plugin_versions_plugin_identity_idx").on( table.pluginId, table.id, ), }), ); export const capabilityFacets = pgTable( "capability_facets", { id: uuid("id").primaryKey().defaultRandom(), pluginVersionId: uuid("plugin_version_id") .notNull() .references(() => capabilityPluginVersions.id, { onDelete: "cascade" }), facetKey: text("facet_key").notNull(), kind: text("kind").notNull(), activationMode: text("activation_mode").notNull(), required: boolean("required").notNull().default(true), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ versionKey: uniqueIndex("capability_facets_version_key_idx").on( table.pluginVersionId, table.facetKey, ), versionKind: index("capability_facets_version_kind_idx").on(table.pluginVersionId, table.kind), }), ); export const capabilityIntegrationFacets = pgTable("capability_integration_facets", { facetId: uuid("facet_id") .primaryKey() .references(() => capabilityFacets.id, { onDelete: "cascade" }), providerDomain: text("provider_domain").notNull(), connectionKinds: jsonb("connection_kinds").$type().notNull().default([]), ownership: text("ownership").notNull(), requiredScopes: jsonb("required_scopes").$type().notNull().default([]), resourceSelection: text("resource_selection").notNull().default("none"), }); export const capabilityMcpFacets = pgTable( "capability_mcp_facets", { facetId: uuid("facet_id") .primaryKey() .references(() => capabilityFacets.id, { onDelete: "cascade" }), serverId: text("server_id").notNull(), endpointUrl: text("endpoint_url").notNull(), transport: text("transport").notNull(), authKind: text("auth_kind").notNull(), integrationFacetId: uuid("integration_facet_id").references( () => capabilityIntegrationFacets.facetId, { onDelete: "restrict" }, ), allowedTools: jsonb("allowed_tools").$type().notNull().default([]), }, (table) => ({ server: index("capability_mcp_facets_server_idx").on(table.serverId), }), ); export const capabilityApiFacets = pgTable("capability_api_facets", { facetId: uuid("facet_id") .primaryKey() .references(() => capabilityFacets.id, { onDelete: "cascade" }), protocol: text("protocol").notNull(), baseUrl: text("base_url").notNull(), specSourceUrl: text("spec_source_url"), authScheme: jsonb("auth_scheme").$type>().notNull().default({}), integrationFacetId: uuid("integration_facet_id").references( () => capabilityIntegrationFacets.facetId, { onDelete: "restrict" }, ), }); export const capabilitySkillFacets = pgTable( "capability_skill_facets", { facetId: uuid("facet_id") .primaryKey() .references(() => capabilityFacets.id, { onDelete: "cascade" }), capabilityId: text("capability_id").notNull(), name: text("name").notNull(), description: text("description").notNull(), sourceUrl: text("source_url").notNull(), sourceCommit: text("source_commit").notNull(), sourcePath: text("source_path").notNull(), contentSha256: text("content_sha256").notNull(), fileCount: integer("file_count").notNull(), totalBytes: integer("total_bytes").notNull(), license: text("license"), }, (table) => ({ content: index("capability_skill_facets_content_idx").on(table.contentSha256), }), ); export const capabilitySkillFiles = pgTable( "capability_skill_files", { id: uuid("id").primaryKey().defaultRandom(), skillFacetId: uuid("skill_facet_id") .notNull() .references(() => capabilitySkillFacets.facetId, { onDelete: "cascade" }), path: text("path").notNull(), content: text("content").notNull(), byteSize: integer("byte_size").notNull(), contentSha256: text("content_sha256").notNull(), }, (table) => ({ skillPath: uniqueIndex("capability_skill_files_skill_path_idx").on( table.skillFacetId, table.path, ), }), ); export const capabilityPluginInstallations = pgTable( "capability_plugin_installations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), pluginId: uuid("plugin_id") .notNull() .references(() => capabilityPlugins.id, { onDelete: "restrict" }), pluginVersionId: uuid("plugin_version_id").notNull(), status: text("status").notNull().default("active"), version: integer("version").notNull().default(1), installedBySubjectId: text("installed_by_subject_id").notNull(), installedAt: timestamp("installed_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ pluginVersion: foreignKey({ columns: [table.pluginId, table.pluginVersionId], foreignColumns: [capabilityPluginVersions.pluginId, capabilityPluginVersions.id], name: "capability_plugin_installations_plugin_version_fk", }).onDelete("restrict"), workspacePlugin: uniqueIndex("capability_plugin_installations_workspace_plugin_idx").on( table.workspaceId, table.pluginId, ), workspaceStatus: index("capability_plugin_installations_workspace_status_idx").on( table.workspaceId, table.status, ), }), ); export const capabilityFacetInstallations = pgTable( "capability_facet_installations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), pluginInstallationId: uuid("plugin_installation_id") .notNull() .references(() => capabilityPluginInstallations.id, { onDelete: "cascade", }), facetId: uuid("facet_id") .notNull() .references(() => capabilityFacets.id, { onDelete: "restrict" }), connectionId: uuid("connection_id").references(() => connections.id, { onDelete: "restrict", }), status: text("status").notNull().default("active"), config: jsonb("config").$type>().notNull().default({}), version: integer("version").notNull().default(1), attentionCode: text("attention_code"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ installationFacet: uniqueIndex("capability_facet_installations_installation_facet_idx").on( table.pluginInstallationId, table.facetId, ), workspaceStatus: index("capability_facet_installations_workspace_status_idx").on( table.workspaceId, table.status, ), }), ); export const capabilityComponentOwners = pgTable( "capability_component_owners", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), facetInstallationId: uuid("facet_installation_id") .notNull() .references(() => capabilityFacetInstallations.id, { onDelete: "cascade", }), ownerKind: text("owner_kind").notNull(), ownerId: text("owner_id").notNull(), removable: boolean("removable").notNull().default(true), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ uniqueOwner: uniqueIndex("capability_component_owners_unique_idx").on( table.facetInstallationId, table.ownerKind, table.ownerId, ), workspaceOwner: index("capability_component_owners_workspace_owner_idx").on( table.workspaceId, table.ownerKind, table.ownerId, ), }), ); export const integrationSpecRevisions = pgTable( "integration_spec_revisions", { id: uuid("id").primaryKey().defaultRandom(), apiFacetId: uuid("api_facet_id") .notNull() .references(() => capabilityApiFacets.facetId, { onDelete: "cascade" }), revision: integer("revision").notNull(), protocol: text("protocol").notNull(), sourceUrl: text("source_url"), specDigest: text("spec_digest").notNull(), spec: jsonb("spec").$type>().notNull(), status: text("status").notNull().default("active"), fetchedAt: timestamp("fetched_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ facetRevision: uniqueIndex("integration_spec_revisions_facet_revision_idx").on( table.apiFacetId, table.revision, ), facetDigest: uniqueIndex("integration_spec_revisions_facet_digest_idx").on( table.apiFacetId, table.specDigest, ), }), ); export const integrationTools = pgTable( "integration_tools", { id: uuid("id").primaryKey().defaultRandom(), facetId: uuid("facet_id") .notNull() .references(() => capabilityFacets.id, { onDelete: "cascade" }), toolKey: text("tool_key").notNull(), name: text("name").notNull(), description: text("description"), inputSchema: jsonb("input_schema").$type>().notNull().default({}), outputSchema: jsonb("output_schema").$type>(), effect: text("effect").notNull().default("read"), active: boolean("active").notNull().default(true), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ facetTool: uniqueIndex("integration_tools_facet_tool_idx").on(table.facetId, table.toolKey), }), ); export const integrationFacetDefinitions = pgTable( "integration_facet_definitions", { id: uuid("id").primaryKey().defaultRandom(), integrationFacetId: uuid("integration_facet_id") .notNull() .references(() => capabilityIntegrationFacets.facetId, { onDelete: "cascade", }), facetKey: text("facet_key").notNull(), kind: text("kind").notNull(), configSchema: jsonb("config_schema").$type>().notNull().default({}), capabilities: jsonb("capabilities").$type>().notNull().default({}), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ integrationFacet: uniqueIndex("integration_facet_definitions_integration_facet_idx").on( table.integrationFacetId, table.facetKey, ), integrationKind: index("integration_facet_definitions_integration_kind_idx").on( table.integrationFacetId, table.kind, ), }), ); export const integrationFacetBindings = pgTable( "integration_facet_bindings", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), facetDefinitionId: uuid("facet_definition_id") .notNull() .references(() => integrationFacetDefinitions.id, { onDelete: "restrict", }), integrationFacetInstallationId: uuid("integration_facet_installation_id") .notNull() .references(() => capabilityFacetInstallations.id, { onDelete: "cascade", }), bindingKey: text("binding_key").notNull(), displayName: text("display_name").notNull(), runtimeKey: text("runtime_key"), connectionId: uuid("connection_id").references(() => connections.id, { onDelete: "restrict", }), status: text("status").notNull().default("active"), config: jsonb("config").$type>().notNull().default({}), cursor: jsonb("cursor").$type>().notNull().default({}), version: integer("version").notNull().default(1), lastSuccessAt: timestamp("last_success_at", { withTimezone: true }), lastErrorCode: text("last_error_code"), createdBySubjectId: text("created_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ installationFacetKey: uniqueIndex("integration_facet_bindings_installation_facet_key_idx").on( table.workspaceId, table.integrationFacetInstallationId, table.facetDefinitionId, table.bindingKey, ), workspaceRuntime: uniqueIndex("integration_facet_bindings_workspace_runtime_idx") .on(table.workspaceId, table.runtimeKey) .where(sql`${table.runtimeKey} is not null`), workspaceStatus: index("integration_facet_bindings_workspace_status_idx").on( table.workspaceId, table.status, ), }), ); export const integrationFacetBindingOwners = pgTable( "integration_facet_binding_owners", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), bindingId: uuid("binding_id") .notNull() .references(() => integrationFacetBindings.id, { onDelete: "cascade" }), ownerKind: text("owner_kind").notNull(), ownerId: text("owner_id").notNull(), removable: boolean("removable").notNull().default(true), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ uniqueOwner: uniqueIndex("integration_facet_binding_owners_unique_idx").on( table.bindingId, table.ownerKind, table.ownerId, ), workspaceOwner: index("integration_facet_binding_owners_workspace_owner_idx").on( table.workspaceId, table.ownerKind, table.ownerId, ), }), ); export const capabilityOperations = pgTable( "capability_operations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), idempotencyKey: text("idempotency_key").notNull(), requestDigest: text("request_digest").notNull(), kind: text("kind").notNull(), targetKind: text("target_kind").notNull(), targetId: text("target_id").notNull(), status: text("status").notNull().default("pending"), phase: text("phase").notNull().default("admitted"), version: integer("version").notNull().default(1), result: jsonb("result").$type>(), errorCode: text("error_code"), createdBySubjectId: text("created_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), completedAt: timestamp("completed_at", { withTimezone: true }), }, (table) => ({ workspaceIdempotency: uniqueIndex("capability_operations_workspace_idempotency_idx").on( table.workspaceId, table.idempotencyKey, ), workspaceStatus: index("capability_operations_workspace_status_idx").on( table.workspaceId, table.status, table.updatedAt, ), }), ); export const socialConnections = pgTable( "social_connections", { id: uuid("id").primaryKey().defaultRandom(), version: integer("version").notNull().default(1), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), subjectId: text("subject_id"), provider: text("provider").notNull(), accountHandle: text("account_handle").notNull(), accountName: text("account_name"), externalAccountId: text("external_account_id"), status: text("status").notNull().default("connected"), scopes: jsonb("scopes").$type().notNull().default([]), credentialRef: text("credential_ref"), // AES-256-GCM envelope (environment-crypto v1 format) holding the OAuth // token bundle. Never exposed through contracts or MCP tools; only the // host-side social API client decrypts it. credentialEncrypted: text("credential_encrypted"), tokenMetadata: jsonb("token_metadata").$type>().notNull().default({}), metadata: jsonb("metadata").$type>().notNull().default({}), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceProviderHandle: uniqueIndex("social_connections_workspace_provider_handle_idx") .on(table.workspaceId, table.provider, table.accountHandle) .where(sql`${table.subjectId} is null`), subjectProviderHandle: uniqueIndex("social_connections_subject_provider_handle_idx") .on(table.workspaceId, table.subjectId, table.provider) .where(sql`${table.subjectId} is not null`), providerStatus: index("social_connections_workspace_provider_status_idx").on( table.workspaceId, table.provider, table.status, ), subjectProviderStatus: index("social_connections_subject_provider_status_idx").on( table.workspaceId, table.subjectId, table.provider, table.status, ), }), ); export const socialPosts = pgTable( "social_posts", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), connectionId: uuid("connection_id") .notNull() .references(() => socialConnections.id, { onDelete: "cascade" }), provider: text("provider").notNull(), externalPostId: text("external_post_id"), url: text("url"), authorHandle: text("author_handle"), text: text("text").notNull(), publishedAt: timestamp("published_at", { withTimezone: true }).notNull(), metrics: jsonb("metrics").$type>().notNull().default({}), raw: jsonb("raw").$type>().notNull().default({}), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ connectionExternalPost: uniqueIndex("social_posts_workspace_connection_external_post_idx").on( table.workspaceId, table.connectionId, table.externalPostId, ), connectionPublished: index("social_posts_workspace_connection_published_idx").on( table.workspaceId, table.connectionId, table.publishedAt, ), providerPublished: index("social_posts_workspace_provider_published_idx").on( table.workspaceId, table.provider, table.publishedAt, ), }), ); // Rigs (migration 0047): workspace-scoped, versioned sandbox machine definitions. // A rig is the named truth; each sandbox is a disposable fork of a rig version. export const rigs = pgTable( "rigs", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), name: text("name").notNull(), description: text("description"), // Attribution string: 'user:' | 'session:' | 'system'. createdBy: text("created_by"), authorityScope: text("authority_scope").notNull().default("workspace"), authorityId: uuid("authority_id"), ownerOrganizationMembershipId: uuid("owner_organization_membership_id"), originWorkspaceId: uuid("origin_workspace_id"), generation: bigint("generation", { mode: "number" }).notNull().default(1), status: text("status").notNull().default("active"), // Where an organization rig works besides the workspace it was made in // (migration 1190), as for organization machines. Unused otherwise. allowedWorkspaceIds: uuid("allowed_workspace_ids").array(), allowPersonalWorkspaces: boolean("allow_personal_workspaces").notNull().default(true), allowManagedWorkspaces: boolean("allow_managed_workspaces").notNull().default(false), revokedAt: timestamp("revoked_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceName: uniqueIndex("rigs_workspace_name_active_idx") .on(table.workspaceId, table.name) .where(sql`${table.authorityScope} = 'workspace' and ${table.status} = 'active'`), organizationName: uniqueIndex("rigs_organization_name_active_idx") .on(table.accountId, table.name) .where(sql`${table.authorityScope} = 'organization' and ${table.status} = 'active'`), userName: uniqueIndex("rigs_user_name_active_idx") .on(table.accountId, table.ownerOrganizationMembershipId, table.name) .where(sql`${table.authorityScope} = 'user' and ${table.status} = 'active'`), workspaceCreated: index("rigs_workspace_created_idx").on(table.workspaceId, table.createdAt), authorityShape: check( "rigs_authority_shape_check", sql`( ${table.authorityScope} in ('organization', 'workspace') and ${table.authorityId} is null and ${table.ownerOrganizationMembershipId} is null ) or ( ${table.authorityScope} = 'user' and ${table.authorityId} is not null and ${table.ownerOrganizationMembershipId} is not null )`, ), authorityScopeValid: check( "rigs_authority_scope_check", sql`${table.authorityScope} in ('organization', 'workspace', 'user')`, ), generationPositive: check("rigs_generation_check", sql`${table.generation} > 0`), statusValid: check("rigs_status_check", sql`${table.status} in ('active', 'revoked')`), revocationShape: check( "rigs_revocation_check", sql`(${table.status} = 'active' and ${table.revokedAt} is null) or (${table.status} = 'revoked' and ${table.revokedAt} is not null)`, ), authority: foreignKey({ name: "rigs_authority_fk", columns: [table.authorityId, table.accountId, table.ownerOrganizationMembershipId], foreignColumns: [ organizationUserResourceAuthorities.id, organizationUserResourceAuthorities.accountId, organizationUserResourceAuthorities.organizationMembershipId, ], }).onDelete("restrict"), // Migration 0230 owns the origin-workspace FK's column-subset SET NULL. }), ); // Append-only, definition-content-immutable rig versions. Exactly one active // per rig (partial unique index). Definition columns never UPDATE; only the // `active` flag and provider-image build metadata are operationally mutable. export const rigVersions = pgTable( "rig_versions", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), rigId: uuid("rig_id") .notNull() .references(() => rigs.id, { onDelete: "cascade" }), version: integer("version").notNull(), // Legacy audit field only. Migration 0356 rejects new non-null values; // runtime always uses the deployment platform sandbox image. image: text("image"), setupScript: text("setup_script"), // Self-declared health checks: [{ name, command }]. checks: jsonb("checks").$type>().notNull().default([]), // Registered credential-hook names (resolved to hook implementations in M3). credentialHooks: jsonb("credential_hooks").$type().notNull().default([]), changelog: text("changelog"), // Build-once provider-native image state, keyed by sandbox backend. This is // operational metadata bound to the exact immutable version definition; // it never contains credentials, variable values, repositories, archives, // session state, or process state. providerImages: jsonb("provider_images").$type().notNull().default({}), createdBy: text("created_by"), active: boolean("active").notNull().default(false), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ rigVersion: uniqueIndex("rig_versions_rig_version_idx").on(table.rigId, table.version), // At most one active version per rig — the single-active invariant, in the DB. rigActive: uniqueIndex("rig_versions_rig_active_idx") .on(table.rigId) .where(sql`${table.active}`), workspaceRig: index("rig_versions_workspace_rig_idx").on( table.workspaceId, table.rigId, table.version, ), }), ); // Proposed/verified rig changes (M4 substrate). M2 creates the table + CRUD only; // verification/auto-merge/promotion land in M4. export const rigChanges = pgTable( "rig_changes", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), rigId: uuid("rig_id") .notNull() .references(() => rigs.id, { onDelete: "cascade" }), baseVersionId: uuid("base_version_id").references(() => rigVersions.id, { onDelete: "set null", }), // 'setup_append' | 'definition_edit' (CHECK in migration 0047). kind: text("kind").notNull(), payload: losslessJsonb("payload").$type>().notNull(), payloadCodecVersion: losslessCodecVersion("payload_codec_version"), // 'proposed' | 'verifying' | 'merged' | 'rejected' | 'failed' (CHECK in 0047). status: text("status").notNull().default("proposed"), proposedBy: text("proposed_by"), verification: losslessJsonb("verification").$type>(), verificationCodecVersion: losslessCodecVersion("verification_codec_version"), resultVersionId: uuid("result_version_id").references(() => rigVersions.id, { onDelete: "set null", }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceRig: index("rig_changes_workspace_rig_idx").on( table.workspaceId, table.rigId, table.createdAt, ), workspaceStatus: index("rig_changes_workspace_status_idx").on(table.workspaceId, table.status), }), ); export const deploymentModelCatalog = pgTable( "deployment_model_catalog", { singleton: boolean("singleton").primaryKey().notNull().default(true), document: jsonb("document").$type().notNull(), version: bigint("version", { mode: "number" }).notNull().default(1), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ singletonCheck: check("deployment_model_catalog_singleton_chk", sql`${table.singleton}`), documentCheck: check( "deployment_model_catalog_document_chk", sql`jsonb_typeof(${table.document}) = 'object'`, ), versionCheck: check("deployment_model_catalog_version_chk", sql`${table.version} > 0`), }), ); export const workspaceGatewayCustomModels = pgTable( "workspace_gateway_custom_models", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), workspaceId: uuid("workspace_id") .notNull() .references(() => workspaces.id, { onDelete: "cascade" }), providerKind: text("provider_kind") .$type<"vercel_gateway" | "openrouter" | "anthropic" | "claude_subscription" | "opper">() .notNull(), upstreamModelId: text("upstream_model_id").notNull(), label: text("label"), version: integer("version").notNull().default(1), createOperationId: uuid("create_operation_id").notNull(), createRequestHash: text("create_request_hash").notNull(), deleteOperationId: uuid("delete_operation_id"), deleteRequestHash: text("delete_request_hash"), createdBySubjectId: text("created_by_subject_id").notNull(), retiredAt: timestamp("retired_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceAccountFk: foreignKey({ name: "workspace_gateway_custom_models_workspace_account_fk", columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), workspaceUpstream: uniqueIndex("workspace_gateway_custom_models_workspace_upstream_uq") .on(table.workspaceId, table.providerKind, table.upstreamModelId) .where(sql`${table.retiredAt} is null`), createOperation: uniqueIndex("workspace_gateway_custom_models_create_operation_uq").on( table.workspaceId, table.providerKind, table.createOperationId, ), deleteOperation: uniqueIndex("workspace_gateway_custom_models_delete_operation_uq") .on(table.workspaceId, table.providerKind, table.deleteOperationId) .where(sql`${table.deleteOperationId} is not null`), providerKindCheck: check( "workspace_gateway_custom_models_provider_kind_chk", sql`${table.providerKind} in ('vercel_gateway', 'openrouter', 'anthropic', 'claude_subscription', 'opper')`, ), upstreamCheck: check( "workspace_gateway_custom_models_upstream_chk", sql`octet_length(${table.upstreamModelId}) between 1 and 238 and ${table.upstreamModelId} ~ '^[!-~]+$' and ${table.upstreamModelId} !~ '[|]'`, ), labelCheck: check( "workspace_gateway_custom_models_label_chk", sql`${table.label} is null or (octet_length(${table.label}) between 1 and 128 and ${table.label} !~ '[\r\n|]')`, ), actorCheck: check( "workspace_gateway_custom_models_actor_chk", sql`octet_length(${table.createdBySubjectId}) between 1 and 1024`, ), versionCheck: check("workspace_gateway_custom_models_version_chk", sql`${table.version} > 0`), createHashCheck: check( "workspace_gateway_custom_models_create_hash_chk", sql`${table.createRequestHash} ~ '^[a-f0-9]{64}$'`, ), deleteReceiptCheck: check( "workspace_gateway_custom_models_delete_receipt_chk", sql`(${table.deleteOperationId} is null and ${table.deleteRequestHash} is null) or (${table.deleteOperationId} is not null and ${table.deleteRequestHash} ~ '^[a-f0-9]{64}$' and ${table.retiredAt} is not null)`, ), }), ); export const organizationModelProviderConnections = pgTable( "organization_model_provider_connections", { allowedModelIds: text("allowed_model_ids").array(), allowedWorkspaceIds: uuid("allowed_workspace_ids").array(), allowPersonalWorkspaces: boolean("allow_personal_workspaces").notNull().default(true), accessPolicyVersion: integer("access_policy_version").notNull().default(1), accessPolicyUpdatedBy: text("access_policy_updated_by"), accessPolicyUpdatedAt: timestamp("access_policy_updated_at", { withTimezone: true }), id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), providerKind: text("provider_kind") .$type< | "vercel_gateway" | "openrouter" | "anthropic" | "claude_subscription" | "opper" | "elevenlabs" | "openai" | "azure_openai" | "openai_compatible" >() .notNull(), status: text("status").$type<"active" | "revoked">().notNull().default("active"), credentialEncrypted: text("credential_encrypted").notNull(), /** * Non-secret base URL: Azure OpenAI's `https://.openai.azure.com/openai/v1`, * or an OpenAI-compatible endpoint's public HTTPS base URL; null for every other kind. */ endpoint: text("endpoint"), /** OpenAI-compatible endpoints only: the API format they follow. */ compatibleApi: text("compatible_api").$type<"chat" | "responses">(), /** OpenAI-compatible endpoints only: an optional display name. */ label: text("label"), /** * Anthropic API connections only: the organization's further API keys. * The connection's own key is the first member. */ apiKeyMembers: jsonb("api_key_members").$type(), /** * Anthropic API connections only: member id to the time Anthropic refused * that key for lack of credits (the connection's own key is * `primary-v`). */ apiKeyCreditRefusals: jsonb("api_key_credit_refusals").$type>(), /** How the connection signs in; Microsoft Entra ID methods are Azure OpenAI only. */ authMethod: text("auth_method") .$type() .notNull() .default("api_key"), version: integer("version").notNull().default(1), operationId: uuid("operation_id").notNull(), requestHash: text("request_hash").notNull(), updatedBySubjectId: text("updated_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ // One connection per kind, except OpenAI-compatible endpoints (several each). accountProvider: uniqueIndex("organization_model_provider_connections_account_provider_uq") .on(table.accountId, table.providerKind) .where(sql`${table.providerKind} <> 'openai_compatible'`), idAccount: unique("organization_model_provider_connections_id_account_key").on( table.id, table.accountId, ), operation: uniqueIndex("organization_model_provider_connections_operation_uq").on( table.accountId, table.providerKind, table.operationId, ), providerKindCheck: check( "organization_model_provider_connections_provider_kind_chk", sql`${table.providerKind} in ('vercel_gateway', 'openrouter', 'anthropic', 'claude_subscription', 'opper', 'elevenlabs', 'openai', 'azure_openai', 'openai_compatible')`, ), statusCheck: check( "organization_model_provider_connections_status_chk", sql`${table.status} in ('active', 'revoked')`, ), versionCheck: check( "organization_model_provider_connections_version_chk", sql`${table.version} > 0`, ), requestHashCheck: check( "organization_model_provider_connections_request_hash_chk", sql`${table.requestHash} ~ '^[a-f0-9]{64}$'`, ), actorCheck: check( "organization_model_provider_connections_actor_chk", sql`octet_length(${table.updatedBySubjectId}) between 1 and 1024`, ), endpointCheck: check( "organization_model_provider_connections_endpoint_chk", sql`(${table.providerKind} in ('azure_openai', 'openai_compatible')) = (${table.endpoint} is not null) and (${table.endpoint} is null or (${table.providerKind} = 'azure_openai' and ${table.endpoint} ~ '^https://[a-z0-9-]+\\.openai\\.azure\\.com/openai/v1$') or (${table.providerKind} = 'openai_compatible' and octet_length(${table.endpoint}) between 9 and 2048 and ${table.endpoint} ~ '^https://[!-~]+$'))`, ), compatibleApiCheck: check( "organization_model_provider_connections_compatible_api_chk", sql`(${table.providerKind} = 'openai_compatible') = (${table.compatibleApi} is not null) and (${table.compatibleApi} is null or ${table.compatibleApi} in ('chat', 'responses'))`, ), labelCheck: check( "organization_model_provider_connections_label_chk", sql`${table.label} is null or (${table.providerKind} = 'openai_compatible' and octet_length(${table.label}) between 1 and 128 and ${table.label} !~ '[\r\n|]')`, ), authMethodCheck: check( "organization_model_provider_connections_auth_method_chk", sql`${table.authMethod} in ('api_key', 'entra_client_secret', 'entra_deployment_identity') and (${table.authMethod} = 'api_key' or ${table.providerKind} = 'azure_openai')`, ), apiKeyMembersCheck: check( "organization_model_provider_connections_api_key_members_chk", sql`${table.apiKeyMembers} is null or (${table.providerKind} = 'anthropic' and jsonb_typeof(${table.apiKeyMembers}) = 'array' and jsonb_array_length(${table.apiKeyMembers}) <= 63)`, ), apiKeyRefusalsCheck: check( "organization_model_provider_connections_api_key_refusals_chk", sql`${table.apiKeyCreditRefusals} is null or (${table.providerKind} = 'anthropic' and jsonb_typeof(${table.apiKeyCreditRefusals}) = 'object')`, ), }), ); /** One further API key of an organization's Anthropic API connection. */ export type StoredAnthropicApiKeyMember = { id: string; label: string; credentialEncrypted: string; credentialDigest: string; anthropicOrganizationId: string | null; createdAt: string; createdBySubjectId: string; }; export const organizationModelProviderConnectionOperations = pgTable( "organization_model_provider_connection_operations", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), providerKind: text("provider_kind") .$type< | "vercel_gateway" | "openrouter" | "anthropic" | "claude_subscription" | "opper" | "elevenlabs" | "openai" | "azure_openai" >() .notNull(), operationId: uuid("operation_id").notNull(), requestHash: text("request_hash").notNull(), resultStatus: text("result_status").$type<"active" | "revoked">().notNull(), resultVersion: integer("result_version").notNull(), resultEndpoint: text("result_endpoint"), resultAuthMethod: text("result_auth_method") .$type() .notNull() .default("api_key"), resultCreatedAt: timestamp("result_created_at", { withTimezone: true, }).notNull(), resultUpdatedAt: timestamp("result_updated_at", { withTimezone: true, }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ operation: uniqueIndex("organization_model_provider_connection_operations_operation_uq").on( table.accountId, table.providerKind, table.operationId, ), providerKindCheck: check( "organization_model_provider_connection_operations_provider_kind_chk", sql`${table.providerKind} in ('vercel_gateway', 'openrouter', 'anthropic', 'claude_subscription', 'opper', 'elevenlabs', 'openai', 'azure_openai')`, ), resultStatusCheck: check( "organization_model_provider_connection_operations_result_status_chk", sql`${table.resultStatus} in ('active', 'revoked')`, ), resultVersionCheck: check( "organization_model_provider_connection_operations_result_version_chk", sql`${table.resultVersion} > 0`, ), requestHashCheck: check( "organization_model_provider_connection_operations_request_hash_chk", sql`${table.requestHash} ~ '^[a-f0-9]{64}$'`, ), endpointCheck: check( "organization_model_provider_connection_operations_endpoint_chk", sql`(${table.providerKind} = 'azure_openai') = (${table.resultEndpoint} is not null) and (${table.resultEndpoint} is null or ${table.resultEndpoint} ~ '^https://[a-z0-9-]+\\.openai\\.azure\\.com/openai/v1$')`, ), authMethodCheck: check( "organization_model_provider_connection_operations_auth_chk", sql`${table.resultAuthMethod} in ('api_key', 'entra_client_secret', 'entra_deployment_identity') and (${table.resultAuthMethod} = 'api_key' or ${table.providerKind} = 'azure_openai')`, ), }), ); /** How an organization model provider connection signs in. */ export type OrganizationModelProviderAuthMethod = | "api_key" | "entra_client_secret" | "entra_deployment_identity"; export const organizationModelProviderCustomModels = pgTable( "organization_model_provider_custom_models", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), providerKind: text("provider_kind") .$type< | "vercel_gateway" | "openrouter" | "anthropic" | "claude_subscription" | "opper" | "openai" | "azure_openai" | "openai_compatible" >() .notNull(), /** OpenAI-compatible endpoints only: the endpoint connection serving this model. */ connectionId: uuid("connection_id"), upstreamModelId: text("upstream_model_id").notNull(), label: text("label"), /** OpenAI-compatible endpoint models only: accepted reasoning levels, lowest first. */ reasoningEfforts: text("reasoning_efforts") .array() .$type<("none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max")[]>(), /** OpenAI-compatible endpoint models only: the declared default level. */ defaultReasoningEffort: text("default_reasoning_effort").$type< "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" >(), /** * OpenAI, Azure OpenAI and OpenAI-compatible models only: the catalogue * model whose list rate prices this model's usage estimates (an Azure * deployment's base model). Null when unknown or `list_pricing` is set. */ priceBasisModelId: text("price_basis_model_id"), /** The administrator's own list rate for the model, in USD micros per 1M tokens. */ listPricing: jsonb("list_pricing").$type(), version: integer("version").notNull().default(1), createOperationId: uuid("create_operation_id").notNull(), createRequestHash: text("create_request_hash").notNull(), deleteOperationId: uuid("delete_operation_id"), deleteRequestHash: text("delete_request_hash"), createdBySubjectId: text("created_by_subject_id").notNull(), retiredAt: timestamp("retired_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ accountUpstream: uniqueIndex("organization_model_provider_custom_models_active_uq") .on( table.accountId, table.providerKind, sql`coalesce(${table.connectionId}, '00000000-0000-0000-0000-000000000000'::uuid)`, table.upstreamModelId, ) .where(sql`${table.retiredAt} is null`), connection: index("organization_model_provider_custom_models_connection_idx") .on(table.connectionId) .where(sql`${table.connectionId} is not null`), connectionReference: foreignKey({ name: "organization_model_provider_custom_models_connection_fk", columns: [table.connectionId, table.accountId], foreignColumns: [ organizationModelProviderConnections.id, organizationModelProviderConnections.accountId, ], }).onDelete("cascade"), connectionCheck: check( "organization_model_provider_custom_models_connection_chk", sql`(${table.providerKind} = 'openai_compatible') = (${table.connectionId} is not null)`, ), reasoningCheck: check( "organization_model_provider_custom_models_reasoning_chk", sql`(${table.reasoningEfforts} is null) = (${table.defaultReasoningEffort} is null) and (${table.reasoningEfforts} is null or (${table.providerKind} = 'openai_compatible' and cardinality(${table.reasoningEfforts}) between 1 and 7 and ${table.reasoningEfforts} <@ array['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']::text[] and ${table.defaultReasoningEffort} = any (${table.reasoningEfforts})))`, ), createOperation: uniqueIndex( "organization_model_provider_custom_models_create_operation_uq", ).on(table.accountId, table.providerKind, table.createOperationId), deleteOperation: uniqueIndex("organization_model_provider_custom_models_delete_operation_uq") .on(table.accountId, table.providerKind, table.deleteOperationId) .where(sql`${table.deleteOperationId} is not null`), providerKindCheck: check( "organization_model_provider_custom_models_provider_kind_chk", sql`${table.providerKind} in ('vercel_gateway', 'openrouter', 'anthropic', 'claude_subscription', 'opper', 'openai', 'azure_openai', 'openai_compatible')`, ), upstreamCheck: check( "organization_model_provider_custom_models_upstream_chk", sql`octet_length(${table.upstreamModelId}) between 1 and 238 and ${table.upstreamModelId} ~ '^[!-~]+$' and ${table.upstreamModelId} !~ '[|]'`, ), labelCheck: check( "organization_model_provider_custom_models_label_chk", sql`${table.label} is null or (octet_length(${table.label}) between 1 and 128 and ${table.label} !~ '[\r\n|]')`, ), versionCheck: check( "organization_model_provider_custom_models_version_chk", sql`${table.version} > 0`, ), actorCheck: check( "organization_model_provider_custom_models_actor_chk", sql`octet_length(${table.createdBySubjectId}) between 1 and 1024`, ), createHashCheck: check( "organization_model_provider_custom_models_create_hash_chk", sql`${table.createRequestHash} ~ '^[a-f0-9]{64}$'`, ), deleteReceiptCheck: check( "organization_model_provider_custom_models_delete_receipt_chk", sql`(${table.deleteOperationId} is null and ${table.deleteRequestHash} is null) or (${table.deleteOperationId} is not null and ${table.deleteRequestHash} ~ '^[a-f0-9]{64}$' and ${table.retiredAt} is not null)`, ), listPriceCheck: check( "organization_model_provider_custom_models_list_price_chk", sql`(${table.priceBasisModelId} is null or ${table.listPricing} is null) and ((${table.priceBasisModelId} is null and ${table.listPricing} is null) or ${table.providerKind} in ('openai', 'azure_openai', 'openai_compatible')) and (${table.priceBasisModelId} is null or (octet_length(${table.priceBasisModelId}) between 1 and 256 and ${table.priceBasisModelId} ~ '^[!-~]+$')) and (${table.listPricing} is null or jsonb_typeof(${table.listPricing}) = 'object')`, ), }), ); /** An administrator's own list rate for a connected model, in USD micros per 1M tokens. */ export type ConnectedModelListPricing = { inputMicrosPerMillionTokens: number; cachedInputMicrosPerMillionTokens?: number | undefined; cacheWriteMicrosPerMillionTokens?: number | undefined; outputMicrosPerMillionTokens: number; }; export * from "./workspace-instruction-policies-schema"; export * from "./company-profile-schema"; export * from "./workspace-learning-policy-schema"; export * from "./slack-task-policy-schema"; export * from "./preference-registry-schema"; export * from "./skills-schema"; export * from "./memory-governance-schema"; export * from "./scoped-knowledge-schema"; export * from "./task-notes-schema"; export * from "./work-claims-schema"; export * from "./company-brain-context-selection-schema"; export * from "./governed-learning-evaluator-schema"; export * from "./governed-learning-activation-schema"; export * from "./recordings-schema"; export * from "./interaction-schema"; export * from "./site-data-schema"; /** Immutable feedback, scoped to its submitting principal and optional session. */ export const feedbackSubmissions = pgTable( "feedback_submissions", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), subjectId: text("subject_id").notNull(), principalKind: text("principal_kind"), idempotencyKey: uuid("idempotency_key").notNull(), sessionId: uuid("session_id"), turnId: uuid("turn_id"), sentiment: text("sentiment"), comment: losslessText("comment"), commentCodecVersion: losslessCodecVersion("comment_codec_version"), /** App and device facts the report was sent with (FeedbackContext). */ context: jsonb("context").$type>(), /** Screenshot metadata in send order (FeedbackScreenshot); bytes are in object storage. */ screenshots: jsonb("screenshots").$type().notNull().default([]), /** What the server knew when the report arrived (FeedbackDiagnostics); never sent to clients. */ diagnostics: jsonb("diagnostics").$type>(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspace: foreignKey({ columns: [table.workspaceId, table.accountId], foreignColumns: [workspaces.id, workspaces.accountId], }).onDelete("cascade"), session: foreignKey({ columns: [table.workspaceId, table.sessionId], foreignColumns: [sessions.workspaceId, sessions.id], }).onDelete("cascade"), turn: foreignKey({ columns: [table.workspaceId, table.turnId], foreignColumns: [sessionTurns.workspaceId, sessionTurns.id], }).onDelete("cascade"), request: uniqueIndex("feedback_submissions_request_idx").on( table.workspaceId, table.subjectId, table.idempotencyKey, ), author: index("feedback_submissions_author_idx").on( table.workspaceId, table.subjectId, table.createdAt, table.id, ), sessionTime: index("feedback_submissions_session_idx").on( table.workspaceId, table.sessionId, table.createdAt, table.id, ), }), ); /** * An agent ringing a person's phones (1107): one row per call, from ringing * to its outcome. Answering opens the chat's voice call. */ export const agentCalls = pgTable( "agent_calls", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sessionId: uuid("session_id") .notNull() .references(() => sessions.id, { onDelete: "cascade" }), calleeSubjectId: text("callee_subject_id").notNull(), callerSubjectId: text("caller_subject_id"), callerLabel: text("caller_label"), reason: text("reason").notNull(), state: text("state").notNull().default("ringing"), devices: integer("devices").notNull().default(0), ringUntil: timestamp("ring_until", { withTimezone: true }).notNull(), answeredBy: text("answered_by"), realtimeId: uuid("realtime_id"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), endedAt: timestamp("ended_at", { withTimezone: true }), }, (table) => ({ session: index("agent_calls_session_idx").on( table.workspaceId, table.sessionId, table.createdAt.desc(), ), ringingCallee: index("agent_calls_ringing_callee_idx") .on(table.calleeSubjectId) .where(sql`${table.state} = 'ringing'`), ringingDeadline: index("agent_calls_ringing_deadline_idx") .on(table.ringUntil) .where(sql`${table.state} = 'ringing'`), stateCheck: check( "agent_calls_state_chk", sql`${table.state} in ('ringing', 'answered', 'declined', 'missed', 'cancelled')`, ), }), ); /** * Phones a product embedding Opengeni rings for agent calls itself (1143_agent_call_host_phones): * how many of the person's phones, and whether teammates' agents may ring them. */ export const agentCallHostPhones = pgTable( "agent_call_host_phones", { accountId: uuid("account_id") .notNull() .references(() => managedAccounts.id, { onDelete: "cascade" }), subjectId: text("subject_id").notNull(), phones: integer("phones").notNull(), teammates: boolean("teammates").notNull().default(false), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ identity: primaryKey({ columns: [table.accountId, table.subjectId] }) }), ); /** Promotion eligibility is separate from account access and paid funding. */ export const promotionDecisions = pgTable("promotion_decisions", { accountId: uuid("account_id").primaryKey(), decision: text("decision").notNull(), revision: bigint("revision", { mode: "number" }).notNull(), actor: text("actor").notNull(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }); export const promotionEnforcement = pgTable("promotion_enforcement", { singleton: boolean("singleton").primaryKey().default(true), enabled: boolean("enabled").notNull().default(false), });