@opengeni/db 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/{chunk-OGCE6O2X.js → chunk-7LDU7F5P.js} +31 -3
  2. package/dist/chunk-7LDU7F5P.js.map +1 -0
  3. package/dist/chunk-O3D7DABC.js +2314 -0
  4. package/dist/chunk-O3D7DABC.js.map +1 -0
  5. package/dist/{chunk-57MLICFR.js → chunk-YFQ7SGE4.js} +18 -6
  6. package/dist/chunk-YFQ7SGE4.js.map +1 -0
  7. package/dist/index.d.ts +2 -2
  8. package/dist/index.js +13129 -3496
  9. package/dist/index.js.map +1 -1
  10. package/dist/migrate.js +1 -1
  11. package/dist/provision-roles.d.ts +1836 -222
  12. package/dist/provision-roles.js +1 -1
  13. package/dist/{schema-Dsz6UHNv.d.ts → schema-Dp2MbBxx.d.ts} +7480 -3305
  14. package/dist/schema.d.ts +1 -1
  15. package/dist/schema.js +33 -5
  16. package/drizzle/0043_credit_balance_observability.sql +22 -0
  17. package/drizzle/0044_reap_dead_turn_holders.sql +104 -0
  18. package/drizzle/0045_workspace_captures.sql +83 -0
  19. package/drizzle/0045_workspace_memory_v1.sql +71 -0
  20. package/drizzle/0046_variable_sets_rename.sql +56 -0
  21. package/drizzle/0047_rigs.sql +151 -0
  22. package/drizzle/0048_rig_runtime.sql +9 -0
  23. package/drizzle/0049_enrollment_went_offline.sql +28 -0
  24. package/drizzle/0050_enrollment_op_stream.sql +1 -0
  25. package/drizzle/0051_codex_pin_source.sql +48 -0
  26. package/drizzle/0052_file_upload_cleanup.sql +91 -0
  27. package/drizzle/0053_codex_credential_leases.sql +230 -0
  28. package/drizzle/0054_session_pins.sql +85 -0
  29. package/drizzle/0055_session_list_snapshots.sql +73 -0
  30. package/drizzle/0056_workspace_model_policies.sql +48 -0
  31. package/drizzle/0057_durable_queue_control.sql +536 -0
  32. package/drizzle/0058_turn_admission_usage_enrollment.sql +158 -0
  33. package/drizzle/0059_workspace_pause_control_kind.sql +12 -0
  34. package/drizzle/0060_session_system_update_deferral.sql +10 -0
  35. package/drizzle/0061_session_workflow_wake_outbox.sql +157 -0
  36. package/drizzle/0062_session_list_snapshot_reaper.sql +48 -0
  37. package/package.json +17 -13
  38. package/src/codex-token-resolver.ts +58 -23
  39. package/src/connection-token-resolver.ts +146 -57
  40. package/src/environment-crypto.ts +5 -1
  41. package/src/event-payload-sanitizer.ts +29 -1
  42. package/src/index.ts +22460 -6492
  43. package/src/memory-domain.ts +218 -0
  44. package/src/migrate.ts +58 -3
  45. package/src/provision-roles.ts +46 -17
  46. package/src/schema.ts +2557 -1121
  47. package/src/session-control-cutover-audit.ts +1203 -0
  48. package/dist/chunk-57MLICFR.js.map +0 -1
  49. package/dist/chunk-OGCE6O2X.js.map +0 -1
  50. package/dist/chunk-ZIUCA2IO.js +0 -1268
  51. package/dist/chunk-ZIUCA2IO.js.map +0 -1
package/src/schema.ts CHANGED
@@ -1,5 +1,20 @@
1
1
  import { sql } from "drizzle-orm";
2
- import { bigint, boolean, index, integer, jsonb, numeric, pgTable, text, timestamp, uniqueIndex, uuid, customType } from "drizzle-orm/pg-core";
2
+ import {
3
+ bigint,
4
+ boolean,
5
+ check,
6
+ foreignKey,
7
+ index,
8
+ integer,
9
+ jsonb,
10
+ numeric,
11
+ pgTable,
12
+ text,
13
+ timestamp,
14
+ uniqueIndex,
15
+ uuid,
16
+ customType,
17
+ } from "drizzle-orm/pg-core";
3
18
 
4
19
  const vector = customType<{ data: number[]; driverData: string }>({
5
20
  dataType() {
@@ -10,216 +25,347 @@ const vector = customType<{ data: number[]; driverData: string }>({
10
25
  },
11
26
  });
12
27
 
13
- export const managedAccounts = pgTable("managed_accounts", {
14
- id: uuid("id").primaryKey().defaultRandom(),
15
- name: text("name").notNull(),
16
- externalSource: text("external_source"),
17
- externalId: text("external_id"),
18
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
19
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
20
- }, (table) => ({
21
- external: uniqueIndex("managed_accounts_external_idx").on(table.externalSource, table.externalId),
22
- }));
23
-
24
- export const workspaces = pgTable("workspaces", {
25
- id: uuid("id").primaryKey().defaultRandom(),
26
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
27
- name: text("name").notNull(),
28
- slug: text("slug"),
29
- externalSource: text("external_source"),
30
- externalId: text("external_id"),
31
- // White-label agent persona template override. NULL means the deployment
32
- // default (OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE / DEFAULT_AGENT_INSTRUCTIONS).
33
- agentInstructions: text("agent_instructions"),
34
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
35
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
36
- }, (table) => ({
37
- account: index("workspaces_account_idx").on(table.accountId),
38
- accountSlug: uniqueIndex("workspaces_account_slug_idx").on(table.accountId, table.slug).where(sql`${table.slug} is not null`),
39
- external: uniqueIndex("workspaces_external_idx").on(table.externalSource, table.externalId),
40
- }));
41
-
42
- export const workspaceMemberships = pgTable("workspace_memberships", {
43
- id: uuid("id").primaryKey().defaultRandom(),
44
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
45
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
46
- subjectId: text("subject_id").notNull(),
47
- subjectLabel: text("subject_label"),
48
- role: text("role").notNull().default("member"),
49
- permissions: jsonb("permissions").$type<string[]>().notNull().default([]),
50
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
51
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
52
- }, (table) => ({
53
- subjectWorkspace: uniqueIndex("workspace_memberships_subject_workspace_idx").on(table.subjectId, table.workspaceId),
54
- subject: index("workspace_memberships_subject_idx").on(table.subjectId),
55
- account: index("workspace_memberships_account_idx").on(table.accountId),
56
- }));
57
-
58
- export const apiKeys = pgTable("api_keys", {
59
- id: uuid("id").primaryKey().defaultRandom(),
60
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
61
- workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }),
62
- name: text("name").notNull(),
63
- prefix: text("prefix").notNull(),
64
- keyHash: text("key_hash").notNull(),
65
- permissions: jsonb("permissions").$type<string[]>().notNull().default([]),
66
- expiresAt: timestamp("expires_at", { withTimezone: true }),
67
- revokedAt: timestamp("revoked_at", { withTimezone: true }),
68
- lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
69
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
70
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
71
- }, (table) => ({
72
- prefix: index("api_keys_prefix_idx").on(table.prefix),
73
- hash: uniqueIndex("api_keys_key_hash_idx").on(table.keyHash),
74
- account: index("api_keys_account_idx").on(table.accountId),
75
- workspace: index("api_keys_workspace_idx").on(table.workspaceId),
76
- }));
77
-
78
- export const workspaceEnvironments = pgTable("workspace_environments", {
79
- id: uuid("id").primaryKey().defaultRandom(),
80
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
81
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
82
- name: text("name").notNull(),
83
- description: text("description"),
84
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
85
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
86
- }, (table) => ({
87
- workspaceName: uniqueIndex("workspace_environments_workspace_name_idx").on(table.workspaceId, table.name),
88
- workspaceCreated: index("workspace_environments_workspace_created_idx").on(table.workspaceId, table.createdAt),
89
- }));
90
-
91
- export const workspaceEnvironmentVariables = pgTable("workspace_environment_variables", {
92
- id: uuid("id").primaryKey().defaultRandom(),
93
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
94
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
95
- environmentId: uuid("environment_id").notNull().references(() => workspaceEnvironments.id, { onDelete: "cascade" }),
96
- name: text("name").notNull(),
97
- // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. Never returned by any API.
98
- valueEncrypted: text("value_encrypted").notNull(),
99
- version: integer("version").notNull().default(1),
100
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
101
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
102
- }, (table) => ({
103
- environmentName: uniqueIndex("workspace_environment_variables_env_name_idx").on(table.workspaceId, table.environmentId, table.name),
104
- environment: index("workspace_environment_variables_workspace_env_idx").on(table.workspaceId, table.environmentId),
105
- }));
28
+ export const managedAccounts = pgTable(
29
+ "managed_accounts",
30
+ {
31
+ id: uuid("id").primaryKey().defaultRandom(),
32
+ name: text("name").notNull(),
33
+ externalSource: text("external_source"),
34
+ externalId: text("external_id"),
35
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
36
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
37
+ },
38
+ (table) => ({
39
+ external: uniqueIndex("managed_accounts_external_idx").on(
40
+ table.externalSource,
41
+ table.externalId,
42
+ ),
43
+ }),
44
+ );
45
+
46
+ export const workspaces = pgTable(
47
+ "workspaces",
48
+ {
49
+ id: uuid("id").primaryKey().defaultRandom(),
50
+ accountId: uuid("account_id")
51
+ .notNull()
52
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
53
+ name: text("name").notNull(),
54
+ slug: text("slug"),
55
+ externalSource: text("external_source"),
56
+ externalId: text("external_id"),
57
+ // White-label agent persona template override. NULL means the deployment
58
+ // default (OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE / DEFAULT_AGENT_INSTRUCTIONS).
59
+ agentInstructions: text("agent_instructions"),
60
+ // Growth-ready per-workspace settings bag (migration 0045). Holds memoryEnabled
61
+ // and future workspace-level toggles; validated/merged via WorkspaceSettingsSchema.
62
+ settings: jsonb("settings").$type<Record<string, unknown>>().notNull().default({}),
63
+ inferenceState: text("inference_state").notNull().default("active"),
64
+ inferenceGeneration: integer("inference_generation").notNull().default(0),
65
+ inferenceReason: text("inference_reason"),
66
+ inferenceChangedBy: text("inference_changed_by"),
67
+ inferenceChangedAt: timestamp("inference_changed_at", { withTimezone: true }),
68
+ // The workspace's default rig (migration 0047). NULL ⇒ no default; sessions
69
+ // created without an explicit rig ride no rig (today's behavior exactly). FK
70
+ // (-> rigs(id) ON DELETE SET NULL) lives in migration 0047, not a Drizzle
71
+ // .references(), because `rigs` is declared later in this file (same
72
+ // forward-reference pattern as sessions.activeSandboxId). Consumed in M3.
73
+ defaultRigId: uuid("default_rig_id"),
74
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
75
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
76
+ },
77
+ (table) => ({
78
+ account: index("workspaces_account_idx").on(table.accountId),
79
+ accountSlug: uniqueIndex("workspaces_account_slug_idx")
80
+ .on(table.accountId, table.slug)
81
+ .where(sql`${table.slug} is not null`),
82
+ external: uniqueIndex("workspaces_external_idx").on(table.externalSource, table.externalId),
83
+ }),
84
+ );
85
+
86
+ export const workspaceMemberships = pgTable(
87
+ "workspace_memberships",
88
+ {
89
+ id: uuid("id").primaryKey().defaultRandom(),
90
+ accountId: uuid("account_id")
91
+ .notNull()
92
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
93
+ workspaceId: uuid("workspace_id")
94
+ .notNull()
95
+ .references(() => workspaces.id, { onDelete: "cascade" }),
96
+ subjectId: text("subject_id").notNull(),
97
+ subjectLabel: text("subject_label"),
98
+ role: text("role").notNull().default("member"),
99
+ permissions: jsonb("permissions").$type<string[]>().notNull().default([]),
100
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
101
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
102
+ },
103
+ (table) => ({
104
+ subjectWorkspace: uniqueIndex("workspace_memberships_subject_workspace_idx").on(
105
+ table.subjectId,
106
+ table.workspaceId,
107
+ ),
108
+ subject: index("workspace_memberships_subject_idx").on(table.subjectId),
109
+ account: index("workspace_memberships_account_idx").on(table.accountId),
110
+ }),
111
+ );
112
+
113
+ export const apiKeys = pgTable(
114
+ "api_keys",
115
+ {
116
+ id: uuid("id").primaryKey().defaultRandom(),
117
+ accountId: uuid("account_id")
118
+ .notNull()
119
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
120
+ workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }),
121
+ name: text("name").notNull(),
122
+ prefix: text("prefix").notNull(),
123
+ keyHash: text("key_hash").notNull(),
124
+ permissions: jsonb("permissions").$type<string[]>().notNull().default([]),
125
+ expiresAt: timestamp("expires_at", { withTimezone: true }),
126
+ revokedAt: timestamp("revoked_at", { withTimezone: true }),
127
+ lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
128
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
129
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
130
+ },
131
+ (table) => ({
132
+ prefix: index("api_keys_prefix_idx").on(table.prefix),
133
+ hash: uniqueIndex("api_keys_key_hash_idx").on(table.keyHash),
134
+ account: index("api_keys_account_idx").on(table.accountId),
135
+ workspace: index("api_keys_workspace_idx").on(table.workspaceId),
136
+ }),
137
+ );
138
+
139
+ export const workspaceVariableSets = pgTable(
140
+ "workspace_variable_sets",
141
+ {
142
+ id: uuid("id").primaryKey().defaultRandom(),
143
+ accountId: uuid("account_id")
144
+ .notNull()
145
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
146
+ workspaceId: uuid("workspace_id")
147
+ .notNull()
148
+ .references(() => workspaces.id, { onDelete: "cascade" }),
149
+ name: text("name").notNull(),
150
+ description: text("description"),
151
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
152
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
153
+ },
154
+ (table) => ({
155
+ workspaceName: uniqueIndex("workspace_variable_sets_workspace_name_idx").on(
156
+ table.workspaceId,
157
+ table.name,
158
+ ),
159
+ workspaceCreated: index("workspace_variable_sets_workspace_created_idx").on(
160
+ table.workspaceId,
161
+ table.createdAt,
162
+ ),
163
+ }),
164
+ );
165
+
166
+ export const workspaceVariableSetVariables = pgTable(
167
+ "workspace_variable_set_variables",
168
+ {
169
+ id: uuid("id").primaryKey().defaultRandom(),
170
+ accountId: uuid("account_id")
171
+ .notNull()
172
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
173
+ workspaceId: uuid("workspace_id")
174
+ .notNull()
175
+ .references(() => workspaces.id, { onDelete: "cascade" }),
176
+ variableSetId: uuid("variable_set_id")
177
+ .notNull()
178
+ .references(() => workspaceVariableSets.id, { onDelete: "cascade" }),
179
+ name: text("name").notNull(),
180
+ // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. Never returned by any API.
181
+ valueEncrypted: text("value_encrypted").notNull(),
182
+ version: integer("version").notNull().default(1),
183
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
184
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
185
+ },
186
+ (table) => ({
187
+ variableSetName: uniqueIndex("workspace_variable_set_variables_env_name_idx").on(
188
+ table.workspaceId,
189
+ table.variableSetId,
190
+ table.name,
191
+ ),
192
+ variableSet: index("workspace_variable_set_variables_workspace_env_idx").on(
193
+ table.workspaceId,
194
+ table.variableSetId,
195
+ ),
196
+ }),
197
+ );
106
198
 
107
199
  // Per-workspace ChatGPT/Codex subscription credential. One row per workspace.
108
200
  // access/refresh/id tokens live INSIDE credential_encrypted (v1 AES-256-GCM,
109
- // same envelope as workspace_environment_variables); the other columns are
201
+ // same envelope as workspace_variable_set_variables); the other columns are
110
202
  // plaintext metadata (header value + UI). RLS-isolated per workspace.
111
- export const codexSubscriptionCredentials = pgTable("codex_subscription_credentials", {
112
- id: uuid("id").primaryKey().defaultRandom(),
113
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
114
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
115
- // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. JSON {access_token, refresh_token, id_token}. Never returned by any API.
116
- credentialEncrypted: text("credential_encrypted").notNull(),
117
- chatgptAccountId: text("chatgpt_account_id"), // plaintext ChatGPT-Account-ID header value (non-secret)
118
- scopes: text("scopes"), // space-delimited, as granted
119
- planType: text("plan_type"),
120
- isFedramp: boolean("is_fedramp").notNull().default(false),
121
- expiresAt: timestamp("expires_at", { withTimezone: true }), // derived from access-token JWT exp
122
- lastRefreshAt: timestamp("last_refresh_at", { withTimezone: true }),
123
- status: text("status").notNull().default("active"), // active | needs_relogin | error
124
- lastError: text("last_error"),
125
- version: integer("version").notNull().default(1),
126
- label: text("label"), // user-chosen nickname; null ⇒ derive from email/plan/account
127
- accountEmail: text("account_email"), // email from the id_token (user's own email; non-secret)
128
- // P2 usage cache (plaintext metadata; NEVER a token). Snapshotted from
129
- // GET /wham/usage; drives the quota bars + the cache TTL. primary = 5h window
130
- // (limit_window_seconds 18000), secondary = weekly (604800).
131
- primaryUsedPercent: integer("primary_used_percent"),
132
- primaryResetAt: timestamp("primary_reset_at", { withTimezone: true }),
133
- secondaryUsedPercent: integer("secondary_used_percent"),
134
- secondaryResetAt: timestamp("secondary_reset_at", { withTimezone: true }),
135
- usageCheckedAt: timestamp("usage_checked_at", { withTimezone: true }), // snapshot freshness cache TTL clock
136
- // P3 rotation cooldown (plaintext metadata; NEVER a token). Set when this account hit its
137
- // usage cap on a rotation turn; the rotation engine treats `exhausted_until > now()` as
138
- // capped/skip so it isn't immediately re-picked. Self-clears via the now() comparison.
139
- exhaustedUntil: timestamp("exhausted_until", { withTimezone: true }),
140
- // P4 connector-aware rotation cache (plaintext metadata; NEVER a token). The set
141
- // of ORIGINAL-dotted connector namespaces (github/gmail/linear/…) this account
142
- // exposes via codex_apps, captured from the per-turn tools/list. null never
143
- // probed (the ranker treats it as unknown: never credited as covering, never
144
- // excluded). The writer only ever sets a NON-empty set, so a flaky empty turn
145
- // can't false-drop coverage. connectorsCheckedAt is the freshness clock.
146
- connectorNamespaces: text("connector_namespaces").array(),
147
- connectorsCheckedAt: timestamp("connectors_checked_at", { withTimezone: true }),
148
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
149
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
150
- }, (table) => ({
151
- // REPLACES codex_subscription_credentials_workspace_idx (the one-per-workspace cap).
152
- // One row per (workspace, ChatGPT account). Partial WHERE chatgpt_account_id IS NOT NULL
153
- // so degenerate null-account rows can't collide; the device-grant connect path always
154
- // populates chatgpt_account_id.
155
- wsAccount: uniqueIndex("codex_subscription_credentials_ws_account_idx")
156
- .on(table.workspaceId, table.chatgptAccountId)
157
- .where(sql`${table.chatgptAccountId} is not null`),
158
- workspace: index("codex_subscription_credentials_workspace_lookup_idx").on(table.workspaceId),
159
- }));
203
+ export const codexSubscriptionCredentials = pgTable(
204
+ "codex_subscription_credentials",
205
+ {
206
+ id: uuid("id").primaryKey().defaultRandom(),
207
+ accountId: uuid("account_id")
208
+ .notNull()
209
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
210
+ workspaceId: uuid("workspace_id")
211
+ .notNull()
212
+ .references(() => workspaces.id, { onDelete: "cascade" }),
213
+ // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. JSON {access_token, refresh_token, id_token}. Never returned by any API.
214
+ credentialEncrypted: text("credential_encrypted").notNull(),
215
+ chatgptAccountId: text("chatgpt_account_id"), // plaintext ChatGPT-Account-ID header value (non-secret)
216
+ scopes: text("scopes"), // space-delimited, as granted
217
+ planType: text("plan_type"),
218
+ isFedramp: boolean("is_fedramp").notNull().default(false),
219
+ expiresAt: timestamp("expires_at", { withTimezone: true }), // derived from access-token JWT exp
220
+ lastRefreshAt: timestamp("last_refresh_at", { withTimezone: true }),
221
+ status: text("status").notNull().default("active"), // active | needs_relogin | error
222
+ lastError: text("last_error"),
223
+ version: integer("version").notNull().default(1),
224
+ label: text("label"), // user-chosen nickname; null ⇒ derive from email/plan/account
225
+ accountEmail: text("account_email"), // email from the id_token (user's own email; non-secret)
226
+ // P2 usage cache (plaintext metadata; NEVER a token). Snapshotted from
227
+ // GET /wham/usage; drives the quota bars + the cache TTL. primary = 5h window
228
+ // (limit_window_seconds 18000), secondary = weekly (604800).
229
+ primaryUsedPercent: integer("primary_used_percent"),
230
+ primaryResetAt: timestamp("primary_reset_at", { withTimezone: true }),
231
+ secondaryUsedPercent: integer("secondary_used_percent"),
232
+ secondaryResetAt: timestamp("secondary_reset_at", { withTimezone: true }),
233
+ usageCheckedAt: timestamp("usage_checked_at", { withTimezone: true }), // snapshot freshness → cache TTL clock
234
+ // P3 rotation cooldown (plaintext metadata; NEVER a token). Set when this account hit its
235
+ // usage cap on a rotation turn; the rotation engine treats `exhausted_until > now()` as
236
+ // capped/skip so it isn't immediately re-picked. Self-clears via the now() comparison.
237
+ exhaustedUntil: timestamp("exhausted_until", { withTimezone: true }),
238
+ // P4 connector-aware rotation cache (plaintext metadata; NEVER a token). The set
239
+ // of ORIGINAL-dotted connector namespaces (github/gmail/linear/…) this account
240
+ // exposes via codex_apps, captured from the per-turn tools/list. null ⇒ never
241
+ // probed (the ranker treats it as unknown: never credited as covering, never
242
+ // excluded). The writer only ever sets a NON-empty set, so a flaky empty turn
243
+ // can't false-drop coverage. connectorsCheckedAt is the freshness clock.
244
+ connectorNamespaces: text("connector_namespaces").array(),
245
+ connectorsCheckedAt: timestamp("connectors_checked_at", { withTimezone: true }),
246
+ // Workspace-local, server-held fairness cursor. Provider usage headers are
247
+ // capacity hints, never the sole allocator: live lease count is ranked first
248
+ // and this cursor deterministically breaks equal-load/equal-capacity ties.
249
+ // This flag controls NEW automatic allocations only. Credential health,
250
+ // refresh, encrypted material, and already-frozen/in-flight turns are
251
+ // intentionally independent. OPE-24 owns toggle OCC/audit and product UI.
252
+ allocatorEnabled: boolean("allocator_enabled").notNull().default(true),
253
+ selectionCount: integer("selection_count").notNull().default(0),
254
+ lastSelectedAt: timestamp("last_selected_at", { withTimezone: true }),
255
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
256
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
257
+ },
258
+ (table) => ({
259
+ // REPLACES codex_subscription_credentials_workspace_idx (the one-per-workspace cap).
260
+ // One row per (workspace, ChatGPT account). Partial WHERE chatgpt_account_id IS NOT NULL
261
+ // so degenerate null-account rows can't collide; the device-grant connect path always
262
+ // populates chatgpt_account_id.
263
+ wsAccount: uniqueIndex("codex_subscription_credentials_ws_account_idx")
264
+ .on(table.workspaceId, table.chatgptAccountId)
265
+ .where(sql`${table.chatgptAccountId} is not null`),
266
+ workspace: index("codex_subscription_credentials_workspace_lookup_idx").on(table.workspaceId),
267
+ // Composite identity is the defense-in-depth FK target for workspace-local
268
+ // lease references in migration 0053.
269
+ workspaceIdentity: uniqueIndex("codex_subscription_credentials_workspace_id_idx").on(
270
+ table.workspaceId,
271
+ table.id,
272
+ ),
273
+ }),
274
+ );
160
275
 
161
276
  // Generic external-service credential spine. credential_encrypted is the ONLY
162
277
  // secret-bearing column; normal API reads use metadata-only helpers below the DB
163
278
  // layer. Runtime token material is decrypted only by the broker accessor.
164
- export const connections = pgTable("connections", {
165
- id: uuid("id").primaryKey().defaultRandom(),
166
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
167
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
168
- subjectId: text("subject_id"),
169
- providerDomain: text("provider_domain").notNull(),
170
- kind: text("kind").notNull(),
171
- status: text("status").notNull().default("active"),
172
- credentialEncrypted: text("credential_encrypted").notNull(),
173
- grantedScopes: jsonb("granted_scopes").$type<string[]>().notNull().default([]),
174
- expiresAt: timestamp("expires_at", { withTimezone: true }),
175
- lastRefreshAt: timestamp("last_refresh_at", { withTimezone: true }),
176
- lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
177
- lastError: text("last_error"),
178
- version: integer("version").notNull().default(1),
179
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
180
- createdBySubjectId: text("created_by_subject_id"),
181
- updatedBySubjectId: text("updated_by_subject_id"),
182
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
183
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
184
- }, (table) => ({
185
- workspaceProviderStatus: index("connections_workspace_provider_status_idx").on(table.workspaceId, table.providerDomain, table.status),
186
- workspaceSubjectProvider: index("connections_workspace_subject_provider_idx").on(table.workspaceId, table.subjectId, table.providerDomain),
187
- workspaceKind: index("connections_workspace_kind_idx").on(table.workspaceId, table.kind),
188
- workspaceExpires: index("connections_workspace_expires_idx").on(table.workspaceId, table.expiresAt),
189
- }));
279
+ export const connections = pgTable(
280
+ "connections",
281
+ {
282
+ id: uuid("id").primaryKey().defaultRandom(),
283
+ accountId: uuid("account_id")
284
+ .notNull()
285
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
286
+ workspaceId: uuid("workspace_id")
287
+ .notNull()
288
+ .references(() => workspaces.id, { onDelete: "cascade" }),
289
+ subjectId: text("subject_id"),
290
+ providerDomain: text("provider_domain").notNull(),
291
+ kind: text("kind").notNull(),
292
+ status: text("status").notNull().default("active"),
293
+ credentialEncrypted: text("credential_encrypted").notNull(),
294
+ grantedScopes: jsonb("granted_scopes").$type<string[]>().notNull().default([]),
295
+ expiresAt: timestamp("expires_at", { withTimezone: true }),
296
+ lastRefreshAt: timestamp("last_refresh_at", { withTimezone: true }),
297
+ lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
298
+ lastError: text("last_error"),
299
+ version: integer("version").notNull().default(1),
300
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
301
+ createdBySubjectId: text("created_by_subject_id"),
302
+ updatedBySubjectId: text("updated_by_subject_id"),
303
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
304
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
305
+ },
306
+ (table) => ({
307
+ workspaceProviderStatus: index("connections_workspace_provider_status_idx").on(
308
+ table.workspaceId,
309
+ table.providerDomain,
310
+ table.status,
311
+ ),
312
+ workspaceSubjectProvider: index("connections_workspace_subject_provider_idx").on(
313
+ table.workspaceId,
314
+ table.subjectId,
315
+ table.providerDomain,
316
+ ),
317
+ workspaceKind: index("connections_workspace_kind_idx").on(table.workspaceId, table.kind),
318
+ workspaceExpires: index("connections_workspace_expires_idx").on(
319
+ table.workspaceId,
320
+ table.expiresAt,
321
+ ),
322
+ }),
323
+ );
190
324
 
191
325
  // OAuth client registrations minted through MCP DCR, keyed by authorization
192
326
  // server issuer. This is deployment-wide client identity, not a workspace
193
327
  // credential; per-user/provider tokens still live only in connections.
194
- export const integrationOauthClients = pgTable("integration_oauth_clients", {
195
- id: uuid("id").primaryKey().defaultRandom(),
196
- issuer: text("issuer").notNull(),
197
- authorizationServer: text("authorization_server").notNull(),
198
- clientId: text("client_id").notNull(),
199
- clientSecretEncrypted: text("client_secret_encrypted"),
200
- tokenEndpointAuthMethod: text("token_endpoint_auth_method").notNull().default("none"),
201
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
202
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
203
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
204
- }, (table) => ({
205
- issuer: uniqueIndex("integration_oauth_clients_issuer_idx").on(table.issuer),
206
- authorizationServer: index("integration_oauth_clients_as_idx").on(table.authorizationServer),
207
- }));
328
+ export const integrationOauthClients = pgTable(
329
+ "integration_oauth_clients",
330
+ {
331
+ id: uuid("id").primaryKey().defaultRandom(),
332
+ issuer: text("issuer").notNull(),
333
+ authorizationServer: text("authorization_server").notNull(),
334
+ clientId: text("client_id").notNull(),
335
+ clientSecretEncrypted: text("client_secret_encrypted"),
336
+ tokenEndpointAuthMethod: text("token_endpoint_auth_method").notNull().default("none"),
337
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
338
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
339
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
340
+ },
341
+ (table) => ({
342
+ issuer: uniqueIndex("integration_oauth_clients_issuer_idx").on(table.issuer),
343
+ authorizationServer: index("integration_oauth_clients_as_idx").on(table.authorizationServer),
344
+ }),
345
+ );
208
346
 
209
347
  // Consumed OAuth state nonces. Rows are inserted only on callback; the primary
210
348
  // key makes a verified state single-use across API instances.
211
- export const integrationOauthStateNonces = pgTable("integration_oauth_state_nonces", {
212
- nonce: text("nonce").primaryKey(),
213
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
214
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
215
- subjectId: text("subject_id").notNull(),
216
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
217
- usedAt: timestamp("used_at", { withTimezone: true }).notNull().defaultNow(),
218
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
219
- }, (table) => ({
220
- workspace: index("integration_oauth_state_nonces_workspace_idx").on(table.workspaceId),
221
- expires: index("integration_oauth_state_nonces_expires_idx").on(table.expiresAt),
222
- }));
349
+ export const integrationOauthStateNonces = pgTable(
350
+ "integration_oauth_state_nonces",
351
+ {
352
+ nonce: text("nonce").primaryKey(),
353
+ accountId: uuid("account_id")
354
+ .notNull()
355
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
356
+ workspaceId: uuid("workspace_id")
357
+ .notNull()
358
+ .references(() => workspaces.id, { onDelete: "cascade" }),
359
+ subjectId: text("subject_id").notNull(),
360
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
361
+ usedAt: timestamp("used_at", { withTimezone: true }).notNull().defaultNow(),
362
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
363
+ },
364
+ (table) => ({
365
+ workspace: index("integration_oauth_state_nonces_workspace_idx").on(table.workspaceId),
366
+ expires: index("integration_oauth_state_nonces_expires_idx").on(table.expiresAt),
367
+ }),
368
+ );
223
369
 
224
370
  // Per-workspace Codex account selection (the ACTIVE pointer) + P3 rotation
225
371
  // forward-compat. One row per workspace. The only P1-load-bearing column is
@@ -229,357 +375,1063 @@ export const integrationOauthStateNonces = pgTable("integration_oauth_state_nonc
229
375
  // policy. active_credential_id's FK is declared in the MIGRATION (not
230
376
  // .references()) to avoid a forward-reference on the const ordering, exactly like
231
377
  // sessions.activeSandboxId; ON DELETE SET NULL.
232
- export const codexRotationSettings = pgTable("codex_rotation_settings", {
233
- id: uuid("id").primaryKey().defaultRandom(),
234
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
235
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
236
- activeCredentialId: uuid("active_credential_id"),
237
- rotationEnabled: boolean("rotation_enabled").notNull().default(false), // P3, inert in P1
238
- rotationStrategy: text("rotation_strategy").notNull().default("most_remaining"), // P3, inert
239
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
240
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
241
- }, (table) => ({
242
- workspace: uniqueIndex("codex_rotation_settings_workspace_idx").on(table.workspaceId),
243
- }));
244
-
245
- export const sessions = pgTable("sessions", {
246
- id: uuid("id").primaryKey().defaultRandom(),
247
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
248
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
249
- status: text("status").notNull().default("queued"),
250
- initialMessage: text("initial_message").notNull(),
251
- title: text("title"),
252
- titleSource: text("title_source"),
253
- // Per-session agent persona/system instructions supplied at create (the
254
- // per-agent-type prompt lever for embedding hosts). NULL ⇒ the session
255
- // carried none, so the composed agent instructions are byte-identical to a
256
- // workspace-only persona (no backfill, no behavior change for existing rows).
257
- // Composed system-level AFTER the workspace agentInstructions; never emitted
258
- // as a timeline event.
259
- instructions: text("instructions"),
260
- resources: jsonb("resources").$type<unknown[]>().notNull().default([]),
261
- tools: jsonb("tools").$type<unknown[]>().notNull().default([]),
262
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
263
- model: text("model").notNull(),
264
- sandboxBackend: text("sandbox_backend").notNull(),
265
- // The OS this session's box runs. Defaults to 'linux' (today's only OS, so
266
- // every existing + new row is a behavior-preserving no-op). CHECK-constrained
267
- // to the SandboxOs enum (linux|macos|windows) in migration 0018.
268
- sandboxOs: text("sandbox_os").notNull().default("linux"),
269
- // The shared-sandbox group this session's box belongs to. Defaults to the
270
- // session's OWN id (a singleton group: group === session today's 1:1
271
- // behavior). When spawned shared via session_create, set to the PARENT's
272
- // sandboxGroupId so both run in ONE box. Immutable once set. NOT an FK (the
273
- // value is this row's id or an ancestor session's id in the same workspace;
274
- // the live lease row, not a sandbox_groups table, materializes the group).
275
- // The app generates the uuid and uses it for both id and sandbox_group_id in
276
- // one insert — it cannot SQL-default to id (id is defaultRandom()).
277
- sandboxGroupId: uuid("sandbox_group_id").notNull(),
278
- // The first-class swappable-sandbox POINTER (bring-your-own-compute M2,
279
- // dossier §10.3). NULL == "use the session's own group sandbox" (the
280
- // backward-compat default — every existing/new row is a behavior-preserving
281
- // no-op). The routing proxy re-reads (active_sandbox_id, active_epoch) PER
282
- // TOOL CALL to make a Modal<->selfhosted hot-swap seamless. The FK
283
- // (-> sandboxes(id) ON DELETE SET NULL — a deleted sandbox degrades the
284
- // pointer to the group default, never dangles) lives in migration 0024, NOT a
285
- // Drizzle .references() exactly like parentSessionId below, so the const
286
- // ordering imposes no forward-reference.
287
- activeSandboxId: uuid("active_sandbox_id"),
288
- // The SECOND epoch ABOVE sandbox_leases.lease_epoch, bumped on every swap; an
289
- // in-flight op fenced by a stale active_epoch retries against the new active
290
- // sandbox. integer (NOT bigint) — the lease-epoch spike: int8 reads back as a
291
- // JS string and breaks the strict fence; int4 returns a number.
292
- activeEpoch: integer("active_epoch").notNull().default(0),
293
- // The session's WORKING DIRECTORY the path/cwd base the (selfhosted) box's
294
- // agent/terminal/file-dock operate under. A launch-workspace_root-relative
295
- // subdir or an absolute machine path; surfaced alongside the active-sandbox
296
- // pointer (readActiveSandbox) and written through the epoch-fenced
297
- // setActiveSandbox CAS, NOT the row INSERT. NULL (the default) ⇒ today's
298
- // behavior exactly the agent substitutes its workspace_root for an empty cwd,
299
- // so an unset working_dir is a byte-identical no-op. Create-time only (Stage A).
300
- workingDir: text("working_dir"),
301
- environmentId: uuid("environment_id").references(() => workspaceEnvironments.id, { onDelete: "set null" }),
302
- // Non-default first-party MCP token permissions (manager-style sessions);
303
- // null means the fixed worker default set in @opengeni/runtime.
304
- firstPartyMcpPermissions: jsonb("first_party_mcp_permissions").$type<string[]>(),
305
- // The manager session that spawned this one via session_create. Set only
306
- // when the creating grant carried a worker-signed sessionId claim (a session
307
- // spawning a worker); null for direct API creates and scheduled-task runs.
308
- // When set, this worker's terminal-for-now transitions wake the parent so a
309
- // manager can orchestrate workers without busy-polling. Self-referencing FK,
310
- // ON DELETE SET NULL so deleting a manager never cascades into its workers.
311
- parentSessionId: uuid("parent_session_id"),
312
- // Workspace-scoped CREATE idempotency key. NULL means the create carried no
313
- // key (each such create is independent). When set, the partial unique index
314
- // below collapses concurrent/retried creates with the same key in the same
315
- // workspace to a single session row — the dedup that closes the
316
- // double-submit/double-dispatch stuck-queued bug.
317
- createIdempotencyKey: text("create_idempotency_key"),
318
- temporalWorkflowId: text("temporal_workflow_id"),
319
- activeTurnId: uuid("active_turn_id"),
320
- // Actual input tokens reported for the last model call of the most recent
321
- // turn. The pre-turn client-side compaction trigger reads this as its budget
322
- // signal (char/4 estimate is the same-turn fallback). Null until a turn with
323
- // usage has completed.
324
- lastInputTokens: integer("last_input_tokens"),
325
- // Operator /compact request flag (client-side compaction path). The API sets
326
- // it true; the worker honors it BEFORE the next turn's model call by forcing
327
- // a compaction, then clears it. A durable flag (not a transient signal) so
328
- // the trigger survives a worker restart and converges before the next turn.
329
- compactRequested: boolean("compact_requested").notNull().default(false),
330
- lastSequence: integer("last_sequence").notNull().default(0),
331
- // The session's PINNED Codex account (manual override from the in-session
332
- // switcher). NULL ⇒ follow the workspace active pointer. FK declared in the
333
- // migration with ON DELETE SET NULL (a disconnected pin degrades to "follow
334
- // active", never dangles), same pattern as activeSandboxId.
335
- codexPinnedCredentialId: uuid("codex_pinned_credential_id"),
336
- // The Codex account the session's most recent turn ACTUALLY ran on — drives
337
- // the "Running on:" indicator. Written by the worker at the turn boundary. FK
338
- // ON DELETE SET NULL (migration).
339
- codexLastCredentialId: uuid("codex_last_credential_id"),
340
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
341
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
342
- }, (table) => ({
343
- workspaceCreated: index("sessions_workspace_created_idx").on(table.workspaceId, table.createdAt),
344
- environment: index("sessions_environment_idx").on(table.workspaceId, table.environmentId),
345
- parent: index("sessions_parent_idx").on(table.workspaceId, table.parentSessionId),
346
- // Routing index: resolve session_id -> sandbox_group_id at every lease entry
347
- // point and enumerate all sessions in a group for attribution/disclosure.
348
- sandboxGroup: index("sessions_sandbox_group_idx").on(table.workspaceId, table.sandboxGroupId),
349
- // Partial unique index: one session per (workspace, create_idempotency_key)
350
- // when a key is present. Concurrent creates racing on the same key see a
351
- // unique violation on all but one; the domain layer catches it and returns
352
- // the winning row instead of erroring.
353
- createIdempotency: uniqueIndex("sessions_workspace_create_idempotency_idx").on(table.workspaceId, table.createIdempotencyKey).where(sql`${table.createIdempotencyKey} is not null`),
354
- }));
355
-
356
- export const sessionMcpServers = pgTable("session_mcp_servers", {
357
- id: uuid("id").primaryKey().defaultRandom(),
358
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
359
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
360
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
361
- serverId: text("server_id").notNull(),
362
- name: text("name"),
363
- url: text("url").notNull(),
364
- allowedTools: jsonb("allowed_tools").$type<string[]>(),
365
- timeoutMs: integer("timeout_ms"),
366
- cacheToolsList: boolean("cache_tools_list").notNull().default(false),
367
- // Human-approval policy: `true` = every tool requires approval, a string[] of
368
- // UNPREFIXED tool names = only those require it, null/absent = auto-run.
369
- requireApproval: jsonb("require_approval").$type<boolean | string[]>(),
370
- // Map of header name -> AES-GCM ciphertext. Values are decrypted only by the
371
- // worker's run-preparation path and never returned by API helpers.
372
- headersEncrypted: jsonb("headers_encrypted").$type<Record<string, string>>().notNull().default({}),
373
- credentialVersion: integer("credential_version").notNull().default(1),
374
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
375
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
376
- }, (table) => ({
377
- sessionServer: uniqueIndex("session_mcp_servers_session_server_idx").on(table.workspaceId, table.sessionId, table.serverId),
378
- session: index("session_mcp_servers_session_idx").on(table.workspaceId, table.sessionId),
379
- }));
380
-
381
- export const files = pgTable("files", {
382
- id: uuid("id").primaryKey().defaultRandom(),
383
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
384
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
385
- status: text("status").notNull().default("pending_upload"),
386
- filename: text("filename").notNull(),
387
- safeFilename: text("safe_filename").notNull(),
388
- contentType: text("content_type").notNull(),
389
- sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(),
390
- sha256: text("sha256"),
391
- bucket: text("bucket").notNull(),
392
- objectKey: text("object_key").notNull(),
393
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
394
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
395
- }, (table) => ({
396
- workspaceCreated: index("files_workspace_created_idx").on(table.workspaceId, table.createdAt),
397
- objectKey: uniqueIndex("files_object_key_idx").on(table.objectKey),
398
- status: index("files_status_idx").on(table.status),
399
- }));
400
-
401
- export const fileUploads = pgTable("file_uploads", {
402
- id: uuid("id").primaryKey().defaultRandom(),
403
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
404
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
405
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "cascade" }),
406
- status: text("status").notNull().default("pending"),
407
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
408
- completedAt: timestamp("completed_at", { withTimezone: true }),
409
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
410
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
411
- }, (table) => ({
412
- workspace: index("file_uploads_workspace_idx").on(table.workspaceId),
413
- fileId: index("file_uploads_file_id_idx").on(table.fileId),
414
- status: index("file_uploads_status_idx").on(table.status),
415
- }));
416
-
417
- export const documentBases = pgTable("document_bases", {
418
- id: uuid("id").primaryKey().defaultRandom(),
419
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
420
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
421
- name: text("name").notNull(),
422
- description: text("description"),
423
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
424
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
425
- }, (table) => ({
426
- workspaceCreated: index("document_bases_workspace_created_idx").on(table.workspaceId, table.createdAt),
427
- }));
428
-
429
- export const documents = pgTable("documents", {
430
- id: uuid("id").primaryKey().defaultRandom(),
431
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
432
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
433
- baseId: uuid("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
434
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
435
- status: text("status").notNull().default("queued"),
436
- title: text("title").notNull(),
437
- parser: text("parser").notNull().default("liteparse"),
438
- chunkCount: integer("chunk_count").notNull().default(0),
439
- error: text("error"),
440
- sourceKind: text("source_kind").notNull().default("manual_upload"),
441
- sourceUri: text("source_uri"),
442
- sourceExternalId: text("source_external_id"),
443
- sourceTitle: text("source_title"),
444
- sourceAuthor: text("source_author"),
445
- sourceCreatedAt: timestamp("source_created_at", { withTimezone: true }),
446
- sourceUpdatedAt: timestamp("source_updated_at", { withTimezone: true }),
447
- sourceVersion: text("source_version"),
448
- aclTags: jsonb("acl_tags").$type<string[]>().notNull().default([]),
449
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
450
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
451
- }, (table) => ({
452
- baseFile: uniqueIndex("documents_workspace_base_file_idx").on(table.workspaceId, table.baseId, table.fileId),
453
- baseStatus: index("documents_workspace_base_status_idx").on(table.workspaceId, table.baseId, table.status),
454
- sourceKind: index("documents_workspace_source_kind_idx").on(table.workspaceId, table.sourceKind),
455
- sourceExternalId: index("documents_workspace_source_external_id_idx").on(table.workspaceId, table.sourceExternalId),
456
- }));
457
-
458
- export const documentChunks = pgTable("document_chunks", {
459
- id: uuid("id").primaryKey().defaultRandom(),
460
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
461
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
462
- documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
463
- baseId: uuid("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
464
- fileId: uuid("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
465
- chunkIndex: integer("chunk_index").notNull(),
466
- text: text("text").notNull(),
467
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
468
- embedding: vector("embedding").notNull(),
469
- embeddingModel: text("embedding_model").notNull(),
470
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
471
- }, (table) => ({
472
- documentIndex: uniqueIndex("document_chunks_workspace_document_index_idx").on(table.workspaceId, table.documentId, table.chunkIndex),
473
- base: index("document_chunks_workspace_base_idx").on(table.workspaceId, table.baseId),
474
- }));
475
-
476
- export const knowledgeMemories = pgTable("knowledge_memories", {
477
- id: uuid("id").primaryKey().defaultRandom(),
478
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
479
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
480
- status: text("status").notNull().default("proposed"),
481
- kind: text("kind").notNull().default("semantic"),
482
- scope: text("scope").notNull().default("workspace"),
483
- text: text("text").notNull(),
484
- sourceRefs: jsonb("source_refs").$type<unknown[]>().notNull().default([]),
485
- confidence: integer("confidence").notNull().default(50),
486
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
487
- createdBySessionId: uuid("created_by_session_id").references(() => sessions.id, { onDelete: "set null" }),
488
- reviewedBy: text("reviewed_by"),
489
- reviewedAt: timestamp("reviewed_at", { withTimezone: true }),
490
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
491
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
492
- }, (table) => ({
493
- workspaceStatus: index("knowledge_memories_workspace_status_idx").on(table.workspaceId, table.status, table.updatedAt),
494
- workspaceKind: index("knowledge_memories_workspace_kind_idx").on(table.workspaceId, table.kind),
495
- workspaceScope: index("knowledge_memories_workspace_scope_idx").on(table.workspaceId, table.scope),
496
- createdBySession: index("knowledge_memories_workspace_created_by_session_idx").on(table.workspaceId, table.createdBySessionId),
497
- }));
498
-
499
- export const sessionTurns = pgTable("session_turns", {
500
- id: uuid("id").primaryKey().defaultRandom(),
501
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
502
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
503
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
504
- triggerEventId: uuid("trigger_event_id").notNull(),
505
- temporalWorkflowId: text("temporal_workflow_id").notNull(),
506
- status: text("status").notNull(),
507
- source: text("source").notNull().default("user"),
508
- position: integer("position").notNull(),
509
- prompt: text("prompt").notNull(),
510
- resources: jsonb("resources").$type<unknown[]>().notNull().default([]),
511
- tools: jsonb("tools").$type<unknown[]>().notNull().default([]),
512
- model: text("model").notNull(),
513
- reasoningEffort: text("reasoning_effort").notNull(),
514
- sandboxBackend: text("sandbox_backend").notNull(),
515
- // Per-turn OS override. NULL = inherit the session's sandbox_os. CHECK-
516
- // constrained to the SandboxOs enum (or NULL) in migration 0018.
517
- sandboxOs: text("sandbox_os"),
518
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
519
- // Atomic per-turn toolspace call budget counter (migration 0043). Incremented
520
- // by a single conditional UPDATE at tools/call time; the row lock serializes
521
- // concurrent reservations so exactly `toolspaceMaxCallsPerTurn` succeed.
522
- toolspaceCallCount: integer("toolspace_call_count").notNull().default(0),
523
- startedAt: timestamp("started_at", { withTimezone: true }),
524
- finishedAt: timestamp("finished_at", { withTimezone: true }),
525
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
526
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
527
- }, (table) => ({
528
- queue: index("session_turns_workspace_queue_idx").on(table.workspaceId, table.sessionId, table.status, table.position),
529
- }));
530
-
531
- export const sessionGoals = pgTable("session_goals", {
532
- id: uuid("id").primaryKey().defaultRandom(),
533
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
534
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
535
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
536
- status: text("status").notNull().default("active"), // active | paused | completed
537
- text: text("text").notNull(),
538
- successCriteria: text("success_criteria"),
539
- evidence: text("evidence"), // set by goal_complete
540
- rationale: text("rationale"), // set by goal_pause
541
- pausedReason: text("paused_reason"), // agent | user_interrupt | api | no_progress | max_auto_continuations | limits
542
- createdBy: text("created_by").notNull().default("api"), // api | agent | scheduled_task
543
- version: integer("version").notNull().default(1), // bumped on every set/update; progress signal
544
- autoContinuations: integer("auto_continuations").notNull().default(0),
545
- noProgressStreak: integer("no_progress_streak").notNull().default(0),
546
- maxAutoContinuations: integer("max_auto_continuations"), // per-goal override; a configured settings cap (if any) remains the hard ceiling
547
- lastContinuationTurnId: uuid("last_continuation_turn_id"),
548
- versionAtLastContinuation: integer("version_at_last_continuation"),
549
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
550
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
551
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
552
- }, (table) => ({
553
- workspaceSession: uniqueIndex("session_goals_workspace_session_idx").on(table.workspaceId, table.sessionId),
554
- status: index("session_goals_workspace_status_idx").on(table.workspaceId, table.status),
555
- }));
556
-
557
- export const sessionEvents = pgTable("session_events", {
558
- id: uuid("id").primaryKey().defaultRandom(),
559
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
560
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
561
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
562
- turnId: uuid("turn_id"),
563
- sequence: integer("sequence").notNull(),
564
- type: text("type").notNull(),
565
- payload: jsonb("payload").$type<unknown>().notNull().default({}),
566
- clientEventId: text("client_event_id"),
567
- producerId: text("producer_id"),
568
- producerSeq: integer("producer_seq"),
569
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
570
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
571
- }, (table) => ({
572
- sessionSequence: uniqueIndex("session_events_workspace_session_sequence_idx").on(table.workspaceId, table.sessionId, table.sequence),
573
- clientEvent: uniqueIndex("session_events_workspace_client_event_idx").on(table.workspaceId, table.sessionId, table.clientEventId).where(sql`${table.clientEventId} is not null`),
574
- 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`),
575
- sessionCreated: index("session_events_workspace_session_created_idx").on(table.workspaceId, table.sessionId, table.createdAt),
576
- }));
378
+ export const codexRotationSettings = pgTable(
379
+ "codex_rotation_settings",
380
+ {
381
+ id: uuid("id").primaryKey().defaultRandom(),
382
+ accountId: uuid("account_id")
383
+ .notNull()
384
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
385
+ workspaceId: uuid("workspace_id")
386
+ .notNull()
387
+ .references(() => workspaces.id, { onDelete: "cascade" }),
388
+ activeCredentialId: uuid("active_credential_id"),
389
+ // Legacy selector bit. Keep false as the DB default forever: an old worker
390
+ // only understands this column, so a schema-first rollout or binary
391
+ // rollback must never make it enter the non-atomic rotation path.
392
+ rotationEnabled: boolean("rotation_enabled").notNull().default(false),
393
+ // Revision-aware allocator cutover. Only migration-compatible API/worker
394
+ // code reads this bit; old binaries safely ignore it and keep the legacy
395
+ // pin/rotation policy.
396
+ leaseRotationEnabled: boolean("lease_rotation_enabled").notNull().default(false),
397
+ rotationStrategy: text("rotation_strategy").notNull().default("most_remaining"), // P3, inert
398
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
399
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
400
+ },
401
+ (table) => ({
402
+ workspace: uniqueIndex("codex_rotation_settings_workspace_idx").on(table.workspaceId),
403
+ }),
404
+ );
405
+
406
+ // Per-workspace model/provider availability policy — the HARD blocker deciding
407
+ // which providers/models may serve a turn in this workspace AT ALL. NULL columns
408
+ // mean unrestricted (today's behavior for every workspace without a row). A
409
+ // non-null allowed_providers is a strict allowlist over provider identities
410
+ // (the same identities the model router resolves to, with the built-in
411
+ // OpenAI/Azure client including the legacy resolveTurnModel-null fallback
412
+ // mapped to one well-known id); a non-null allowed_models is an additional
413
+ // exact-model-id allowlist. Enforced at the API model-choke points (422) and,
414
+ // authoritatively, in the worker immediately after turn model resolution: a
415
+ // blocked resolution NEVER reaches a model call and NEVER silently remaps.
416
+ // This exists so a codex-subscription workspace can be fail-closed to codex
417
+ // a turn can wait/fail loud, but can never fall through to the paid built-in.
418
+ export const workspaceModelPolicies = pgTable(
419
+ "workspace_model_policies",
420
+ {
421
+ id: uuid("id").primaryKey().defaultRandom(),
422
+ accountId: uuid("account_id")
423
+ .notNull()
424
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
425
+ workspaceId: uuid("workspace_id")
426
+ .notNull()
427
+ .references(() => workspaces.id, { onDelete: "cascade" }),
428
+ allowedProviders: text("allowed_providers").array(),
429
+ allowedModels: text("allowed_models").array(),
430
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
431
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
432
+ },
433
+ (table) => ({
434
+ workspace: uniqueIndex("workspace_model_policies_workspace_idx").on(table.workspaceId),
435
+ }),
436
+ );
437
+
438
+ // One workspace-local short-lived holder per running Codex turn. Selection and
439
+ // insertion happen atomically while codex_rotation_settings is locked FOR
440
+ // UPDATE, so concurrent replicas in the SAME workspace see one another's
441
+ // assignments before choosing. Workspaces never share or correlate lease state.
442
+ // The composite (workspace, account), (workspace, credential), and
443
+ // (workspace, turn) FKs are declared in migration 0053 (sessionTurns is defined
444
+ // later in this module).
445
+ export const codexCredentialLeases = pgTable(
446
+ "codex_credential_leases",
447
+ {
448
+ id: uuid("id").primaryKey().defaultRandom(),
449
+ accountId: uuid("account_id")
450
+ .notNull()
451
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
452
+ workspaceId: uuid("workspace_id")
453
+ .notNull()
454
+ .references(() => workspaces.id, { onDelete: "cascade" }),
455
+ credentialId: uuid("credential_id").notNull(),
456
+ turnId: uuid("turn_id").notNull(),
457
+ // Temporal activity execution fence. A successor dispatch for the same
458
+ // durable turn replaces holderId and increments generation atomically;
459
+ // stale/zombie heartbeats and releases must match both values.
460
+ holderId: text("holder_id").notNull(),
461
+ generation: integer("generation").notNull().default(1),
462
+ leasedUntil: timestamp("leased_until", { withTimezone: true }).notNull(),
463
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
464
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
465
+ },
466
+ (table) => ({
467
+ turn: uniqueIndex("codex_credential_leases_workspace_turn_idx").on(
468
+ table.workspaceId,
469
+ table.turnId,
470
+ ),
471
+ activeCredential: index("codex_credential_leases_active_credential_idx").on(
472
+ table.workspaceId,
473
+ table.credentialId,
474
+ table.leasedUntil,
475
+ ),
476
+ expiry: index("codex_credential_leases_expiry_idx").on(table.leasedUntil),
477
+ }),
478
+ );
479
+
480
+ export const sessions = pgTable(
481
+ "sessions",
482
+ {
483
+ id: uuid("id").primaryKey().defaultRandom(),
484
+ accountId: uuid("account_id")
485
+ .notNull()
486
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
487
+ workspaceId: uuid("workspace_id")
488
+ .notNull()
489
+ .references(() => workspaces.id, { onDelete: "cascade" }),
490
+ status: text("status").notNull().default("queued"),
491
+ initialMessage: text("initial_message").notNull(),
492
+ title: text("title"),
493
+ titleSource: text("title_source"),
494
+ // Per-session agent persona/system instructions supplied at create (the
495
+ // per-agent-type prompt lever for embedding hosts). NULL ⇒ the session
496
+ // carried none, so the composed agent instructions are byte-identical to a
497
+ // workspace-only persona (no backfill, no behavior change for existing rows).
498
+ // Composed system-level AFTER the workspace agentInstructions; never emitted
499
+ // as a timeline event.
500
+ instructions: text("instructions"),
501
+ resources: jsonb("resources").$type<unknown[]>().notNull().default([]),
502
+ tools: jsonb("tools").$type<unknown[]>().notNull().default([]),
503
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
504
+ model: text("model").notNull(),
505
+ sandboxBackend: text("sandbox_backend").notNull(),
506
+ // The OS this session's box runs. Defaults to 'linux' (today's only OS, so
507
+ // every existing + new row is a behavior-preserving no-op). CHECK-constrained
508
+ // to the SandboxOs enum (linux|macos|windows) in migration 0018.
509
+ sandboxOs: text("sandbox_os").notNull().default("linux"),
510
+ // The shared-sandbox group this session's box belongs to. Defaults to the
511
+ // session's OWN id (a singleton group: group === session — today's 1:1
512
+ // behavior). When spawned shared via session_create, set to the PARENT's
513
+ // sandboxGroupId so both run in ONE box. Immutable once set. NOT an FK (the
514
+ // value is this row's id or an ancestor session's id in the same workspace;
515
+ // the live lease row, not a sandbox_groups table, materializes the group).
516
+ // The app generates the uuid and uses it for both id and sandbox_group_id in
517
+ // one insert it cannot SQL-default to id (id is defaultRandom()).
518
+ sandboxGroupId: uuid("sandbox_group_id").notNull(),
519
+ // The first-class swappable-sandbox POINTER (bring-your-own-compute M2,
520
+ // dossier §10.3). NULL == "use the session's own group sandbox" (the
521
+ // backward-compat default every existing/new row is a behavior-preserving
522
+ // no-op). The routing proxy re-reads (active_sandbox_id, active_epoch) PER
523
+ // TOOL CALL to make a Modal<->selfhosted hot-swap seamless. The FK
524
+ // (-> sandboxes(id) ON DELETE SET NULL — a deleted sandbox degrades the
525
+ // pointer to the group default, never dangles) lives in migration 0024, NOT a
526
+ // Drizzle .references() — exactly like parentSessionId below, so the const
527
+ // ordering imposes no forward-reference.
528
+ activeSandboxId: uuid("active_sandbox_id"),
529
+ // The SECOND epoch ABOVE sandbox_leases.lease_epoch, bumped on every swap; an
530
+ // in-flight op fenced by a stale active_epoch retries against the new active
531
+ // sandbox. integer (NOT bigint) — the lease-epoch spike: int8 reads back as a
532
+ // JS string and breaks the strict fence; int4 returns a number.
533
+ activeEpoch: integer("active_epoch").notNull().default(0),
534
+ // The session's WORKING DIRECTORY — the path/cwd base the (selfhosted) box's
535
+ // agent/terminal/file-dock operate under. A launch-workspace_root-relative
536
+ // subdir or an absolute machine path; surfaced alongside the active-sandbox
537
+ // pointer (readActiveSandbox) and written through the epoch-fenced
538
+ // setActiveSandbox CAS, NOT the row INSERT. NULL (the default) ⇒ today's
539
+ // behavior exactly the agent substitutes its workspace_root for an empty cwd,
540
+ // so an unset working_dir is a byte-identical no-op. Create-time only (Stage A).
541
+ workingDir: text("working_dir"),
542
+ variableSetId: uuid("variable_set_id").references(() => workspaceVariableSets.id, {
543
+ onDelete: "set null",
544
+ }),
545
+ // The rig this session rides + the exact rig version frozen at create time
546
+ // (migration 0047). NULL ⇒ the session rides no rig (today's behavior). FKs
547
+ // (-> rigs(id)/rig_versions(id) ON DELETE SET NULL) live in migration 0047,
548
+ // not Drizzle .references(), because those tables are declared later in this
549
+ // file (forward-reference pattern, same as activeSandboxId). Consumed in M3.
550
+ rigId: uuid("rig_id"),
551
+ rigVersionId: uuid("rig_version_id"),
552
+ // Non-default first-party MCP token permissions (manager-style sessions);
553
+ // null means the fixed worker default set in @opengeni/runtime.
554
+ firstPartyMcpPermissions: jsonb("first_party_mcp_permissions").$type<string[]>(),
555
+ // The manager session that spawned this one via session_create. Set only
556
+ // when the creating grant carried a worker-signed sessionId claim (a session
557
+ // spawning a worker); null for direct API creates and scheduled-task runs.
558
+ // When set, this worker's terminal-for-now transitions wake the parent so a
559
+ // manager can orchestrate workers without busy-polling. Self-referencing FK,
560
+ // ON DELETE SET NULL so deleting a manager never cascades into its workers.
561
+ parentSessionId: uuid("parent_session_id"),
562
+ // Workspace-scoped CREATE idempotency key. NULL means the create carried no
563
+ // key (each such create is independent). When set, the partial unique index
564
+ // below collapses concurrent/retried creates with the same key in the same
565
+ // workspace to a single session row — the dedup that closes the
566
+ // double-submit/double-dispatch stuck-queued bug.
567
+ createIdempotencyKey: text("create_idempotency_key"),
568
+ temporalWorkflowId: text("temporal_workflow_id"),
569
+ activeTurnId: uuid("active_turn_id"),
570
+ // Actual input tokens reported for the last model call of the most recent
571
+ // turn. The pre-turn portable compaction trigger reads this as its budget
572
+ // signal (char/4 estimate is the same-turn fallback). Null until a turn with
573
+ // usage has completed.
574
+ lastInputTokens: integer("last_input_tokens"),
575
+ // Operator /compact request flag. The API sets
576
+ // it true; the worker honors it BEFORE the next turn's model call by forcing
577
+ // a compaction, then clears it. A durable flag (not a transient signal) so
578
+ // the trigger survives a worker restart and converges before the next turn.
579
+ compactRequested: boolean("compact_requested").notNull().default(false),
580
+ queueVersion: integer("queue_version").notNull().default(0),
581
+ queueHeadPosition: bigint("queue_head_position", { mode: "number" }).notNull().default(0),
582
+ queueTailPosition: bigint("queue_tail_position", { mode: "number" }).notNull().default(0),
583
+ controlState: text("control_state").notNull().default("active"),
584
+ controlGeneration: integer("control_generation").notNull().default(0),
585
+ controlReason: text("control_reason"),
586
+ controlChangedBy: text("control_changed_by"),
587
+ controlChangedAt: timestamp("control_changed_at", { withTimezone: true }),
588
+ pendingControlEventId: uuid("pending_control_event_id"),
589
+ pendingControlKind: text("pending_control_kind"),
590
+ pendingControlExpectedTurnId: uuid("pending_control_expected_turn_id"),
591
+ pendingControlExpectedGeneration: integer("pending_control_expected_generation"),
592
+ pendingControlExpectedAttemptId: uuid("pending_control_expected_attempt_id"),
593
+ workspaceRunExceptionGeneration: integer("workspace_run_exception_generation"),
594
+ lastSequence: integer("last_sequence").notNull().default(0),
595
+ // The session's PINNED Codex account (manual override from the in-session
596
+ // switcher). NULL follow the workspace active pointer. FK declared in the
597
+ // migration with ON DELETE SET NULL (a disconnected pin degrades to "follow
598
+ // active", never dangles), same pattern as activeSandboxId.
599
+ codexPinnedCredentialId: uuid("codex_pinned_credential_id"),
600
+ // The Codex account the session's most recent turn ACTUALLY ran on — drives
601
+ // the "Running on:" indicator. Written by the worker at the turn boundary. FK
602
+ // ON DELETE SET NULL (migration).
603
+ codexLastCredentialId: uuid("codex_last_credential_id"),
604
+ // The SOURCE of codex_pinned_credential_id (AM-2): 'manual' — the user's
605
+ // in-session account switcher, which is SACRED and never moved by any policy —
606
+ // or 'policy' the sharded rotation strategy's deterministic per-session home
607
+ // assignment, which MAY be re-sharded to another account when its own account
608
+ // caps. NULL when there is no pin (and for every pre-existing row). CHECK
609
+ // (manual|policy) lives in the migration; no FK (it describes the pin, not an
610
+ // account).
611
+ codexPinSource: text("codex_pin_source"),
612
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
613
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
614
+ },
615
+ (table) => ({
616
+ workspaceIdentity: uniqueIndex("sessions_workspace_id_idx").on(table.workspaceId, table.id),
617
+ workspaceCreated: index("sessions_workspace_created_idx").on(
618
+ table.workspaceId,
619
+ table.createdAt,
620
+ ),
621
+ variableSet: index("sessions_variable_set_idx").on(table.workspaceId, table.variableSetId),
622
+ parent: index("sessions_parent_idx").on(table.workspaceId, table.parentSessionId),
623
+ // Routing index: resolve session_id -> sandbox_group_id at every lease entry
624
+ // point and enumerate all sessions in a group for attribution/disclosure.
625
+ sandboxGroup: index("sessions_sandbox_group_idx").on(table.workspaceId, table.sandboxGroupId),
626
+ // Partial unique index: one session per (workspace, create_idempotency_key)
627
+ // when a key is present. Concurrent creates racing on the same key see a
628
+ // unique violation on all but one; the domain layer catches it and returns
629
+ // the winning row instead of erroring.
630
+ createIdempotency: uniqueIndex("sessions_workspace_create_idempotency_idx")
631
+ .on(table.workspaceId, table.createIdempotencyKey)
632
+ .where(sql`${table.createIdempotencyKey} is not null`),
633
+ }),
634
+ );
635
+
636
+ // Per-authenticated-subject session organization. This is deliberately a
637
+ // relation instead of a session column: one member's pin must never reorder a
638
+ // shared workspace for another member, and a session's own activity timestamps
639
+ // must remain agent/runtime truth. `subjectId` is the trusted AccessGrant
640
+ // subject, which is text because configured/delegated principals are not always
641
+ // UUIDs. The account/workspace pair carries the standard forced-RLS boundary.
642
+ export const sessionPins = pgTable(
643
+ "session_pins",
644
+ {
645
+ id: uuid("id").primaryKey().defaultRandom(),
646
+ accountId: uuid("account_id")
647
+ .notNull()
648
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
649
+ workspaceId: uuid("workspace_id")
650
+ .notNull()
651
+ .references(() => workspaces.id, { onDelete: "cascade" }),
652
+ subjectId: text("subject_id").notNull(),
653
+ sessionId: uuid("session_id")
654
+ .notNull()
655
+ .references(() => sessions.id, { onDelete: "cascade" }),
656
+ // Keep an unpinned tombstone (pinned=false, pinned_at=null) rather than
657
+ // deleting it. That preserves a monotonic version and prevents an ABA race:
658
+ // a stale client that saw pin version 1 cannot silently overwrite a later
659
+ // unpin+re-pin that would otherwise recreate version 1.
660
+ pinned: boolean("pinned").notNull().default(true),
661
+ pinnedAt: timestamp("pinned_at", { withTimezone: true }).defaultNow(),
662
+ version: integer("version").notNull().default(1),
663
+ },
664
+ (table) => ({
665
+ subjectNonempty: check(
666
+ "session_pins_subject_nonempty",
667
+ sql`length(btrim(${table.subjectId})) > 0`,
668
+ ),
669
+ versionPositive: check("session_pins_version_positive", sql`${table.version} >= 1`),
670
+ stateConsistent: check(
671
+ "session_pins_state_consistent",
672
+ sql`((${table.pinned}) and (${table.pinnedAt}) is not null) or ((not ${table.pinned}) and (${table.pinnedAt}) is null)`,
673
+ ),
674
+ workspaceAccount: foreignKey({
675
+ name: "session_pins_workspace_account_fk",
676
+ columns: [table.workspaceId, table.accountId],
677
+ foreignColumns: [workspaces.id, workspaces.accountId],
678
+ }).onDelete("cascade"),
679
+ workspaceSession: foreignKey({
680
+ name: "session_pins_workspace_session_fk",
681
+ columns: [table.workspaceId, table.sessionId],
682
+ foreignColumns: [sessions.workspaceId, sessions.id],
683
+ }).onDelete("cascade"),
684
+ subjectSession: uniqueIndex("session_pins_subject_workspace_session_idx").on(
685
+ table.subjectId,
686
+ table.workspaceId,
687
+ table.sessionId,
688
+ ),
689
+ subjectPinned: index("session_pins_workspace_subject_pinned_idx").on(
690
+ table.workspaceId,
691
+ table.subjectId,
692
+ table.pinned,
693
+ table.pinnedAt.desc(),
694
+ table.sessionId.desc(),
695
+ ),
696
+ }),
697
+ );
698
+
699
+ // A short-lived server-owned continuation snapshot for the pin-aware session
700
+ // list. The ordinary list is ordered by mutable activity, so a cursor cannot
701
+ // safely replay that order from updated_at alone across HTTP requests. The
702
+ // snapshot stores the already-ordered ordinary ids; the list query still joins
703
+ // live session rows for current lifecycle/title data and expires snapshots
704
+ // opportunistically.
705
+ export const sessionListSnapshots = pgTable(
706
+ "session_list_snapshots",
707
+ {
708
+ id: uuid("id").primaryKey().defaultRandom(),
709
+ accountId: uuid("account_id").notNull(),
710
+ workspaceId: uuid("workspace_id").notNull(),
711
+ subjectId: text("subject_id").notNull(),
712
+ parentSessionFilter: text("parent_session_filter").notNull().default("all"),
713
+ search: text("search"),
714
+ ordinarySessionIds: uuid("ordinary_session_ids")
715
+ .array()
716
+ .notNull()
717
+ .default(sql`'{}'::uuid[]`),
718
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
719
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
720
+ },
721
+ (table) => ({
722
+ workspaceAccount: foreignKey({
723
+ name: "session_list_snapshots_workspace_account_fk",
724
+ columns: [table.workspaceId, table.accountId],
725
+ foreignColumns: [workspaces.id, workspaces.accountId],
726
+ }).onDelete("cascade"),
727
+ subjectNonempty: check(
728
+ "session_list_snapshots_subject_nonempty",
729
+ sql`length(btrim(${table.subjectId})) > 0`,
730
+ ),
731
+ parentFilterValid: check(
732
+ "session_list_snapshots_parent_filter_valid",
733
+ sql`${table.parentSessionFilter} = 'all' or ${table.parentSessionFilter} = 'null' or ${table.parentSessionFilter} ~ '^[0-9a-fA-F-]{36}$'`,
734
+ ),
735
+ searchLength: check(
736
+ "session_list_snapshots_search_length",
737
+ sql`${table.search} is null or length(${table.search}) <= 200`,
738
+ ),
739
+ workspaceExpiry: index("session_list_snapshots_workspace_expiry_idx").on(
740
+ table.workspaceId,
741
+ table.subjectId,
742
+ table.expiresAt,
743
+ ),
744
+ expiryReaper: index("session_list_snapshots_expiry_reaper_idx").on(table.expiresAt, table.id),
745
+ }),
746
+ );
747
+
748
+ export const sessionMcpServers = pgTable(
749
+ "session_mcp_servers",
750
+ {
751
+ id: uuid("id").primaryKey().defaultRandom(),
752
+ accountId: uuid("account_id")
753
+ .notNull()
754
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
755
+ workspaceId: uuid("workspace_id")
756
+ .notNull()
757
+ .references(() => workspaces.id, { onDelete: "cascade" }),
758
+ sessionId: uuid("session_id")
759
+ .notNull()
760
+ .references(() => sessions.id, { onDelete: "cascade" }),
761
+ serverId: text("server_id").notNull(),
762
+ name: text("name"),
763
+ url: text("url").notNull(),
764
+ allowedTools: jsonb("allowed_tools").$type<string[]>(),
765
+ timeoutMs: integer("timeout_ms"),
766
+ cacheToolsList: boolean("cache_tools_list").notNull().default(false),
767
+ // Human-approval policy: `true` = every tool requires approval, a string[] of
768
+ // UNPREFIXED tool names = only those require it, null/absent = auto-run.
769
+ requireApproval: jsonb("require_approval").$type<boolean | string[]>(),
770
+ // Map of header name -> AES-GCM ciphertext. Values are decrypted only by the
771
+ // worker's run-preparation path and never returned by API helpers.
772
+ headersEncrypted: jsonb("headers_encrypted")
773
+ .$type<Record<string, string>>()
774
+ .notNull()
775
+ .default({}),
776
+ credentialVersion: integer("credential_version").notNull().default(1),
777
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
778
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
779
+ },
780
+ (table) => ({
781
+ sessionServer: uniqueIndex("session_mcp_servers_session_server_idx").on(
782
+ table.workspaceId,
783
+ table.sessionId,
784
+ table.serverId,
785
+ ),
786
+ session: index("session_mcp_servers_session_idx").on(table.workspaceId, table.sessionId),
787
+ }),
788
+ );
789
+
790
+ export const files = pgTable(
791
+ "files",
792
+ {
793
+ id: uuid("id").primaryKey().defaultRandom(),
794
+ accountId: uuid("account_id")
795
+ .notNull()
796
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
797
+ workspaceId: uuid("workspace_id")
798
+ .notNull()
799
+ .references(() => workspaces.id, { onDelete: "cascade" }),
800
+ status: text("status").notNull().default("pending_upload"),
801
+ filename: text("filename").notNull(),
802
+ safeFilename: text("safe_filename").notNull(),
803
+ contentType: text("content_type").notNull(),
804
+ sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(),
805
+ sha256: text("sha256"),
806
+ bucket: text("bucket").notNull(),
807
+ objectKey: text("object_key").notNull(),
808
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
809
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
810
+ },
811
+ (table) => ({
812
+ workspaceCreated: index("files_workspace_created_idx").on(table.workspaceId, table.createdAt),
813
+ objectKey: uniqueIndex("files_object_key_idx").on(table.objectKey),
814
+ status: index("files_status_idx").on(table.status),
815
+ }),
816
+ );
817
+
818
+ export const fileUploads = pgTable(
819
+ "file_uploads",
820
+ {
821
+ id: uuid("id").primaryKey().defaultRandom(),
822
+ accountId: uuid("account_id")
823
+ .notNull()
824
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
825
+ workspaceId: uuid("workspace_id")
826
+ .notNull()
827
+ .references(() => workspaces.id, { onDelete: "cascade" }),
828
+ fileId: uuid("file_id")
829
+ .notNull()
830
+ .references(() => files.id, { onDelete: "cascade" }),
831
+ status: text("status").notNull().default("pending"),
832
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
833
+ completedAt: timestamp("completed_at", { withTimezone: true }),
834
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
835
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
836
+ },
837
+ (table) => ({
838
+ workspace: index("file_uploads_workspace_idx").on(table.workspaceId),
839
+ fileId: index("file_uploads_file_id_idx").on(table.fileId),
840
+ status: index("file_uploads_status_idx").on(table.status),
841
+ }),
842
+ );
843
+
844
+ export const documentBases = pgTable(
845
+ "document_bases",
846
+ {
847
+ id: uuid("id").primaryKey().defaultRandom(),
848
+ accountId: uuid("account_id")
849
+ .notNull()
850
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
851
+ workspaceId: uuid("workspace_id")
852
+ .notNull()
853
+ .references(() => workspaces.id, { onDelete: "cascade" }),
854
+ name: text("name").notNull(),
855
+ description: text("description"),
856
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
857
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
858
+ },
859
+ (table) => ({
860
+ workspaceCreated: index("document_bases_workspace_created_idx").on(
861
+ table.workspaceId,
862
+ table.createdAt,
863
+ ),
864
+ }),
865
+ );
866
+
867
+ export const documents = pgTable(
868
+ "documents",
869
+ {
870
+ id: uuid("id").primaryKey().defaultRandom(),
871
+ accountId: uuid("account_id")
872
+ .notNull()
873
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
874
+ workspaceId: uuid("workspace_id")
875
+ .notNull()
876
+ .references(() => workspaces.id, { onDelete: "cascade" }),
877
+ baseId: uuid("base_id")
878
+ .notNull()
879
+ .references(() => documentBases.id, { onDelete: "cascade" }),
880
+ fileId: uuid("file_id")
881
+ .notNull()
882
+ .references(() => files.id, { onDelete: "restrict" }),
883
+ status: text("status").notNull().default("queued"),
884
+ title: text("title").notNull(),
885
+ parser: text("parser").notNull().default("liteparse"),
886
+ chunkCount: integer("chunk_count").notNull().default(0),
887
+ error: text("error"),
888
+ sourceKind: text("source_kind").notNull().default("manual_upload"),
889
+ sourceUri: text("source_uri"),
890
+ sourceExternalId: text("source_external_id"),
891
+ sourceTitle: text("source_title"),
892
+ sourceAuthor: text("source_author"),
893
+ sourceCreatedAt: timestamp("source_created_at", { withTimezone: true }),
894
+ sourceUpdatedAt: timestamp("source_updated_at", { withTimezone: true }),
895
+ sourceVersion: text("source_version"),
896
+ aclTags: jsonb("acl_tags").$type<string[]>().notNull().default([]),
897
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
898
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
899
+ },
900
+ (table) => ({
901
+ baseFile: uniqueIndex("documents_workspace_base_file_idx").on(
902
+ table.workspaceId,
903
+ table.baseId,
904
+ table.fileId,
905
+ ),
906
+ baseStatus: index("documents_workspace_base_status_idx").on(
907
+ table.workspaceId,
908
+ table.baseId,
909
+ table.status,
910
+ ),
911
+ sourceKind: index("documents_workspace_source_kind_idx").on(
912
+ table.workspaceId,
913
+ table.sourceKind,
914
+ ),
915
+ sourceExternalId: index("documents_workspace_source_external_id_idx").on(
916
+ table.workspaceId,
917
+ table.sourceExternalId,
918
+ ),
919
+ }),
920
+ );
921
+
922
+ export const documentChunks = pgTable(
923
+ "document_chunks",
924
+ {
925
+ id: uuid("id").primaryKey().defaultRandom(),
926
+ accountId: uuid("account_id")
927
+ .notNull()
928
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
929
+ workspaceId: uuid("workspace_id")
930
+ .notNull()
931
+ .references(() => workspaces.id, { onDelete: "cascade" }),
932
+ documentId: uuid("document_id")
933
+ .notNull()
934
+ .references(() => documents.id, { onDelete: "cascade" }),
935
+ baseId: uuid("base_id")
936
+ .notNull()
937
+ .references(() => documentBases.id, { onDelete: "cascade" }),
938
+ fileId: uuid("file_id")
939
+ .notNull()
940
+ .references(() => files.id, { onDelete: "restrict" }),
941
+ chunkIndex: integer("chunk_index").notNull(),
942
+ text: text("text").notNull(),
943
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
944
+ embedding: vector("embedding").notNull(),
945
+ embeddingModel: text("embedding_model").notNull(),
946
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
947
+ },
948
+ (table) => ({
949
+ documentIndex: uniqueIndex("document_chunks_workspace_document_index_idx").on(
950
+ table.workspaceId,
951
+ table.documentId,
952
+ table.chunkIndex,
953
+ ),
954
+ base: index("document_chunks_workspace_base_idx").on(table.workspaceId, table.baseId),
955
+ }),
956
+ );
957
+
958
+ export const knowledgeMemories = pgTable(
959
+ "knowledge_memories",
960
+ {
961
+ id: uuid("id").primaryKey().defaultRandom(),
962
+ accountId: uuid("account_id")
963
+ .notNull()
964
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
965
+ workspaceId: uuid("workspace_id")
966
+ .notNull()
967
+ .references(() => workspaces.id, { onDelete: "cascade" }),
968
+ status: text("status").notNull().default("proposed"),
969
+ kind: text("kind").notNull().default("semantic"),
970
+ scope: text("scope").notNull().default("workspace"),
971
+ text: text("text").notNull(),
972
+ sourceRefs: jsonb("source_refs").$type<unknown[]>().notNull().default([]),
973
+ confidence: integer("confidence").notNull().default(50),
974
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
975
+ createdBySessionId: uuid("created_by_session_id").references(() => sessions.id, {
976
+ onDelete: "set null",
977
+ }),
978
+ reviewedBy: text("reviewed_by"),
979
+ reviewedAt: timestamp("reviewed_at", { withTimezone: true }),
980
+ // Workspace Memory V1 (migration 0045). Embedding is nullable: fail-soft writes
981
+ // (embedder unavailable) persist keyword-searchable rows without a vector.
982
+ embedding: vector("embedding"),
983
+ embeddingModel: text("embedding_model"),
984
+ pinned: boolean("pinned").notNull().default(false),
985
+ usageCount: integer("usage_count").notNull().default(0),
986
+ lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
987
+ // Self-referential supersession chain. FKs live in migration 0045 (ON DELETE SET
988
+ // NULL); declared here as plain columns like the migration-only composite FK.
989
+ supersedesId: uuid("supersedes_id"),
990
+ supersededById: uuid("superseded_by_id"),
991
+ validFrom: timestamp("valid_from", { withTimezone: true }).notNull().defaultNow(),
992
+ validUntil: timestamp("valid_until", { withTimezone: true }),
993
+ // sha256(normalizeMemoryText(text)) — exact-dedup key; see memory-domain.
994
+ textHash: text("text_hash"),
995
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
996
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
997
+ },
998
+ (table) => ({
999
+ workspaceStatus: index("knowledge_memories_workspace_status_idx").on(
1000
+ table.workspaceId,
1001
+ table.status,
1002
+ table.updatedAt,
1003
+ ),
1004
+ workspaceKind: index("knowledge_memories_workspace_kind_idx").on(table.workspaceId, table.kind),
1005
+ workspaceScope: index("knowledge_memories_workspace_scope_idx").on(
1006
+ table.workspaceId,
1007
+ table.scope,
1008
+ ),
1009
+ createdBySession: index("knowledge_memories_workspace_created_by_session_idx").on(
1010
+ table.workspaceId,
1011
+ table.createdBySessionId,
1012
+ ),
1013
+ // Working-set selection (partial index mirrors migration 0045).
1014
+ workspaceVisible: index("knowledge_memories_workspace_visible_idx")
1015
+ .on(table.workspaceId, table.pinned, table.updatedAt)
1016
+ .where(sql`${table.status} in ('active', 'approved')`),
1017
+ workspaceTextHash: index("knowledge_memories_workspace_text_hash_idx").on(
1018
+ table.workspaceId,
1019
+ table.textHash,
1020
+ ),
1021
+ workspaceVisibleTextHashUnique: uniqueIndex("knowledge_memories_workspace_visible_text_hash_uq")
1022
+ .on(table.workspaceId, table.textHash)
1023
+ .where(sql`${table.status} in ('active', 'approved') and ${table.textHash} is not null`),
1024
+ }),
1025
+ );
1026
+
1027
+ export const sessionTurns = pgTable(
1028
+ "session_turns",
1029
+ {
1030
+ id: uuid("id").primaryKey().defaultRandom(),
1031
+ accountId: uuid("account_id")
1032
+ .notNull()
1033
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1034
+ workspaceId: uuid("workspace_id")
1035
+ .notNull()
1036
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1037
+ sessionId: uuid("session_id")
1038
+ .notNull()
1039
+ .references(() => sessions.id, { onDelete: "cascade" }),
1040
+ triggerEventId: uuid("trigger_event_id").notNull(),
1041
+ temporalWorkflowId: text("temporal_workflow_id").notNull(),
1042
+ status: text("status").notNull(),
1043
+ source: text("source").notNull().default("user"),
1044
+ position: bigint("position", { mode: "number" }).notNull(),
1045
+ prompt: text("prompt").notNull(),
1046
+ resources: jsonb("resources").$type<unknown[]>().notNull().default([]),
1047
+ tools: jsonb("tools").$type<unknown[]>().notNull().default([]),
1048
+ model: text("model").notNull(),
1049
+ reasoningEffort: text("reasoning_effort").notNull(),
1050
+ sandboxBackend: text("sandbox_backend").notNull(),
1051
+ // Per-turn OS override. NULL = inherit the session's sandbox_os. CHECK-
1052
+ // constrained to the SandboxOs enum (or NULL) in migration 0018.
1053
+ sandboxOs: text("sandbox_os"),
1054
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
1055
+ version: integer("version").notNull().default(1),
1056
+ executionGeneration: integer("execution_generation").notNull().default(0),
1057
+ activeAttemptId: uuid("active_attempt_id"),
1058
+ lineage: jsonb("lineage").$type<Record<string, unknown>>().notNull().default({}),
1059
+ cancelledBy: text("cancelled_by"),
1060
+ cancelReason: text("cancel_reason"),
1061
+ // Atomic per-turn toolspace call budget counter (migration 0043). Incremented
1062
+ // by a single conditional UPDATE at tools/call time; the row lock serializes
1063
+ // concurrent reservations so exactly `toolspaceMaxCallsPerTurn` succeed.
1064
+ toolspaceCallCount: integer("toolspace_call_count").notNull().default(0),
1065
+ startedAt: timestamp("started_at", { withTimezone: true }),
1066
+ finishedAt: timestamp("finished_at", { withTimezone: true }),
1067
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1068
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1069
+ },
1070
+ (table) => ({
1071
+ workspaceIdentity: uniqueIndex("session_turns_workspace_id_idx").on(
1072
+ table.workspaceId,
1073
+ table.id,
1074
+ ),
1075
+ queue: index("session_turns_workspace_queue_idx").on(
1076
+ table.workspaceId,
1077
+ table.sessionId,
1078
+ table.status,
1079
+ table.position,
1080
+ ),
1081
+ oneCurrentInference: uniqueIndex("session_turns_one_current_inference_uq")
1082
+ .on(table.workspaceId, table.sessionId)
1083
+ .where(sql`${table.status} in ('running','requires_action','recovering','waiting_capacity')`),
1084
+ }),
1085
+ );
1086
+
1087
+ export const sessionSystemUpdates = pgTable(
1088
+ "session_system_updates",
1089
+ {
1090
+ id: uuid("id").primaryKey().defaultRandom(),
1091
+ accountId: uuid("account_id")
1092
+ .notNull()
1093
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1094
+ workspaceId: uuid("workspace_id")
1095
+ .notNull()
1096
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1097
+ sessionId: uuid("session_id")
1098
+ .notNull()
1099
+ .references(() => sessions.id, { onDelete: "cascade" }),
1100
+ kind: text("kind").notNull(),
1101
+ classification: text("classification").notNull().default("info"),
1102
+ sourceId: text("source_id").notNull(),
1103
+ dedupeKey: text("dedupe_key").notNull(),
1104
+ summary: text("summary").notNull(),
1105
+ payload: jsonb("payload").$type<Record<string, unknown>>().notNull().default({}),
1106
+ lineage: jsonb("lineage").$type<Record<string, unknown>>().notNull().default({}),
1107
+ // pending: eligible to start/attach to an inference; deferred: preserved
1108
+ // after a failed internal-only inference but dormant until a real prompt or
1109
+ // a genuinely new pending update arrives; delivered/cancelled/failed are
1110
+ // terminal for that delivery attempt.
1111
+ state: text("state").notNull().default("pending"),
1112
+ deliveredTurnId: uuid("delivered_turn_id").references(() => sessionTurns.id, {
1113
+ onDelete: "set null",
1114
+ }),
1115
+ deliveredAt: timestamp("delivered_at", { withTimezone: true }),
1116
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1117
+ },
1118
+ (table) => ({
1119
+ dedupe: uniqueIndex("session_system_updates_dedupe_uq").on(
1120
+ table.workspaceId,
1121
+ table.sessionId,
1122
+ table.dedupeKey,
1123
+ ),
1124
+ pending: index("session_system_updates_pending_idx").on(
1125
+ table.workspaceId,
1126
+ table.sessionId,
1127
+ table.state,
1128
+ table.createdAt,
1129
+ ),
1130
+ }),
1131
+ );
1132
+
1133
+ /**
1134
+ * Stable idempotency record for session and workspace pause operations.
1135
+ * `result` contains only durable IDs/state
1136
+ * snapshots; delivery repair always revalidates those exact IDs against the
1137
+ * current pending fence instead of consulting an unrelated newer operation.
1138
+ */
1139
+ export const runtimeControlOperations = pgTable(
1140
+ "runtime_control_operations",
1141
+ {
1142
+ id: uuid("id").primaryKey().defaultRandom(),
1143
+ accountId: uuid("account_id")
1144
+ .notNull()
1145
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1146
+ workspaceId: uuid("workspace_id")
1147
+ .notNull()
1148
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1149
+ scope: text("scope").notNull(),
1150
+ targetId: uuid("target_id").notNull(),
1151
+ clientEventId: text("client_event_id").notNull(),
1152
+ requestedState: text("requested_state").notNull(),
1153
+ expectedState: text("expected_state"),
1154
+ expectedGeneration: integer("expected_generation"),
1155
+ result: jsonb("result").$type<Record<string, unknown>>().notNull().default({}),
1156
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1157
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1158
+ },
1159
+ (table) => ({
1160
+ idempotency: uniqueIndex("runtime_control_operations_client_uq").on(
1161
+ table.workspaceId,
1162
+ table.clientEventId,
1163
+ ),
1164
+ target: index("runtime_control_operations_target_idx").on(
1165
+ table.workspaceId,
1166
+ table.scope,
1167
+ table.targetId,
1168
+ table.createdAt,
1169
+ ),
1170
+ }),
1171
+ );
1172
+
1173
+ /**
1174
+ * Durable child-terminal producer outbox. The source terminal transaction
1175
+ * inserts this row; fan-in delivery marks it delivered inside
1176
+ * addSessionSystemUpdateWithSourceMutation. A bounded reconciler may retry a
1177
+ * committed row after any worker/process death without duplicating a member.
1178
+ */
1179
+ export const sessionSystemUpdateOutbox = pgTable(
1180
+ "session_system_update_outbox",
1181
+ {
1182
+ id: uuid("id").primaryKey().defaultRandom(),
1183
+ accountId: uuid("account_id")
1184
+ .notNull()
1185
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1186
+ workspaceId: uuid("workspace_id")
1187
+ .notNull()
1188
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1189
+ sourceSessionId: uuid("source_session_id")
1190
+ .notNull()
1191
+ .references(() => sessions.id, { onDelete: "cascade" }),
1192
+ targetSessionId: uuid("target_session_id")
1193
+ .notNull()
1194
+ .references(() => sessions.id, { onDelete: "cascade" }),
1195
+ dedupeKey: text("dedupe_key").notNull(),
1196
+ kind: text("kind").notNull(),
1197
+ classification: text("classification").notNull(),
1198
+ sourceId: text("source_id").notNull(),
1199
+ summary: text("summary").notNull(),
1200
+ payload: jsonb("payload").$type<Record<string, unknown>>().notNull().default({}),
1201
+ lineage: jsonb("lineage").$type<Record<string, unknown>>().notNull().default({}),
1202
+ status: text("status").notNull().default("pending"),
1203
+ attempts: integer("attempts").notNull().default(0),
1204
+ updateId: uuid("update_id"),
1205
+ lastError: text("last_error"),
1206
+ deliveredAt: timestamp("delivered_at", { withTimezone: true }),
1207
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1208
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1209
+ },
1210
+ (table) => ({
1211
+ dedupe: uniqueIndex("session_system_update_outbox_dedupe_uq").on(
1212
+ table.workspaceId,
1213
+ table.dedupeKey,
1214
+ ),
1215
+ pending: index("session_system_update_outbox_pending_idx").on(table.status, table.createdAt),
1216
+ }),
1217
+ );
1218
+
1219
+ /**
1220
+ * Transactional delivery ledger for session-workflow wakeups. Postgres owns
1221
+ * work eligibility; Temporal signals are only nudges. One coalescing row per
1222
+ * session makes a committed mutation repairable without periodically scanning
1223
+ * every session that happens to look runnable.
1224
+ */
1225
+ export const sessionWorkflowWakeOutbox = pgTable(
1226
+ "session_workflow_wake_outbox",
1227
+ {
1228
+ sessionId: uuid("session_id").primaryKey(),
1229
+ accountId: uuid("account_id").notNull(),
1230
+ workspaceId: uuid("workspace_id").notNull(),
1231
+ temporalWorkflowId: text("temporal_workflow_id").notNull(),
1232
+ wakeRevision: bigint("wake_revision", { mode: "number" }).notNull().default(1),
1233
+ deliveredRevision: bigint("delivered_revision", { mode: "number" }).notNull().default(0),
1234
+ reason: text("reason").notNull(),
1235
+ attempts: integer("attempts").notNull().default(0),
1236
+ nextAttemptAt: timestamp("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
1237
+ lastError: text("last_error"),
1238
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1239
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1240
+ },
1241
+ (table) => ({
1242
+ revisionValid: check(
1243
+ "session_workflow_wake_outbox_revision_check",
1244
+ sql`${table.wakeRevision} > 0 and ${table.deliveredRevision} >= 0 and ${table.deliveredRevision} <= ${table.wakeRevision}`,
1245
+ ),
1246
+ workspaceAccount: foreignKey({
1247
+ name: "session_workflow_wake_outbox_workspace_account_fk",
1248
+ columns: [table.workspaceId, table.accountId],
1249
+ foreignColumns: [workspaces.id, workspaces.accountId],
1250
+ }).onDelete("cascade"),
1251
+ workspaceSessionFk: foreignKey({
1252
+ name: "session_workflow_wake_outbox_workspace_session_fk",
1253
+ columns: [table.workspaceId, table.sessionId],
1254
+ foreignColumns: [sessions.workspaceId, sessions.id],
1255
+ }).onDelete("cascade"),
1256
+ workspaceSession: uniqueIndex("session_workflow_wake_outbox_workspace_session_uq").on(
1257
+ table.workspaceId,
1258
+ table.sessionId,
1259
+ ),
1260
+ pending: index("session_workflow_wake_outbox_pending_idx")
1261
+ .on(table.nextAttemptAt, table.updatedAt, table.sessionId)
1262
+ .where(sql`${table.wakeRevision} > ${table.deliveredRevision}`),
1263
+ }),
1264
+ );
1265
+
1266
+ export const sessionGoals = pgTable(
1267
+ "session_goals",
1268
+ {
1269
+ id: uuid("id").primaryKey().defaultRandom(),
1270
+ accountId: uuid("account_id")
1271
+ .notNull()
1272
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1273
+ workspaceId: uuid("workspace_id")
1274
+ .notNull()
1275
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1276
+ sessionId: uuid("session_id")
1277
+ .notNull()
1278
+ .references(() => sessions.id, { onDelete: "cascade" }),
1279
+ status: text("status").notNull().default("active"), // active | paused | completed
1280
+ text: text("text").notNull(),
1281
+ successCriteria: text("success_criteria"),
1282
+ evidence: text("evidence"), // set by goal_complete
1283
+ rationale: text("rationale"), // set by goal_pause
1284
+ pausedReason: text("paused_reason"), // agent | user_pause | api | no_progress | max_auto_continuations | limits
1285
+ createdBy: text("created_by").notNull().default("api"), // api | agent | scheduled_task
1286
+ version: integer("version").notNull().default(1), // bumped on every set/update; progress signal
1287
+ autoContinuations: integer("auto_continuations").notNull().default(0),
1288
+ noProgressStreak: integer("no_progress_streak").notNull().default(0),
1289
+ maxAutoContinuations: integer("max_auto_continuations"), // per-goal override; a configured settings cap (if any) remains the hard ceiling
1290
+ lastContinuationTurnId: uuid("last_continuation_turn_id"),
1291
+ versionAtLastContinuation: integer("version_at_last_continuation"),
1292
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
1293
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1294
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1295
+ },
1296
+ (table) => ({
1297
+ workspaceIdentity: uniqueIndex("session_goals_workspace_id_idx").on(
1298
+ table.workspaceId,
1299
+ table.id,
1300
+ ),
1301
+ workspaceSession: uniqueIndex("session_goals_workspace_session_idx").on(
1302
+ table.workspaceId,
1303
+ table.sessionId,
1304
+ ),
1305
+ status: index("session_goals_workspace_status_idx").on(table.workspaceId, table.status),
1306
+ }),
1307
+ );
1308
+
1309
+ // OPE-21: one durable, coalescing capacity waiter per session. The row is both
1310
+ // the wait state and the commit->signal outbox: capacity mutations increment
1311
+ // wakeRevision in the SAME transaction as the mutation, while the session
1312
+ // workflow advances observedWakeRevision only after it has re-evaluated the
1313
+ // allocator. Temporal signals are therefore repairable nudges rather than the
1314
+ // source of truth. No credential material or provider response is stored here.
1315
+ //
1316
+ // The session/goal/turn foreign keys are declared in migration 0053 so the
1317
+ // table keeps the same composite workspace-integrity posture as credential
1318
+ // leases. OPE-18 may later supply a non-zero controlGeneration; legacy rows use
1319
+ // zero and remain fenced by goal version + session/queue/turn truth. OPE-32
1320
+ // supplies policyHash when accepted-turn pool routing lands.
1321
+ export const codexCapacityWaiters = pgTable(
1322
+ "codex_capacity_waiters",
1323
+ {
1324
+ id: uuid("id").primaryKey().defaultRandom(),
1325
+ accountId: uuid("account_id")
1326
+ .notNull()
1327
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1328
+ workspaceId: uuid("workspace_id")
1329
+ .notNull()
1330
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1331
+ sessionId: uuid("session_id").notNull(),
1332
+ goalId: uuid("goal_id").notNull(),
1333
+ blockedTurnId: uuid("blocked_turn_id").notNull(),
1334
+ workflowId: text("workflow_id").notNull(),
1335
+ generation: integer("generation").notNull().default(1),
1336
+ status: text("status").notNull().default("waiting"), // waiting | resumed | superseded
1337
+ goalVersion: integer("goal_version").notNull(),
1338
+ controlGeneration: integer("control_generation").notNull().default(0),
1339
+ policyHash: text("policy_hash"),
1340
+ earliestResetAt: timestamp("earliest_reset_at", { withTimezone: true }),
1341
+ nextCheckAt: timestamp("next_check_at", { withTimezone: true }).notNull(),
1342
+ resetKind: text("reset_kind").notNull(), // authoritative | bounded_refresh
1343
+ refreshAttempt: integer("refresh_attempt").notNull().default(0),
1344
+ // Coalescing outbox generation. Every eligibility-affecting mutation bumps
1345
+ // wakeRevision. Duplicate/lost Temporal signals are harmless because only
1346
+ // the row-locked evaluator moves observedWakeRevision and may enqueue work.
1347
+ wakeRevision: integer("wake_revision").notNull().default(1),
1348
+ observedWakeRevision: integer("observed_wake_revision").notNull().default(0),
1349
+ lastWakeReason: text("last_wake_reason").notNull().default("capacity_wait_armed"),
1350
+ resumedUpdateId: uuid("resumed_update_id"),
1351
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1352
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1353
+ },
1354
+ (table) => ({
1355
+ workspaceSession: uniqueIndex("codex_capacity_waiters_workspace_session_idx").on(
1356
+ table.workspaceId,
1357
+ table.sessionId,
1358
+ ),
1359
+ workspaceId: uniqueIndex("codex_capacity_waiters_workspace_id_idx").on(
1360
+ table.workspaceId,
1361
+ table.id,
1362
+ ),
1363
+ pending: index("codex_capacity_waiters_pending_idx").on(
1364
+ table.workspaceId,
1365
+ table.status,
1366
+ table.nextCheckAt,
1367
+ ),
1368
+ wakeRepair: index("codex_capacity_waiters_wake_repair_idx").on(
1369
+ table.status,
1370
+ table.wakeRevision,
1371
+ table.observedWakeRevision,
1372
+ ),
1373
+ }),
1374
+ );
1375
+
1376
+ export const sessionEvents = pgTable(
1377
+ "session_events",
1378
+ {
1379
+ id: uuid("id").primaryKey().defaultRandom(),
1380
+ accountId: uuid("account_id")
1381
+ .notNull()
1382
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1383
+ workspaceId: uuid("workspace_id")
1384
+ .notNull()
1385
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1386
+ sessionId: uuid("session_id")
1387
+ .notNull()
1388
+ .references(() => sessions.id, { onDelete: "cascade" }),
1389
+ turnId: uuid("turn_id"),
1390
+ turnGeneration: integer("turn_generation"),
1391
+ turnAttemptId: uuid("turn_attempt_id"),
1392
+ turnAssociation: text("turn_association"),
1393
+ duplicateOfEventId: uuid("duplicate_of_event_id"),
1394
+ duplicateReason: text("duplicate_reason"),
1395
+ sequence: integer("sequence").notNull(),
1396
+ type: text("type").notNull(),
1397
+ payload: jsonb("payload").$type<unknown>().notNull().default({}),
1398
+ clientEventId: text("client_event_id"),
1399
+ producerId: text("producer_id"),
1400
+ producerSeq: integer("producer_seq"),
1401
+ occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
1402
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1403
+ },
1404
+ (table) => ({
1405
+ sessionSequence: uniqueIndex("session_events_workspace_session_sequence_idx").on(
1406
+ table.workspaceId,
1407
+ table.sessionId,
1408
+ table.sequence,
1409
+ ),
1410
+ clientEvent: uniqueIndex("session_events_workspace_client_event_idx")
1411
+ .on(table.workspaceId, table.sessionId, table.clientEventId)
1412
+ .where(sql`${table.clientEventId} is not null`),
1413
+ producer: uniqueIndex("session_events_workspace_producer_idx")
1414
+ .on(table.workspaceId, table.sessionId, table.producerId, table.producerSeq)
1415
+ .where(sql`${table.producerId} is not null and ${table.producerSeq} is not null`),
1416
+ sessionCreated: index("session_events_workspace_session_created_idx").on(
1417
+ table.workspaceId,
1418
+ table.sessionId,
1419
+ table.createdAt,
1420
+ ),
1421
+ }),
1422
+ );
577
1423
 
578
1424
  export const agentRunStates = pgTable("agent_run_states", {
579
1425
  id: uuid("id").primaryKey().defaultRandom(),
580
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
581
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
582
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1426
+ accountId: uuid("account_id")
1427
+ .notNull()
1428
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1429
+ workspaceId: uuid("workspace_id")
1430
+ .notNull()
1431
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1432
+ sessionId: uuid("session_id")
1433
+ .notNull()
1434
+ .references(() => sessions.id, { onDelete: "cascade" }),
583
1435
  turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
584
1436
  stateVersion: integer("state_version").notNull(),
585
1437
  serializedRunState: text("serialized_run_state").notNull(),
@@ -591,8 +1443,8 @@ export const agentRunStates = pgTable("agent_run_states", {
591
1443
  // ChatGPT/Codex backend — account/org-bound, so a foreign blob 400s — and the
592
1444
  // foreign reasoning ids the Responses backend validates; but the blob carries
593
1445
  // NO per-item producer tag (those live only on session_history_items). So we
594
- // stamp the freezing account here: on a resume (approval decision, or the
595
- // items-mode run-state fallback) whose codex account DIFFERS from this value,
1446
+ // stamp the freezing account here: on an approval resume whose codex account
1447
+ // DIFFERS from this value,
596
1448
  // the replay path neutralizes every reasoning item's account-bound identity
597
1449
  // (encrypted_content + provider id) in the blob before it reaches the model.
598
1450
  // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect (a
@@ -606,56 +1458,130 @@ export const agentRunStates = pgTable("agent_run_states", {
606
1458
  // Conversation truth: ordered, verbatim SDK input items (issue #35). The
607
1459
  // model-facing memory store — unredacted and replay-ready. session_events
608
1460
  // remains the redacted human/audit timeline.
609
- export const sessionHistoryItems = pgTable("session_history_items", {
610
- id: uuid("id").primaryKey().defaultRandom(),
611
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
612
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
613
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
614
- turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
615
- // Numeric (not integer) so the synthetic compaction-summary row can be
616
- // inserted at a FRACTIONAL position (boundaryPosition - 0.5) that sorts ahead
617
- // of the kept tail without colliding with — and thus overwriting — the real
618
- // prefix row at boundaryPosition - 1. Normally-appended rows keep whole-number
619
- // positions; only the summary uses the half-step. `mode: "number"` maps the
620
- // postgres.js string back to a JS number so every reader stays numeric.
621
- position: numeric("position", { mode: "number" }).notNull(),
622
- item: jsonb("item").$type<Record<string, unknown>>().notNull(),
623
- // Live-row flag for client-side context compaction. The read path selects
624
- // only active rows; a compaction supersedes the summarized prefix (sets this
625
- // false never deletes, so the full transcript stays as an audit trail) and
626
- // inserts ONE synthetic active summary row at the boundary. Defaults true so
627
- // every existing and normally-appended row is live.
628
- active: boolean("active").notNull().default(true),
629
- // The Codex account that PRODUCED these items: the per-turn resolved codex
630
- // credential id (pin > workspace-active), or NULL when produced on the
631
- // non-codex / Azure path (or before this column existed). Used to strip
632
- // cross-account `reasoning.encrypted_content` blobs those are account/org-
633
- // bound, minted by the ChatGPT/Codex backend, so replaying account A's blob
634
- // into a turn running on account B 400s. The read path drops the encrypted
635
- // reasoning of any item whose producer != the turn's current codex account.
636
- // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect
637
- // (an ON DELETE SET NULL would erase the tag, and a stale-but-null tag still
638
- // mismatches a live codex id so the strip stays correct either way).
639
- producerCodexCredentialId: uuid("producer_codex_credential_id"),
640
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
641
- }, (table) => ({
642
- positionIdx: uniqueIndex("session_history_items_position_idx").on(table.workspaceId, table.sessionId, table.position),
643
- }));
1461
+ export const sessionHistoryItems = pgTable(
1462
+ "session_history_items",
1463
+ {
1464
+ id: uuid("id").primaryKey().defaultRandom(),
1465
+ accountId: uuid("account_id")
1466
+ .notNull()
1467
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1468
+ workspaceId: uuid("workspace_id")
1469
+ .notNull()
1470
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1471
+ sessionId: uuid("session_id")
1472
+ .notNull()
1473
+ .references(() => sessions.id, { onDelete: "cascade" }),
1474
+ turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
1475
+ // Numeric (not integer) so the synthetic compaction-summary row can be
1476
+ // inserted at a FRACTIONAL position (boundaryPosition - 0.5) that sorts ahead
1477
+ // of the kept tail without colliding with and thus overwriting the real
1478
+ // prefix row at boundaryPosition - 1. Normally-appended rows keep whole-number
1479
+ // positions; only the summary uses the half-step. `mode: "number"` maps the
1480
+ // postgres.js string back to a JS number so every reader stays numeric.
1481
+ position: numeric("position", { mode: "number" }).notNull(),
1482
+ item: jsonb("item").$type<Record<string, unknown>>().notNull(),
1483
+ // Live-row flag for client-side context compaction. The read path selects
1484
+ // only active rows; a compaction supersedes the summarized prefix (sets this
1485
+ // false — never deletes, so the full transcript stays as an audit trail) and
1486
+ // inserts ONE synthetic active summary row at the boundary. Defaults true so
1487
+ // every existing and normally-appended row is live.
1488
+ active: boolean("active").notNull().default(true),
1489
+ // The Codex account that PRODUCED these items: the per-turn resolved codex
1490
+ // credential id (pin > workspace-active), or NULL when produced on the
1491
+ // non-codex / Azure path (or before this column existed). Used to strip
1492
+ // cross-account `reasoning.encrypted_content` blobs those are account/org-
1493
+ // bound, minted by the ChatGPT/Codex backend, so replaying account A's blob
1494
+ // into a turn running on account B 400s. The read path drops the encrypted
1495
+ // reasoning of any item whose producer != the turn's current codex account.
1496
+ // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect
1497
+ // (an ON DELETE SET NULL would erase the tag, and a stale-but-null tag still
1498
+ // mismatches a live codex id so the strip stays correct either way).
1499
+ producerCodexCredentialId: uuid("producer_codex_credential_id"),
1500
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1501
+ },
1502
+ (table) => ({
1503
+ positionIdx: uniqueIndex("session_history_items_position_idx").on(
1504
+ table.workspaceId,
1505
+ table.sessionId,
1506
+ table.position,
1507
+ ),
1508
+ }),
1509
+ );
1510
+
1511
+ // Turn-lineage ledger for a tool call that the SDK emitted but has not yet
1512
+ // produced a durably reconciled result. The raw call item is model-facing truth
1513
+ // (not the redacted session-event projection). The attempt/generation identify
1514
+ // where the call originated, but the receipt survives an approval resume into a
1515
+ // newer attempt of the same logical turn. Turn-ending transactions
1516
+ // consume these rows atomically and append a valid interrupted result so a
1517
+ // recovered model sees an explicit unknown outcome instead of a silently
1518
+ // dropped call.
1519
+ export const sessionPendingToolCalls = pgTable(
1520
+ "session_pending_tool_calls",
1521
+ {
1522
+ id: uuid("id").primaryKey().defaultRandom(),
1523
+ accountId: uuid("account_id")
1524
+ .notNull()
1525
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1526
+ workspaceId: uuid("workspace_id")
1527
+ .notNull()
1528
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1529
+ sessionId: uuid("session_id")
1530
+ .notNull()
1531
+ .references(() => sessions.id, { onDelete: "cascade" }),
1532
+ turnId: uuid("turn_id")
1533
+ .notNull()
1534
+ .references(() => sessionTurns.id, { onDelete: "cascade" }),
1535
+ executionGeneration: integer("execution_generation").notNull(),
1536
+ attemptId: uuid("attempt_id").notNull(),
1537
+ callId: text("call_id").notNull(),
1538
+ callType: text("call_type").notNull(),
1539
+ callItem: jsonb("call_item").$type<Record<string, unknown>>().notNull(),
1540
+ resultItem: jsonb("result_item").$type<Record<string, unknown>>(),
1541
+ resultRecordedAt: timestamp("result_recorded_at", { withTimezone: true }),
1542
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1543
+ },
1544
+ (table) => ({
1545
+ turnCall: uniqueIndex("session_pending_tool_calls_turn_call_idx").on(
1546
+ table.workspaceId,
1547
+ table.turnId,
1548
+ table.callId,
1549
+ ),
1550
+ sessionTurn: index("session_pending_tool_calls_session_turn_idx").on(
1551
+ table.workspaceId,
1552
+ table.sessionId,
1553
+ table.turnId,
1554
+ ),
1555
+ }),
1556
+ );
644
1557
 
645
1558
  // Sandbox recovery descriptor, decoupled from the RunState blob: the small
646
1559
  // versioned envelope (provider handle / snapshot ref / manifest) needed to
647
1560
  // reattach, restore, or rebuild the session's sandbox on its next turn.
648
- export const sandboxSessionEnvelopes = pgTable("sandbox_session_envelopes", {
649
- id: uuid("id").primaryKey().defaultRandom(),
650
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
651
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
652
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
653
- envelope: jsonb("envelope").$type<Record<string, unknown>>().notNull(),
654
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
655
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
656
- }, (table) => ({
657
- sessionIdx: uniqueIndex("sandbox_session_envelopes_session_idx").on(table.workspaceId, table.sessionId),
658
- }));
1561
+ export const sandboxSessionEnvelopes = pgTable(
1562
+ "sandbox_session_envelopes",
1563
+ {
1564
+ id: uuid("id").primaryKey().defaultRandom(),
1565
+ accountId: uuid("account_id")
1566
+ .notNull()
1567
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1568
+ workspaceId: uuid("workspace_id")
1569
+ .notNull()
1570
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1571
+ sessionId: uuid("session_id")
1572
+ .notNull()
1573
+ .references(() => sessions.id, { onDelete: "cascade" }),
1574
+ envelope: jsonb("envelope").$type<Record<string, unknown>>().notNull(),
1575
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1576
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1577
+ },
1578
+ (table) => ({
1579
+ sessionIdx: uniqueIndex("sandbox_session_envelopes_session_idx").on(
1580
+ table.workspaceId,
1581
+ table.sessionId,
1582
+ ),
1583
+ }),
1584
+ );
659
1585
 
660
1586
  // The 4 liveness states of the singleton lease. Exported so the query layer and
661
1587
  // the stateless resume-by-id path share one source of truth for the domain.
@@ -669,83 +1595,119 @@ export const sandboxLeaseLivenessValues = ["cold", "warming", "warm", "draining"
669
1595
  // of sandboxSessionEnvelopes; sandboxGroupId is a BARE uuid (NOT an FK — the
670
1596
  // value is a session id or an ancestor's, and an FK would let a founder's
671
1597
  // deletion cascade-kill a box still in use by a spawned session).
672
- export const sandboxLeases = pgTable("sandbox_leases", {
673
- id: uuid("id").primaryKey().defaultRandom(),
674
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
675
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
676
- sandboxGroupId: uuid("sandbox_group_id").notNull(),
677
-
678
- liveness: text("liveness", { enum: sandboxLeaseLivenessValues }).notNull().default("cold"),
679
- refcount: integer("refcount").notNull().default(0),
680
- turnHolders: integer("turn_holders").notNull().default(0),
681
- viewerHolders: integer("viewer_holders").notNull().default(0),
682
-
683
- instanceId: text("instance_id"),
684
- backend: text("backend").notNull(),
685
- os: text("os").notNull().default("linux"),
686
- // The container IMAGE the group box runs (Modal image ref / docker image). A shared
687
- // box is SHARED STATE: all its sessions run the SAME filesystem, so they must run the
688
- // same image. This column stamps the image the live box was created with; a resume
689
- // whose resolved image DIFFERS is a conflict (B3): a solo holder recreates the box on
690
- // the new image, N-holders are rejected (SandboxImageConflictError). Nullable — a
691
- // legacy/cold row reads NULL = "image unknown", which never conflicts.
692
- image: text("image"),
693
- dataPlaneUrl: text("data_plane_url"),
694
- // The REAL PTY terminal (ttyd pty-ws) rides a SEPARATE provider tunnel (7681)
695
- // from the desktop noVNC (6080), so its resolved URL is cached independently.
696
- // Recorded under the epoch fence by recordLeaseTerminalDataPlaneUrl; reset to
697
- // null on every box re-key (warm-commit / fail / drain), symmetric with
698
- // data_plane_url.
699
- terminalDataPlaneUrl: text("terminal_data_plane_url"),
700
-
701
- // integer (NOT bigint): the lease-epoch spike proved a raw int8 read returns a
702
- // JS STRING from postgres-js, breaking the strict epoch-fence comparison (it
703
- // was always-true every turn fenced); int4 returns a JS number, the fix.
704
- // Epochs never approach 2^31, so the narrower type loses nothing.
705
- leaseEpoch: integer("lease_epoch").notNull().default(0),
706
-
707
- // The group box-envelope (the "envelope split" Critical): the small recovery
708
- // descriptor to resume()-by-id the group's box without a per-session join.
709
- resumeBackendId: text("resume_backend_id"),
710
- resumeState: jsonb("resume_state").$type<Record<string, unknown>>(),
711
-
712
- // Warm-time billing cursor: last_meter_at = accrual cursor; last_meter_tick =
713
- // idempotency tick (warm_seconds accrued idempotent on
714
- // (sandbox_group_id, lease_epoch, last_meter_tick) in P2.1).
715
- lastMeterAt: timestamp("last_meter_at", { withTimezone: true }),
716
- lastMeterTick: integer("last_meter_tick").notNull().default(0),
717
-
718
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
719
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
720
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
721
- }, (table) => ({
722
- groupIdx: uniqueIndex("sandbox_leases_group_idx").on(table.workspaceId, table.sandboxGroupId),
723
- reaperIdx: index("sandbox_leases_reaper_idx").on(table.expiresAt)
724
- .where(sql`${table.liveness} in ('warming','warm','draining')`),
725
- }));
1598
+ export const sandboxLeases = pgTable(
1599
+ "sandbox_leases",
1600
+ {
1601
+ id: uuid("id").primaryKey().defaultRandom(),
1602
+ accountId: uuid("account_id")
1603
+ .notNull()
1604
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1605
+ workspaceId: uuid("workspace_id")
1606
+ .notNull()
1607
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1608
+ sandboxGroupId: uuid("sandbox_group_id").notNull(),
1609
+
1610
+ liveness: text("liveness", { enum: sandboxLeaseLivenessValues }).notNull().default("cold"),
1611
+ refcount: integer("refcount").notNull().default(0),
1612
+ turnHolders: integer("turn_holders").notNull().default(0),
1613
+ viewerHolders: integer("viewer_holders").notNull().default(0),
1614
+
1615
+ instanceId: text("instance_id"),
1616
+ backend: text("backend").notNull(),
1617
+ os: text("os").notNull().default("linux"),
1618
+ // The container IMAGE the group box runs (Modal image ref / docker image). A shared
1619
+ // box is SHARED STATE: all its sessions run the SAME filesystem, so they must run the
1620
+ // same image. This column stamps the image the live box was created with; a resume
1621
+ // whose resolved image DIFFERS is a conflict (B3): a solo holder recreates the box on
1622
+ // the new image, N-holders are rejected (SandboxImageConflictError). Nullable — a
1623
+ // legacy/cold row reads NULL = "image unknown", which never conflicts.
1624
+ image: text("image"),
1625
+ // The frozen rig version the live box was created under (M3). Like `image`,
1626
+ // this is SHARED STATE: all the box's sessions run the same rig-baked setup,
1627
+ // so a resume resolving a DIFFERENT rig_version_id conflicts (solo holder
1628
+ // recreates cold on the new rig; N-holders throw SandboxRigConflictError).
1629
+ // Nullable a legacy/cold row or a rig-less session reads NULL = "rig
1630
+ // unknown", which never conflicts. No FK (symmetric with sandbox_group_id's
1631
+ // bare-uuid rationale: this lease outlives no single rig_versions row's RLS).
1632
+ rigVersionId: uuid("rig_version_id"),
1633
+ dataPlaneUrl: text("data_plane_url"),
1634
+ // The REAL PTY terminal (ttyd pty-ws) rides a SEPARATE provider tunnel (7681)
1635
+ // from the desktop noVNC (6080), so its resolved URL is cached independently.
1636
+ // Recorded under the epoch fence by recordLeaseTerminalDataPlaneUrl; reset to
1637
+ // null on every box re-key (warm-commit / fail / drain), symmetric with
1638
+ // data_plane_url.
1639
+ terminalDataPlaneUrl: text("terminal_data_plane_url"),
1640
+
1641
+ // integer (NOT bigint): the lease-epoch spike proved a raw int8 read returns a
1642
+ // JS STRING from postgres-js, breaking the strict epoch-fence comparison (it
1643
+ // was always-true → every turn fenced); int4 returns a JS number, the fix.
1644
+ // Epochs never approach 2^31, so the narrower type loses nothing.
1645
+ leaseEpoch: integer("lease_epoch").notNull().default(0),
1646
+
1647
+ // The group box-envelope (the "envelope split" Critical): the small recovery
1648
+ // descriptor to resume()-by-id the group's box without a per-session join.
1649
+ resumeBackendId: text("resume_backend_id"),
1650
+ resumeState: jsonb("resume_state").$type<Record<string, unknown>>(),
1651
+
1652
+ // Warm-time billing cursor: last_meter_at = accrual cursor; last_meter_tick =
1653
+ // idempotency tick (warm_seconds accrued idempotent on
1654
+ // (sandbox_group_id, lease_epoch, last_meter_tick) in P2.1).
1655
+ lastMeterAt: timestamp("last_meter_at", { withTimezone: true }),
1656
+ lastMeterTick: integer("last_meter_tick").notNull().default(0),
1657
+
1658
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
1659
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1660
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1661
+ },
1662
+ (table) => ({
1663
+ groupIdx: uniqueIndex("sandbox_leases_group_idx").on(table.workspaceId, table.sandboxGroupId),
1664
+ reaperIdx: index("sandbox_leases_reaper_idx")
1665
+ .on(table.expiresAt)
1666
+ .where(sql`${table.liveness} in ('warming','warm','draining')`),
1667
+ }),
1668
+ );
726
1669
 
727
1670
  // N rows per group: one per live holder. Makes release idempotent
728
1671
  // (delete-my-row, never blind decrement) and lets the reaper recompute refcount.
729
- export const sandboxLeaseHolders = pgTable("sandbox_lease_holders", {
730
- id: uuid("id").primaryKey().defaultRandom(),
731
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
732
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
733
- leaseId: uuid("lease_id").notNull().references(() => sandboxLeases.id, { onDelete: "cascade" }),
734
- kind: text("kind", { enum: ["turn", "viewer"] }).notNull(),
735
- holderId: text("holder_id").notNull(),
736
- // The attributing session within the (possibly shared) group.
737
- subjectId: uuid("subject_id"),
738
- lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true }).notNull().defaultNow(),
739
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
740
- }, (table) => ({
741
- holderIdx: uniqueIndex("sandbox_lease_holders_holder_idx").on(table.leaseId, table.kind, table.holderId),
742
- staleIdx: index("sandbox_lease_holders_stale_idx").on(table.kind, table.lastHeartbeatAt),
743
- leaseIdx: index("sandbox_lease_holders_lease_idx").on(table.leaseId),
744
- }));
1672
+ export const sandboxLeaseHolders = pgTable(
1673
+ "sandbox_lease_holders",
1674
+ {
1675
+ id: uuid("id").primaryKey().defaultRandom(),
1676
+ accountId: uuid("account_id")
1677
+ .notNull()
1678
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1679
+ workspaceId: uuid("workspace_id")
1680
+ .notNull()
1681
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1682
+ leaseId: uuid("lease_id")
1683
+ .notNull()
1684
+ .references(() => sandboxLeases.id, { onDelete: "cascade" }),
1685
+ kind: text("kind", { enum: ["turn", "viewer"] }).notNull(),
1686
+ holderId: text("holder_id").notNull(),
1687
+ // The attributing session within the (possibly shared) group.
1688
+ subjectId: uuid("subject_id"),
1689
+ lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true }).notNull().defaultNow(),
1690
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1691
+ },
1692
+ (table) => ({
1693
+ holderIdx: uniqueIndex("sandbox_lease_holders_holder_idx").on(
1694
+ table.leaseId,
1695
+ table.kind,
1696
+ table.holderId,
1697
+ ),
1698
+ staleIdx: index("sandbox_lease_holders_stale_idx").on(table.kind, table.lastHeartbeatAt),
1699
+ leaseIdx: index("sandbox_lease_holders_lease_idx").on(table.leaseId),
1700
+ }),
1701
+ );
745
1702
 
746
1703
  // The recording lifecycle states (P4.3). Exported so the activity + the query
747
1704
  // layer share one source of truth for the §3.1 state machine.
748
- export const sessionRecordingStateValues = ["recording", "finalizing", "available", "failed"] as const;
1705
+ export const sessionRecordingStateValues = [
1706
+ "recording",
1707
+ "finalizing",
1708
+ "available",
1709
+ "failed",
1710
+ ] as const;
749
1711
  export const sessionRecordingModeValues = ["manual", "on-turn", "on-verify"] as const;
750
1712
  export const sessionRecordingCodecValues = ["h264-mp4", "vp9-webm"] as const;
751
1713
 
@@ -755,31 +1717,104 @@ export const sessionRecordingCodecValues = ["h264-mp4", "vp9-webm"] as const;
755
1717
  // process that holds the resumed-by-id handle (never a Temporal payload, F10).
756
1718
  // Mirrors the account/workspace/session FK chain of sandboxSessionEnvelopes;
757
1719
  // turnId is ON DELETE SET NULL (a deleted turn must not kill the artifact row).
758
- export const sessionRecordings = pgTable("session_recordings", {
759
- id: uuid("id").primaryKey().defaultRandom(),
760
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
761
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
762
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
763
- turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
764
-
765
- state: text("state", { enum: sessionRecordingStateValues }).notNull(),
766
- mode: text("mode", { enum: sessionRecordingModeValues }).notNull(),
767
- codec: text("codec", { enum: sessionRecordingCodecValues }).notNull(),
768
-
769
- storageKey: text("storage_key"),
770
- sizeBytes: bigint("size_bytes", { mode: "number" }),
771
- durationSeconds: numeric("duration_seconds").$type<number>(),
772
-
773
- width: integer("width").notNull(),
774
- height: integer("height").notNull(),
775
-
776
- reason: text("reason"),
777
-
778
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
779
- finalizedAt: timestamp("finalized_at", { withTimezone: true }),
780
- }, (table) => ({
781
- sessionIdx: index("session_recordings_session_idx").on(table.workspaceId, table.sessionId, table.createdAt),
782
- }));
1720
+ export const sessionRecordings = pgTable(
1721
+ "session_recordings",
1722
+ {
1723
+ id: uuid("id").primaryKey().defaultRandom(),
1724
+ accountId: uuid("account_id")
1725
+ .notNull()
1726
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1727
+ workspaceId: uuid("workspace_id")
1728
+ .notNull()
1729
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1730
+ sessionId: uuid("session_id")
1731
+ .notNull()
1732
+ .references(() => sessions.id, { onDelete: "cascade" }),
1733
+ turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
1734
+
1735
+ state: text("state", { enum: sessionRecordingStateValues }).notNull(),
1736
+ mode: text("mode", { enum: sessionRecordingModeValues }).notNull(),
1737
+ codec: text("codec", { enum: sessionRecordingCodecValues }).notNull(),
1738
+
1739
+ storageKey: text("storage_key"),
1740
+ sizeBytes: bigint("size_bytes", { mode: "number" }),
1741
+ durationSeconds: numeric("duration_seconds").$type<number>(),
1742
+
1743
+ width: integer("width").notNull(),
1744
+ height: integer("height").notNull(),
1745
+
1746
+ reason: text("reason"),
1747
+
1748
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1749
+ finalizedAt: timestamp("finalized_at", { withTimezone: true }),
1750
+ },
1751
+ (table) => ({
1752
+ sessionIdx: index("session_recordings_session_idx").on(
1753
+ table.workspaceId,
1754
+ table.sessionId,
1755
+ table.createdAt,
1756
+ ),
1757
+ }),
1758
+ );
1759
+
1760
+ // Workbench v2 turn-end workspace capture (dossier §10.2; model: sessionRecordings).
1761
+ // One row per capture revision — a point-in-time snapshot of a session's changed
1762
+ // files, probed off the live box at turn end. The manifest (tree index + per-repo
1763
+ // status/diff + file index) and each after-image blob live in @opengeni/storage;
1764
+ // this row is the durable index the read routes serve from. `revision` is
1765
+ // monotonic per session (unique (session_id, revision)); `blob_keys` records the
1766
+ // content-addressed after-image keys this revision references so the keep-latest-10
1767
+ // GC can delete only blobs no surviving revision shares (set-difference GC without
1768
+ // a storage read). `lease_epoch` fences a write: an insert whose lease was
1769
+ // superseded writes zero rows (see insertWorkspaceCapture).
1770
+ export const workspaceCaptures = pgTable(
1771
+ "workspace_captures",
1772
+ {
1773
+ id: uuid("id").primaryKey().defaultRandom(),
1774
+ accountId: uuid("account_id")
1775
+ .notNull()
1776
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1777
+ workspaceId: uuid("workspace_id")
1778
+ .notNull()
1779
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1780
+ sessionId: uuid("session_id")
1781
+ .notNull()
1782
+ .references(() => sessions.id, { onDelete: "cascade" }),
1783
+ turnId: uuid("turn_id").references(() => sessionTurns.id, { onDelete: "set null" }),
1784
+
1785
+ revision: bigint("revision", { mode: "number" }).notNull(),
1786
+ leaseEpoch: integer("lease_epoch").notNull(),
1787
+ // 'available' on a committed capture. 'failed' reserved for a future two-phase
1788
+ // write; the current synchronous capture only ever inserts 'available'.
1789
+ state: text("state", { enum: ["available", "failed"] })
1790
+ .notNull()
1791
+ .default("available"),
1792
+
1793
+ // Single JSON manifest blob (tree index + repos + file refs) — the cold-paint payload.
1794
+ manifestKey: text("manifest_key"),
1795
+ // The fs tree index blob, kept separate from the manifest so the API can inline
1796
+ // or sign it independently of the (usually small) manifest metadata.
1797
+ treeIndexKey: text("tree_index_key"),
1798
+ // Content-addressed after-image blob keys this revision references (GC input).
1799
+ blobKeys: jsonb("blob_keys").$type<string[]>().notNull().default([]),
1800
+
1801
+ sizeBytes: bigint("size_bytes", { mode: "number" }),
1802
+ stats: jsonb("stats").$type<Record<string, unknown>>().notNull().default({}),
1803
+
1804
+ capturedAt: timestamp("captured_at", { withTimezone: true }).notNull().defaultNow(),
1805
+ },
1806
+ (table) => ({
1807
+ sessionRevision: uniqueIndex("workspace_captures_session_revision_idx").on(
1808
+ table.sessionId,
1809
+ table.revision,
1810
+ ),
1811
+ latest: index("workspace_captures_latest_idx").on(
1812
+ table.workspaceId,
1813
+ table.sessionId,
1814
+ table.revision,
1815
+ ),
1816
+ }),
1817
+ );
783
1818
 
784
1819
  // Channel-A interactive PTY sessions (P4.4 / modules/08-channel-a.md §3.1). The
785
1820
  // ONLY new persistent state Channel A needs — FS/Git reads are stateless point
@@ -789,31 +1824,41 @@ export const sessionRecordings = pgTable("session_recordings", {
789
1824
  // opened on (a box re-key strands the PTY -> reaped with reason owner_gone), and
790
1825
  // a last_input_at heartbeat so the reaper can kill idle/orphaned PTYs. Mirrors
791
1826
  // the account/workspace/session FK chain of sandboxSessionEnvelopes.
792
- export const sandboxPtySessions = pgTable("sandbox_pty_sessions", {
793
- id: uuid("id").primaryKey().defaultRandom(), // == ptyId on the wire
794
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
795
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
796
- sessionId: uuid("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
797
- // The SDK numeric exec-session id used by writeStdin({ sessionId }). Null until
798
- // the open exec yields a still-running process (a fast-exiting shell has none).
799
- execSessionId: integer("exec_session_id"),
800
- leaseEpoch: integer("lease_epoch").notNull(), // fenced to the box that opened it
801
- cols: integer("cols").notNull(),
802
- rows: integer("rows").notNull(),
803
- shell: text("shell").notNull(),
804
- cwd: text("cwd").notNull(),
805
- status: text("status").notNull().default("open"), // 'open' | 'closed'
806
- // The viewer grant/subject that opened it (free-text access subjects are not
807
- // always UUIDs, M5; so a text column, never a uuid NOT NULL).
808
- openedBy: text("opened_by").notNull(),
809
- lastInputAt: timestamp("last_input_at", { withTimezone: true }).notNull().defaultNow(),
810
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
811
- closedAt: timestamp("closed_at", { withTimezone: true }),
812
- }, (table) => ({
813
- openIdx: index("sandbox_pty_sessions_session_idx")
814
- .on(table.workspaceId, table.sessionId)
815
- .where(sql`${table.status} = 'open'`),
816
- }));
1827
+ export const sandboxPtySessions = pgTable(
1828
+ "sandbox_pty_sessions",
1829
+ {
1830
+ id: uuid("id").primaryKey().defaultRandom(), // == ptyId on the wire
1831
+ accountId: uuid("account_id")
1832
+ .notNull()
1833
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1834
+ workspaceId: uuid("workspace_id")
1835
+ .notNull()
1836
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1837
+ sessionId: uuid("session_id")
1838
+ .notNull()
1839
+ .references(() => sessions.id, { onDelete: "cascade" }),
1840
+ // The SDK numeric exec-session id used by writeStdin({ sessionId }). Null until
1841
+ // the open exec yields a still-running process (a fast-exiting shell has none).
1842
+ execSessionId: integer("exec_session_id"),
1843
+ leaseEpoch: integer("lease_epoch").notNull(), // fenced to the box that opened it
1844
+ cols: integer("cols").notNull(),
1845
+ rows: integer("rows").notNull(),
1846
+ shell: text("shell").notNull(),
1847
+ cwd: text("cwd").notNull(),
1848
+ status: text("status").notNull().default("open"), // 'open' | 'closed'
1849
+ // The viewer grant/subject that opened it (free-text — access subjects are not
1850
+ // always UUIDs, M5; so a text column, never a uuid NOT NULL).
1851
+ openedBy: text("opened_by").notNull(),
1852
+ lastInputAt: timestamp("last_input_at", { withTimezone: true }).notNull().defaultNow(),
1853
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1854
+ closedAt: timestamp("closed_at", { withTimezone: true }),
1855
+ },
1856
+ (table) => ({
1857
+ openIdx: index("sandbox_pty_sessions_session_idx")
1858
+ .on(table.workspaceId, table.sessionId)
1859
+ .where(sql`${table.status} = 'open'`),
1860
+ }),
1861
+ );
817
1862
 
818
1863
  // ============================================================================
819
1864
  // Bring-your-own-compute (M2): first-class swappable sandboxes + enrollment +
@@ -834,37 +1879,61 @@ export const sandboxKindValues = ["modal", "selfhosted"] as const;
834
1879
  // are the desktop/computer-use consent bits (default false — opt-in). status is
835
1880
  // the active|revoked lifecycle; last_seen_at the heartbeat liveness cursor the
836
1881
  // Machines dashboard renders online/reconnecting/offline from.
837
- export const enrollments = pgTable("enrollments", {
838
- id: uuid("id").primaryKey().defaultRandom(),
839
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
840
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
841
- // The agent's ed25519 public key (the machine identity).
842
- pubkey: text("pubkey").notNull(),
843
- exposure: text("exposure", { enum: enrollmentExposureValues }).notNull().default("whole-machine"),
844
- hasDisplay: boolean("has_display").notNull().default(false),
845
- // When the machine has a display it CANNOT capture (macOS Screen Recording / TCC
846
- // not granted), the agent reports has_display=false AND a human, actionable reason
847
- // here (e.g. "grant Screen Recording in System Settings"). NULL means capture is
848
- // permitted (has_display=true) or the machine is genuinely headless — the reason
849
- // distinguishes "display present but capture not granted" from plain "no display"
850
- // so the Machines dashboard / VM picker can surface the specific hint. Refreshed
851
- // from every connect Hello alongside has_display.
852
- desktopUnavailableReason: text("desktop_unavailable_reason"),
853
- allowScreenControl: boolean("allow_screen_control").notNull().default(false),
854
- status: text("status", { enum: enrollmentStatusValues }).notNull().default("active"),
855
- os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
856
- arch: text("arch").notNull().default("x86_64"),
857
- // Heartbeat liveness cursor. Null until the first connect.
858
- lastSeenAt: timestamp("last_seen_at", { withTimezone: true }),
859
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
860
- revokedAt: timestamp("revoked_at", { withTimezone: true }),
861
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
862
- }, (table) => ({
863
- // One enrollment per (workspace, pubkey): a re-enroll is an idempotent upsert.
864
- workspacePubkey: uniqueIndex("enrollments_workspace_pubkey_idx").on(table.workspaceId, table.pubkey),
865
- // List a workspace's ACTIVE machines without scanning revoked rows.
866
- workspaceStatus: index("enrollments_workspace_status_idx").on(table.workspaceId, table.status),
867
- }));
1882
+ export const enrollments = pgTable(
1883
+ "enrollments",
1884
+ {
1885
+ id: uuid("id").primaryKey().defaultRandom(),
1886
+ accountId: uuid("account_id")
1887
+ .notNull()
1888
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1889
+ workspaceId: uuid("workspace_id")
1890
+ .notNull()
1891
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1892
+ // The agent's ed25519 public key (the machine identity).
1893
+ pubkey: text("pubkey").notNull(),
1894
+ exposure: text("exposure", { enum: enrollmentExposureValues })
1895
+ .notNull()
1896
+ .default("whole-machine"),
1897
+ hasDisplay: boolean("has_display").notNull().default(false),
1898
+ // Refreshed from every connect Hello (Capabilities.op_stream); false for
1899
+ // agents predating the op-stream engine.
1900
+ opStream: boolean("op_stream").notNull().default(false),
1901
+ // When the machine has a display it CANNOT capture (macOS Screen Recording / TCC
1902
+ // not granted), the agent reports has_display=false AND a human, actionable reason
1903
+ // here (e.g. "grant Screen Recording in System Settings"). NULL means capture is
1904
+ // permitted (has_display=true) or the machine is genuinely headless — the reason
1905
+ // distinguishes "display present but capture not granted" from plain "no display"
1906
+ // so the Machines dashboard / VM picker can surface the specific hint. Refreshed
1907
+ // from every connect Hello alongside has_display.
1908
+ desktopUnavailableReason: text("desktop_unavailable_reason"),
1909
+ allowScreenControl: boolean("allow_screen_control").notNull().default(false),
1910
+ status: text("status", { enum: enrollmentStatusValues }).notNull().default("active"),
1911
+ os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
1912
+ arch: text("arch").notNull().default("x86_64"),
1913
+ // Heartbeat liveness cursor. Null until the first connect.
1914
+ lastSeenAt: timestamp("last_seen_at", { withTimezone: true }),
1915
+ // Clean going-offline marker (migration 0049). Set when the machine announces a
1916
+ // typed GoingOffline (user-stop / self-update / host-shutdown); the liveness
1917
+ // derivation reads an un-cleared marker as OFFLINE immediately, regardless of a
1918
+ // still-fresh last_seen. Any newer liveness signal (a reconnect Hello or a
1919
+ // fresher heartbeat via touchEnrollmentLastSeen) clears BOTH back to NULL. NULL
1920
+ // (the default) ⇒ no goodbye pending — today's last_seen-aging behavior.
1921
+ wentOfflineAt: timestamp("went_offline_at", { withTimezone: true }),
1922
+ wentOfflineReason: text("went_offline_reason"),
1923
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1924
+ revokedAt: timestamp("revoked_at", { withTimezone: true }),
1925
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1926
+ },
1927
+ (table) => ({
1928
+ // One enrollment per (workspace, pubkey): a re-enroll is an idempotent upsert.
1929
+ workspacePubkey: uniqueIndex("enrollments_workspace_pubkey_idx").on(
1930
+ table.workspaceId,
1931
+ table.pubkey,
1932
+ ),
1933
+ // List a workspace's ACTIVE machines without scanning revoked rows.
1934
+ workspaceStatus: index("enrollments_workspace_status_idx").on(table.workspaceId, table.status),
1935
+ }),
1936
+ );
868
1937
 
869
1938
  // The OAuth 2.0 device-authorization (RFC 8628) PENDING request (M5, migration
870
1939
  // 0025 / dossier §10.2 enrollment + §18 LOUD consent). An agent's `enroll` starts
@@ -882,61 +1951,74 @@ export const enrollments = pgTable("enrollments", {
882
1951
  // `enrollments` row the approve produced.
883
1952
  export const deviceEnrollmentStatusValues = ["pending", "approved", "denied", "consumed"] as const;
884
1953
 
885
- export const deviceEnrollmentRequests = pgTable("device_enrollment_requests", {
886
- id: uuid("id").primaryKey().defaultRandom(),
887
- // The opaque code the agent polls with (unguessable, single-use). Unique.
888
- deviceCode: text("device_code").notNull(),
889
- // The short human-typed code (e.g. "WDJB-MJHT"). Unique among LIVE (pending)
890
- // rows via a partial unique index so a recycled code never collides with a
891
- // terminal row.
892
- userCode: text("user_code").notNull(),
893
- // The workspace this request was started for (resolved from the deployment-edge
894
- // request context — the agent presents the access key, the flow binds to the
895
- // single managed workspace OR a workspace hint). account_id rides along for RLS.
896
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
897
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
898
- // The agent's ed25519 public key (the machine identity the enrollment binds to).
899
- pubkey: text("pubkey").notNull(),
900
- os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
901
- arch: text("arch").notNull().default("x86_64"),
902
- machineName: text("machine_name"),
903
- // The exposure the agent REQUESTED (whole-machine in v1; loudly consented at
904
- // approve). Mirrors the enrollment column domain.
905
- requestedExposure: text("requested_exposure", { enum: enrollmentExposureValues }).notNull().default("whole-machine"),
906
- // The agent CAN offer a display (a real screen / Xvfb is available) — gates
907
- // whether screen-control consent is even meaningful. has_display on the
908
- // resulting enrollment is derived from this.
909
- canOfferDisplay: boolean("can_offer_display").notNull().default(false),
910
- // The agent REQUESTS screen control (computer-use). The user's allow_screen_control
911
- // at approve is the AUTHORITATIVE consent; this is only the agent's request.
912
- requestsScreenControl: boolean("requests_screen_control").notNull().default(false),
913
- status: text("status", { enum: deviceEnrollmentStatusValues }).notNull().default("pending"),
914
- // ── LOUD CONSENT capture (who/when/what), stamped at approve ──────────────
915
- approvedBySubjectId: text("approved_by_subject_id"),
916
- approvedBySubjectLabel: text("approved_by_subject_label"),
917
- // The user's screen-control consent decision (whole-machine is mandatory at
918
- // approve; screen-control is opt-in per this flag).
919
- allowScreenControl: boolean("allow_screen_control").notNull().default(false),
920
- approvedAt: timestamp("approved_at", { withTimezone: true }),
921
- // The enrollment + sandbox the approve produced (acceptance #2: an enrollment
922
- // row AND a sandbox row appear). Null until approved.
923
- enrollmentId: uuid("enrollment_id").references(() => enrollments.id, { onDelete: "set null" }),
924
- sandboxId: uuid("sandbox_id").references(() => sandboxes.id, { onDelete: "set null" }),
925
- // The short-TTL expiry; a pending row past this is EXPIRED on poll.
926
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
927
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
928
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
929
- }, (table) => ({
930
- // The device_code is the agent's poll key globally unique + indexed.
931
- deviceCode: uniqueIndex("device_enrollment_requests_device_code_idx").on(table.deviceCode),
932
- // The user_code must be unique among LIVE (pending) rows so the approve lookup
933
- // is unambiguous; a terminal row's code may be recycled.
934
- userCodePending: uniqueIndex("device_enrollment_requests_user_code_pending_idx")
935
- .on(table.userCode)
936
- .where(sql`${table.status} = 'pending'`),
937
- workspaceCreated: index("device_enrollment_requests_workspace_created_idx").on(table.workspaceId, table.createdAt),
938
- expires: index("device_enrollment_requests_expires_idx").on(table.expiresAt),
939
- }));
1954
+ export const deviceEnrollmentRequests = pgTable(
1955
+ "device_enrollment_requests",
1956
+ {
1957
+ id: uuid("id").primaryKey().defaultRandom(),
1958
+ // The opaque code the agent polls with (unguessable, single-use). Unique.
1959
+ deviceCode: text("device_code").notNull(),
1960
+ // The short human-typed code (e.g. "WDJB-MJHT"). Unique among LIVE (pending)
1961
+ // rows via a partial unique index so a recycled code never collides with a
1962
+ // terminal row.
1963
+ userCode: text("user_code").notNull(),
1964
+ // The workspace this request was started for (resolved from the deployment-edge
1965
+ // request context — the agent presents the access key, the flow binds to the
1966
+ // single managed workspace OR a workspace hint). account_id rides along for RLS.
1967
+ accountId: uuid("account_id")
1968
+ .notNull()
1969
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
1970
+ workspaceId: uuid("workspace_id")
1971
+ .notNull()
1972
+ .references(() => workspaces.id, { onDelete: "cascade" }),
1973
+ // The agent's ed25519 public key (the machine identity the enrollment binds to).
1974
+ pubkey: text("pubkey").notNull(),
1975
+ os: text("os", { enum: enrollmentOsValues }).notNull().default("linux"),
1976
+ arch: text("arch").notNull().default("x86_64"),
1977
+ machineName: text("machine_name"),
1978
+ // The exposure the agent REQUESTED (whole-machine in v1; loudly consented at
1979
+ // approve). Mirrors the enrollment column domain.
1980
+ requestedExposure: text("requested_exposure", { enum: enrollmentExposureValues })
1981
+ .notNull()
1982
+ .default("whole-machine"),
1983
+ // The agent CAN offer a display (a real screen / Xvfb is available) — gates
1984
+ // whether screen-control consent is even meaningful. has_display on the
1985
+ // resulting enrollment is derived from this.
1986
+ canOfferDisplay: boolean("can_offer_display").notNull().default(false),
1987
+ // The agent REQUESTS screen control (computer-use). The user's allow_screen_control
1988
+ // at approve is the AUTHORITATIVE consent; this is only the agent's request.
1989
+ requestsScreenControl: boolean("requests_screen_control").notNull().default(false),
1990
+ status: text("status", { enum: deviceEnrollmentStatusValues }).notNull().default("pending"),
1991
+ // ── LOUD CONSENT capture (who/when/what), stamped at approve ──────────────
1992
+ approvedBySubjectId: text("approved_by_subject_id"),
1993
+ approvedBySubjectLabel: text("approved_by_subject_label"),
1994
+ // The user's screen-control consent decision (whole-machine is mandatory at
1995
+ // approve; screen-control is opt-in per this flag).
1996
+ allowScreenControl: boolean("allow_screen_control").notNull().default(false),
1997
+ approvedAt: timestamp("approved_at", { withTimezone: true }),
1998
+ // The enrollment + sandbox the approve produced (acceptance #2: an enrollment
1999
+ // row AND a sandbox row appear). Null until approved.
2000
+ enrollmentId: uuid("enrollment_id").references(() => enrollments.id, { onDelete: "set null" }),
2001
+ sandboxId: uuid("sandbox_id").references(() => sandboxes.id, { onDelete: "set null" }),
2002
+ // The short-TTL expiry; a pending row past this is EXPIRED on poll.
2003
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
2004
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2005
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2006
+ },
2007
+ (table) => ({
2008
+ // The device_code is the agent's poll key — globally unique + indexed.
2009
+ deviceCode: uniqueIndex("device_enrollment_requests_device_code_idx").on(table.deviceCode),
2010
+ // The user_code must be unique among LIVE (pending) rows so the approve lookup
2011
+ // is unambiguous; a terminal row's code may be recycled.
2012
+ userCodePending: uniqueIndex("device_enrollment_requests_user_code_pending_idx")
2013
+ .on(table.userCode)
2014
+ .where(sql`${table.status} = 'pending'`),
2015
+ workspaceCreated: index("device_enrollment_requests_workspace_created_idx").on(
2016
+ table.workspaceId,
2017
+ table.createdAt,
2018
+ ),
2019
+ expires: index("device_enrollment_requests_expires_idx").on(table.expiresAt),
2020
+ }),
2021
+ );
940
2022
 
941
2023
  // The first-class NAMED sandbox a session's active_sandbox_id points AT. kind
942
2024
  // discriminates the backend the routing proxy resolves to: 'modal' (cloud box,
@@ -945,179 +2027,308 @@ export const deviceEnrollmentRequests = pgTable("device_enrollment_requests", {
945
2027
  // the sandboxes_selfhosted_enrollment_chk CHECK in migration 0024. enrollment_id
946
2028
  // is ON DELETE SET NULL so deleting an enrollment never cascade-kills a sandbox a
947
2029
  // session might still point at (the routing layer surfaces agent_offline instead).
948
- export const sandboxes = pgTable("sandboxes", {
949
- id: uuid("id").primaryKey().defaultRandom(),
950
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
951
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
952
- kind: text("kind", { enum: sandboxKindValues }).notNull(),
953
- name: text("name").notNull(),
954
- enrollmentId: uuid("enrollment_id").references(() => enrollments.id, { onDelete: "set null" }),
955
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
956
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
957
- }, (table) => ({
958
- workspaceCreated: index("sandboxes_workspace_created_idx").on(table.workspaceId, table.createdAt),
959
- enrollment: index("sandboxes_enrollment_idx").on(table.enrollmentId).where(sql`${table.enrollmentId} is not null`),
960
- }));
2030
+ export const sandboxes = pgTable(
2031
+ "sandboxes",
2032
+ {
2033
+ id: uuid("id").primaryKey().defaultRandom(),
2034
+ accountId: uuid("account_id")
2035
+ .notNull()
2036
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2037
+ workspaceId: uuid("workspace_id")
2038
+ .notNull()
2039
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2040
+ kind: text("kind", { enum: sandboxKindValues }).notNull(),
2041
+ name: text("name").notNull(),
2042
+ enrollmentId: uuid("enrollment_id").references(() => enrollments.id, { onDelete: "set null" }),
2043
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2044
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2045
+ },
2046
+ (table) => ({
2047
+ workspaceCreated: index("sandboxes_workspace_created_idx").on(
2048
+ table.workspaceId,
2049
+ table.createdAt,
2050
+ ),
2051
+ enrollment: index("sandboxes_enrollment_idx")
2052
+ .on(table.enrollmentId)
2053
+ .where(sql`${table.enrollmentId} is not null`),
2054
+ }),
2055
+ );
961
2056
 
962
2057
  // Last-sample upsert: ONE row per enrollment, overwritten on every sample (the
963
2058
  // PK on enrollment_id is the ON CONFLICT target). The §10.7 signals; nullable
964
2059
  // where a platform/sample may not provide it (no GPU, headless).
965
- export const machineMetricsLatest = pgTable("machine_metrics_latest", {
966
- enrollmentId: uuid("enrollment_id").primaryKey().references(() => enrollments.id, { onDelete: "cascade" }),
967
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
968
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
969
- cpuPercent: numeric("cpu_percent").$type<number>(),
970
- load1: numeric("load1").$type<number>(),
971
- load5: numeric("load5").$type<number>(),
972
- load15: numeric("load15").$type<number>(),
973
- memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
974
- memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
975
- diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
976
- diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
977
- gpuUtilPercent: numeric("gpu_util_percent").$type<number>(),
978
- gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
979
- gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
980
- contention: numeric("contention").$type<number>(),
981
- sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
982
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
983
- }, (table) => ({
984
- workspace: index("machine_metrics_latest_workspace_idx").on(table.workspaceId),
985
- }));
2060
+ export const machineMetricsLatest = pgTable(
2061
+ "machine_metrics_latest",
2062
+ {
2063
+ enrollmentId: uuid("enrollment_id")
2064
+ .primaryKey()
2065
+ .references(() => enrollments.id, { onDelete: "cascade" }),
2066
+ accountId: uuid("account_id")
2067
+ .notNull()
2068
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2069
+ workspaceId: uuid("workspace_id")
2070
+ .notNull()
2071
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2072
+ cpuPercent: numeric("cpu_percent").$type<number>(),
2073
+ load1: numeric("load1").$type<number>(),
2074
+ load5: numeric("load5").$type<number>(),
2075
+ load15: numeric("load15").$type<number>(),
2076
+ memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
2077
+ memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
2078
+ diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
2079
+ diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
2080
+ gpuUtilPercent: numeric("gpu_util_percent").$type<number>(),
2081
+ gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
2082
+ gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
2083
+ contention: numeric("contention").$type<number>(),
2084
+ sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
2085
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2086
+ },
2087
+ (table) => ({
2088
+ workspace: index("machine_metrics_latest_workspace_idx").on(table.workspaceId),
2089
+ }),
2090
+ );
986
2091
 
987
2092
  // Append-only downsampled history (~1/min per enrollment, retained N days). Same
988
2093
  // signal columns as _latest. The (enrollment_id, sampled_at) index serves the
989
2094
  // dashboard time-range read AND the (later) retention sweep.
990
- export const machineMetricsSeries = pgTable("machine_metrics_series", {
991
- id: uuid("id").primaryKey().defaultRandom(),
992
- enrollmentId: uuid("enrollment_id").notNull().references(() => enrollments.id, { onDelete: "cascade" }),
993
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
994
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
995
- cpuPercent: numeric("cpu_percent").$type<number>(),
996
- load1: numeric("load1").$type<number>(),
997
- load5: numeric("load5").$type<number>(),
998
- load15: numeric("load15").$type<number>(),
999
- memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
1000
- memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
1001
- diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
1002
- diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
1003
- gpuUtilPercent: numeric("gpu_util_percent").$type<number>(),
1004
- gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
1005
- gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
1006
- contention: numeric("contention").$type<number>(),
1007
- sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
1008
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1009
- }, (table) => ({
1010
- enrollmentSampled: index("machine_metrics_series_enrollment_sampled_idx").on(table.enrollmentId, table.sampledAt),
1011
- sampled: index("machine_metrics_series_sampled_idx").on(table.sampledAt),
1012
- }));
1013
-
1014
- export const scheduledTasks = pgTable("scheduled_tasks", {
1015
- id: uuid("id").primaryKey().defaultRandom(),
1016
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1017
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1018
- name: text("name").notNull(),
1019
- status: text("status").notNull().default("active"),
1020
- schedule: jsonb("schedule").$type<unknown>().notNull(),
1021
- temporalScheduleId: text("temporal_schedule_id").notNull(),
1022
- runMode: text("run_mode").notNull().default("new_session_per_run"),
1023
- overlapPolicy: text("overlap_policy").notNull().default("allow_concurrent"),
1024
- agentConfig: jsonb("agent_config").$type<unknown>().notNull(),
1025
- reusableSessionId: uuid("reusable_session_id").references(() => sessions.id, { onDelete: "set null" }),
1026
- environmentId: uuid("environment_id").references(() => workspaceEnvironments.id, { onDelete: "restrict" }),
1027
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
1028
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1029
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1030
- }, (table) => ({
1031
- temporalScheduleId: uniqueIndex("scheduled_tasks_workspace_temporal_schedule_id_idx").on(table.workspaceId, table.temporalScheduleId),
1032
- status: index("scheduled_tasks_workspace_status_idx").on(table.workspaceId, table.status),
1033
- environment: index("scheduled_tasks_environment_idx").on(table.workspaceId, table.environmentId),
1034
- }));
1035
-
1036
- export const scheduledTaskRuns = pgTable("scheduled_task_runs", {
1037
- id: uuid("id").primaryKey().defaultRandom(),
1038
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1039
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1040
- taskId: uuid("task_id").notNull().references(() => scheduledTasks.id, { onDelete: "cascade" }),
1041
- status: text("status").notNull().default("queued"),
1042
- triggerType: text("trigger_type").notNull(),
1043
- scheduledAt: timestamp("scheduled_at", { withTimezone: true }),
1044
- firedAt: timestamp("fired_at", { withTimezone: true }).notNull().defaultNow(),
1045
- sessionId: uuid("session_id").references(() => sessions.id, { onDelete: "set null" }),
1046
- triggerEventId: uuid("trigger_event_id"),
1047
- error: text("error"),
1048
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1049
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1050
- }, (table) => ({
1051
- taskCreated: index("scheduled_task_runs_workspace_task_created_idx").on(table.workspaceId, table.taskId, table.createdAt),
1052
- session: index("scheduled_task_runs_workspace_session_idx").on(table.workspaceId, table.sessionId),
1053
- }));
1054
-
1055
- export const githubInstallations = pgTable("github_installations", {
1056
- id: uuid("id").primaryKey().defaultRandom(),
1057
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1058
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1059
- installationId: integer("installation_id").notNull(),
1060
- accountLogin: text("account_login"),
1061
- accountType: text("account_type"),
1062
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1063
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1064
- }, (table) => ({
1065
- workspaceInstallation: uniqueIndex("github_installations_workspace_installation_idx").on(table.workspaceId, table.installationId),
1066
- installation: index("github_installations_installation_idx").on(table.installationId),
1067
- workspace: index("github_installations_workspace_idx").on(table.workspaceId),
1068
- }));
1069
-
1070
- export const usageEvents = pgTable("usage_events", {
1071
- id: uuid("id").primaryKey().defaultRandom(),
1072
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1073
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1074
- subjectId: text("subject_id"),
1075
- eventType: text("event_type").notNull(),
1076
- quantity: bigint("quantity", { mode: "number" }).notNull(),
1077
- unit: text("unit").notNull(),
1078
- sourceResourceType: text("source_resource_type"),
1079
- sourceResourceId: text("source_resource_id"),
1080
- idempotencyKey: text("idempotency_key").notNull(),
1081
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
1082
- recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull().defaultNow(),
1083
- exportedToBillingAt: timestamp("exported_to_billing_at", { withTimezone: true }),
1084
- billingProviderEventId: text("billing_provider_event_id"),
1085
- }, (table) => ({
1086
- idempotency: uniqueIndex("usage_events_idempotency_idx").on(table.idempotencyKey),
1087
- workspaceMetric: index("usage_events_workspace_metric_idx").on(table.workspaceId, table.eventType, table.occurredAt),
1088
- accountMetric: index("usage_events_account_metric_idx").on(table.accountId, table.eventType, table.occurredAt),
1089
- }));
1090
-
1091
- export const creditLedgerEntries = pgTable("credit_ledger_entries", {
1092
- id: uuid("id").primaryKey().defaultRandom(),
1093
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1094
- workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "set null" }),
1095
- type: text("type").notNull(),
1096
- amountMicros: bigint("amount_micros", { mode: "number" }).notNull(),
1097
- currency: text("currency").notNull().default("usd"),
1098
- sourceType: text("source_type"),
1099
- sourceId: text("source_id"),
1100
- idempotencyKey: text("idempotency_key").notNull(),
1101
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
1102
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
1103
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1104
- }, (table) => ({
1105
- idempotency: uniqueIndex("credit_ledger_entries_idempotency_idx").on(table.idempotencyKey),
1106
- accountCreated: index("credit_ledger_entries_account_created_idx").on(table.accountId, table.createdAt),
1107
- }));
1108
-
1109
- export const billingCustomers = pgTable("billing_customers", {
1110
- id: uuid("id").primaryKey().defaultRandom(),
1111
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1112
- provider: text("provider").notNull().default("stripe"),
1113
- providerCustomerId: text("provider_customer_id").notNull(),
1114
- email: text("email"),
1115
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1116
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1117
- }, (table) => ({
1118
- accountProvider: uniqueIndex("billing_customers_account_provider_idx").on(table.accountId, table.provider),
1119
- providerCustomer: uniqueIndex("billing_customers_provider_customer_idx").on(table.provider, table.providerCustomerId),
1120
- }));
2095
+ export const machineMetricsSeries = pgTable(
2096
+ "machine_metrics_series",
2097
+ {
2098
+ id: uuid("id").primaryKey().defaultRandom(),
2099
+ enrollmentId: uuid("enrollment_id")
2100
+ .notNull()
2101
+ .references(() => enrollments.id, { onDelete: "cascade" }),
2102
+ accountId: uuid("account_id")
2103
+ .notNull()
2104
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2105
+ workspaceId: uuid("workspace_id")
2106
+ .notNull()
2107
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2108
+ cpuPercent: numeric("cpu_percent").$type<number>(),
2109
+ load1: numeric("load1").$type<number>(),
2110
+ load5: numeric("load5").$type<number>(),
2111
+ load15: numeric("load15").$type<number>(),
2112
+ memUsedBytes: bigint("mem_used_bytes", { mode: "number" }),
2113
+ memTotalBytes: bigint("mem_total_bytes", { mode: "number" }),
2114
+ diskUsedBytes: bigint("disk_used_bytes", { mode: "number" }),
2115
+ diskTotalBytes: bigint("disk_total_bytes", { mode: "number" }),
2116
+ gpuUtilPercent: numeric("gpu_util_percent").$type<number>(),
2117
+ gpuMemUsedBytes: bigint("gpu_mem_used_bytes", { mode: "number" }),
2118
+ gpuMemTotalBytes: bigint("gpu_mem_total_bytes", { mode: "number" }),
2119
+ contention: numeric("contention").$type<number>(),
2120
+ sampledAt: timestamp("sampled_at", { withTimezone: true }).notNull(),
2121
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2122
+ },
2123
+ (table) => ({
2124
+ enrollmentSampled: index("machine_metrics_series_enrollment_sampled_idx").on(
2125
+ table.enrollmentId,
2126
+ table.sampledAt,
2127
+ ),
2128
+ sampled: index("machine_metrics_series_sampled_idx").on(table.sampledAt),
2129
+ }),
2130
+ );
2131
+
2132
+ export const scheduledTasks = pgTable(
2133
+ "scheduled_tasks",
2134
+ {
2135
+ id: uuid("id").primaryKey().defaultRandom(),
2136
+ accountId: uuid("account_id")
2137
+ .notNull()
2138
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2139
+ workspaceId: uuid("workspace_id")
2140
+ .notNull()
2141
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2142
+ name: text("name").notNull(),
2143
+ status: text("status").notNull().default("active"),
2144
+ schedule: jsonb("schedule").$type<unknown>().notNull(),
2145
+ temporalScheduleId: text("temporal_schedule_id").notNull(),
2146
+ runMode: text("run_mode").notNull().default("new_session_per_run"),
2147
+ overlapPolicy: text("overlap_policy").notNull().default("allow_concurrent"),
2148
+ agentConfig: jsonb("agent_config").$type<unknown>().notNull(),
2149
+ reusableSessionId: uuid("reusable_session_id").references(() => sessions.id, {
2150
+ onDelete: "set null",
2151
+ }),
2152
+ variableSetId: uuid("variable_set_id").references(() => workspaceVariableSets.id, {
2153
+ onDelete: "restrict",
2154
+ }),
2155
+ // The rig this task's runs ride; the active version is resolved per fire
2156
+ // (migration 0047). NULL ⇒ no rig. FK (-> rigs(id) ON DELETE SET NULL) lives
2157
+ // in migration 0047 (forward-reference pattern). Consumed in M3.
2158
+ rigId: uuid("rig_id"),
2159
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
2160
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2161
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2162
+ },
2163
+ (table) => ({
2164
+ temporalScheduleId: uniqueIndex("scheduled_tasks_workspace_temporal_schedule_id_idx").on(
2165
+ table.workspaceId,
2166
+ table.temporalScheduleId,
2167
+ ),
2168
+ status: index("scheduled_tasks_workspace_status_idx").on(table.workspaceId, table.status),
2169
+ variableSet: index("scheduled_tasks_variable_set_idx").on(
2170
+ table.workspaceId,
2171
+ table.variableSetId,
2172
+ ),
2173
+ }),
2174
+ );
2175
+
2176
+ export const scheduledTaskRuns = pgTable(
2177
+ "scheduled_task_runs",
2178
+ {
2179
+ id: uuid("id").primaryKey().defaultRandom(),
2180
+ accountId: uuid("account_id")
2181
+ .notNull()
2182
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2183
+ workspaceId: uuid("workspace_id")
2184
+ .notNull()
2185
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2186
+ taskId: uuid("task_id")
2187
+ .notNull()
2188
+ .references(() => scheduledTasks.id, { onDelete: "cascade" }),
2189
+ status: text("status").notNull().default("queued"),
2190
+ triggerType: text("trigger_type").notNull(),
2191
+ scheduledAt: timestamp("scheduled_at", { withTimezone: true }),
2192
+ firedAt: timestamp("fired_at", { withTimezone: true }).notNull().defaultNow(),
2193
+ sessionId: uuid("session_id").references(() => sessions.id, { onDelete: "set null" }),
2194
+ triggerEventId: uuid("trigger_event_id"),
2195
+ // Stable Temporal producer identity. Activity replay/re-dispatch returns
2196
+ // the exact run instead of allocating a second schedule source row.
2197
+ producerKey: text("producer_key"),
2198
+ error: text("error"),
2199
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2200
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2201
+ },
2202
+ (table) => ({
2203
+ taskCreated: index("scheduled_task_runs_workspace_task_created_idx").on(
2204
+ table.workspaceId,
2205
+ table.taskId,
2206
+ table.createdAt,
2207
+ ),
2208
+ session: index("scheduled_task_runs_workspace_session_idx").on(
2209
+ table.workspaceId,
2210
+ table.sessionId,
2211
+ ),
2212
+ producer: uniqueIndex("scheduled_task_runs_producer_key_uq")
2213
+ .on(table.workspaceId, table.producerKey)
2214
+ .where(sql`${table.producerKey} is not null`),
2215
+ }),
2216
+ );
2217
+
2218
+ export const githubInstallations = pgTable(
2219
+ "github_installations",
2220
+ {
2221
+ id: uuid("id").primaryKey().defaultRandom(),
2222
+ accountId: uuid("account_id")
2223
+ .notNull()
2224
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2225
+ workspaceId: uuid("workspace_id")
2226
+ .notNull()
2227
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2228
+ installationId: integer("installation_id").notNull(),
2229
+ accountLogin: text("account_login"),
2230
+ accountType: text("account_type"),
2231
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2232
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2233
+ },
2234
+ (table) => ({
2235
+ workspaceInstallation: uniqueIndex("github_installations_workspace_installation_idx").on(
2236
+ table.workspaceId,
2237
+ table.installationId,
2238
+ ),
2239
+ installation: index("github_installations_installation_idx").on(table.installationId),
2240
+ workspace: index("github_installations_workspace_idx").on(table.workspaceId),
2241
+ }),
2242
+ );
2243
+
2244
+ export const usageEvents = pgTable(
2245
+ "usage_events",
2246
+ {
2247
+ id: uuid("id").primaryKey().defaultRandom(),
2248
+ accountId: uuid("account_id")
2249
+ .notNull()
2250
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2251
+ workspaceId: uuid("workspace_id")
2252
+ .notNull()
2253
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2254
+ subjectId: text("subject_id"),
2255
+ eventType: text("event_type").notNull(),
2256
+ quantity: bigint("quantity", { mode: "number" }).notNull(),
2257
+ unit: text("unit").notNull(),
2258
+ sourceResourceType: text("source_resource_type"),
2259
+ sourceResourceId: text("source_resource_id"),
2260
+ idempotencyKey: text("idempotency_key").notNull(),
2261
+ occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
2262
+ recordedAt: timestamp("recorded_at", { withTimezone: true }).notNull().defaultNow(),
2263
+ exportedToBillingAt: timestamp("exported_to_billing_at", { withTimezone: true }),
2264
+ billingProviderEventId: text("billing_provider_event_id"),
2265
+ },
2266
+ (table) => ({
2267
+ idempotency: uniqueIndex("usage_events_idempotency_idx").on(table.idempotencyKey),
2268
+ workspaceMetric: index("usage_events_workspace_metric_idx").on(
2269
+ table.workspaceId,
2270
+ table.eventType,
2271
+ table.occurredAt,
2272
+ ),
2273
+ accountMetric: index("usage_events_account_metric_idx").on(
2274
+ table.accountId,
2275
+ table.eventType,
2276
+ table.occurredAt,
2277
+ ),
2278
+ }),
2279
+ );
2280
+
2281
+ export const creditLedgerEntries = pgTable(
2282
+ "credit_ledger_entries",
2283
+ {
2284
+ id: uuid("id").primaryKey().defaultRandom(),
2285
+ accountId: uuid("account_id")
2286
+ .notNull()
2287
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2288
+ workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "set null" }),
2289
+ type: text("type").notNull(),
2290
+ amountMicros: bigint("amount_micros", { mode: "number" }).notNull(),
2291
+ currency: text("currency").notNull().default("usd"),
2292
+ sourceType: text("source_type"),
2293
+ sourceId: text("source_id"),
2294
+ idempotencyKey: text("idempotency_key").notNull(),
2295
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
2296
+ occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
2297
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2298
+ },
2299
+ (table) => ({
2300
+ idempotency: uniqueIndex("credit_ledger_entries_idempotency_idx").on(table.idempotencyKey),
2301
+ accountCreated: index("credit_ledger_entries_account_created_idx").on(
2302
+ table.accountId,
2303
+ table.createdAt,
2304
+ ),
2305
+ }),
2306
+ );
2307
+
2308
+ export const billingCustomers = pgTable(
2309
+ "billing_customers",
2310
+ {
2311
+ id: uuid("id").primaryKey().defaultRandom(),
2312
+ accountId: uuid("account_id")
2313
+ .notNull()
2314
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2315
+ provider: text("provider").notNull().default("stripe"),
2316
+ providerCustomerId: text("provider_customer_id").notNull(),
2317
+ email: text("email"),
2318
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2319
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2320
+ },
2321
+ (table) => ({
2322
+ accountProvider: uniqueIndex("billing_customers_account_provider_idx").on(
2323
+ table.accountId,
2324
+ table.provider,
2325
+ ),
2326
+ providerCustomer: uniqueIndex("billing_customers_provider_customer_idx").on(
2327
+ table.provider,
2328
+ table.providerCustomerId,
2329
+ ),
2330
+ }),
2331
+ );
1121
2332
 
1122
2333
  export const stripeWebhookEvents = pgTable("stripe_webhook_events", {
1123
2334
  id: text("id").primaryKey(),
@@ -1128,160 +2339,385 @@ export const stripeWebhookEvents = pgTable("stripe_webhook_events", {
1128
2339
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1129
2340
  });
1130
2341
 
1131
- export const auditEvents = pgTable("audit_events", {
1132
- id: uuid("id").primaryKey().defaultRandom(),
1133
- accountId: uuid("account_id").references(() => managedAccounts.id, { onDelete: "set null" }),
1134
- workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "set null" }),
1135
- subjectId: text("subject_id"),
1136
- action: text("action").notNull(),
1137
- targetType: text("target_type"),
1138
- targetId: text("target_id"),
1139
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
1140
- occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
1141
- }, (table) => ({
1142
- accountCreated: index("audit_events_account_created_idx").on(table.accountId, table.occurredAt),
1143
- workspaceCreated: index("audit_events_workspace_created_idx").on(table.workspaceId, table.occurredAt),
1144
- }));
1145
-
1146
- export const packInstallations = pgTable("pack_installations", {
1147
- id: uuid("id").primaryKey().defaultRandom(),
1148
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1149
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1150
- packId: text("pack_id").notNull(),
1151
- status: text("status").notNull().default("active"),
1152
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
1153
- enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
1154
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1155
- }, (table) => ({
1156
- workspacePack: uniqueIndex("pack_installations_workspace_pack_idx").on(table.workspaceId, table.packId),
1157
- status: index("pack_installations_workspace_status_idx").on(table.workspaceId, table.status),
1158
- }));
1159
-
1160
- export const workspacePacks = pgTable("workspace_packs", {
1161
- id: uuid("id").primaryKey().defaultRandom(),
1162
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1163
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1164
- packId: text("pack_id").notNull(),
1165
- manifest: jsonb("manifest").$type<Record<string, unknown>>().notNull(),
1166
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1167
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1168
- }, (table) => ({
1169
- workspacePack: uniqueIndex("workspace_packs_workspace_pack_idx").on(table.workspaceId, table.packId),
1170
- }));
1171
-
1172
- export const importBatches = pgTable("import_batches", {
1173
- id: uuid("id").primaryKey().defaultRandom(),
1174
- source: text("source").notNull(),
1175
- snapshotDate: timestamp("snapshot_date", { withTimezone: true }).notNull(),
1176
- snapshotRef: text("snapshot_ref"),
1177
- attributionNote: text("attribution_note").notNull(),
1178
- importedCount: integer("imported_count").notNull().default(0),
1179
- skippedCount: integer("skipped_count").notNull().default(0),
1180
- quarantinedCount: integer("quarantined_count").notNull().default(0),
1181
- logoFailureCount: integer("logo_failure_count").notNull().default(0),
1182
- staleCount: integer("stale_count").notNull().default(0),
1183
- details: jsonb("details").$type<Record<string, unknown>>().notNull().default({}),
1184
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1185
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1186
- }, (table) => ({
1187
- sourceSnapshot: index("import_batches_source_snapshot_idx").on(table.source, table.snapshotDate),
1188
- createdAt: index("import_batches_created_at_idx").on(table.createdAt),
1189
- }));
1190
-
1191
- export const capabilityCatalogItems = pgTable("capability_catalog_items", {
1192
- id: text("id").notNull(),
1193
- accountId: uuid("account_id").references(() => managedAccounts.id, { onDelete: "cascade" }),
1194
- workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }),
1195
- kind: text("kind").notNull(),
1196
- source: text("source").notNull().default("manual"),
1197
- name: text("name").notNull(),
1198
- description: text("description"),
1199
- category: text("category").notNull().default("custom"),
1200
- tags: jsonb("tags").$type<string[]>().notNull().default([]),
1201
- homepageUrl: text("homepage_url"),
1202
- endpointUrl: text("endpoint_url"),
1203
- installUrl: text("install_url"),
1204
- authModel: text("auth_model"),
1205
- providerDomain: text("provider_domain"),
1206
- surfaceType: text("surface_type"),
1207
- transport: text("transport"),
1208
- mcpUrl: text("mcp_url"),
1209
- authKind: text("auth_kind"),
1210
- credentialFacts: jsonb("credential_facts").$type<Array<Record<string, unknown>>>().notNull().default([]),
1211
- tier: text("tier"),
1212
- provenance: text("provenance"),
1213
- logoAssetPath: text("logo_asset_path"),
1214
- importBatchId: uuid("import_batch_id").references(() => importBatches.id, { onDelete: "set null" }),
1215
- stale: boolean("stale").notNull().default(false),
1216
- staleAt: timestamp("stale_at", { withTimezone: true }),
1217
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
1218
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1219
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1220
- }, (table) => ({
1221
- workspaceCapability: uniqueIndex("capability_catalog_items_workspace_capability_idx").on(table.workspaceId, table.id),
1222
- registrySurface: uniqueIndex("capability_catalog_items_registry_surface_idx").on(table.source, table.providerDomain, table.mcpUrl),
1223
- globalCapability: uniqueIndex("capability_catalog_items_global_capability_idx").on(table.id).where(sql`${table.workspaceId} is null`),
1224
- kind: index("capability_catalog_items_workspace_kind_idx").on(table.workspaceId, table.kind),
1225
- category: index("capability_catalog_items_workspace_category_idx").on(table.workspaceId, table.category),
1226
- source: index("capability_catalog_items_workspace_source_idx").on(table.workspaceId, table.source),
1227
- providerDomain: index("capability_catalog_items_provider_domain_idx").on(table.providerDomain),
1228
- importBatch: index("capability_catalog_items_import_batch_idx").on(table.importBatchId),
1229
- stale: index("capability_catalog_items_source_stale_idx").on(table.source, table.stale),
1230
- }));
1231
-
1232
- export const capabilityInstallations = pgTable("capability_installations", {
1233
- id: uuid("id").primaryKey().defaultRandom(),
1234
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1235
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1236
- capabilityId: text("capability_id").notNull(),
1237
- kind: text("kind").notNull(),
1238
- status: text("status").notNull().default("active"),
1239
- config: jsonb("config").$type<Record<string, unknown>>().notNull().default({}),
1240
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
1241
- enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
1242
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1243
- }, (table) => ({
1244
- workspaceCapability: uniqueIndex("capability_installations_workspace_capability_idx").on(table.workspaceId, table.capabilityId),
1245
- kind: index("capability_installations_workspace_kind_idx").on(table.workspaceId, table.kind),
1246
- status: index("capability_installations_workspace_status_idx").on(table.workspaceId, table.status),
1247
- }));
1248
-
1249
- export const socialConnections = pgTable("social_connections", {
1250
- id: uuid("id").primaryKey().defaultRandom(),
1251
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1252
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1253
- provider: text("provider").notNull(),
1254
- accountHandle: text("account_handle").notNull(),
1255
- accountName: text("account_name"),
1256
- externalAccountId: text("external_account_id"),
1257
- status: text("status").notNull().default("connected"),
1258
- scopes: jsonb("scopes").$type<string[]>().notNull().default([]),
1259
- credentialRef: text("credential_ref"),
1260
- tokenMetadata: jsonb("token_metadata").$type<Record<string, unknown>>().notNull().default({}),
1261
- metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
1262
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1263
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1264
- }, (table) => ({
1265
- workspaceProviderHandle: uniqueIndex("social_connections_workspace_provider_handle_idx").on(table.workspaceId, table.provider, table.accountHandle),
1266
- providerStatus: index("social_connections_workspace_provider_status_idx").on(table.workspaceId, table.provider, table.status),
1267
- }));
1268
-
1269
- export const socialPosts = pgTable("social_posts", {
1270
- id: uuid("id").primaryKey().defaultRandom(),
1271
- accountId: uuid("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1272
- workspaceId: uuid("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1273
- connectionId: uuid("connection_id").notNull().references(() => socialConnections.id, { onDelete: "cascade" }),
1274
- provider: text("provider").notNull(),
1275
- externalPostId: text("external_post_id"),
1276
- url: text("url"),
1277
- authorHandle: text("author_handle"),
1278
- text: text("text").notNull(),
1279
- publishedAt: timestamp("published_at", { withTimezone: true }).notNull(),
1280
- metrics: jsonb("metrics").$type<Record<string, number>>().notNull().default({}),
1281
- raw: jsonb("raw").$type<Record<string, unknown>>().notNull().default({}),
1282
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1283
- }, (table) => ({
1284
- connectionExternalPost: uniqueIndex("social_posts_workspace_connection_external_post_idx").on(table.workspaceId, table.connectionId, table.externalPostId),
1285
- connectionPublished: index("social_posts_workspace_connection_published_idx").on(table.workspaceId, table.connectionId, table.publishedAt),
1286
- providerPublished: index("social_posts_workspace_provider_published_idx").on(table.workspaceId, table.provider, table.publishedAt),
1287
- }));
2342
+ export const auditEvents = pgTable(
2343
+ "audit_events",
2344
+ {
2345
+ id: uuid("id").primaryKey().defaultRandom(),
2346
+ accountId: uuid("account_id").references(() => managedAccounts.id, { onDelete: "set null" }),
2347
+ workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "set null" }),
2348
+ subjectId: text("subject_id"),
2349
+ action: text("action").notNull(),
2350
+ targetType: text("target_type"),
2351
+ targetId: text("target_id"),
2352
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
2353
+ occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull().defaultNow(),
2354
+ },
2355
+ (table) => ({
2356
+ accountCreated: index("audit_events_account_created_idx").on(table.accountId, table.occurredAt),
2357
+ workspaceCreated: index("audit_events_workspace_created_idx").on(
2358
+ table.workspaceId,
2359
+ table.occurredAt,
2360
+ ),
2361
+ }),
2362
+ );
2363
+
2364
+ export const packInstallations = pgTable(
2365
+ "pack_installations",
2366
+ {
2367
+ id: uuid("id").primaryKey().defaultRandom(),
2368
+ accountId: uuid("account_id")
2369
+ .notNull()
2370
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2371
+ workspaceId: uuid("workspace_id")
2372
+ .notNull()
2373
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2374
+ packId: text("pack_id").notNull(),
2375
+ status: text("status").notNull().default("active"),
2376
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
2377
+ enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
2378
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2379
+ },
2380
+ (table) => ({
2381
+ workspacePack: uniqueIndex("pack_installations_workspace_pack_idx").on(
2382
+ table.workspaceId,
2383
+ table.packId,
2384
+ ),
2385
+ status: index("pack_installations_workspace_status_idx").on(table.workspaceId, table.status),
2386
+ }),
2387
+ );
2388
+
2389
+ export const workspacePacks = pgTable(
2390
+ "workspace_packs",
2391
+ {
2392
+ id: uuid("id").primaryKey().defaultRandom(),
2393
+ accountId: uuid("account_id")
2394
+ .notNull()
2395
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2396
+ workspaceId: uuid("workspace_id")
2397
+ .notNull()
2398
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2399
+ packId: text("pack_id").notNull(),
2400
+ manifest: jsonb("manifest").$type<Record<string, unknown>>().notNull(),
2401
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2402
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2403
+ },
2404
+ (table) => ({
2405
+ workspacePack: uniqueIndex("workspace_packs_workspace_pack_idx").on(
2406
+ table.workspaceId,
2407
+ table.packId,
2408
+ ),
2409
+ }),
2410
+ );
2411
+
2412
+ export const importBatches = pgTable(
2413
+ "import_batches",
2414
+ {
2415
+ id: uuid("id").primaryKey().defaultRandom(),
2416
+ source: text("source").notNull(),
2417
+ snapshotDate: timestamp("snapshot_date", { withTimezone: true }).notNull(),
2418
+ snapshotRef: text("snapshot_ref"),
2419
+ attributionNote: text("attribution_note").notNull(),
2420
+ importedCount: integer("imported_count").notNull().default(0),
2421
+ skippedCount: integer("skipped_count").notNull().default(0),
2422
+ quarantinedCount: integer("quarantined_count").notNull().default(0),
2423
+ logoFailureCount: integer("logo_failure_count").notNull().default(0),
2424
+ staleCount: integer("stale_count").notNull().default(0),
2425
+ details: jsonb("details").$type<Record<string, unknown>>().notNull().default({}),
2426
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2427
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2428
+ },
2429
+ (table) => ({
2430
+ sourceSnapshot: index("import_batches_source_snapshot_idx").on(
2431
+ table.source,
2432
+ table.snapshotDate,
2433
+ ),
2434
+ createdAt: index("import_batches_created_at_idx").on(table.createdAt),
2435
+ }),
2436
+ );
2437
+
2438
+ export const capabilityCatalogItems = pgTable(
2439
+ "capability_catalog_items",
2440
+ {
2441
+ id: text("id").notNull(),
2442
+ accountId: uuid("account_id").references(() => managedAccounts.id, { onDelete: "cascade" }),
2443
+ workspaceId: uuid("workspace_id").references(() => workspaces.id, { onDelete: "cascade" }),
2444
+ kind: text("kind").notNull(),
2445
+ source: text("source").notNull().default("manual"),
2446
+ name: text("name").notNull(),
2447
+ description: text("description"),
2448
+ category: text("category").notNull().default("custom"),
2449
+ tags: jsonb("tags").$type<string[]>().notNull().default([]),
2450
+ homepageUrl: text("homepage_url"),
2451
+ endpointUrl: text("endpoint_url"),
2452
+ installUrl: text("install_url"),
2453
+ authModel: text("auth_model"),
2454
+ providerDomain: text("provider_domain"),
2455
+ surfaceType: text("surface_type"),
2456
+ transport: text("transport"),
2457
+ mcpUrl: text("mcp_url"),
2458
+ authKind: text("auth_kind"),
2459
+ credentialFacts: jsonb("credential_facts")
2460
+ .$type<Array<Record<string, unknown>>>()
2461
+ .notNull()
2462
+ .default([]),
2463
+ tier: text("tier"),
2464
+ provenance: text("provenance"),
2465
+ logoAssetPath: text("logo_asset_path"),
2466
+ importBatchId: uuid("import_batch_id").references(() => importBatches.id, {
2467
+ onDelete: "set null",
2468
+ }),
2469
+ stale: boolean("stale").notNull().default(false),
2470
+ staleAt: timestamp("stale_at", { withTimezone: true }),
2471
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
2472
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2473
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2474
+ },
2475
+ (table) => ({
2476
+ workspaceCapability: uniqueIndex("capability_catalog_items_workspace_capability_idx").on(
2477
+ table.workspaceId,
2478
+ table.id,
2479
+ ),
2480
+ registrySurface: uniqueIndex("capability_catalog_items_registry_surface_idx").on(
2481
+ table.source,
2482
+ table.providerDomain,
2483
+ table.mcpUrl,
2484
+ ),
2485
+ globalCapability: uniqueIndex("capability_catalog_items_global_capability_idx")
2486
+ .on(table.id)
2487
+ .where(sql`${table.workspaceId} is null`),
2488
+ kind: index("capability_catalog_items_workspace_kind_idx").on(table.workspaceId, table.kind),
2489
+ category: index("capability_catalog_items_workspace_category_idx").on(
2490
+ table.workspaceId,
2491
+ table.category,
2492
+ ),
2493
+ source: index("capability_catalog_items_workspace_source_idx").on(
2494
+ table.workspaceId,
2495
+ table.source,
2496
+ ),
2497
+ providerDomain: index("capability_catalog_items_provider_domain_idx").on(table.providerDomain),
2498
+ importBatch: index("capability_catalog_items_import_batch_idx").on(table.importBatchId),
2499
+ stale: index("capability_catalog_items_source_stale_idx").on(table.source, table.stale),
2500
+ }),
2501
+ );
2502
+
2503
+ export const capabilityInstallations = pgTable(
2504
+ "capability_installations",
2505
+ {
2506
+ id: uuid("id").primaryKey().defaultRandom(),
2507
+ accountId: uuid("account_id")
2508
+ .notNull()
2509
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2510
+ workspaceId: uuid("workspace_id")
2511
+ .notNull()
2512
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2513
+ capabilityId: text("capability_id").notNull(),
2514
+ kind: text("kind").notNull(),
2515
+ status: text("status").notNull().default("active"),
2516
+ config: jsonb("config").$type<Record<string, unknown>>().notNull().default({}),
2517
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
2518
+ enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(),
2519
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2520
+ },
2521
+ (table) => ({
2522
+ workspaceCapability: uniqueIndex("capability_installations_workspace_capability_idx").on(
2523
+ table.workspaceId,
2524
+ table.capabilityId,
2525
+ ),
2526
+ kind: index("capability_installations_workspace_kind_idx").on(table.workspaceId, table.kind),
2527
+ status: index("capability_installations_workspace_status_idx").on(
2528
+ table.workspaceId,
2529
+ table.status,
2530
+ ),
2531
+ }),
2532
+ );
2533
+
2534
+ export const socialConnections = pgTable(
2535
+ "social_connections",
2536
+ {
2537
+ id: uuid("id").primaryKey().defaultRandom(),
2538
+ accountId: uuid("account_id")
2539
+ .notNull()
2540
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2541
+ workspaceId: uuid("workspace_id")
2542
+ .notNull()
2543
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2544
+ provider: text("provider").notNull(),
2545
+ accountHandle: text("account_handle").notNull(),
2546
+ accountName: text("account_name"),
2547
+ externalAccountId: text("external_account_id"),
2548
+ status: text("status").notNull().default("connected"),
2549
+ scopes: jsonb("scopes").$type<string[]>().notNull().default([]),
2550
+ credentialRef: text("credential_ref"),
2551
+ tokenMetadata: jsonb("token_metadata").$type<Record<string, unknown>>().notNull().default({}),
2552
+ metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
2553
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2554
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2555
+ },
2556
+ (table) => ({
2557
+ workspaceProviderHandle: uniqueIndex("social_connections_workspace_provider_handle_idx").on(
2558
+ table.workspaceId,
2559
+ table.provider,
2560
+ table.accountHandle,
2561
+ ),
2562
+ providerStatus: index("social_connections_workspace_provider_status_idx").on(
2563
+ table.workspaceId,
2564
+ table.provider,
2565
+ table.status,
2566
+ ),
2567
+ }),
2568
+ );
2569
+
2570
+ export const socialPosts = pgTable(
2571
+ "social_posts",
2572
+ {
2573
+ id: uuid("id").primaryKey().defaultRandom(),
2574
+ accountId: uuid("account_id")
2575
+ .notNull()
2576
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2577
+ workspaceId: uuid("workspace_id")
2578
+ .notNull()
2579
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2580
+ connectionId: uuid("connection_id")
2581
+ .notNull()
2582
+ .references(() => socialConnections.id, { onDelete: "cascade" }),
2583
+ provider: text("provider").notNull(),
2584
+ externalPostId: text("external_post_id"),
2585
+ url: text("url"),
2586
+ authorHandle: text("author_handle"),
2587
+ text: text("text").notNull(),
2588
+ publishedAt: timestamp("published_at", { withTimezone: true }).notNull(),
2589
+ metrics: jsonb("metrics").$type<Record<string, number>>().notNull().default({}),
2590
+ raw: jsonb("raw").$type<Record<string, unknown>>().notNull().default({}),
2591
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2592
+ },
2593
+ (table) => ({
2594
+ connectionExternalPost: uniqueIndex("social_posts_workspace_connection_external_post_idx").on(
2595
+ table.workspaceId,
2596
+ table.connectionId,
2597
+ table.externalPostId,
2598
+ ),
2599
+ connectionPublished: index("social_posts_workspace_connection_published_idx").on(
2600
+ table.workspaceId,
2601
+ table.connectionId,
2602
+ table.publishedAt,
2603
+ ),
2604
+ providerPublished: index("social_posts_workspace_provider_published_idx").on(
2605
+ table.workspaceId,
2606
+ table.provider,
2607
+ table.publishedAt,
2608
+ ),
2609
+ }),
2610
+ );
2611
+
2612
+ // Rigs (migration 0047): workspace-scoped, versioned sandbox machine definitions.
2613
+ // A rig is the named truth; each sandbox is a disposable fork of a rig version.
2614
+ export const rigs = pgTable(
2615
+ "rigs",
2616
+ {
2617
+ id: uuid("id").primaryKey().defaultRandom(),
2618
+ accountId: uuid("account_id")
2619
+ .notNull()
2620
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2621
+ workspaceId: uuid("workspace_id")
2622
+ .notNull()
2623
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2624
+ name: text("name").notNull(),
2625
+ description: text("description"),
2626
+ // Attribution string: 'user:<subject>' | 'session:<id>' | 'system'.
2627
+ createdBy: text("created_by"),
2628
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2629
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2630
+ },
2631
+ (table) => ({
2632
+ workspaceName: uniqueIndex("rigs_workspace_name_idx").on(table.workspaceId, table.name),
2633
+ workspaceCreated: index("rigs_workspace_created_idx").on(table.workspaceId, table.createdAt),
2634
+ }),
2635
+ );
2636
+
2637
+ // Append-only, content-immutable rig versions. Exactly one active per rig
2638
+ // (partial unique index). The domain layer never UPDATEs a content column; only
2639
+ // the `active` flag flips (activateRigVersion).
2640
+ export const rigVersions = pgTable(
2641
+ "rig_versions",
2642
+ {
2643
+ id: uuid("id").primaryKey().defaultRandom(),
2644
+ accountId: uuid("account_id")
2645
+ .notNull()
2646
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2647
+ workspaceId: uuid("workspace_id")
2648
+ .notNull()
2649
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2650
+ rigId: uuid("rig_id")
2651
+ .notNull()
2652
+ .references(() => rigs.id, { onDelete: "cascade" }),
2653
+ version: integer("version").notNull(),
2654
+ image: text("image"),
2655
+ setupScript: text("setup_script"),
2656
+ // Self-declared health checks: [{ name, command }].
2657
+ checks: jsonb("checks").$type<Array<{ name: string; command: string }>>().notNull().default([]),
2658
+ // Registered credential-hook names (resolved to hook implementations in M3).
2659
+ credentialHooks: jsonb("credential_hooks").$type<string[]>().notNull().default([]),
2660
+ // Variable-set ids layered below the session's variable set at run time (M3).
2661
+ defaultVariableSetIds: jsonb("default_variable_set_ids")
2662
+ .$type<string[]>()
2663
+ .notNull()
2664
+ .default([]),
2665
+ changelog: text("changelog"),
2666
+ createdBy: text("created_by"),
2667
+ active: boolean("active").notNull().default(false),
2668
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2669
+ },
2670
+ (table) => ({
2671
+ rigVersion: uniqueIndex("rig_versions_rig_version_idx").on(table.rigId, table.version),
2672
+ // At most one active version per rig — the single-active invariant, in the DB.
2673
+ rigActive: uniqueIndex("rig_versions_rig_active_idx")
2674
+ .on(table.rigId)
2675
+ .where(sql`${table.active}`),
2676
+ workspaceRig: index("rig_versions_workspace_rig_idx").on(
2677
+ table.workspaceId,
2678
+ table.rigId,
2679
+ table.version,
2680
+ ),
2681
+ }),
2682
+ );
2683
+
2684
+ // Proposed/verified rig changes (M4 substrate). M2 creates the table + CRUD only;
2685
+ // verification/auto-merge/promotion land in M4.
2686
+ export const rigChanges = pgTable(
2687
+ "rig_changes",
2688
+ {
2689
+ id: uuid("id").primaryKey().defaultRandom(),
2690
+ accountId: uuid("account_id")
2691
+ .notNull()
2692
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
2693
+ workspaceId: uuid("workspace_id")
2694
+ .notNull()
2695
+ .references(() => workspaces.id, { onDelete: "cascade" }),
2696
+ rigId: uuid("rig_id")
2697
+ .notNull()
2698
+ .references(() => rigs.id, { onDelete: "cascade" }),
2699
+ baseVersionId: uuid("base_version_id").references(() => rigVersions.id, {
2700
+ onDelete: "set null",
2701
+ }),
2702
+ // 'setup_append' | 'definition_edit' (CHECK in migration 0047).
2703
+ kind: text("kind").notNull(),
2704
+ payload: jsonb("payload").$type<Record<string, unknown>>().notNull(),
2705
+ // 'proposed' | 'verifying' | 'merged' | 'rejected' | 'failed' (CHECK in 0047).
2706
+ status: text("status").notNull().default("proposed"),
2707
+ proposedBy: text("proposed_by"),
2708
+ verification: jsonb("verification").$type<Record<string, unknown>>(),
2709
+ resultVersionId: uuid("result_version_id").references(() => rigVersions.id, {
2710
+ onDelete: "set null",
2711
+ }),
2712
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2713
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
2714
+ },
2715
+ (table) => ({
2716
+ workspaceRig: index("rig_changes_workspace_rig_idx").on(
2717
+ table.workspaceId,
2718
+ table.rigId,
2719
+ table.createdAt,
2720
+ ),
2721
+ workspaceStatus: index("rig_changes_workspace_status_idx").on(table.workspaceId, table.status),
2722
+ }),
2723
+ );