@opengeni/db 0.14.0 → 0.16.2

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 (63) hide show
  1. package/dist/{chunk-ELMUCYZF.js → chunk-4RUK5CON.js} +183 -42
  2. package/dist/chunk-4RUK5CON.js.map +1 -0
  3. package/dist/chunk-HZD7KVAR.js +4648 -0
  4. package/dist/chunk-HZD7KVAR.js.map +1 -0
  5. package/dist/{chunk-Y5WZZVQK.js → chunk-SK7YYHBI.js} +5 -2
  6. package/dist/chunk-SK7YYHBI.js.map +1 -0
  7. package/dist/codex-token-resolver.d.ts +64 -0
  8. package/dist/connection-token-resolver.d.ts +90 -0
  9. package/dist/environment-crypto.d.ts +11 -0
  10. package/dist/event-payload-sanitizer.d.ts +32 -0
  11. package/dist/index.d.ts +6217 -10
  12. package/dist/index.js +6992 -2728
  13. package/dist/index.js.map +1 -1
  14. package/dist/insights.d.ts +157 -0
  15. package/dist/memory-domain.d.ts +44 -0
  16. package/dist/migrate.d.ts +5 -7
  17. package/dist/migrate.js +1 -1
  18. package/dist/new-session-drafts.d.ts +49 -0
  19. package/dist/persistence-errors.d.ts +69 -0
  20. package/dist/preference-registry-schema.d.ts +1147 -0
  21. package/dist/preference-registry.d.ts +878 -0
  22. package/dist/provision-roles.d.ts +4 -6478
  23. package/dist/provision-roles.js +1 -1
  24. package/dist/role-relationships.d.ts +35 -0
  25. package/dist/runtime-posture-cli.d.ts +1 -0
  26. package/dist/runtime-posture.d.ts +103 -0
  27. package/dist/schema.d.ts +23533 -3
  28. package/dist/schema.js +17 -1
  29. package/dist/session-control.d.ts +331 -0
  30. package/dist/session-queue-commands.d.ts +186 -0
  31. package/dist/session-tool-call-settlement.d.ts +32 -0
  32. package/dist/turn-initiator.d.ts +28 -0
  33. package/dist/workspace-instruction-policies-schema.d.ts +735 -0
  34. package/dist/workspace-instruction-policies.d.ts +64 -0
  35. package/drizzle/0136_unified_session_tool_policy.sql +109 -0
  36. package/drizzle/0137_preference_registry.sql +1347 -0
  37. package/drizzle/0138_sandbox_checkpoint_artifacts_and_deadlines.sql +1074 -0
  38. package/drizzle/0139_codex_provider_artifact_invalidations.sql +51 -0
  39. package/drizzle/0140_sandbox_restore_and_reaper_fences.sql +276 -0
  40. package/drizzle/0142_sandbox_archive_capture_gate.sql +80 -0
  41. package/drizzle/0143_session_codex_compaction_mode.sql +20 -0
  42. package/drizzle/0144_sandbox_viewer_force_drain_gate.sql +95 -0
  43. package/drizzle/0145_model_call_facts.sql +96 -0
  44. package/drizzle/0146_slack_bot_delete_idempotency.sql +105 -0
  45. package/drizzle/0147_draft_latency_mode.sql +12 -0
  46. package/drizzle/0148_session_turn_latency_mode.sql +12 -0
  47. package/package.json +6 -6
  48. package/src/index.ts +5095 -430
  49. package/src/insights.ts +837 -0
  50. package/src/migrate.ts +9 -1
  51. package/src/new-session-drafts.ts +4 -0
  52. package/src/preference-registry-schema.ts +170 -0
  53. package/src/preference-registry.ts +1220 -0
  54. package/src/provision-roles.ts +95 -22
  55. package/src/role-relationships.ts +132 -0
  56. package/src/runtime-posture.ts +28 -26
  57. package/src/schema.ts +484 -12
  58. package/src/session-queue-commands.ts +47 -46
  59. package/dist/chunk-ELMUCYZF.js.map +0 -1
  60. package/dist/chunk-PQKVUWQW.js +0 -4047
  61. package/dist/chunk-PQKVUWQW.js.map +0 -1
  62. package/dist/chunk-Y5WZZVQK.js.map +0 -1
  63. package/dist/schema-FoPub9yt.d.ts +0 -22666
@@ -0,0 +1,4648 @@
1
+ import {
2
+ __export
3
+ } from "./chunk-PZ5AY32C.js";
4
+
5
+ // src/schema.ts
6
+ var schema_exports = {};
7
+ __export(schema_exports, {
8
+ agentRunStates: () => agentRunStates,
9
+ apiKeys: () => apiKeys,
10
+ auditEvents: () => auditEvents,
11
+ billingCustomers: () => billingCustomers,
12
+ capabilityCatalogItems: () => capabilityCatalogItems,
13
+ capabilityInstallations: () => capabilityInstallations,
14
+ codexCapacityWaiters: () => codexCapacityWaiters,
15
+ codexCredentialLeases: () => codexCredentialLeases,
16
+ codexResetRedemptionAttempts: () => codexResetRedemptionAttempts,
17
+ codexRotationSettings: () => codexRotationSettings,
18
+ codexSubscriptionCredentials: () => codexSubscriptionCredentials,
19
+ composerDrafts: () => composerDrafts,
20
+ connections: () => connections,
21
+ creditLedgerEntries: () => creditLedgerEntries,
22
+ deviceEnrollmentRequests: () => deviceEnrollmentRequests,
23
+ deviceEnrollmentStatusValues: () => deviceEnrollmentStatusValues,
24
+ documentBases: () => documentBases,
25
+ documentChunks: () => documentChunks,
26
+ documents: () => documents,
27
+ enrollmentExposureValues: () => enrollmentExposureValues,
28
+ enrollmentOsValues: () => enrollmentOsValues,
29
+ enrollmentStatusValues: () => enrollmentStatusValues,
30
+ enrollments: () => enrollments,
31
+ fileUploads: () => fileUploads,
32
+ files: () => files,
33
+ githubInstallationRepositories: () => githubInstallationRepositories,
34
+ githubInstallations: () => githubInstallations,
35
+ hostExportConfig: () => hostExportConfig,
36
+ hostExportConsumers: () => hostExportConsumers,
37
+ hostExportCursorState: () => hostExportCursorState,
38
+ hostExportDeadLetters: () => hostExportDeadLetters,
39
+ hostExportOutbox: () => hostExportOutbox,
40
+ importBatches: () => importBatches,
41
+ integrationOauthClients: () => integrationOauthClients,
42
+ integrationOauthStateNonces: () => integrationOauthStateNonces,
43
+ knowledgeMemories: () => knowledgeMemories,
44
+ machineMetricsLatest: () => machineMetricsLatest,
45
+ machineMetricsSeries: () => machineMetricsSeries,
46
+ managedAccounts: () => managedAccounts,
47
+ modelCallFacts: () => modelCallFacts,
48
+ nestedAgentDepthConfiguration: () => nestedAgentDepthConfiguration,
49
+ newSessionDrafts: () => newSessionDrafts,
50
+ packInstallations: () => packInstallations,
51
+ preferenceRegistryEvents: () => preferenceRegistryEvents,
52
+ preferenceRegistryPreferences: () => preferenceRegistryPreferences,
53
+ preferenceRegistryRevisions: () => preferenceRegistryRevisions,
54
+ preferenceRegistrySnapshots: () => preferenceRegistrySnapshots,
55
+ rigChanges: () => rigChanges,
56
+ rigVersions: () => rigVersions,
57
+ rigs: () => rigs,
58
+ sandboxCheckpointArtifactStateValues: () => sandboxCheckpointArtifactStateValues,
59
+ sandboxCheckpointArtifacts: () => sandboxCheckpointArtifacts,
60
+ sandboxKindValues: () => sandboxKindValues,
61
+ sandboxLeaseHolders: () => sandboxLeaseHolders,
62
+ sandboxLeaseLivenessValues: () => sandboxLeaseLivenessValues,
63
+ sandboxLeases: () => sandboxLeases,
64
+ sandboxPtySessions: () => sandboxPtySessions,
65
+ sandboxRetainedProcessStateValues: () => sandboxRetainedProcessStateValues,
66
+ sandboxRetainedProcesses: () => sandboxRetainedProcesses,
67
+ sandboxSessionEnvelopes: () => sandboxSessionEnvelopes,
68
+ sandboxWorkspaceMutationActorKindValues: () => sandboxWorkspaceMutationActorKindValues,
69
+ sandboxWorkspaceMutationAdmissions: () => sandboxWorkspaceMutationAdmissions,
70
+ sandboxWorkspaceMutationHolderKindValues: () => sandboxWorkspaceMutationHolderKindValues,
71
+ sandboxes: () => sandboxes,
72
+ scheduledTaskRuns: () => scheduledTaskRuns,
73
+ scheduledTasks: () => scheduledTasks,
74
+ sessionAttemptInterruptions: () => sessionAttemptInterruptions,
75
+ sessionCommandReceipts: () => sessionCommandReceipts,
76
+ sessionEvents: () => sessionEvents,
77
+ sessionGoals: () => sessionGoals,
78
+ sessionHistoryItems: () => sessionHistoryItems,
79
+ sessionHumanInputRequests: () => sessionHumanInputRequests,
80
+ sessionListSnapshots: () => sessionListSnapshots,
81
+ sessionMcpServers: () => sessionMcpServers,
82
+ sessionPendingToolCalls: () => sessionPendingToolCalls,
83
+ sessionPins: () => sessionPins,
84
+ sessionRecordingCodecValues: () => sessionRecordingCodecValues,
85
+ sessionRecordingModeValues: () => sessionRecordingModeValues,
86
+ sessionRecordingStateValues: () => sessionRecordingStateValues,
87
+ sessionRecordings: () => sessionRecordings,
88
+ sessionSpawnDenials: () => sessionSpawnDenials,
89
+ sessionSystemUpdateOutbox: () => sessionSystemUpdateOutbox,
90
+ sessionSystemUpdates: () => sessionSystemUpdates,
91
+ sessionTurnAttempts: () => sessionTurnAttempts,
92
+ sessionTurns: () => sessionTurns,
93
+ sessionWorkflowWakeOutbox: () => sessionWorkflowWakeOutbox,
94
+ sessions: () => sessions,
95
+ slackBotDeleteOperations: () => slackBotDeleteOperations,
96
+ slackBotPostOperations: () => slackBotPostOperations,
97
+ socialConnections: () => socialConnections,
98
+ socialPosts: () => socialPosts,
99
+ stripeWebhookEvents: () => stripeWebhookEvents,
100
+ usageEvents: () => usageEvents,
101
+ workspaceCaptures: () => workspaceCaptures,
102
+ workspaceControlEvents: () => workspaceControlEvents,
103
+ workspaceInferenceControls: () => workspaceInferenceControls,
104
+ workspaceInstructionPolicyActivationEvents: () => workspaceInstructionPolicyActivationEvents,
105
+ workspaceInstructionPolicyHeads: () => workspaceInstructionPolicyHeads,
106
+ workspaceInstructionPolicyRevisions: () => workspaceInstructionPolicyRevisions,
107
+ workspaceMemberships: () => workspaceMemberships,
108
+ workspaceModelPolicies: () => workspaceModelPolicies,
109
+ workspacePacks: () => workspacePacks,
110
+ workspaceSessionActivityRevisions: () => workspaceSessionActivityRevisions,
111
+ workspaceVariableSetVariables: () => workspaceVariableSetVariables,
112
+ workspaceVariableSets: () => workspaceVariableSets,
113
+ workspaces: () => workspaces
114
+ });
115
+ import { sql as sql3 } from "drizzle-orm";
116
+ import {
117
+ bigint as bigint3,
118
+ boolean as boolean2,
119
+ check as check3,
120
+ foreignKey,
121
+ index as index3,
122
+ integer as integer2,
123
+ jsonb as jsonb2,
124
+ numeric,
125
+ pgTable as pgTable3,
126
+ text as text3,
127
+ timestamp as timestamp3,
128
+ uniqueIndex as uniqueIndex3,
129
+ uuid as uuid3,
130
+ customType
131
+ } from "drizzle-orm/pg-core";
132
+
133
+ // src/workspace-instruction-policies-schema.ts
134
+ import { sql } from "drizzle-orm";
135
+ import {
136
+ bigint,
137
+ check,
138
+ index,
139
+ pgTable,
140
+ text,
141
+ timestamp,
142
+ uniqueIndex,
143
+ uuid
144
+ } from "drizzle-orm/pg-core";
145
+ var workspaceInstructionPolicyRevisions = pgTable(
146
+ "workspace_instruction_policy_revisions",
147
+ {
148
+ id: uuid("id").primaryKey().defaultRandom(),
149
+ accountId: uuid("account_id").notNull(),
150
+ workspaceId: uuid("workspace_id").notNull(),
151
+ revision: bigint("revision", { mode: "number" }).notNull().default(sql`nextval('workspace_instruction_policy_revision_seq')`),
152
+ kind: text("kind").notNull(),
153
+ scope: text("scope").notNull(),
154
+ roleKey: text("role_key"),
155
+ content: text("content").notNull(),
156
+ contentHash: text("content_hash").notNull(),
157
+ provenanceSource: text("provenance_source").notNull(),
158
+ provenanceSourceId: text("provenance_source_id"),
159
+ supersedesRevisionId: uuid("supersedes_revision_id"),
160
+ createdBySubjectId: text("created_by_subject_id").notNull(),
161
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
162
+ },
163
+ (table) => ({
164
+ workspaceRevision: uniqueIndex(
165
+ "workspace_instruction_policy_revisions_workspace_revision_uq"
166
+ ).on(table.workspaceId, table.revision),
167
+ workspaceHistory: index("workspace_instruction_policy_revisions_workspace_history_idx").on(
168
+ table.workspaceId,
169
+ table.kind,
170
+ table.scope,
171
+ table.roleKey,
172
+ table.revision
173
+ ),
174
+ target: check(
175
+ "workspace_instruction_policy_revisions_target_chk",
176
+ sql`(
177
+ (${table.kind} = 'charter' and ${table.scope} = 'global' and ${table.roleKey} is null)
178
+ or (${table.kind} = 'policy' and ${table.scope} = 'global' and ${table.roleKey} is null)
179
+ or (${table.kind} = 'policy' and ${table.scope} = 'role' and ${table.roleKey} is not null)
180
+ )`
181
+ )
182
+ })
183
+ );
184
+ var workspaceInstructionPolicyHeads = pgTable(
185
+ "workspace_instruction_policy_heads",
186
+ {
187
+ id: uuid("id").primaryKey().defaultRandom(),
188
+ accountId: uuid("account_id").notNull(),
189
+ workspaceId: uuid("workspace_id").notNull(),
190
+ kind: text("kind").notNull(),
191
+ scope: text("scope").notNull(),
192
+ roleKey: text("role_key"),
193
+ revisionId: uuid("revision_id").notNull(),
194
+ revision: bigint("revision", { mode: "number" }).notNull(),
195
+ contentHash: text("content_hash").notNull(),
196
+ activationVersion: bigint("activation_version", { mode: "number" }).notNull(),
197
+ activatedAt: timestamp("activated_at", { withTimezone: true }).notNull().defaultNow()
198
+ },
199
+ (table) => ({
200
+ charter: uniqueIndex("workspace_instruction_policy_heads_charter_uq").on(table.workspaceId).where(sql`${table.kind} = 'charter'`),
201
+ globalPolicy: uniqueIndex("workspace_instruction_policy_heads_global_policy_uq").on(table.workspaceId).where(sql`${table.kind} = 'policy' and ${table.scope} = 'global'`),
202
+ rolePolicy: uniqueIndex("workspace_instruction_policy_heads_role_policy_uq").on(table.workspaceId, table.roleKey).where(sql`${table.kind} = 'policy' and ${table.scope} = 'role'`),
203
+ target: check(
204
+ "workspace_instruction_policy_heads_target_chk",
205
+ sql`(
206
+ (${table.kind} = 'charter' and ${table.scope} = 'global' and ${table.roleKey} is null)
207
+ or (${table.kind} = 'policy' and ${table.scope} = 'global' and ${table.roleKey} is null)
208
+ or (${table.kind} = 'policy' and ${table.scope} = 'role' and ${table.roleKey} is not null)
209
+ )`
210
+ )
211
+ })
212
+ );
213
+ var workspaceInstructionPolicyActivationEvents = pgTable(
214
+ "workspace_instruction_policy_activation_events",
215
+ {
216
+ id: uuid("id").primaryKey().defaultRandom(),
217
+ accountId: uuid("account_id").notNull(),
218
+ workspaceId: uuid("workspace_id").notNull(),
219
+ kind: text("kind").notNull(),
220
+ scope: text("scope").notNull(),
221
+ roleKey: text("role_key"),
222
+ type: text("type").notNull(),
223
+ activationVersion: bigint("activation_version", { mode: "number" }).notNull(),
224
+ oldRevisionId: uuid("old_revision_id"),
225
+ oldRevision: bigint("old_revision", { mode: "number" }),
226
+ oldContentHash: text("old_content_hash"),
227
+ newRevisionId: uuid("new_revision_id").notNull(),
228
+ newRevision: bigint("new_revision", { mode: "number" }).notNull(),
229
+ newContentHash: text("new_content_hash").notNull(),
230
+ actorSubjectId: text("actor_subject_id").notNull(),
231
+ reason: text("reason").notNull(),
232
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
233
+ },
234
+ (table) => ({
235
+ workspaceActivationVersion: uniqueIndex(
236
+ "workspace_instruction_policy_events_target_version_uq"
237
+ ).on(
238
+ table.workspaceId,
239
+ table.kind,
240
+ table.scope,
241
+ sql`coalesce(${table.roleKey}, '')`,
242
+ table.activationVersion
243
+ ),
244
+ workspaceTimeline: index("workspace_instruction_policy_events_workspace_time_idx").on(
245
+ table.workspaceId,
246
+ table.createdAt,
247
+ table.id
248
+ ),
249
+ target: check(
250
+ "workspace_instruction_policy_activation_events_target_chk",
251
+ sql`(
252
+ (${table.kind} = 'charter' and ${table.scope} = 'global' and ${table.roleKey} is null)
253
+ or (${table.kind} = 'policy' and ${table.scope} = 'global' and ${table.roleKey} is null)
254
+ or (${table.kind} = 'policy' and ${table.scope} = 'role' and ${table.roleKey} is not null)
255
+ )`
256
+ )
257
+ })
258
+ );
259
+
260
+ // src/preference-registry-schema.ts
261
+ import { sql as sql2 } from "drizzle-orm";
262
+ import {
263
+ bigint as bigint2,
264
+ boolean,
265
+ check as check2,
266
+ index as index2,
267
+ integer,
268
+ jsonb,
269
+ pgTable as pgTable2,
270
+ text as text2,
271
+ timestamp as timestamp2,
272
+ uniqueIndex as uniqueIndex2,
273
+ uuid as uuid2
274
+ } from "drizzle-orm/pg-core";
275
+ var preferenceRegistryPreferences = pgTable2(
276
+ "preference_registry_preferences",
277
+ {
278
+ id: uuid2("id").primaryKey().defaultRandom(),
279
+ accountId: uuid2("account_id").notNull(),
280
+ stableKey: text2("stable_key").notNull(),
281
+ scope: text2("scope").notNull(),
282
+ scopeWorkspaceId: uuid2("scope_workspace_id"),
283
+ scopeSubjectId: text2("scope_subject_id"),
284
+ status: text2("status").notNull().default("proposed"),
285
+ scopeVersion: integer("scope_version").notNull().default(1),
286
+ activationVersion: integer("activation_version").notNull().default(0),
287
+ activeRevisionId: uuid2("active_revision_id"),
288
+ activeRevision: bigint2("active_revision", { mode: "number" }),
289
+ activeContentHash: text2("active_content_hash"),
290
+ supersededByPreferenceId: uuid2("superseded_by_preference_id"),
291
+ createdBySubjectId: text2("created_by_subject_id").notNull(),
292
+ createdAt: timestamp2("created_at", { withTimezone: true }).notNull().defaultNow(),
293
+ updatedAt: timestamp2("updated_at", { withTimezone: true }).notNull().defaultNow()
294
+ },
295
+ (table) => ({
296
+ organizationStableKey: uniqueIndex2("preference_registry_preferences_organization_key_uq").on(table.accountId, table.stableKey).where(sql2`${table.scope} = 'organization'`),
297
+ workspaceStableKey: uniqueIndex2("preference_registry_preferences_workspace_key_uq").on(table.accountId, table.scopeWorkspaceId, table.stableKey).where(sql2`${table.scope} = 'workspace'`),
298
+ userStableKey: uniqueIndex2("preference_registry_preferences_user_key_uq").on(table.accountId, table.scopeSubjectId, table.stableKey).where(sql2`${table.scope} = 'user'`),
299
+ applicable: index2("preference_registry_preferences_applicable_idx").on(
300
+ table.accountId,
301
+ table.scope,
302
+ table.scopeWorkspaceId,
303
+ table.scopeSubjectId,
304
+ table.status,
305
+ table.stableKey
306
+ ),
307
+ scopeShape: check2(
308
+ "preference_registry_preferences_scope_shape_chk",
309
+ sql2`(
310
+ (${table.scope} = 'organization' and ${table.scopeWorkspaceId} is null and ${table.scopeSubjectId} is null)
311
+ or (${table.scope} = 'workspace' and ${table.scopeWorkspaceId} is not null and ${table.scopeSubjectId} is null)
312
+ or (${table.scope} = 'user' and ${table.scopeWorkspaceId} is null and ${table.scopeSubjectId} is not null)
313
+ )`
314
+ )
315
+ })
316
+ );
317
+ var preferenceRegistryRevisions = pgTable2(
318
+ "preference_registry_revisions",
319
+ {
320
+ id: uuid2("id").primaryKey().defaultRandom(),
321
+ accountId: uuid2("account_id").notNull(),
322
+ preferenceId: uuid2("preference_id").notNull(),
323
+ revision: bigint2("revision", { mode: "number" }).notNull().default(sql2`nextval('preference_registry_revision_seq')`),
324
+ title: text2("title").notNull(),
325
+ description: text2("description").notNull(),
326
+ content: text2("content").notNull(),
327
+ contentHash: text2("content_hash").notNull(),
328
+ precedenceRank: integer("precedence_rank").notNull().default(0),
329
+ conflictStrategy: text2("conflict_strategy").notNull(),
330
+ conflictsWith: jsonb("conflicts_with").$type().notNull().default([]),
331
+ provenanceSource: text2("provenance_source").notNull(),
332
+ provenanceSourceId: text2("provenance_source_id"),
333
+ trust: text2("trust").notNull(),
334
+ expiresAt: timestamp2("expires_at", { withTimezone: true }),
335
+ correctsRevisionId: uuid2("corrects_revision_id"),
336
+ createdBySubjectId: text2("created_by_subject_id").notNull(),
337
+ createdAt: timestamp2("created_at", { withTimezone: true }).notNull().defaultNow()
338
+ },
339
+ (table) => ({
340
+ preferenceRevision: uniqueIndex2("preference_registry_revisions_preference_revision_uq").on(
341
+ table.preferenceId,
342
+ table.revision
343
+ ),
344
+ history: index2("preference_registry_revisions_history_idx").on(
345
+ table.preferenceId,
346
+ table.revision
347
+ )
348
+ })
349
+ );
350
+ var preferenceRegistryEvents = pgTable2(
351
+ "preference_registry_events",
352
+ {
353
+ id: uuid2("id").primaryKey().defaultRandom(),
354
+ accountId: uuid2("account_id").notNull(),
355
+ preferenceId: uuid2("preference_id").notNull(),
356
+ type: text2("type").notNull(),
357
+ version: integer("version").notNull(),
358
+ oldRevisionId: uuid2("old_revision_id"),
359
+ newRevisionId: uuid2("new_revision_id"),
360
+ oldScope: text2("old_scope"),
361
+ oldWorkspaceId: uuid2("old_workspace_id"),
362
+ oldSubjectId: text2("old_subject_id"),
363
+ newScope: text2("new_scope"),
364
+ newWorkspaceId: uuid2("new_workspace_id"),
365
+ newSubjectId: text2("new_subject_id"),
366
+ relatedPreferenceId: uuid2("related_preference_id"),
367
+ actorSubjectId: text2("actor_subject_id").notNull(),
368
+ reason: text2("reason").notNull(),
369
+ createdAt: timestamp2("created_at", { withTimezone: true }).notNull().defaultNow()
370
+ },
371
+ (table) => ({
372
+ preferenceVersion: uniqueIndex2("preference_registry_events_preference_version_uq").on(
373
+ table.preferenceId,
374
+ table.version
375
+ ),
376
+ timeline: index2("preference_registry_events_timeline_idx").on(
377
+ table.preferenceId,
378
+ table.createdAt,
379
+ table.id
380
+ )
381
+ })
382
+ );
383
+ var preferenceRegistrySnapshots = pgTable2(
384
+ "preference_registry_snapshots",
385
+ {
386
+ id: uuid2("id").primaryKey().defaultRandom(),
387
+ accountId: uuid2("account_id").notNull(),
388
+ workspaceId: uuid2("workspace_id").notNull(),
389
+ sessionId: uuid2("session_id").notNull(),
390
+ turnId: uuid2("turn_id").notNull(),
391
+ attemptId: uuid2("attempt_id").notNull(),
392
+ executionGeneration: integer("execution_generation").notNull(),
393
+ initiatingHumanSubjectId: text2("initiating_human_subject_id").notNull(),
394
+ descriptors: jsonb("descriptors").$type().notNull(),
395
+ descriptorHash: text2("descriptor_hash").notNull(),
396
+ truncated: boolean("truncated").notNull().default(false),
397
+ createdAt: timestamp2("created_at", { withTimezone: true }).notNull().defaultNow()
398
+ },
399
+ (table) => ({
400
+ attempt: uniqueIndex2("preference_registry_snapshots_attempt_uq").on(
401
+ table.accountId,
402
+ table.workspaceId,
403
+ table.attemptId
404
+ ),
405
+ humanTimeline: index2("preference_registry_snapshots_human_timeline_idx").on(
406
+ table.workspaceId,
407
+ table.initiatingHumanSubjectId,
408
+ table.createdAt
409
+ ),
410
+ descriptorBytes: check2(
411
+ "preference_registry_snapshots_descriptor_bytes_chk",
412
+ sql2`octet_length(convert_to(${table.descriptors}::text, 'UTF8')) <= 16384`
413
+ )
414
+ })
415
+ );
416
+
417
+ // src/schema.ts
418
+ var vector = customType({
419
+ dataType() {
420
+ return "vector(3072)";
421
+ },
422
+ toDriver(value) {
423
+ return `[${value.join(",")}]`;
424
+ }
425
+ });
426
+ var managedAccounts = pgTable3(
427
+ "managed_accounts",
428
+ {
429
+ id: uuid3("id").primaryKey().defaultRandom(),
430
+ name: text3("name").notNull(),
431
+ externalSource: text3("external_source"),
432
+ externalId: text3("external_id"),
433
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
434
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
435
+ },
436
+ (table) => ({
437
+ external: uniqueIndex3("managed_accounts_external_idx").on(
438
+ table.externalSource,
439
+ table.externalId
440
+ )
441
+ })
442
+ );
443
+ var workspaces = pgTable3(
444
+ "workspaces",
445
+ {
446
+ id: uuid3("id").primaryKey().defaultRandom(),
447
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
448
+ name: text3("name").notNull(),
449
+ slug: text3("slug"),
450
+ externalSource: text3("external_source"),
451
+ externalId: text3("external_id"),
452
+ // White-label agent persona template override. NULL means the deployment
453
+ // default (OPENGENI_AGENT_INSTRUCTIONS_TEMPLATE / DEFAULT_AGENT_INSTRUCTIONS).
454
+ agentInstructions: text3("agent_instructions"),
455
+ // Growth-ready per-workspace settings bag (migration 0045). Holds memoryEnabled
456
+ // and future workspace-level toggles; validated/merged via WorkspaceSettingsSchema.
457
+ settings: jsonb2("settings").$type().notNull().default({}),
458
+ // The workspace's default rig (migration 0047). NULL ⇒ no default; sessions
459
+ // created without an explicit rig ride no rig (today's behavior exactly). FK
460
+ // (-> rigs(id) ON DELETE SET NULL) lives in migration 0047, not a Drizzle
461
+ // .references(), because `rigs` is declared later in this file (same
462
+ // forward-reference pattern as sessions.activeSandboxId). Consumed in M3.
463
+ defaultRigId: uuid3("default_rig_id"),
464
+ // Workspace-wide viewer admission intent set by the warm-meter reaper when
465
+ // managed credits or the monthly warm allowance are exhausted. It is
466
+ // deliberately independent of a lease so a dashboard cannot re-arm a
467
+ // draining box or spawn a cold successor before a fresh limit evaluation
468
+ // clears the gate.
469
+ sandboxViewerForceDrainReason: text3("sandbox_viewer_force_drain_reason", {
470
+ enum: ["balance", "warm_cap"]
471
+ }),
472
+ sandboxViewerForceDrainRequestedAt: timestamp3("sandbox_viewer_force_drain_requested_at", {
473
+ withTimezone: true
474
+ }),
475
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
476
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
477
+ },
478
+ (table) => ({
479
+ account: index3("workspaces_account_idx").on(table.accountId),
480
+ accountSlug: uniqueIndex3("workspaces_account_slug_idx").on(table.accountId, table.slug).where(sql3`${table.slug} is not null`),
481
+ external: uniqueIndex3("workspaces_external_idx").on(table.externalSource, table.externalId),
482
+ sandboxViewerForceDrain: index3("workspaces_sandbox_viewer_force_drain_idx").on(table.id).where(sql3`${table.sandboxViewerForceDrainReason} is not null`),
483
+ sandboxViewerForceDrainValid: check3(
484
+ "workspaces_sandbox_viewer_force_drain_check",
485
+ sql3`(
486
+ ${table.sandboxViewerForceDrainReason} is null
487
+ and ${table.sandboxViewerForceDrainRequestedAt} is null
488
+ ) or (
489
+ ${table.sandboxViewerForceDrainReason} in ('balance', 'warm_cap')
490
+ and ${table.sandboxViewerForceDrainRequestedAt} is not null
491
+ )`
492
+ )
493
+ })
494
+ );
495
+ var nestedAgentDepthConfiguration = pgTable3(
496
+ "nested_agent_depth_configuration",
497
+ {
498
+ singleton: boolean2("singleton").primaryKey().notNull().default(true),
499
+ maxNestedAgentDepth: integer2("max_nested_agent_depth").notNull(),
500
+ policySource: text3("policy_source").$type().notNull(),
501
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
502
+ },
503
+ (table) => ({
504
+ singletonOnly: check3(
505
+ "nested_agent_depth_configuration_singleton_check",
506
+ sql3`${table.singleton}`
507
+ ),
508
+ maxValid: check3(
509
+ "nested_agent_depth_configuration_max_check",
510
+ sql3`${table.maxNestedAgentDepth} >= 0`
511
+ ),
512
+ sourceValid: check3(
513
+ "nested_agent_depth_configuration_source_check",
514
+ sql3`${table.policySource} in ('deployment', 'default')`
515
+ )
516
+ })
517
+ );
518
+ var workspaceInferenceControls = pgTable3(
519
+ "workspace_inference_controls",
520
+ {
521
+ workspaceId: uuid3("workspace_id").primaryKey(),
522
+ accountId: uuid3("account_id").notNull(),
523
+ revision: bigint3("revision", { mode: "number" }).notNull().default(0),
524
+ workspaceState: text3("workspace_state").notNull().default("active"),
525
+ workspacePauseRevision: bigint3("workspace_pause_revision", {
526
+ mode: "number"
527
+ }),
528
+ reason: text3("reason"),
529
+ changedBy: text3("changed_by"),
530
+ changedAt: timestamp3("changed_at", { withTimezone: true }),
531
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
532
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
533
+ },
534
+ (table) => ({
535
+ workspaceAccount: foreignKey({
536
+ name: "workspace_inference_controls_workspace_account_fk",
537
+ columns: [table.workspaceId, table.accountId],
538
+ foreignColumns: [workspaces.id, workspaces.accountId]
539
+ }).onDelete("cascade"),
540
+ workspaceAccountIdentity: uniqueIndex3("workspace_inference_controls_workspace_account_uq").on(
541
+ table.workspaceId,
542
+ table.accountId
543
+ ),
544
+ stateValid: check3(
545
+ "workspace_inference_controls_state_check",
546
+ sql3`${table.workspaceState} in ('active', 'paused')`
547
+ ),
548
+ pauseRevisionConsistent: check3(
549
+ "workspace_inference_controls_pause_revision_check",
550
+ sql3`(${table.workspaceState} = 'active' and ${table.workspacePauseRevision} is null)
551
+ or (${table.workspaceState} = 'paused' and ${table.workspacePauseRevision} is not null)`
552
+ ),
553
+ revisionValid: check3(
554
+ "workspace_inference_controls_revision_check",
555
+ sql3`${table.revision} >= 0 and (${table.workspacePauseRevision} is null or ${table.workspacePauseRevision} <= ${table.revision})`
556
+ )
557
+ })
558
+ );
559
+ var workspaceSessionActivityRevisions = pgTable3(
560
+ "workspace_session_activity_revisions",
561
+ {
562
+ workspaceId: uuid3("workspace_id").primaryKey(),
563
+ accountId: uuid3("account_id").notNull(),
564
+ revision: bigint3("revision", { mode: "number" }).notNull().default(0)
565
+ },
566
+ (table) => ({
567
+ workspaceAccount: foreignKey({
568
+ name: "workspace_session_activity_revisions_workspace_account_fk",
569
+ columns: [table.workspaceId, table.accountId],
570
+ foreignColumns: [workspaces.id, workspaces.accountId]
571
+ }).onDelete("cascade"),
572
+ revisionValid: check3(
573
+ "workspace_session_activity_revisions_revision_check",
574
+ sql3`${table.revision} >= 0`
575
+ )
576
+ })
577
+ );
578
+ var workspaceMemberships = pgTable3(
579
+ "workspace_memberships",
580
+ {
581
+ id: uuid3("id").primaryKey().defaultRandom(),
582
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
583
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
584
+ subjectId: text3("subject_id").notNull(),
585
+ subjectLabel: text3("subject_label"),
586
+ role: text3("role").notNull().default("member"),
587
+ permissions: jsonb2("permissions").$type().notNull().default([]),
588
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
589
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
590
+ },
591
+ (table) => ({
592
+ subjectWorkspace: uniqueIndex3("workspace_memberships_subject_workspace_idx").on(
593
+ table.subjectId,
594
+ table.workspaceId
595
+ ),
596
+ subject: index3("workspace_memberships_subject_idx").on(table.subjectId),
597
+ account: index3("workspace_memberships_account_idx").on(table.accountId)
598
+ })
599
+ );
600
+ var apiKeys = pgTable3(
601
+ "api_keys",
602
+ {
603
+ id: uuid3("id").primaryKey().defaultRandom(),
604
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
605
+ workspaceId: uuid3("workspace_id").references(() => workspaces.id, {
606
+ onDelete: "cascade"
607
+ }),
608
+ name: text3("name").notNull(),
609
+ prefix: text3("prefix").notNull(),
610
+ keyHash: text3("key_hash").notNull(),
611
+ permissions: jsonb2("permissions").$type().notNull().default([]),
612
+ expiresAt: timestamp3("expires_at", { withTimezone: true }),
613
+ revokedAt: timestamp3("revoked_at", { withTimezone: true }),
614
+ lastUsedAt: timestamp3("last_used_at", { withTimezone: true }),
615
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
616
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
617
+ },
618
+ (table) => ({
619
+ prefix: index3("api_keys_prefix_idx").on(table.prefix),
620
+ hash: uniqueIndex3("api_keys_key_hash_idx").on(table.keyHash),
621
+ account: index3("api_keys_account_idx").on(table.accountId),
622
+ workspace: index3("api_keys_workspace_idx").on(table.workspaceId)
623
+ })
624
+ );
625
+ var workspaceVariableSets = pgTable3(
626
+ "workspace_variable_sets",
627
+ {
628
+ id: uuid3("id").primaryKey().defaultRandom(),
629
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
630
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
631
+ name: text3("name").notNull(),
632
+ description: text3("description"),
633
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
634
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
635
+ },
636
+ (table) => ({
637
+ workspaceName: uniqueIndex3("workspace_variable_sets_workspace_name_idx").on(
638
+ table.workspaceId,
639
+ table.name
640
+ ),
641
+ workspaceCreated: index3("workspace_variable_sets_workspace_created_idx").on(
642
+ table.workspaceId,
643
+ table.createdAt
644
+ )
645
+ })
646
+ );
647
+ var workspaceVariableSetVariables = pgTable3(
648
+ "workspace_variable_set_variables",
649
+ {
650
+ id: uuid3("id").primaryKey().defaultRandom(),
651
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
652
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
653
+ variableSetId: uuid3("variable_set_id").notNull().references(() => workspaceVariableSets.id, { onDelete: "cascade" }),
654
+ name: text3("name").notNull(),
655
+ // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. Never returned by any API.
656
+ valueEncrypted: text3("value_encrypted").notNull(),
657
+ version: integer2("version").notNull().default(1),
658
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
659
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
660
+ },
661
+ (table) => ({
662
+ variableSetName: uniqueIndex3("workspace_variable_set_variables_env_name_idx").on(
663
+ table.workspaceId,
664
+ table.variableSetId,
665
+ table.name
666
+ ),
667
+ variableSet: index3("workspace_variable_set_variables_workspace_env_idx").on(
668
+ table.workspaceId,
669
+ table.variableSetId
670
+ )
671
+ })
672
+ );
673
+ var codexSubscriptionCredentials = pgTable3(
674
+ "codex_subscription_credentials",
675
+ {
676
+ id: uuid3("id").primaryKey().defaultRandom(),
677
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
678
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
679
+ // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. JSON {access_token, refresh_token, id_token}. Never returned by any API.
680
+ credentialEncrypted: text3("credential_encrypted").notNull(),
681
+ chatgptAccountId: text3("chatgpt_account_id"),
682
+ // plaintext ChatGPT-Account-ID header value (non-secret)
683
+ scopes: text3("scopes"),
684
+ // space-delimited, as granted
685
+ planType: text3("plan_type"),
686
+ isFedramp: boolean2("is_fedramp").notNull().default(false),
687
+ expiresAt: timestamp3("expires_at", { withTimezone: true }),
688
+ // derived from access-token JWT exp
689
+ lastRefreshAt: timestamp3("last_refresh_at", { withTimezone: true }),
690
+ status: text3("status").notNull().default("active"),
691
+ // active | needs_relogin | error
692
+ lastError: text3("last_error"),
693
+ version: integer2("version").notNull().default(1),
694
+ label: text3("label"),
695
+ // user-chosen nickname; null ⇒ derive from email/plan/account
696
+ accountEmail: text3("account_email"),
697
+ // email from the id_token (user's own email; non-secret)
698
+ // P2 usage cache (plaintext metadata; NEVER a token). Snapshotted from
699
+ // GET /wham/usage; drives the quota bars + the cache TTL. primary = 5h window
700
+ // (limit_window_seconds 18000), secondary = weekly (604800).
701
+ primaryUsedPercent: integer2("primary_used_percent"),
702
+ primaryResetAt: timestamp3("primary_reset_at", { withTimezone: true }),
703
+ secondaryUsedPercent: integer2("secondary_used_percent"),
704
+ secondaryResetAt: timestamp3("secondary_reset_at", { withTimezone: true }),
705
+ usageCheckedAt: timestamp3("usage_checked_at", { withTimezone: true }),
706
+ // snapshot freshness → cache TTL clock
707
+ // P3 rotation cooldown (plaintext metadata; NEVER a token). Set when this account hit its
708
+ // usage cap on a rotation turn; the rotation engine treats `exhausted_until > now()` as
709
+ // capped/skip so it isn't immediately re-picked. Self-clears via the now() comparison.
710
+ exhaustedUntil: timestamp3("exhausted_until", { withTimezone: true }),
711
+ // P4 connector-aware rotation cache (plaintext metadata; NEVER a token). The set
712
+ // of ORIGINAL-dotted connector namespaces (github/gmail/linear/…) this account
713
+ // exposes via codex_apps, captured from the per-turn tools/list. null ⇒ never
714
+ // probed (the ranker treats it as unknown: never credited as covering, never
715
+ // excluded). The writer only ever sets a NON-empty set, so a flaky empty turn
716
+ // can't false-drop coverage. connectorsCheckedAt is the freshness clock.
717
+ connectorNamespaces: text3("connector_namespaces").array(),
718
+ connectorsCheckedAt: timestamp3("connectors_checked_at", {
719
+ withTimezone: true
720
+ }),
721
+ // Workspace-local, server-held fairness cursor. Provider usage headers are
722
+ // capacity hints, never the sole allocator: live lease count is ranked first
723
+ // and this cursor deterministically breaks equal-load/equal-capacity ties.
724
+ // This flag controls NEW automatic allocations only. Credential health,
725
+ // refresh, encrypted material, and already-frozen/in-flight turns are
726
+ // intentionally independent. account eligibility policy owns toggle OCC/audit and product UI.
727
+ allocatorEnabled: boolean2("allocator_enabled").notNull().default(true),
728
+ // Independent OCC/audit sequence for the allocator toggle. Token refresh
729
+ // continues to own `version`; quota/cache writes own neither counter.
730
+ allocatorVersion: integer2("allocator_version").notNull().default(1),
731
+ allocatorUpdatedBySubjectId: text3("allocator_updated_by_subject_id"),
732
+ allocatorUpdatedAt: timestamp3("allocator_updated_at", { withTimezone: true }),
733
+ // Authoritative count-only summary cached from /wham/usage. Detailed rows
734
+ // are never persisted as redemption authority; every first POST preflights
735
+ // the provider's fresh detail endpoint.
736
+ resetCreditAvailableCount: integer2("reset_credit_available_count"),
737
+ resetCreditsCheckedAt: timestamp3("reset_credits_checked_at", { withTimezone: true }),
738
+ // Set only by a direct Better Auth cookie connection/reconnection. Legacy,
739
+ // configured, delegated, API-key, and agent-created rows remain view-only.
740
+ connectedBySubjectId: text3("connected_by_subject_id"),
741
+ selectionCount: integer2("selection_count").notNull().default(0),
742
+ lastSelectedAt: timestamp3("last_selected_at", { withTimezone: true }),
743
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
744
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
745
+ },
746
+ (table) => ({
747
+ // REPLACES codex_subscription_credentials_workspace_idx (the one-per-workspace cap).
748
+ // One row per (workspace, ChatGPT account). Partial WHERE chatgpt_account_id IS NOT NULL
749
+ // so degenerate null-account rows can't collide; the device-grant connect path always
750
+ // populates chatgpt_account_id.
751
+ wsAccount: uniqueIndex3("codex_subscription_credentials_ws_account_idx").on(table.workspaceId, table.chatgptAccountId).where(sql3`${table.chatgptAccountId} is not null`),
752
+ workspace: index3("codex_subscription_credentials_workspace_lookup_idx").on(table.workspaceId),
753
+ // Composite identity is the defense-in-depth FK target for workspace-local
754
+ // lease references in migration 0053.
755
+ workspaceIdentity: uniqueIndex3("codex_subscription_credentials_workspace_id_idx").on(
756
+ table.workspaceId,
757
+ table.id
758
+ )
759
+ })
760
+ );
761
+ var codexResetRedemptionAttempts = pgTable3(
762
+ "codex_reset_redemption_attempts",
763
+ {
764
+ id: uuid3("id").primaryKey(),
765
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
766
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
767
+ credentialId: uuid3("credential_id").notNull(),
768
+ subjectId: text3("subject_id").notNull(),
769
+ browserSessionHash: text3("browser_session_hash").notNull(),
770
+ creditId: text3("credit_id").notNull(),
771
+ upstreamIdempotencyKey: uuid3("upstream_idempotency_key").notNull().defaultRandom(),
772
+ status: text3("status").notNull().default("processing"),
773
+ outcome: text3("outcome"),
774
+ claimHolderId: uuid3("claim_holder_id"),
775
+ claimExpiresAt: timestamp3("claim_expires_at", { withTimezone: true }),
776
+ confirmationExpiresAt: timestamp3("confirmation_expires_at", { withTimezone: true }).notNull(),
777
+ providerStartedAt: timestamp3("provider_started_at", { withTimezone: true }),
778
+ completedAt: timestamp3("completed_at", { withTimezone: true }),
779
+ lastFailureKind: text3("last_failure_kind"),
780
+ retryCount: integer2("retry_count").notNull().default(0),
781
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
782
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
783
+ },
784
+ (table) => ({
785
+ workspaceAccount: foreignKey({
786
+ name: "codex_reset_redemption_workspace_account_fk",
787
+ columns: [table.workspaceId, table.accountId],
788
+ foreignColumns: [workspaces.id, workspaces.accountId]
789
+ }).onDelete("cascade"),
790
+ upstreamKey: uniqueIndex3("codex_reset_redemption_upstream_key_idx").on(
791
+ table.upstreamIdempotencyKey
792
+ ),
793
+ credentialCredit: uniqueIndex3("codex_reset_redemption_credential_credit_idx").on(table.workspaceId, table.credentialId, table.creditId).where(
794
+ sql3`${table.status} <> 'completed' or ${table.outcome} in ('reset', 'alreadyRedeemed')`
795
+ ),
796
+ workspaceCredential: index3("codex_reset_redemption_workspace_credential_idx").on(
797
+ table.workspaceId,
798
+ table.credentialId,
799
+ table.createdAt
800
+ ),
801
+ claimExpiry: index3("codex_reset_redemption_claim_expiry_idx").on(table.claimExpiresAt).where(sql3`${table.status} <> 'completed'`),
802
+ statusValid: check3(
803
+ "codex_reset_redemption_status_check",
804
+ sql3`${table.status} in ('processing', 'provider_started', 'completed')`
805
+ ),
806
+ outcomeValid: check3(
807
+ "codex_reset_redemption_outcome_check",
808
+ sql3`${table.outcome} is null or ${table.outcome} in ('reset', 'nothingToReset', 'noCredit', 'alreadyRedeemed')`
809
+ ),
810
+ completionConsistent: check3(
811
+ "codex_reset_redemption_completed_check",
812
+ sql3`(${table.status} = 'completed') = (${table.outcome} is not null and ${table.completedAt} is not null)`
813
+ ),
814
+ retryCountValid: check3(
815
+ "codex_reset_redemption_retry_count_check",
816
+ sql3`${table.retryCount} >= 0`
817
+ ),
818
+ humanSubjectValid: check3(
819
+ "codex_reset_redemption_human_subject_check",
820
+ sql3`${table.subjectId} like 'user:_%'`
821
+ )
822
+ })
823
+ );
824
+ var connections = pgTable3(
825
+ "connections",
826
+ {
827
+ id: uuid3("id").primaryKey().defaultRandom(),
828
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
829
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
830
+ subjectId: text3("subject_id"),
831
+ providerDomain: text3("provider_domain").notNull(),
832
+ kind: text3("kind").notNull(),
833
+ status: text3("status").notNull().default("active"),
834
+ credentialEncrypted: text3("credential_encrypted").notNull(),
835
+ grantedScopes: jsonb2("granted_scopes").$type().notNull().default([]),
836
+ expiresAt: timestamp3("expires_at", { withTimezone: true }),
837
+ lastRefreshAt: timestamp3("last_refresh_at", { withTimezone: true }),
838
+ lastUsedAt: timestamp3("last_used_at", { withTimezone: true }),
839
+ lastError: text3("last_error"),
840
+ version: integer2("version").notNull().default(1),
841
+ // Server-owned proof that the dedicated install route verified the exact
842
+ // credential at this connection version. Generic/legacy writers cannot set
843
+ // these columns, and migration 0131 clears them when protected fields change
844
+ // without a fresh verification in the same statement.
845
+ verifiedInstallAt: timestamp3("verified_install_at", { withTimezone: true }),
846
+ verifiedInstallVersion: integer2("verified_install_version"),
847
+ metadata: jsonb2("metadata").$type().notNull().default({}),
848
+ createdBySubjectId: text3("created_by_subject_id"),
849
+ updatedBySubjectId: text3("updated_by_subject_id"),
850
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
851
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
852
+ },
853
+ (table) => ({
854
+ workspaceProviderStatus: index3("connections_workspace_provider_status_idx").on(
855
+ table.workspaceId,
856
+ table.providerDomain,
857
+ table.status
858
+ ),
859
+ workspaceSubjectProvider: index3("connections_workspace_subject_provider_idx").on(
860
+ table.workspaceId,
861
+ table.subjectId,
862
+ table.providerDomain
863
+ ),
864
+ workspaceKind: index3("connections_workspace_kind_idx").on(table.workspaceId, table.kind),
865
+ workspaceExpires: index3("connections_workspace_expires_idx").on(
866
+ table.workspaceId,
867
+ table.expiresAt
868
+ )
869
+ })
870
+ );
871
+ var slackBotPostOperations = pgTable3(
872
+ "slack_bot_post_operations",
873
+ {
874
+ id: uuid3("id").primaryKey().defaultRandom(),
875
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
876
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
877
+ connectionId: uuid3("connection_id").notNull().references(() => connections.id, { onDelete: "cascade" }),
878
+ operationId: uuid3("operation_id").notNull(),
879
+ clientMessageId: uuid3("client_message_id").notNull(),
880
+ targetKind: text3("target_kind").$type().notNull(),
881
+ targetId: text3("target_id").notNull(),
882
+ requestDigest: text3("request_digest").notNull(),
883
+ status: text3("status").$type().notNull(),
884
+ claimHolderId: uuid3("claim_holder_id"),
885
+ claimExpiresAt: timestamp3("claim_expires_at", { withTimezone: true }),
886
+ attemptCount: integer2("attempt_count").notNull().default(0),
887
+ lastFailureCode: text3("last_failure_code"),
888
+ slackChannelId: text3("slack_channel_id"),
889
+ slackMessageTimestamp: text3("slack_message_timestamp"),
890
+ completedAt: timestamp3("completed_at", { withTimezone: true }),
891
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
892
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
893
+ },
894
+ (table) => ({
895
+ workspaceOperation: uniqueIndex3("slack_bot_post_operations_workspace_operation_uq").on(
896
+ table.workspaceId,
897
+ table.connectionId,
898
+ table.operationId
899
+ ),
900
+ workspaceStatus: index3("slack_bot_post_operations_workspace_status_idx").on(
901
+ table.workspaceId,
902
+ table.status,
903
+ table.updatedAt
904
+ ),
905
+ targetKindValid: check3(
906
+ "slack_bot_post_operations_target_kind_check",
907
+ sql3`${table.targetKind} in ('channel', 'user')`
908
+ ),
909
+ statusValid: check3(
910
+ "slack_bot_post_operations_status_check",
911
+ sql3`${table.status} in ('provider_started', 'completed')`
912
+ ),
913
+ identityValid: check3(
914
+ "slack_bot_post_operations_identity_check",
915
+ sql3`${table.clientMessageId} = ${table.operationId}
916
+ and length(${table.targetId}) between 1 and 64
917
+ and ${table.requestDigest} ~ '^[0-9a-f]{64}$'
918
+ and ${table.attemptCount} > 0
919
+ and ((${table.claimHolderId} is null) = (${table.claimExpiresAt} is null))`
920
+ ),
921
+ completionValid: check3(
922
+ "slack_bot_post_operations_completion_check",
923
+ sql3`(
924
+ ${table.status} = 'provider_started'
925
+ and ${table.slackChannelId} is null
926
+ and ${table.slackMessageTimestamp} is null
927
+ and ${table.completedAt} is null
928
+ ) or (
929
+ ${table.status} = 'completed'
930
+ and ${table.claimHolderId} is null
931
+ and ${table.claimExpiresAt} is null
932
+ and ${table.slackChannelId} is not null
933
+ and ${table.slackMessageTimestamp} is not null
934
+ and ${table.completedAt} is not null
935
+ )`
936
+ )
937
+ })
938
+ );
939
+ var slackBotDeleteOperations = pgTable3(
940
+ "slack_bot_delete_operations",
941
+ {
942
+ id: uuid3("id").primaryKey().defaultRandom(),
943
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
944
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
945
+ connectionId: uuid3("connection_id").notNull().references(() => connections.id, { onDelete: "cascade" }),
946
+ operationId: uuid3("operation_id").notNull(),
947
+ principalType: text3("principal_type").$type().notNull(),
948
+ principalId: text3("principal_id").notNull(),
949
+ toolName: text3("tool_name").notNull(),
950
+ channelId: text3("channel_id").notNull(),
951
+ messageTimestamp: text3("message_timestamp").notNull(),
952
+ requestDigest: text3("request_digest").notNull(),
953
+ status: text3("status").$type().notNull(),
954
+ claimHolderId: uuid3("claim_holder_id"),
955
+ claimExpiresAt: timestamp3("claim_expires_at", { withTimezone: true }),
956
+ attemptCount: integer2("attempt_count").notNull().default(0),
957
+ lastFailureCode: text3("last_failure_code"),
958
+ slackChannelId: text3("slack_channel_id"),
959
+ slackMessageTimestamp: text3("slack_message_timestamp"),
960
+ completedAt: timestamp3("completed_at", { withTimezone: true }),
961
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
962
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
963
+ },
964
+ (table) => ({
965
+ workspaceOperation: uniqueIndex3("slack_bot_delete_operations_workspace_operation_uq").on(
966
+ table.workspaceId,
967
+ table.operationId
968
+ ),
969
+ workspaceStatus: index3("slack_bot_delete_operations_workspace_status_idx").on(
970
+ table.workspaceId,
971
+ table.status,
972
+ table.updatedAt
973
+ ),
974
+ principalValid: check3(
975
+ "slack_bot_delete_operations_principal_check",
976
+ sql3`${table.principalType} in ('subject', 'service')
977
+ and length(${table.principalId}) between 1 and 512`
978
+ ),
979
+ identityValid: check3(
980
+ "slack_bot_delete_operations_identity_check",
981
+ sql3`${table.toolName} = 'slack_bot_delete_message'
982
+ and length(${table.channelId}) between 1 and 64
983
+ and length(${table.messageTimestamp}) between 1 and 64
984
+ and ${table.requestDigest} ~ '^[0-9a-f]{64}$'
985
+ and ${table.attemptCount} > 0
986
+ and ((${table.claimHolderId} is null) = (${table.claimExpiresAt} is null))`
987
+ ),
988
+ statusValid: check3(
989
+ "slack_bot_delete_operations_status_check",
990
+ sql3`${table.status} in ('pending', 'provider_started', 'outcome_unknown', 'completed')`
991
+ ),
992
+ completionValid: check3(
993
+ "slack_bot_delete_operations_completion_check",
994
+ sql3`(
995
+ ${table.status} <> 'completed'
996
+ and ${table.slackChannelId} is null
997
+ and ${table.slackMessageTimestamp} is null
998
+ and ${table.completedAt} is null
999
+ ) or (
1000
+ ${table.status} = 'completed'
1001
+ and ${table.claimHolderId} is null
1002
+ and ${table.claimExpiresAt} is null
1003
+ and ${table.slackChannelId} is not null
1004
+ and ${table.slackMessageTimestamp} is not null
1005
+ and ${table.completedAt} is not null
1006
+ )`
1007
+ )
1008
+ })
1009
+ );
1010
+ var integrationOauthClients = pgTable3(
1011
+ "integration_oauth_clients",
1012
+ {
1013
+ id: uuid3("id").primaryKey().defaultRandom(),
1014
+ issuer: text3("issuer").notNull(),
1015
+ authorizationServer: text3("authorization_server").notNull(),
1016
+ clientId: text3("client_id").notNull(),
1017
+ clientSecretEncrypted: text3("client_secret_encrypted"),
1018
+ tokenEndpointAuthMethod: text3("token_endpoint_auth_method").notNull().default("none"),
1019
+ metadata: jsonb2("metadata").$type().notNull().default({}),
1020
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1021
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1022
+ },
1023
+ (table) => ({
1024
+ issuer: uniqueIndex3("integration_oauth_clients_issuer_idx").on(table.issuer),
1025
+ authorizationServer: index3("integration_oauth_clients_as_idx").on(table.authorizationServer)
1026
+ })
1027
+ );
1028
+ var integrationOauthStateNonces = pgTable3(
1029
+ "integration_oauth_state_nonces",
1030
+ {
1031
+ nonce: text3("nonce").primaryKey(),
1032
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1033
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1034
+ subjectId: text3("subject_id").notNull(),
1035
+ expiresAt: timestamp3("expires_at", { withTimezone: true }).notNull(),
1036
+ usedAt: timestamp3("used_at", { withTimezone: true }).notNull().defaultNow(),
1037
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
1038
+ },
1039
+ (table) => ({
1040
+ workspace: index3("integration_oauth_state_nonces_workspace_idx").on(table.workspaceId),
1041
+ expires: index3("integration_oauth_state_nonces_expires_idx").on(table.expiresAt)
1042
+ })
1043
+ );
1044
+ var codexRotationSettings = pgTable3(
1045
+ "codex_rotation_settings",
1046
+ {
1047
+ id: uuid3("id").primaryKey().defaultRandom(),
1048
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1049
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1050
+ activeCredentialId: uuid3("active_credential_id"),
1051
+ // Legacy selector bit. Keep false as the DB default forever: an old worker
1052
+ // only understands this column, so a schema-first rollout or binary
1053
+ // rollback must never make it enter the non-atomic rotation path.
1054
+ rotationEnabled: boolean2("rotation_enabled").notNull().default(false),
1055
+ // Revision-aware allocator cutover. Only migration-compatible API/worker
1056
+ // code reads this bit; old binaries safely ignore it and keep the legacy
1057
+ // pin/rotation policy.
1058
+ leaseRotationEnabled: boolean2("lease_rotation_enabled").notNull().default(false),
1059
+ rotationStrategy: text3("rotation_strategy").notNull().default("sharded"),
1060
+ // sharded-rotation policy: legacy residue; behavior is always sharded
1061
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1062
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1063
+ },
1064
+ (table) => ({
1065
+ workspace: uniqueIndex3("codex_rotation_settings_workspace_idx").on(table.workspaceId)
1066
+ })
1067
+ );
1068
+ var workspaceModelPolicies = pgTable3(
1069
+ "workspace_model_policies",
1070
+ {
1071
+ id: uuid3("id").primaryKey().defaultRandom(),
1072
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1073
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1074
+ allowedProviders: text3("allowed_providers").array(),
1075
+ allowedModels: text3("allowed_models").array(),
1076
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1077
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1078
+ },
1079
+ (table) => ({
1080
+ workspace: uniqueIndex3("workspace_model_policies_workspace_idx").on(table.workspaceId)
1081
+ })
1082
+ );
1083
+ var codexCredentialLeases = pgTable3(
1084
+ "codex_credential_leases",
1085
+ {
1086
+ id: uuid3("id").primaryKey().defaultRandom(),
1087
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1088
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1089
+ credentialId: uuid3("credential_id").notNull(),
1090
+ turnId: uuid3("turn_id").notNull(),
1091
+ // Temporal activity execution fence. A successor dispatch for the same
1092
+ // durable turn replaces holderId and increments generation atomically;
1093
+ // stale/zombie heartbeats and releases must match both values.
1094
+ holderId: text3("holder_id").notNull(),
1095
+ generation: integer2("generation").notNull().default(1),
1096
+ leasedUntil: timestamp3("leased_until", { withTimezone: true }).notNull(),
1097
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1098
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1099
+ },
1100
+ (table) => ({
1101
+ turn: uniqueIndex3("codex_credential_leases_workspace_turn_idx").on(
1102
+ table.workspaceId,
1103
+ table.turnId
1104
+ ),
1105
+ activeCredential: index3("codex_credential_leases_active_credential_idx").on(
1106
+ table.workspaceId,
1107
+ table.credentialId,
1108
+ table.leasedUntil
1109
+ ),
1110
+ expiry: index3("codex_credential_leases_expiry_idx").on(table.leasedUntil)
1111
+ })
1112
+ );
1113
+ var sessions = pgTable3(
1114
+ "sessions",
1115
+ {
1116
+ id: uuid3("id").primaryKey().defaultRandom(),
1117
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1118
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1119
+ status: text3("status").notNull().default("queued"),
1120
+ initialMessage: text3("initial_message").notNull(),
1121
+ // Invisible host context frozen with the winning session create. The
1122
+ // initial turn copies this value so an idempotent repair can never adopt a
1123
+ // retrying caller's different instructions.
1124
+ initialTurnInstructions: text3("initial_turn_instructions"),
1125
+ title: text3("title"),
1126
+ titleSource: text3("title_source"),
1127
+ // Per-session agent persona/system instructions supplied at create (the
1128
+ // per-agent-type prompt lever for embedding hosts). NULL ⇒ the session
1129
+ // carried none, so the composed agent instructions are byte-identical to a
1130
+ // workspace-only persona (no backfill, no behavior change for existing rows).
1131
+ // Composed system-level AFTER the workspace agentInstructions; never emitted
1132
+ // as a timeline event.
1133
+ instructions: text3("instructions"),
1134
+ resources: jsonb2("resources").$type().notNull().default([]),
1135
+ skills: jsonb2("skills").$type().notNull().default([]),
1136
+ tools: jsonb2("tools").$type().notNull().default([]),
1137
+ metadata: jsonb2("metadata").$type().notNull().default({}),
1138
+ // Frozen creator fact. This is used for creation attribution and for the
1139
+ // idempotent first-turn repair only; later turns capture their own actor.
1140
+ createdByKind: text3("created_by_kind").notNull().default("service"),
1141
+ createdBySubjectId: text3("created_by_subject_id").notNull().default("unattributed-legacy"),
1142
+ createdByContext: jsonb2("created_by_context").$type().notNull().default({ backfill: true }),
1143
+ model: text3("model").notNull(),
1144
+ sandboxBackend: text3("sandbox_backend").notNull(),
1145
+ // The OS this session's box runs. Defaults to 'linux' (today's only OS, so
1146
+ // every existing + new row is a behavior-preserving no-op). CHECK-constrained
1147
+ // to the SandboxOs enum (linux|macos|windows) in migration 0018.
1148
+ sandboxOs: text3("sandbox_os").notNull().default("linux"),
1149
+ // The shared-sandbox group this session's box belongs to. Defaults to the
1150
+ // session's OWN id (a singleton group: group === session — today's 1:1
1151
+ // behavior). When spawned shared via session_create, set to the PARENT's
1152
+ // sandboxGroupId so both run in ONE box. Immutable once set. NOT an FK (the
1153
+ // value is this row's id or an ancestor session's id in the same workspace;
1154
+ // the live lease row, not a sandbox_groups table, materializes the group).
1155
+ // The app generates the uuid and uses it for both id and sandbox_group_id in
1156
+ // one insert — it cannot SQL-default to id (id is defaultRandom()).
1157
+ sandboxGroupId: uuid3("sandbox_group_id").notNull(),
1158
+ // The first-class swappable-sandbox POINTER (bring-your-own-compute M2).
1159
+ // NULL == "use the session's own group sandbox" (the
1160
+ // backward-compat default — every existing/new row is a behavior-preserving
1161
+ // no-op). The routing proxy re-reads (active_sandbox_id, active_epoch) PER
1162
+ // TOOL CALL to make a Modal<->selfhosted hot-swap seamless. The FK
1163
+ // (-> sandboxes(id) ON DELETE SET NULL — a deleted sandbox degrades the
1164
+ // pointer to the group default, never dangles) lives in migration 0024, NOT a
1165
+ // Drizzle .references() — exactly like parentSessionId below, so the const
1166
+ // ordering imposes no forward-reference.
1167
+ activeSandboxId: uuid3("active_sandbox_id"),
1168
+ // The SECOND epoch ABOVE sandbox_leases.lease_epoch, bumped on every swap; an
1169
+ // in-flight op fenced by a stale active_epoch retries against the new active
1170
+ // sandbox. integer (NOT bigint) — the lease-epoch spike: int8 reads back as a
1171
+ // JS string and breaks the strict fence; int4 returns a number.
1172
+ activeEpoch: integer2("active_epoch").notNull().default(0),
1173
+ // The session's WORKING DIRECTORY — the path/cwd base the (selfhosted) box's
1174
+ // agent/terminal/file-dock operate under. A launch-workspace_root-relative
1175
+ // subdir or an absolute machine path; surfaced alongside the active-sandbox
1176
+ // pointer (readActiveSandbox) and written through the epoch-fenced
1177
+ // setActiveSandbox CAS, NOT the row INSERT. NULL (the default) ⇒ today's
1178
+ // behavior exactly — the agent substitutes its workspace_root for an empty cwd,
1179
+ // so an unset working_dir is a byte-identical no-op. Create-time only (Stage A).
1180
+ workingDir: text3("working_dir"),
1181
+ variableSetId: uuid3("variable_set_id").references(() => workspaceVariableSets.id, {
1182
+ onDelete: "set null"
1183
+ }),
1184
+ // The rig this session rides + the exact rig version frozen at create time
1185
+ // (migration 0047). NULL ⇒ the session rides no rig (today's behavior). FKs
1186
+ // (-> rigs(id)/rig_versions(id) ON DELETE SET NULL) live in migration 0047,
1187
+ // not Drizzle .references(), because those tables are declared later in this
1188
+ // file (forward-reference pattern, same as activeSandboxId). Consumed in M3.
1189
+ rigId: uuid3("rig_id"),
1190
+ rigVersionId: uuid3("rig_version_id"),
1191
+ // Non-default first-party MCP token permissions (manager-style sessions);
1192
+ // null means the fixed worker default set in @opengeni/runtime.
1193
+ firstPartyMcpPermissions: jsonb2("first_party_mcp_permissions").$type(),
1194
+ // Exact model-visible first-party tool selection. All catalogued tools are
1195
+ // selected by default; [] intentionally selects no broad-server tools.
1196
+ firstPartyMcpTools: jsonb2("first_party_mcp_tools").$type().notNull(),
1197
+ // Durable tool-policy origin. Migration 0136 removes the old null/legacy
1198
+ // representation so every session has one explicit policy mode.
1199
+ toolPolicy: jsonb2("tool_policy").$type().notNull(),
1200
+ // Optimistic-concurrency fence for durable session tool-policy writes.
1201
+ toolPolicyVersion: integer2("tool_policy_version").notNull().default(1),
1202
+ // The manager session that spawned this one via session_create. Set only
1203
+ // when the creating grant carried a worker-signed sessionId claim (a session
1204
+ // spawning a worker); null for direct API creates and scheduled-task runs.
1205
+ // When set, this worker's terminal-for-now transitions wake the parent so a
1206
+ // manager can orchestrate workers without busy-polling. Self-referencing FK,
1207
+ // ON DELETE SET NULL so deleting a manager never cascades into its workers.
1208
+ parentSessionId: uuid3("parent_session_id"),
1209
+ // Workspace-scoped CREATE idempotency key. NULL means the create carried no
1210
+ // key (each such create is independent). When set, the partial unique index
1211
+ // below collapses concurrent/retried creates with the same key in the same
1212
+ // workspace to a single session row — the dedup that closes the
1213
+ // double-submit/double-dispatch stuck-queued bug.
1214
+ createIdempotencyKey: text3("create_idempotency_key"),
1215
+ // Immutable creation-time hierarchy and policy snapshot. These values are
1216
+ // populated by the database admission boundary and never re-derived from
1217
+ // a live workspace setting for an existing session.
1218
+ rootSessionId: uuid3("root_session_id").notNull(),
1219
+ nestedAgentDepth: integer2("nested_agent_depth").notNull(),
1220
+ maxNestedAgentDepthOverride: integer2("max_nested_agent_depth_override"),
1221
+ effectiveMaxNestedAgentDepth: integer2("effective_max_nested_agent_depth").notNull(),
1222
+ nestedAgentDepthPolicySource: text3("nested_agent_depth_policy_source").notNull(),
1223
+ nestedAgentDepthPolicySessionId: uuid3("nested_agent_depth_policy_session_id"),
1224
+ temporalWorkflowId: text3("temporal_workflow_id"),
1225
+ activeTurnId: uuid3("active_turn_id"),
1226
+ // Actual input tokens reported for the last model call of the most recent
1227
+ // turn. The pre-turn portable compaction trigger reads this as its budget
1228
+ // signal (char/4 estimate is the same-turn fallback). Null until a turn with
1229
+ // usage has completed.
1230
+ lastInputTokens: integer2("last_input_tokens"),
1231
+ // Operator /compact request flag. The API sets
1232
+ // it true; the worker honors it BEFORE the next turn's model call by forcing
1233
+ // a compaction, then clears it. A durable flag (not a transient signal) so
1234
+ // the trigger survives a worker restart and converges before the next turn.
1235
+ compactRequested: boolean2("compact_requested").notNull().default(false),
1236
+ queueVersion: integer2("queue_version").notNull().default(0),
1237
+ queueHeadPosition: bigint3("queue_head_position", { mode: "number" }).notNull().default(0),
1238
+ queueTailPosition: bigint3("queue_tail_position", { mode: "number" }).notNull().default(0),
1239
+ directControlState: text3("direct_control_state").notNull().default("active"),
1240
+ directPauseRevision: bigint3("direct_pause_revision", { mode: "number" }),
1241
+ subtreeRunOverrideRevision: bigint3("subtree_run_override_revision", {
1242
+ mode: "number"
1243
+ }),
1244
+ controlVersion: bigint3("control_version", { mode: "number" }).notNull().default(0),
1245
+ directControlReason: text3("direct_control_reason"),
1246
+ directControlChangedBy: text3("direct_control_changed_by"),
1247
+ directControlChangedAt: timestamp3("direct_control_changed_at", {
1248
+ withTimezone: true
1249
+ }),
1250
+ lastSequence: integer2("last_sequence").notNull().default(0),
1251
+ // The session's PINNED Codex account (manual override from the in-session
1252
+ // switcher). NULL ⇒ follow the workspace active pointer. FK declared in the
1253
+ // migration with ON DELETE SET NULL (a disconnected pin degrades to "follow
1254
+ // active", never dangles), same pattern as activeSandboxId.
1255
+ codexPinnedCredentialId: uuid3("codex_pinned_credential_id"),
1256
+ // The Codex account the session's most recent turn ACTUALLY ran on — drives
1257
+ // the "Running on:" indicator. Written by the worker at the turn boundary. FK
1258
+ // ON DELETE SET NULL (migration).
1259
+ codexLastCredentialId: uuid3("codex_last_credential_id"),
1260
+ // The SOURCE of codex_pinned_credential_id (AM-2): 'manual' — the user's
1261
+ // in-session account switcher, which is SACRED and never moved by any policy —
1262
+ // or 'policy' — the sharded rotation strategy's deterministic per-session home
1263
+ // assignment, which MAY be re-sharded to another account when its own account
1264
+ // caps. NULL when there is no pin (and for every pre-existing row). CHECK
1265
+ // (manual|policy) lives in the migration; no FK (it describes the pin, not an
1266
+ // account).
1267
+ codexPinSource: text3("codex_pin_source"),
1268
+ // Frozen at create: remote_v2 (Codex remote compaction + Codex-only models)
1269
+ // or portable (plaintext compaction + free provider switching). Existing
1270
+ // rows backfill to portable. CHECK lives in the migration.
1271
+ codexCompactionMode: text3("codex_compaction_mode").notNull().default("portable"),
1272
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1273
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow(),
1274
+ // Assigned by the database trigger whenever canonical updated_at activity
1275
+ // advances. Legacy rows remain zero until touched; raw delta-only writers
1276
+ // intentionally omit updated_at and therefore do not allocate revisions.
1277
+ activityRevision: bigint3("activity_revision", { mode: "number" }).notNull().default(0)
1278
+ },
1279
+ (table) => ({
1280
+ workspaceIdentity: uniqueIndex3("sessions_workspace_id_idx").on(table.workspaceId, table.id),
1281
+ workspaceCreated: index3("sessions_workspace_created_idx").on(
1282
+ table.workspaceId,
1283
+ table.createdAt
1284
+ ),
1285
+ // Model-facing monitoring pages use exact (timestamp,id) keysets. Keep the
1286
+ // older prefix index during rolling deploys; these composites serve both
1287
+ // deterministic traversal and updatedAfter change scans.
1288
+ workspaceCreatedId: index3("sessions_workspace_created_id_idx").on(
1289
+ table.workspaceId,
1290
+ table.createdAt.desc(),
1291
+ table.id.desc()
1292
+ ),
1293
+ workspaceUpdatedId: index3("sessions_workspace_updated_id_idx").on(
1294
+ table.workspaceId,
1295
+ table.updatedAt.desc(),
1296
+ table.id.desc()
1297
+ ),
1298
+ workspaceActivityRevision: index3("sessions_workspace_activity_revision_idx").on(
1299
+ table.workspaceId,
1300
+ table.activityRevision.desc(),
1301
+ table.updatedAt.desc(),
1302
+ table.id.desc()
1303
+ ),
1304
+ variableSet: index3("sessions_variable_set_idx").on(table.workspaceId, table.variableSetId),
1305
+ parent: index3("sessions_parent_idx").on(table.workspaceId, table.parentSessionId),
1306
+ // Routing index: resolve session_id -> sandbox_group_id at every lease entry
1307
+ // point and enumerate all sessions in a group for attribution/disclosure.
1308
+ sandboxGroup: index3("sessions_sandbox_group_idx").on(table.workspaceId, table.sandboxGroupId),
1309
+ // Partial unique index: one session per (workspace, create_idempotency_key)
1310
+ // when a key is present. The boundary trigger reserves the cross-outcome
1311
+ // winner before this source row commits; a losing source insert is
1312
+ // suppressed and the domain layer replays the durable winner.
1313
+ createIdempotency: uniqueIndex3("sessions_workspace_create_idempotency_idx").on(table.workspaceId, table.createIdempotencyKey).where(sql3`${table.createIdempotencyKey} is not null`),
1314
+ rootDepth: index3("sessions_workspace_root_depth_idx").on(
1315
+ table.workspaceId,
1316
+ table.rootSessionId,
1317
+ table.nestedAgentDepth
1318
+ )
1319
+ })
1320
+ );
1321
+ var sessionSpawnDenials = pgTable3(
1322
+ "session_spawn_denials",
1323
+ {
1324
+ id: uuid3("id").primaryKey().defaultRandom(),
1325
+ accountId: uuid3("account_id").notNull(),
1326
+ workspaceId: uuid3("workspace_id").notNull(),
1327
+ parentSessionId: uuid3("parent_session_id"),
1328
+ rootSessionId: uuid3("root_session_id"),
1329
+ currentDepth: integer2("current_depth").notNull(),
1330
+ attemptedDepth: bigint3("attempted_depth", { mode: "number" }).notNull(),
1331
+ effectiveMaxNestedAgentDepth: integer2("effective_max_nested_agent_depth").notNull(),
1332
+ requestedMaxNestedAgentDepthOverride: integer2("requested_max_nested_agent_depth_override"),
1333
+ policySource: text3("policy_source").notNull(),
1334
+ policySessionId: uuid3("policy_session_id"),
1335
+ subjectId: text3("subject_id"),
1336
+ code: text3("code").notNull(),
1337
+ idempotencyKey: text3("idempotency_key"),
1338
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
1339
+ },
1340
+ (table) => ({
1341
+ workspaceIdentity: uniqueIndex3("session_spawn_denials_workspace_id_uq").on(
1342
+ table.workspaceId,
1343
+ table.id
1344
+ ),
1345
+ workspaceCreated: index3("session_spawn_denials_workspace_created_idx").on(
1346
+ table.workspaceId,
1347
+ table.createdAt
1348
+ ),
1349
+ parent: index3("session_spawn_denials_parent_idx").on(
1350
+ table.workspaceId,
1351
+ table.parentSessionId,
1352
+ table.createdAt
1353
+ ),
1354
+ idempotency: uniqueIndex3("session_spawn_denials_workspace_idempotency_idx").on(table.workspaceId, table.idempotencyKey).where(sql3`${table.idempotencyKey} is not null`),
1355
+ workspaceAccount: foreignKey({
1356
+ name: "session_spawn_denials_workspace_account_fk",
1357
+ columns: [table.workspaceId, table.accountId],
1358
+ foreignColumns: [workspaces.id, workspaces.accountId]
1359
+ }).onDelete("cascade")
1360
+ })
1361
+ );
1362
+ var sessionPins = pgTable3(
1363
+ "session_pins",
1364
+ {
1365
+ id: uuid3("id").primaryKey().defaultRandom(),
1366
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1367
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1368
+ subjectId: text3("subject_id").notNull(),
1369
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1370
+ // Keep an unpinned tombstone (pinned=false, pinned_at=null) rather than
1371
+ // deleting it. That preserves a monotonic version and prevents an ABA race:
1372
+ // a stale client that saw pin version 1 cannot silently overwrite a later
1373
+ // unpin+re-pin that would otherwise recreate version 1.
1374
+ pinned: boolean2("pinned").notNull().default(true),
1375
+ pinnedAt: timestamp3("pinned_at", { withTimezone: true }).defaultNow(),
1376
+ version: integer2("version").notNull().default(1)
1377
+ },
1378
+ (table) => ({
1379
+ subjectNonempty: check3(
1380
+ "session_pins_subject_nonempty",
1381
+ sql3`length(btrim(${table.subjectId})) > 0`
1382
+ ),
1383
+ versionPositive: check3("session_pins_version_positive", sql3`${table.version} >= 1`),
1384
+ stateConsistent: check3(
1385
+ "session_pins_state_consistent",
1386
+ sql3`((${table.pinned}) and (${table.pinnedAt}) is not null) or ((not ${table.pinned}) and (${table.pinnedAt}) is null)`
1387
+ ),
1388
+ workspaceAccount: foreignKey({
1389
+ name: "session_pins_workspace_account_fk",
1390
+ columns: [table.workspaceId, table.accountId],
1391
+ foreignColumns: [workspaces.id, workspaces.accountId]
1392
+ }).onDelete("cascade"),
1393
+ workspaceSession: foreignKey({
1394
+ name: "session_pins_workspace_session_fk",
1395
+ columns: [table.workspaceId, table.sessionId],
1396
+ foreignColumns: [sessions.workspaceId, sessions.id]
1397
+ }).onDelete("cascade"),
1398
+ subjectSession: uniqueIndex3("session_pins_subject_workspace_session_idx").on(
1399
+ table.subjectId,
1400
+ table.workspaceId,
1401
+ table.sessionId
1402
+ ),
1403
+ subjectPinned: index3("session_pins_workspace_subject_pinned_idx").on(
1404
+ table.workspaceId,
1405
+ table.subjectId,
1406
+ table.pinned,
1407
+ table.pinnedAt.desc(),
1408
+ table.sessionId.desc()
1409
+ )
1410
+ })
1411
+ );
1412
+ var sessionListSnapshots = pgTable3(
1413
+ "session_list_snapshots",
1414
+ {
1415
+ id: uuid3("id").primaryKey().defaultRandom(),
1416
+ accountId: uuid3("account_id").notNull(),
1417
+ workspaceId: uuid3("workspace_id").notNull(),
1418
+ subjectId: text3("subject_id").notNull(),
1419
+ parentSessionFilter: text3("parent_session_filter").notNull().default("all"),
1420
+ search: text3("search"),
1421
+ ordinarySessionIds: uuid3("ordinary_session_ids").array().notNull().default(sql3`'{}'::uuid[]`),
1422
+ expiresAt: timestamp3("expires_at", { withTimezone: true }).notNull(),
1423
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
1424
+ },
1425
+ (table) => ({
1426
+ workspaceAccount: foreignKey({
1427
+ name: "session_list_snapshots_workspace_account_fk",
1428
+ columns: [table.workspaceId, table.accountId],
1429
+ foreignColumns: [workspaces.id, workspaces.accountId]
1430
+ }).onDelete("cascade"),
1431
+ subjectNonempty: check3(
1432
+ "session_list_snapshots_subject_nonempty",
1433
+ sql3`length(btrim(${table.subjectId})) > 0`
1434
+ ),
1435
+ parentFilterValid: check3(
1436
+ "session_list_snapshots_parent_filter_valid",
1437
+ sql3`${table.parentSessionFilter} = 'all' or ${table.parentSessionFilter} = 'null' or ${table.parentSessionFilter} ~ '^[0-9a-fA-F-]{36}$'`
1438
+ ),
1439
+ searchLength: check3(
1440
+ "session_list_snapshots_search_length",
1441
+ sql3`${table.search} is null or length(${table.search}) <= 200`
1442
+ ),
1443
+ workspaceExpiry: index3("session_list_snapshots_workspace_expiry_idx").on(
1444
+ table.workspaceId,
1445
+ table.subjectId,
1446
+ table.expiresAt
1447
+ ),
1448
+ expiryReaper: index3("session_list_snapshots_expiry_reaper_idx").on(table.expiresAt, table.id)
1449
+ })
1450
+ );
1451
+ var sessionMcpServers = pgTable3(
1452
+ "session_mcp_servers",
1453
+ {
1454
+ id: uuid3("id").primaryKey().defaultRandom(),
1455
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1456
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1457
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1458
+ serverId: text3("server_id").notNull(),
1459
+ name: text3("name"),
1460
+ url: text3("url").notNull(),
1461
+ allowedTools: jsonb2("allowed_tools").$type(),
1462
+ timeoutMs: integer2("timeout_ms"),
1463
+ cacheToolsList: boolean2("cache_tools_list").notNull().default(false),
1464
+ // Human-approval policy: `true` = every tool requires approval, a string[] of
1465
+ // UNPREFIXED tool names = only those require it, null/absent = auto-run.
1466
+ requireApproval: jsonb2("require_approval").$type(),
1467
+ // Non-secret pointer resolved at request time by the standalone broker or
1468
+ // an embedding host. Unlike headersEncrypted, this is safe to project.
1469
+ connectionRef: jsonb2("connection_ref").$type(),
1470
+ // Map of header name -> AES-GCM ciphertext. Values are decrypted only by the
1471
+ // worker's run-preparation path and never returned by API helpers.
1472
+ headersEncrypted: jsonb2("headers_encrypted").$type().notNull().default({}),
1473
+ credentialVersion: integer2("credential_version").notNull().default(1),
1474
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1475
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1476
+ },
1477
+ (table) => ({
1478
+ sessionServer: uniqueIndex3("session_mcp_servers_session_server_idx").on(
1479
+ table.workspaceId,
1480
+ table.sessionId,
1481
+ table.serverId
1482
+ ),
1483
+ session: index3("session_mcp_servers_session_idx").on(table.workspaceId, table.sessionId)
1484
+ })
1485
+ );
1486
+ var files = pgTable3(
1487
+ "files",
1488
+ {
1489
+ id: uuid3("id").primaryKey().defaultRandom(),
1490
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1491
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1492
+ status: text3("status").notNull().default("pending_upload"),
1493
+ filename: text3("filename").notNull(),
1494
+ safeFilename: text3("safe_filename").notNull(),
1495
+ contentType: text3("content_type").notNull(),
1496
+ sizeBytes: bigint3("size_bytes", { mode: "number" }).notNull(),
1497
+ sha256: text3("sha256"),
1498
+ bucket: text3("bucket").notNull(),
1499
+ objectKey: text3("object_key").notNull(),
1500
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1501
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1502
+ },
1503
+ (table) => ({
1504
+ workspaceCreated: index3("files_workspace_created_idx").on(table.workspaceId, table.createdAt),
1505
+ objectKey: uniqueIndex3("files_object_key_idx").on(table.objectKey),
1506
+ status: index3("files_status_idx").on(table.status)
1507
+ })
1508
+ );
1509
+ var fileUploads = pgTable3(
1510
+ "file_uploads",
1511
+ {
1512
+ id: uuid3("id").primaryKey().defaultRandom(),
1513
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1514
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1515
+ fileId: uuid3("file_id").notNull().references(() => files.id, { onDelete: "cascade" }),
1516
+ status: text3("status").notNull().default("pending"),
1517
+ expiresAt: timestamp3("expires_at", { withTimezone: true }).notNull(),
1518
+ completedAt: timestamp3("completed_at", { withTimezone: true }),
1519
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1520
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1521
+ },
1522
+ (table) => ({
1523
+ workspace: index3("file_uploads_workspace_idx").on(table.workspaceId),
1524
+ fileId: index3("file_uploads_file_id_idx").on(table.fileId),
1525
+ status: index3("file_uploads_status_idx").on(table.status)
1526
+ })
1527
+ );
1528
+ var documentBases = pgTable3(
1529
+ "document_bases",
1530
+ {
1531
+ id: uuid3("id").primaryKey().defaultRandom(),
1532
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1533
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1534
+ name: text3("name").notNull(),
1535
+ description: text3("description"),
1536
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1537
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1538
+ },
1539
+ (table) => ({
1540
+ workspaceCreated: index3("document_bases_workspace_created_idx").on(
1541
+ table.workspaceId,
1542
+ table.createdAt
1543
+ ),
1544
+ defaultName: uniqueIndex3("document_bases_workspace_default_name_uq").on(table.workspaceId).where(sql3`lower(btrim(${table.name})) = 'default'`)
1545
+ })
1546
+ );
1547
+ var documents = pgTable3(
1548
+ "documents",
1549
+ {
1550
+ id: uuid3("id").primaryKey().defaultRandom(),
1551
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1552
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1553
+ baseId: uuid3("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
1554
+ fileId: uuid3("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
1555
+ status: text3("status").notNull().default("queued"),
1556
+ title: text3("title").notNull(),
1557
+ parser: text3("parser").notNull().default("liteparse"),
1558
+ chunkCount: integer2("chunk_count").notNull().default(0),
1559
+ error: text3("error"),
1560
+ sourceKind: text3("source_kind").notNull().default("manual_upload"),
1561
+ sourceUri: text3("source_uri"),
1562
+ sourceExternalId: text3("source_external_id"),
1563
+ sourceTitle: text3("source_title"),
1564
+ sourceAuthor: text3("source_author"),
1565
+ sourceCreatedAt: timestamp3("source_created_at", { withTimezone: true }),
1566
+ sourceUpdatedAt: timestamp3("source_updated_at", { withTimezone: true }),
1567
+ sourceVersion: text3("source_version"),
1568
+ aclTags: jsonb2("acl_tags").$type().notNull().default([]),
1569
+ // Per-document access controls. visibility 'private' restricts human reads to
1570
+ // created_by (a grant subject id, not a uuid); agent_access=false hides the
1571
+ // document from agent retrieval surfaces (docs MCP) while humans keep REST.
1572
+ visibility: text3("visibility").notNull().default("workspace"),
1573
+ createdBy: text3("created_by"),
1574
+ agentAccess: boolean2("agent_access").notNull().default(true),
1575
+ // Auto-curation output (knowledge drops).
1576
+ summary: text3("summary"),
1577
+ topics: jsonb2("topics").$type().notNull().default([]),
1578
+ curationStatus: text3("curation_status").notNull().default("none"),
1579
+ curation: jsonb2("curation").$type(),
1580
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1581
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1582
+ },
1583
+ (table) => ({
1584
+ baseFile: uniqueIndex3("documents_workspace_base_file_idx").on(
1585
+ table.workspaceId,
1586
+ table.baseId,
1587
+ table.fileId
1588
+ ),
1589
+ baseStatus: index3("documents_workspace_base_status_idx").on(
1590
+ table.workspaceId,
1591
+ table.baseId,
1592
+ table.status
1593
+ ),
1594
+ sourceKind: index3("documents_workspace_source_kind_idx").on(
1595
+ table.workspaceId,
1596
+ table.sourceKind
1597
+ ),
1598
+ sourceExternalId: index3("documents_workspace_source_external_id_idx").on(
1599
+ table.workspaceId,
1600
+ table.sourceExternalId
1601
+ ),
1602
+ curationStatus: index3("documents_workspace_curation_status_idx").on(
1603
+ table.workspaceId,
1604
+ table.curationStatus
1605
+ ),
1606
+ visibilityState: check3(
1607
+ "documents_visibility_chk",
1608
+ sql3`${table.visibility} in ('workspace', 'private')`
1609
+ ),
1610
+ curationState: check3(
1611
+ "documents_curation_status_chk",
1612
+ sql3`${table.curationStatus} in ('none', 'pending', 'suggested', 'auto_filed', 'failed')`
1613
+ ),
1614
+ privateCreator: check3(
1615
+ "documents_private_creator_chk",
1616
+ sql3`${table.visibility} <> 'private' or nullif(btrim(${table.createdBy}), '') is not null`
1617
+ ),
1618
+ topicsArray: check3("documents_topics_array_chk", sql3`jsonb_typeof(${table.topics}) = 'array'`),
1619
+ curationObject: check3(
1620
+ "documents_curation_object_chk",
1621
+ sql3`${table.curation} is null or jsonb_typeof(${table.curation}) = 'object'`
1622
+ )
1623
+ })
1624
+ );
1625
+ var documentChunks = pgTable3(
1626
+ "document_chunks",
1627
+ {
1628
+ id: uuid3("id").primaryKey().defaultRandom(),
1629
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1630
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1631
+ documentId: uuid3("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
1632
+ baseId: uuid3("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
1633
+ fileId: uuid3("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
1634
+ chunkIndex: integer2("chunk_index").notNull(),
1635
+ text: text3("text").notNull(),
1636
+ metadata: jsonb2("metadata").$type().notNull().default({}),
1637
+ embedding: vector("embedding").notNull(),
1638
+ embeddingModel: text3("embedding_model").notNull(),
1639
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
1640
+ },
1641
+ (table) => ({
1642
+ documentIndex: uniqueIndex3("document_chunks_workspace_document_index_idx").on(
1643
+ table.workspaceId,
1644
+ table.documentId,
1645
+ table.chunkIndex
1646
+ ),
1647
+ base: index3("document_chunks_workspace_base_idx").on(table.workspaceId, table.baseId)
1648
+ })
1649
+ );
1650
+ var knowledgeMemories = pgTable3(
1651
+ "knowledge_memories",
1652
+ {
1653
+ id: uuid3("id").primaryKey().defaultRandom(),
1654
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1655
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1656
+ status: text3("status").notNull().default("proposed"),
1657
+ kind: text3("kind").notNull().default("semantic"),
1658
+ scope: text3("scope").notNull().default("workspace"),
1659
+ text: text3("text").notNull(),
1660
+ sourceRefs: jsonb2("source_refs").$type().notNull().default([]),
1661
+ confidence: integer2("confidence").notNull().default(50),
1662
+ metadata: jsonb2("metadata").$type().notNull().default({}),
1663
+ createdBySessionId: uuid3("created_by_session_id").references(() => sessions.id, {
1664
+ onDelete: "set null"
1665
+ }),
1666
+ reviewedBy: text3("reviewed_by"),
1667
+ reviewedAt: timestamp3("reviewed_at", { withTimezone: true }),
1668
+ // Workspace Memory V1 (migration 0045). Embedding is nullable: fail-soft writes
1669
+ // (embedder unavailable) persist keyword-searchable rows without a vector.
1670
+ embedding: vector("embedding"),
1671
+ embeddingModel: text3("embedding_model"),
1672
+ pinned: boolean2("pinned").notNull().default(false),
1673
+ usageCount: integer2("usage_count").notNull().default(0),
1674
+ lastUsedAt: timestamp3("last_used_at", { withTimezone: true }),
1675
+ // Self-referential supersession chain. FKs live in migration 0045 (ON DELETE SET
1676
+ // NULL); declared here as plain columns like the migration-only composite FK.
1677
+ supersedesId: uuid3("supersedes_id"),
1678
+ supersededById: uuid3("superseded_by_id"),
1679
+ validFrom: timestamp3("valid_from", { withTimezone: true }).notNull().defaultNow(),
1680
+ validUntil: timestamp3("valid_until", { withTimezone: true }),
1681
+ // sha256(normalizeMemoryText(text)) — exact-dedup key; see memory-domain.
1682
+ textHash: text3("text_hash"),
1683
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1684
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1685
+ },
1686
+ (table) => ({
1687
+ workspaceStatus: index3("knowledge_memories_workspace_status_idx").on(
1688
+ table.workspaceId,
1689
+ table.status,
1690
+ table.updatedAt
1691
+ ),
1692
+ workspaceKind: index3("knowledge_memories_workspace_kind_idx").on(table.workspaceId, table.kind),
1693
+ workspaceScope: index3("knowledge_memories_workspace_scope_idx").on(
1694
+ table.workspaceId,
1695
+ table.scope
1696
+ ),
1697
+ createdBySession: index3("knowledge_memories_workspace_created_by_session_idx").on(
1698
+ table.workspaceId,
1699
+ table.createdBySessionId
1700
+ ),
1701
+ // Working-set selection (partial index mirrors migration 0045).
1702
+ workspaceVisible: index3("knowledge_memories_workspace_visible_idx").on(table.workspaceId, table.pinned, table.updatedAt).where(sql3`${table.status} in ('active', 'approved')`),
1703
+ workspaceTextHash: index3("knowledge_memories_workspace_text_hash_idx").on(
1704
+ table.workspaceId,
1705
+ table.textHash
1706
+ ),
1707
+ workspaceVisibleTextHashUnique: uniqueIndex3("knowledge_memories_workspace_visible_text_hash_uq").on(table.workspaceId, table.textHash).where(sql3`${table.status} in ('active', 'approved') and ${table.textHash} is not null`)
1708
+ })
1709
+ );
1710
+ var sessionTurns = pgTable3(
1711
+ "session_turns",
1712
+ {
1713
+ id: uuid3("id").primaryKey().defaultRandom(),
1714
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1715
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1716
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
1717
+ triggerEventId: uuid3("trigger_event_id").notNull(),
1718
+ temporalWorkflowId: text3("temporal_workflow_id").notNull(),
1719
+ status: text3("status").notNull(),
1720
+ source: text3("source").notNull().default("user"),
1721
+ position: bigint3("position", { mode: "number" }).notNull(),
1722
+ prompt: text3("prompt").notNull(),
1723
+ // Host context for this exact turn. System-level at runtime and deliberately
1724
+ // separate from the visible prompt/event payload.
1725
+ turnInstructions: text3("turn_instructions"),
1726
+ resources: jsonb2("resources").$type().notNull().default([]),
1727
+ tools: jsonb2("tools").$type().notNull().default([]),
1728
+ // false = inherit the durable session policy; true = this turn explicitly
1729
+ // replaces it with `tools` after the core subset fence.
1730
+ toolsProvided: boolean2("tools_provided").notNull().default(false),
1731
+ model: text3("model").notNull(),
1732
+ reasoningEffort: text3("reasoning_effort").notNull(),
1733
+ // Peer of model + reasoning_effort for Fast/priority inheritance.
1734
+ latencyMode: text3("latency_mode").notNull().default("standard"),
1735
+ sandboxBackend: text3("sandbox_backend").notNull(),
1736
+ // Per-turn OS override. NULL = inherit the session's sandbox_os. CHECK-
1737
+ // constrained to the SandboxOs enum (or NULL) in migration 0018.
1738
+ sandboxOs: text3("sandbox_os"),
1739
+ metadata: jsonb2("metadata").$type().notNull().default({}),
1740
+ version: integer2("version").notNull().default(1),
1741
+ executionGeneration: integer2("execution_generation").notNull().default(0),
1742
+ // Composite FK to session_turn_attempts is installed by migration 0063.
1743
+ // It lives in SQL because attempts carry the reciprocal turn FK and because
1744
+ // the claim transaction preallocates this ID before inserting the attempt;
1745
+ // the SQL constraint is therefore DEFERRABLE INITIALLY DEFERRED.
1746
+ activeAttemptId: uuid3("active_attempt_id"),
1747
+ lineage: jsonb2("lineage").$type().notNull().default({}),
1748
+ // Required immutable authority captured when the turn is accepted. These
1749
+ // columns are deliberately outside mutable metadata/lineage.
1750
+ initiatorKind: text3("initiator_kind").notNull().default("service"),
1751
+ initiatorSubjectId: text3("initiator_subject_id").notNull().default("unattributed-legacy"),
1752
+ initiatorContext: jsonb2("initiator_context").$type().notNull().default({ backfill: true }),
1753
+ cancelledBy: text3("cancelled_by"),
1754
+ cancelReason: text3("cancel_reason"),
1755
+ // Atomic per-turn toolspace call budget counter (migration 0043). Incremented
1756
+ // by a single conditional UPDATE at tools/call time; the row lock serializes
1757
+ // concurrent reservations so exactly `toolspaceMaxCallsPerTurn` succeed.
1758
+ toolspaceCallCount: integer2("toolspace_call_count").notNull().default(0),
1759
+ startedAt: timestamp3("started_at", { withTimezone: true }),
1760
+ finishedAt: timestamp3("finished_at", { withTimezone: true }),
1761
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1762
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1763
+ },
1764
+ (table) => ({
1765
+ workspaceIdentity: uniqueIndex3("session_turns_workspace_id_idx").on(
1766
+ table.workspaceId,
1767
+ table.id
1768
+ ),
1769
+ queue: index3("session_turns_workspace_queue_idx").on(
1770
+ table.workspaceId,
1771
+ table.sessionId,
1772
+ table.status,
1773
+ table.position
1774
+ ),
1775
+ oneCurrentInference: uniqueIndex3("session_turns_one_current_inference_uq").on(table.workspaceId, table.sessionId).where(sql3`${table.status} in ('running','requires_action','recovering','waiting_capacity')`),
1776
+ latencyModeValid: check3(
1777
+ "session_turns_latency_mode_check",
1778
+ sql3`${table.latencyMode} in ('standard', 'priority', 'fast')`
1779
+ )
1780
+ })
1781
+ );
1782
+ var sessionTurnAttempts = pgTable3(
1783
+ "session_turn_attempts",
1784
+ {
1785
+ id: uuid3("id").primaryKey(),
1786
+ accountId: uuid3("account_id").notNull(),
1787
+ workspaceId: uuid3("workspace_id").notNull(),
1788
+ sessionId: uuid3("session_id").notNull(),
1789
+ turnId: uuid3("turn_id").notNull(),
1790
+ executionGeneration: integer2("execution_generation").notNull(),
1791
+ state: text3("state").notNull().default("claimed"),
1792
+ outcome: text3("outcome"),
1793
+ temporalWorkflowId: text3("temporal_workflow_id").notNull(),
1794
+ temporalWorkflowRunId: text3("temporal_workflow_run_id").notNull(),
1795
+ temporalActivityId: text3("temporal_activity_id").notNull(),
1796
+ workerId: text3("worker_id"),
1797
+ leaseId: text3("lease_id"),
1798
+ leaseExpiresAt: timestamp3("lease_expires_at", { withTimezone: true }),
1799
+ verifiedControlRevision: bigint3("verified_control_revision", {
1800
+ mode: "number"
1801
+ }).notNull(),
1802
+ // Immutable policy snapshot captured under the session lock at claim.
1803
+ mcpApprovalPolicies: jsonb2("mcp_approval_policies").$type().notNull(),
1804
+ startedAt: timestamp3("started_at", { withTimezone: true }).notNull().defaultNow(),
1805
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow(),
1806
+ closedAt: timestamp3("closed_at", { withTimezone: true }),
1807
+ // The cancelled activity writes this after losing inference, user-visible
1808
+ // output, and workspace-persistence authority. Fenced/idempotent cleanup
1809
+ // and telemetry may still finish. Temporal activity cancellation or
1810
+ // terminalization is transport state only; queue admission and clients use
1811
+ // this durable receipt as the physical-quiescence authority.
1812
+ quiescedAt: timestamp3("quiesced_at", { withTimezone: true })
1813
+ },
1814
+ (table) => ({
1815
+ workspaceAccount: foreignKey({
1816
+ name: "session_turn_attempts_workspace_account_fk",
1817
+ columns: [table.workspaceId, table.accountId],
1818
+ foreignColumns: [workspaces.id, workspaces.accountId]
1819
+ }).onDelete("cascade"),
1820
+ workspaceSession: foreignKey({
1821
+ name: "session_turn_attempts_workspace_session_fk",
1822
+ columns: [table.workspaceId, table.sessionId],
1823
+ foreignColumns: [sessions.workspaceId, sessions.id]
1824
+ }).onDelete("restrict"),
1825
+ workspaceTurn: foreignKey({
1826
+ name: "session_turn_attempts_workspace_turn_fk",
1827
+ columns: [table.workspaceId, table.turnId],
1828
+ foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
1829
+ }).onDelete("restrict"),
1830
+ workspaceIdentity: uniqueIndex3("session_turn_attempts_workspace_id_uq").on(
1831
+ table.workspaceId,
1832
+ table.id
1833
+ ),
1834
+ ownershipIdentity: uniqueIndex3("session_turn_attempts_human_input_owner_uq").on(
1835
+ table.accountId,
1836
+ table.workspaceId,
1837
+ table.sessionId,
1838
+ table.turnId,
1839
+ table.id
1840
+ ),
1841
+ liveTurn: uniqueIndex3("session_turn_attempts_live_turn_uq").on(table.workspaceId, table.turnId).where(sql3`${table.state} in ('claimed', 'running')`),
1842
+ liveSession: uniqueIndex3("session_turn_attempts_live_session_uq").on(table.workspaceId, table.sessionId).where(sql3`${table.state} in ('claimed', 'running')`),
1843
+ latestSessionAttempt: index3("session_turn_attempts_latest_session_idx").on(
1844
+ table.workspaceId,
1845
+ table.sessionId,
1846
+ table.startedAt.desc(),
1847
+ table.id.desc()
1848
+ ),
1849
+ dispatch: uniqueIndex3("session_turn_attempts_dispatch_uq").on(
1850
+ table.workspaceId,
1851
+ table.temporalWorkflowRunId,
1852
+ table.temporalActivityId
1853
+ ),
1854
+ leaseExpiry: index3("session_turn_attempts_lease_expiry_idx").on(table.leaseExpiresAt, table.workspaceId, table.sessionId).where(sql3`${table.state} in ('claimed', 'running')`),
1855
+ stateValid: check3(
1856
+ "session_turn_attempts_state_check",
1857
+ sql3`${table.state} in ('claimed', 'running', 'closed')`
1858
+ ),
1859
+ outcomeValid: check3(
1860
+ "session_turn_attempts_outcome_check",
1861
+ sql3`${table.outcome} is null or ${table.outcome} in (
1862
+ 'completed', 'failed', 'cancelled', 'superseded', 'requires_action',
1863
+ 'waiting_capacity', 'interrupted_recoverable', 'lease_lost_recoverable',
1864
+ 'pre_cutover_closed'
1865
+ )`
1866
+ ),
1867
+ closedConsistent: check3(
1868
+ "session_turn_attempts_closed_check",
1869
+ sql3`(${table.state} = 'closed' and ${table.outcome} is not null and ${table.closedAt} is not null)
1870
+ or (${table.state} <> 'closed' and ${table.outcome} is null and ${table.closedAt} is null)`
1871
+ )
1872
+ })
1873
+ );
1874
+ var sessionCommandReceipts = pgTable3(
1875
+ "session_command_receipts",
1876
+ {
1877
+ id: uuid3("id").primaryKey().defaultRandom(),
1878
+ accountId: uuid3("account_id").notNull(),
1879
+ workspaceId: uuid3("workspace_id").notNull(),
1880
+ actorType: text3("actor_type").notNull(),
1881
+ actorSubjectId: text3("actor_subject_id"),
1882
+ actorAttemptId: uuid3("actor_attempt_id"),
1883
+ action: text3("action").notNull(),
1884
+ targetSessionId: uuid3("target_session_id"),
1885
+ targetTurnId: uuid3("target_turn_id"),
1886
+ operationKey: text3("operation_key").notNull(),
1887
+ canonicalRequestHash: text3("canonical_request_hash").notNull(),
1888
+ appliedControlRevision: bigint3("applied_control_revision", {
1889
+ mode: "number"
1890
+ }),
1891
+ appliedQueueVersion: integer2("applied_queue_version"),
1892
+ appliedTurnVersion: integer2("applied_turn_version"),
1893
+ appliedDraftRevision: bigint3("applied_draft_revision", { mode: "number" }),
1894
+ result: jsonb2("result").$type().notNull().default({}),
1895
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
1896
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
1897
+ },
1898
+ (table) => ({
1899
+ workspaceAccount: foreignKey({
1900
+ name: "session_command_receipts_workspace_account_fk",
1901
+ columns: [table.workspaceId, table.accountId],
1902
+ foreignColumns: [workspaces.id, workspaces.accountId]
1903
+ }).onDelete("cascade"),
1904
+ actorAttempt: foreignKey({
1905
+ name: "session_command_receipts_actor_attempt_fk",
1906
+ columns: [table.workspaceId, table.actorAttemptId],
1907
+ foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
1908
+ }).onDelete("restrict"),
1909
+ targetSession: foreignKey({
1910
+ name: "session_command_receipts_target_session_fk",
1911
+ columns: [table.workspaceId, table.targetSessionId],
1912
+ foreignColumns: [sessions.workspaceId, sessions.id]
1913
+ }).onDelete("restrict"),
1914
+ targetTurn: foreignKey({
1915
+ name: "session_command_receipts_target_turn_fk",
1916
+ columns: [table.workspaceId, table.targetTurnId],
1917
+ foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
1918
+ }).onDelete("restrict"),
1919
+ workspaceIdentity: uniqueIndex3("session_command_receipts_workspace_id_uq").on(
1920
+ table.workspaceId,
1921
+ table.id
1922
+ ),
1923
+ targetCreated: index3("session_command_receipts_target_created_idx").on(
1924
+ table.workspaceId,
1925
+ table.targetSessionId,
1926
+ table.createdAt
1927
+ ),
1928
+ goalUpdateOperation: uniqueIndex3("session_command_receipts_goal_update_operation_uq").on(table.workspaceId, table.action, table.targetSessionId, table.operationKey).where(sql3`${table.action} = 'goal.update'`),
1929
+ actorValid: check3(
1930
+ "session_command_receipts_actor_check",
1931
+ sql3`(
1932
+ ${table.actorType} = 'agent_attempt'
1933
+ and ${table.actorAttemptId} is not null
1934
+ and ${table.actorSubjectId} is null
1935
+ ) or (
1936
+ ${table.actorType} in ('human', 'operator', 'service')
1937
+ and ${table.actorSubjectId} is not null
1938
+ and ${table.actorAttemptId} is null
1939
+ )`
1940
+ )
1941
+ })
1942
+ );
1943
+ var workspaceControlEvents = pgTable3(
1944
+ "workspace_control_events",
1945
+ {
1946
+ id: uuid3("id").primaryKey().defaultRandom(),
1947
+ accountId: uuid3("account_id").notNull(),
1948
+ workspaceId: uuid3("workspace_id").notNull(),
1949
+ revision: bigint3("revision", { mode: "number" }).notNull(),
1950
+ scope: text3("scope").notNull(),
1951
+ rootSessionId: uuid3("root_session_id"),
1952
+ action: text3("action").notNull(),
1953
+ automatic: boolean2("automatic").notNull().default(false),
1954
+ reason: text3("reason"),
1955
+ reasonOriginalBytes: integer2("reason_original_bytes"),
1956
+ actor: text3("actor").notNull(),
1957
+ // Null is the rolling-upgrade shape for untouched, already-bounded legacy
1958
+ // rows. New writes and rewritten poison rows carry exact source byte facts.
1959
+ actorOriginalBytes: integer2("actor_original_bytes"),
1960
+ occurredAt: timestamp3("occurred_at", { withTimezone: true }).notNull().defaultNow()
1961
+ },
1962
+ (table) => ({
1963
+ workspaceAccount: foreignKey({
1964
+ name: "workspace_control_events_workspace_account_fk",
1965
+ columns: [table.workspaceId, table.accountId],
1966
+ foreignColumns: [workspaces.id, workspaces.accountId]
1967
+ }).onDelete("cascade"),
1968
+ rootSession: foreignKey({
1969
+ name: "workspace_control_events_root_session_fk",
1970
+ columns: [table.workspaceId, table.rootSessionId],
1971
+ foreignColumns: [sessions.workspaceId, sessions.id]
1972
+ }).onDelete("restrict"),
1973
+ workspaceRevision: uniqueIndex3("workspace_control_events_workspace_revision_uq").on(
1974
+ table.workspaceId,
1975
+ table.revision
1976
+ ),
1977
+ revisionValid: check3("workspace_control_events_revision_check", sql3`${table.revision} > 0`),
1978
+ shapeValid: check3(
1979
+ "workspace_control_events_shape_check",
1980
+ sql3`(${table.scope} = 'workspace' and ${table.rootSessionId} is null)
1981
+ or (${table.scope} = 'session' and ${table.rootSessionId} is not null)`
1982
+ ),
1983
+ actionValid: check3(
1984
+ "workspace_control_events_action_check",
1985
+ sql3`${table.action} in ('pause', 'resume')`
1986
+ )
1987
+ })
1988
+ );
1989
+ var sessionAttemptInterruptions = pgTable3(
1990
+ "session_attempt_interruptions",
1991
+ {
1992
+ id: uuid3("id").primaryKey().defaultRandom(),
1993
+ accountId: uuid3("account_id").notNull(),
1994
+ workspaceId: uuid3("workspace_id").notNull(),
1995
+ sessionId: uuid3("session_id").notNull(),
1996
+ operationId: uuid3("operation_id").notNull(),
1997
+ attemptId: uuid3("attempt_id").notNull(),
1998
+ kind: text3("kind").notNull(),
1999
+ controlRevision: bigint3("control_revision", { mode: "number" }).notNull(),
2000
+ state: text3("state").notNull().default("pending"),
2001
+ requestedAt: timestamp3("requested_at", { withTimezone: true }).notNull().defaultNow(),
2002
+ deliveredAt: timestamp3("delivered_at", { withTimezone: true }),
2003
+ acknowledgedAt: timestamp3("acknowledged_at", { withTimezone: true }),
2004
+ settledAt: timestamp3("settled_at", { withTimezone: true })
2005
+ },
2006
+ (table) => ({
2007
+ workspaceAccount: foreignKey({
2008
+ name: "session_attempt_interruptions_workspace_account_fk",
2009
+ columns: [table.workspaceId, table.accountId],
2010
+ foreignColumns: [workspaces.id, workspaces.accountId]
2011
+ }).onDelete("cascade"),
2012
+ workspaceSession: foreignKey({
2013
+ name: "session_attempt_interruptions_workspace_session_fk",
2014
+ columns: [table.workspaceId, table.sessionId],
2015
+ foreignColumns: [sessions.workspaceId, sessions.id]
2016
+ }).onDelete("restrict"),
2017
+ operation: foreignKey({
2018
+ name: "session_attempt_interruptions_operation_fk",
2019
+ columns: [table.workspaceId, table.operationId],
2020
+ foreignColumns: [sessionCommandReceipts.workspaceId, sessionCommandReceipts.id]
2021
+ }).onDelete("restrict"),
2022
+ attempt: foreignKey({
2023
+ name: "session_attempt_interruptions_attempt_fk",
2024
+ columns: [table.workspaceId, table.attemptId],
2025
+ foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
2026
+ }).onDelete("restrict"),
2027
+ operationAttempt: uniqueIndex3("session_attempt_interruptions_operation_attempt_uq").on(
2028
+ table.operationId,
2029
+ table.attemptId
2030
+ ),
2031
+ unsettled: index3("session_attempt_interruptions_unsettled_idx").on(table.workspaceId, table.sessionId, table.requestedAt).where(sql3`${table.state} in ('pending', 'delivered', 'acknowledged')`),
2032
+ kindValid: check3(
2033
+ "session_attempt_interruptions_kind_check",
2034
+ sql3`${table.kind} in ('session_pause', 'workspace_pause', 'steer', 'maintenance')`
2035
+ ),
2036
+ stateValid: check3(
2037
+ "session_attempt_interruptions_state_check",
2038
+ sql3`${table.state} in ('pending', 'delivered', 'acknowledged', 'settled', 'rejected_stale')`
2039
+ )
2040
+ })
2041
+ );
2042
+ var composerDrafts = pgTable3(
2043
+ "composer_drafts",
2044
+ {
2045
+ id: uuid3("id").primaryKey().defaultRandom(),
2046
+ accountId: uuid3("account_id").notNull(),
2047
+ workspaceId: uuid3("workspace_id").notNull(),
2048
+ sessionId: uuid3("session_id").notNull(),
2049
+ subjectId: text3("subject_id").notNull(),
2050
+ revision: bigint3("revision", { mode: "number" }).notNull().default(1),
2051
+ text: text3("text").notNull().default(""),
2052
+ resources: jsonb2("resources").$type().notNull().default([]),
2053
+ tools: jsonb2("tools").$type().notNull().default([]),
2054
+ toolsProvided: boolean2("tools_provided").notNull().default(false),
2055
+ model: text3("model").notNull(),
2056
+ reasoningEffort: text3("reasoning_effort").notNull(),
2057
+ latencyMode: text3("latency_mode").notNull().default("standard"),
2058
+ sourceTurnId: uuid3("source_turn_id"),
2059
+ sourceTurnVersion: integer2("source_turn_version"),
2060
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
2061
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
2062
+ },
2063
+ (table) => ({
2064
+ workspaceAccount: foreignKey({
2065
+ name: "composer_drafts_workspace_account_fk",
2066
+ columns: [table.workspaceId, table.accountId],
2067
+ foreignColumns: [workspaces.id, workspaces.accountId]
2068
+ }).onDelete("cascade"),
2069
+ workspaceSession: foreignKey({
2070
+ name: "composer_drafts_workspace_session_fk",
2071
+ columns: [table.workspaceId, table.sessionId],
2072
+ foreignColumns: [sessions.workspaceId, sessions.id]
2073
+ }).onDelete("cascade"),
2074
+ sourceTurn: foreignKey({
2075
+ name: "composer_drafts_source_turn_fk",
2076
+ columns: [table.workspaceId, table.sourceTurnId],
2077
+ foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
2078
+ }).onDelete("restrict"),
2079
+ subjectSession: uniqueIndex3("composer_drafts_subject_session_uq").on(
2080
+ table.workspaceId,
2081
+ table.sessionId,
2082
+ table.subjectId
2083
+ ),
2084
+ subjectValid: check3(
2085
+ "composer_drafts_subject_check",
2086
+ sql3`length(btrim(${table.subjectId})) > 0`
2087
+ ),
2088
+ revisionValid: check3("composer_drafts_revision_check", sql3`${table.revision} >= 1`),
2089
+ latencyModeValid: check3(
2090
+ "composer_drafts_latency_mode_check",
2091
+ sql3`${table.latencyMode} in ('standard', 'priority', 'fast')`
2092
+ )
2093
+ })
2094
+ );
2095
+ var newSessionDrafts = pgTable3(
2096
+ "new_session_drafts",
2097
+ {
2098
+ id: uuid3("id").primaryKey().defaultRandom(),
2099
+ accountId: uuid3("account_id").notNull(),
2100
+ workspaceId: uuid3("workspace_id").notNull(),
2101
+ subjectId: text3("subject_id").notNull(),
2102
+ revision: bigint3("revision", { mode: "number" }).notNull().default(1),
2103
+ text: text3("text").notNull().default(""),
2104
+ resources: jsonb2("resources").$type().notNull().default([]),
2105
+ tools: jsonb2("tools").$type().notNull().default([]),
2106
+ model: text3("model").notNull(),
2107
+ reasoningEffort: text3("reasoning_effort").notNull(),
2108
+ latencyMode: text3("latency_mode").notNull().default("standard"),
2109
+ sessionOptions: jsonb2("session_options").$type().notNull().default({}),
2110
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
2111
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
2112
+ },
2113
+ (table) => ({
2114
+ workspaceAccount: foreignKey({
2115
+ name: "new_session_drafts_workspace_account_fk",
2116
+ columns: [table.workspaceId, table.accountId],
2117
+ foreignColumns: [workspaces.id, workspaces.accountId]
2118
+ }).onDelete("cascade"),
2119
+ subjectWorkspace: uniqueIndex3("new_session_drafts_subject_workspace_uq").on(
2120
+ table.workspaceId,
2121
+ table.subjectId
2122
+ ),
2123
+ subjectValid: check3(
2124
+ "new_session_drafts_subject_check",
2125
+ sql3`length(btrim(${table.subjectId})) > 0`
2126
+ ),
2127
+ revisionValid: check3("new_session_drafts_revision_check", sql3`${table.revision} >= 1`),
2128
+ latencyModeValid: check3(
2129
+ "new_session_drafts_latency_mode_check",
2130
+ sql3`${table.latencyMode} in ('standard', 'priority', 'fast')`
2131
+ )
2132
+ })
2133
+ );
2134
+ var sessionSystemUpdates = pgTable3(
2135
+ "session_system_updates",
2136
+ {
2137
+ id: uuid3("id").primaryKey().defaultRandom(),
2138
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2139
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2140
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2141
+ kind: text3("kind").notNull(),
2142
+ classification: text3("classification").notNull().default("info"),
2143
+ sourceId: text3("source_id").notNull(),
2144
+ dedupeKey: text3("dedupe_key").notNull(),
2145
+ summary: text3("summary").notNull(),
2146
+ payload: jsonb2("payload").$type().notNull().default({}),
2147
+ lineage: jsonb2("lineage").$type().notNull().default({}),
2148
+ // pending is visible queue truth; delivered means its exact model-memory
2149
+ // batch was durably claimed. Terminal cancellation/supersession is explicit.
2150
+ state: text3("state").notNull().default("pending"),
2151
+ deliveredTurnId: uuid3("delivered_turn_id").references(() => sessionTurns.id, {
2152
+ onDelete: "set null"
2153
+ }),
2154
+ // Migration owns the forward FK to session_history_items, declared later.
2155
+ // Every member of one claimed batch points at the exact model-memory row.
2156
+ deliveredHistoryItemId: uuid3("delivered_history_item_id"),
2157
+ deliveredAt: timestamp3("delivered_at", { withTimezone: true }),
2158
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
2159
+ },
2160
+ (table) => ({
2161
+ kindValid: check3(
2162
+ "system_updates_kind_check",
2163
+ sql3`${table.kind} in ('scheduled_occurrence', 'goal_continuation', 'agent_message', 'agent_steer_instruction', 'child_terminal_result')`
2164
+ ),
2165
+ payloadKindValid: check3(
2166
+ "system_updates_payload_kind_check",
2167
+ sql3`${table.payload} ->> 'type' = ${table.kind}`
2168
+ ),
2169
+ stateValid: check3(
2170
+ "system_updates_state_check",
2171
+ sql3`${table.state} in ('pending', 'delivered', 'cancelled', 'superseded', 'failed')`
2172
+ ),
2173
+ dedupe: uniqueIndex3("session_system_updates_dedupe_uq").on(
2174
+ table.workspaceId,
2175
+ table.sessionId,
2176
+ table.dedupeKey
2177
+ ),
2178
+ pending: index3("session_system_updates_pending_idx").on(
2179
+ table.workspaceId,
2180
+ table.sessionId,
2181
+ table.state,
2182
+ table.createdAt
2183
+ ),
2184
+ onePendingSteer: uniqueIndex3("session_system_updates_one_pending_steer_idx").on(table.workspaceId, table.sessionId).where(sql3`${table.kind} = 'agent_steer_instruction' and ${table.state} = 'pending'`),
2185
+ deliveryHistoryValid: check3(
2186
+ "session_system_updates_delivery_history_check",
2187
+ sql3`(
2188
+ (${table.state} = 'delivered' and ${table.deliveredHistoryItemId} is not null)
2189
+ or
2190
+ (${table.state} <> 'delivered' and ${table.deliveredHistoryItemId} is null)
2191
+ )`
2192
+ )
2193
+ })
2194
+ );
2195
+ var sessionSystemUpdateOutbox = pgTable3(
2196
+ "session_system_update_outbox",
2197
+ {
2198
+ id: uuid3("id").primaryKey().defaultRandom(),
2199
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2200
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2201
+ sourceSessionId: uuid3("source_session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2202
+ targetSessionId: uuid3("target_session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2203
+ dedupeKey: text3("dedupe_key").notNull(),
2204
+ kind: text3("kind").notNull(),
2205
+ classification: text3("classification").notNull(),
2206
+ sourceId: text3("source_id").notNull(),
2207
+ summary: text3("summary").notNull(),
2208
+ payload: jsonb2("payload").$type().notNull().default({}),
2209
+ lineage: jsonb2("lineage").$type().notNull().default({}),
2210
+ status: text3("status").notNull().default("pending"),
2211
+ attempts: integer2("attempts").notNull().default(0),
2212
+ updateId: uuid3("update_id"),
2213
+ lastError: text3("last_error"),
2214
+ deliveredAt: timestamp3("delivered_at", { withTimezone: true }),
2215
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
2216
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
2217
+ },
2218
+ (table) => ({
2219
+ kindValid: check3(
2220
+ "system_update_outbox_kind_check",
2221
+ sql3`${table.kind} = 'child_terminal_result'`
2222
+ ),
2223
+ payloadKindValid: check3(
2224
+ "system_update_outbox_payload_kind_check",
2225
+ sql3`${table.payload} ->> 'type' = 'child_terminal_result'`
2226
+ ),
2227
+ dedupe: uniqueIndex3("session_system_update_outbox_dedupe_uq").on(
2228
+ table.workspaceId,
2229
+ table.dedupeKey
2230
+ ),
2231
+ pending: index3("session_system_update_outbox_pending_idx").on(table.status, table.createdAt)
2232
+ })
2233
+ );
2234
+ var sessionWorkflowWakeOutbox = pgTable3(
2235
+ "session_workflow_wake_outbox",
2236
+ {
2237
+ sessionId: uuid3("session_id").primaryKey(),
2238
+ accountId: uuid3("account_id").notNull(),
2239
+ workspaceId: uuid3("workspace_id").notNull(),
2240
+ temporalWorkflowId: text3("temporal_workflow_id").notNull(),
2241
+ wakeRevision: bigint3("wake_revision", { mode: "number" }).notNull().default(1),
2242
+ deliveredRevision: bigint3("delivered_revision", { mode: "number" }).notNull().default(0),
2243
+ reason: text3("reason").notNull(),
2244
+ attempts: integer2("attempts").notNull().default(0),
2245
+ nextAttemptAt: timestamp3("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
2246
+ lastError: text3("last_error"),
2247
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
2248
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
2249
+ },
2250
+ (table) => ({
2251
+ revisionValid: check3(
2252
+ "session_workflow_wake_outbox_revision_check",
2253
+ sql3`${table.wakeRevision} > 0 and ${table.deliveredRevision} >= 0 and ${table.deliveredRevision} <= ${table.wakeRevision}`
2254
+ ),
2255
+ revisionSafe: check3(
2256
+ "session_workflow_wake_outbox_revision_safe_check",
2257
+ sql3`${table.wakeRevision} <= 9007199254740991 and ${table.deliveredRevision} <= 9007199254740991`
2258
+ ),
2259
+ workspaceAccount: foreignKey({
2260
+ name: "session_workflow_wake_outbox_workspace_account_fk",
2261
+ columns: [table.workspaceId, table.accountId],
2262
+ foreignColumns: [workspaces.id, workspaces.accountId]
2263
+ }).onDelete("cascade"),
2264
+ workspaceSessionFk: foreignKey({
2265
+ name: "session_workflow_wake_outbox_workspace_session_fk",
2266
+ columns: [table.workspaceId, table.sessionId],
2267
+ foreignColumns: [sessions.workspaceId, sessions.id]
2268
+ }).onDelete("cascade"),
2269
+ workspaceSession: uniqueIndex3("session_workflow_wake_outbox_workspace_session_uq").on(
2270
+ table.workspaceId,
2271
+ table.sessionId
2272
+ ),
2273
+ pending: index3("session_workflow_wake_outbox_pending_idx").on(table.nextAttemptAt, table.updatedAt, table.sessionId).where(sql3`${table.wakeRevision} > ${table.deliveredRevision}`)
2274
+ })
2275
+ );
2276
+ var sessionGoals = pgTable3(
2277
+ "session_goals",
2278
+ {
2279
+ id: uuid3("id").primaryKey().defaultRandom(),
2280
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2281
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2282
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2283
+ status: text3("status").notNull().default("active"),
2284
+ // active | paused | completed
2285
+ text: text3("text").notNull(),
2286
+ successCriteria: text3("success_criteria"),
2287
+ evidence: text3("evidence"),
2288
+ // set by goal_complete
2289
+ rationale: text3("rationale"),
2290
+ // set by goal_pause
2291
+ pausedReason: text3("paused_reason"),
2292
+ // agent | user_pause | api | no_progress | max_auto_continuations | limits
2293
+ createdBy: text3("created_by").notNull().default("api"),
2294
+ // api | agent | scheduled_task
2295
+ version: integer2("version").notNull().default(1),
2296
+ // bumped on every set/update; progress signal
2297
+ autoContinuations: integer2("auto_continuations").notNull().default(0),
2298
+ noProgressStreak: integer2("no_progress_streak").notNull().default(0),
2299
+ maxAutoContinuations: integer2("max_auto_continuations"),
2300
+ // per-goal override; a configured settings cap (if any) remains the hard ceiling
2301
+ lastContinuationTurnId: uuid3("last_continuation_turn_id"),
2302
+ versionAtLastContinuation: integer2("version_at_last_continuation"),
2303
+ // Postgres owns the continuation obligation. Terminal settlement advances
2304
+ // wakeRevision in the same transaction that makes the session idle;
2305
+ // materialization advances observedRevision only alongside the one typed
2306
+ // update, timeline events, usage row, and workflow-wake outbox row.
2307
+ // Temporal signals and workflow history are replaceable nudges over these
2308
+ // monotonic revisions.
2309
+ continuationWakeRevision: bigint3("continuation_wake_revision", { mode: "number" }).notNull().default(0),
2310
+ continuationObservedRevision: bigint3("continuation_observed_revision", { mode: "number" }).notNull().default(0),
2311
+ metadata: jsonb2("metadata").$type().notNull().default({}),
2312
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
2313
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
2314
+ },
2315
+ (table) => ({
2316
+ workspaceIdentity: uniqueIndex3("session_goals_workspace_id_idx").on(
2317
+ table.workspaceId,
2318
+ table.id
2319
+ ),
2320
+ workspaceSession: uniqueIndex3("session_goals_workspace_session_idx").on(
2321
+ table.workspaceId,
2322
+ table.sessionId
2323
+ ),
2324
+ status: index3("session_goals_workspace_status_idx").on(table.workspaceId, table.status),
2325
+ continuationRevisionValid: check3(
2326
+ "session_goals_continuation_revision_check",
2327
+ sql3`${table.continuationWakeRevision} >= 0 and ${table.continuationObservedRevision} >= 0 and ${table.continuationObservedRevision} <= ${table.continuationWakeRevision} and ${table.continuationWakeRevision} <= 9007199254740991 and ${table.continuationObservedRevision} <= 9007199254740991`
2328
+ )
2329
+ })
2330
+ );
2331
+ var codexCapacityWaiters = pgTable3(
2332
+ "codex_capacity_waiters",
2333
+ {
2334
+ id: uuid3("id").primaryKey().defaultRandom(),
2335
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2336
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2337
+ sessionId: uuid3("session_id").notNull(),
2338
+ goalId: uuid3("goal_id"),
2339
+ blockedTurnId: uuid3("blocked_turn_id").notNull(),
2340
+ blockedTurnGeneration: integer2("blocked_turn_generation").notNull(),
2341
+ workflowId: text3("workflow_id").notNull(),
2342
+ generation: integer2("generation").notNull().default(1),
2343
+ status: text3("status").notNull().default("waiting"),
2344
+ // waiting | resumed | superseded
2345
+ goalVersion: integer2("goal_version"),
2346
+ policyHash: text3("policy_hash"),
2347
+ earliestResetAt: timestamp3("earliest_reset_at", { withTimezone: true }),
2348
+ nextCheckAt: timestamp3("next_check_at", { withTimezone: true }).notNull(),
2349
+ resetKind: text3("reset_kind").notNull(),
2350
+ // authoritative | bounded_refresh
2351
+ refreshAttempt: integer2("refresh_attempt").notNull().default(0),
2352
+ // Coalescing outbox generation. Every eligibility-affecting mutation bumps
2353
+ // wakeRevision. Duplicate/lost Temporal signals are harmless because only
2354
+ // the row-locked evaluator moves observedWakeRevision and may enqueue work.
2355
+ wakeRevision: integer2("wake_revision").notNull().default(1),
2356
+ observedWakeRevision: integer2("observed_wake_revision").notNull().default(0),
2357
+ lastWakeReason: text3("last_wake_reason").notNull().default("capacity_wait_armed"),
2358
+ resumedUpdateId: uuid3("resumed_update_id"),
2359
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
2360
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
2361
+ },
2362
+ (table) => ({
2363
+ workspaceSession: uniqueIndex3("codex_capacity_waiters_workspace_session_idx").on(
2364
+ table.workspaceId,
2365
+ table.sessionId
2366
+ ),
2367
+ workspaceId: uniqueIndex3("codex_capacity_waiters_workspace_id_idx").on(
2368
+ table.workspaceId,
2369
+ table.id
2370
+ ),
2371
+ pending: index3("codex_capacity_waiters_pending_idx").on(
2372
+ table.workspaceId,
2373
+ table.status,
2374
+ table.nextCheckAt
2375
+ ),
2376
+ wakeRepair: index3("codex_capacity_waiters_wake_repair_idx").on(
2377
+ table.status,
2378
+ table.wakeRevision,
2379
+ table.observedWakeRevision
2380
+ )
2381
+ })
2382
+ );
2383
+ var sessionEvents = pgTable3(
2384
+ "session_events",
2385
+ {
2386
+ id: uuid3("id").primaryKey().defaultRandom(),
2387
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2388
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2389
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2390
+ turnId: uuid3("turn_id"),
2391
+ turnGeneration: integer2("turn_generation"),
2392
+ turnAttemptId: uuid3("turn_attempt_id"),
2393
+ turnAssociation: text3("turn_association"),
2394
+ duplicateOfEventId: uuid3("duplicate_of_event_id"),
2395
+ duplicateReason: text3("duplicate_reason"),
2396
+ sequence: integer2("sequence").notNull(),
2397
+ type: text3("type").notNull(),
2398
+ payload: jsonb2("payload").$type().notNull().default({}),
2399
+ clientEventId: text3("client_event_id"),
2400
+ producerId: text3("producer_id"),
2401
+ producerSeq: integer2("producer_seq"),
2402
+ occurredAt: timestamp3("occurred_at", { withTimezone: true }).notNull().defaultNow(),
2403
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
2404
+ },
2405
+ (table) => ({
2406
+ workspaceAttempt: foreignKey({
2407
+ name: "session_events_workspace_attempt_fk",
2408
+ columns: [table.workspaceId, table.turnAttemptId],
2409
+ foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
2410
+ }).onDelete("restrict"),
2411
+ sessionSequence: uniqueIndex3("session_events_workspace_session_sequence_idx").on(
2412
+ table.workspaceId,
2413
+ table.sessionId,
2414
+ table.sequence
2415
+ ),
2416
+ clientEvent: uniqueIndex3("session_events_workspace_client_event_idx").on(table.workspaceId, table.sessionId, table.clientEventId).where(sql3`${table.clientEventId} is not null`),
2417
+ producer: uniqueIndex3("session_events_workspace_producer_idx").on(table.workspaceId, table.sessionId, table.producerId, table.producerSeq).where(sql3`${table.producerId} is not null and ${table.producerSeq} is not null`),
2418
+ sessionCreated: index3("session_events_workspace_session_created_idx").on(
2419
+ table.workspaceId,
2420
+ table.sessionId,
2421
+ table.createdAt
2422
+ ),
2423
+ sessionTypeSequence: index3("session_events_workspace_session_type_sequence_idx").on(
2424
+ table.workspaceId,
2425
+ table.sessionId,
2426
+ table.type,
2427
+ table.sequence
2428
+ ),
2429
+ monitoringTail: index3("session_events_workspace_session_monitoring_tail_idx").on(table.workspaceId, table.sessionId, table.sequence).where(
2430
+ sql3`${table.type} not in ('agent.message.delta', 'agent.reasoning.delta', 'sandbox.command.output.delta', 'terminal.pty.output.delta')`
2431
+ ),
2432
+ duplicateOfEvent: index3("session_events_duplicate_of_event_idx").on(table.duplicateOfEventId),
2433
+ payloadBytes: check3(
2434
+ "session_events_payload_bytes_check",
2435
+ sql3`octet_length(${table.payload}::text) <= 65536`
2436
+ ),
2437
+ typeBytes: check3(
2438
+ "session_events_type_bytes_check",
2439
+ sql3`octet_length(${table.type}) <= 256 and position(E'\n' in ${table.type}) = 0 and position(E'\r' in ${table.type}) = 0`
2440
+ ),
2441
+ clientEventIdBytes: check3(
2442
+ "session_events_client_event_id_bytes_check",
2443
+ sql3`${table.clientEventId} is null or octet_length(${table.clientEventId}) <= 1024`
2444
+ ),
2445
+ producerIdBytes: check3(
2446
+ "session_events_producer_id_bytes_check",
2447
+ sql3`${table.producerId} is null or octet_length(${table.producerId}) <= 1024`
2448
+ ),
2449
+ turnAssociationBytes: check3(
2450
+ "session_events_turn_association_bytes_check",
2451
+ sql3`${table.turnAssociation} is null or octet_length(${table.turnAssociation}) <= 64`
2452
+ ),
2453
+ duplicateReasonBytes: check3(
2454
+ "session_events_duplicate_reason_bytes_check",
2455
+ sql3`${table.duplicateReason} is null or octet_length(${table.duplicateReason}) <= 4096`
2456
+ )
2457
+ })
2458
+ );
2459
+ var agentRunStates = pgTable3("agent_run_states", {
2460
+ id: uuid3("id").primaryKey().defaultRandom(),
2461
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2462
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2463
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2464
+ turnId: uuid3("turn_id").references(() => sessionTurns.id, {
2465
+ onDelete: "set null"
2466
+ }),
2467
+ stateVersion: integer2("state_version").notNull(),
2468
+ serializedRunState: text3("serialized_run_state").notNull(),
2469
+ pendingApprovals: jsonb2("pending_approvals").$type().notNull().default([]),
2470
+ // The Codex account that FROZE this run state: the turn's resolved codex
2471
+ // credential id (pin > workspace-active), or NULL when frozen on the
2472
+ // non-codex / Azure path (or before this column existed). The serialized
2473
+ // RunState blob round-trips `reasoning.encrypted_content` minted by the
2474
+ // ChatGPT/Codex backend — account/org-bound, so a foreign blob 400s — and the
2475
+ // foreign reasoning ids the Responses backend validates; but the blob carries
2476
+ // NO per-item producer tag (those live only on session_history_items). So we
2477
+ // stamp the freezing account here: on an approval resume whose codex account
2478
+ // DIFFERS from this value,
2479
+ // the replay path neutralizes every reasoning item's account-bound identity
2480
+ // (encrypted_content + provider id) in the blob before it reaches the model.
2481
+ // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect (a
2482
+ // stale-but-null tag still mismatches a live codex id, so the strip stays
2483
+ // correct either way). NULL on both sides (non-codex freeze + non-codex
2484
+ // resume) is a no-op, so single-account and non-codex sessions are unchanged.
2485
+ frozenCodexCredentialId: uuid3("frozen_codex_credential_id"),
2486
+ // Exact provider rejection invalidates only the opaque reasoning identity
2487
+ // inside this frozen state. The serialized receipt remains durable and
2488
+ // auditable; the resume path neutralizes its provider-bound identity.
2489
+ providerArtifactInvalidatedAt: timestamp3("provider_artifact_invalidated_at", {
2490
+ withTimezone: true
2491
+ }),
2492
+ providerArtifactInvalidationReason: text3("provider_artifact_invalidation_reason"),
2493
+ providerArtifactInvalidatedByAttemptId: uuid3("provider_artifact_invalidated_by_attempt_id"),
2494
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
2495
+ });
2496
+ var sessionHumanInputRequests = pgTable3(
2497
+ "session_human_input_requests",
2498
+ {
2499
+ id: uuid3("id").primaryKey().defaultRandom(),
2500
+ accountId: uuid3("account_id").notNull(),
2501
+ workspaceId: uuid3("workspace_id").notNull(),
2502
+ sessionId: uuid3("session_id").notNull(),
2503
+ turnId: uuid3("turn_id").notNull(),
2504
+ turnGeneration: integer2("turn_generation").notNull(),
2505
+ creationAttemptId: uuid3("creation_attempt_id").notNull(),
2506
+ toolCallId: text3("tool_call_id").notNull(),
2507
+ status: text3("status").notNull().default("pending"),
2508
+ questions: jsonb2("questions").$type().notNull(),
2509
+ allowSkip: boolean2("allow_skip").notNull().default(false),
2510
+ response: jsonb2("response").$type(),
2511
+ respondedBy: text3("responded_by"),
2512
+ respondedAt: timestamp3("responded_at", { withTimezone: true }),
2513
+ expiresAt: timestamp3("expires_at", { withTimezone: true }),
2514
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
2515
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
2516
+ },
2517
+ (table) => ({
2518
+ creationAttemptOwner: foreignKey({
2519
+ name: "session_human_input_requests_creation_attempt_fk",
2520
+ columns: [
2521
+ table.accountId,
2522
+ table.workspaceId,
2523
+ table.sessionId,
2524
+ table.turnId,
2525
+ table.creationAttemptId
2526
+ ],
2527
+ foreignColumns: [
2528
+ sessionTurnAttempts.accountId,
2529
+ sessionTurnAttempts.workspaceId,
2530
+ sessionTurnAttempts.sessionId,
2531
+ sessionTurnAttempts.turnId,
2532
+ sessionTurnAttempts.id
2533
+ ]
2534
+ }).onDelete("cascade"),
2535
+ toolCall: uniqueIndex3("session_human_input_requests_tool_call_uq").on(
2536
+ table.workspaceId,
2537
+ table.sessionId,
2538
+ table.turnId,
2539
+ table.toolCallId
2540
+ ),
2541
+ pendingSession: index3("session_human_input_requests_pending_session_idx").on(table.workspaceId, table.sessionId, table.createdAt, table.id).where(sql3`${table.status} = 'pending'`),
2542
+ pendingExpiry: index3("session_human_input_requests_pending_expiry_idx").on(table.expiresAt, table.id).where(sql3`${table.status} = 'pending' and ${table.expiresAt} is not null`),
2543
+ status: check3(
2544
+ "session_human_input_requests_status_check",
2545
+ sql3`${table.status} in ('pending','answered','skipped','expired','cancelled')`
2546
+ ),
2547
+ generation: check3(
2548
+ "session_human_input_requests_generation_check",
2549
+ sql3`${table.turnGeneration} > 0`
2550
+ ),
2551
+ toolCallBytes: check3(
2552
+ "session_human_input_requests_tool_call_bytes_check",
2553
+ sql3`octet_length(${table.toolCallId}) between 1 and 1024`
2554
+ ),
2555
+ questionsBytes: check3(
2556
+ "session_human_input_requests_questions_bytes_check",
2557
+ sql3`octet_length(${table.questions}::text) <= 49152`
2558
+ ),
2559
+ responseBytes: check3(
2560
+ "session_human_input_requests_response_bytes_check",
2561
+ sql3`${table.response} is null or octet_length(${table.response}::text) <= 49152`
2562
+ ),
2563
+ actorBytes: check3(
2564
+ "session_human_input_requests_actor_bytes_check",
2565
+ sql3`${table.respondedBy} is null or octet_length(${table.respondedBy}) <= 1024`
2566
+ )
2567
+ })
2568
+ );
2569
+ var sessionHistoryItems = pgTable3(
2570
+ "session_history_items",
2571
+ {
2572
+ id: uuid3("id").primaryKey().defaultRandom(),
2573
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2574
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2575
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2576
+ turnId: uuid3("turn_id").references(() => sessionTurns.id, {
2577
+ onDelete: "set null"
2578
+ }),
2579
+ // Numeric (not integer) so the synthetic compaction-summary row can be
2580
+ // inserted at a FRACTIONAL position (boundaryPosition - 0.5) that sorts ahead
2581
+ // of the kept tail without colliding with — and thus overwriting — the real
2582
+ // prefix row at boundaryPosition - 1. Normally-appended rows keep whole-number
2583
+ // positions; only the summary uses the half-step. `mode: "number"` maps the
2584
+ // postgres.js string back to a JS number so every reader stays numeric.
2585
+ position: numeric("position", { mode: "number" }).notNull(),
2586
+ item: jsonb2("item").$type().notNull(),
2587
+ // Live-row flag for client-side context compaction. The read path selects
2588
+ // only active rows; a compaction supersedes the summarized prefix (sets this
2589
+ // false — never deletes, so the full transcript stays as an audit trail) and
2590
+ // inserts ONE synthetic active summary row at the boundary. Defaults true so
2591
+ // every existing and normally-appended row is live.
2592
+ active: boolean2("active").notNull().default(true),
2593
+ // The Codex account that PRODUCED these items: the per-turn resolved codex
2594
+ // credential id (pin > workspace-active), or NULL when produced on the
2595
+ // non-codex / Azure path (or before this column existed). Used to strip
2596
+ // cross-account `reasoning.encrypted_content` blobs — those are account/org-
2597
+ // bound, minted by the ChatGPT/Codex backend, so replaying account A's blob
2598
+ // into a turn running on account B 400s. The read path drops the encrypted
2599
+ // reasoning of any item whose producer != the turn's current codex account.
2600
+ // Deliberately NO FK: provenance must OUTLIVE the account's hard-disconnect
2601
+ // (an ON DELETE SET NULL would erase the tag, and a stale-but-null tag still
2602
+ // mismatches a live codex id so the strip stays correct either way).
2603
+ producerCodexCredentialId: uuid3("producer_codex_credential_id"),
2604
+ // An exact provider 400 can prove that an otherwise same-credential opaque
2605
+ // reasoning artifact is no longer decryptable. Keep the original item and
2606
+ // producer provenance immutable, but record the attempt-fenced rejection so
2607
+ // later model reads omit only the provider-bound identity. No FK: the receipt
2608
+ // must outlive operational attempt retention just like producer provenance.
2609
+ providerArtifactInvalidatedAt: timestamp3("provider_artifact_invalidated_at", {
2610
+ withTimezone: true
2611
+ }),
2612
+ providerArtifactInvalidationReason: text3("provider_artifact_invalidation_reason"),
2613
+ providerArtifactInvalidatedByAttemptId: uuid3("provider_artifact_invalidated_by_attempt_id"),
2614
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
2615
+ },
2616
+ (table) => ({
2617
+ positionIdx: uniqueIndex3("session_history_items_position_idx").on(
2618
+ table.workspaceId,
2619
+ table.sessionId,
2620
+ table.position
2621
+ )
2622
+ })
2623
+ );
2624
+ var sessionPendingToolCalls = pgTable3(
2625
+ "session_pending_tool_calls",
2626
+ {
2627
+ id: uuid3("id").primaryKey().defaultRandom(),
2628
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2629
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2630
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2631
+ turnId: uuid3("turn_id").notNull().references(() => sessionTurns.id, { onDelete: "cascade" }),
2632
+ executionGeneration: integer2("execution_generation").notNull(),
2633
+ attemptId: uuid3("attempt_id").notNull(),
2634
+ callId: text3("call_id").notNull(),
2635
+ callType: text3("call_type").notNull(),
2636
+ callItem: jsonb2("call_item").$type().notNull(),
2637
+ modelToolOutputTruncationTokens: integer2("model_tool_output_truncation_tokens"),
2638
+ resultItem: jsonb2("result_item").$type(),
2639
+ resultRecordedAt: timestamp3("result_recorded_at", { withTimezone: true }),
2640
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
2641
+ },
2642
+ (table) => ({
2643
+ workspaceAttempt: foreignKey({
2644
+ name: "pending_tool_calls_workspace_attempt_fk",
2645
+ columns: [table.workspaceId, table.attemptId],
2646
+ foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
2647
+ }).onDelete("restrict"),
2648
+ turnCall: uniqueIndex3("session_pending_tool_calls_turn_call_idx").on(
2649
+ table.workspaceId,
2650
+ table.turnId,
2651
+ table.callId
2652
+ ),
2653
+ sessionTurn: index3("session_pending_tool_calls_session_turn_idx").on(
2654
+ table.workspaceId,
2655
+ table.sessionId,
2656
+ table.turnId
2657
+ )
2658
+ })
2659
+ );
2660
+ var sandboxSessionEnvelopes = pgTable3(
2661
+ "sandbox_session_envelopes",
2662
+ {
2663
+ id: uuid3("id").primaryKey().defaultRandom(),
2664
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2665
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2666
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
2667
+ envelope: jsonb2("envelope").$type().notNull(),
2668
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
2669
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
2670
+ },
2671
+ (table) => ({
2672
+ sessionIdx: uniqueIndex3("sandbox_session_envelopes_session_idx").on(
2673
+ table.workspaceId,
2674
+ table.sessionId
2675
+ )
2676
+ })
2677
+ );
2678
+ var sandboxCheckpointArtifactStateValues = [
2679
+ "candidate",
2680
+ "current",
2681
+ "previous",
2682
+ "delete_pending",
2683
+ "deleting",
2684
+ "delete_failed",
2685
+ "deleted"
2686
+ ];
2687
+ var sandboxCheckpointArtifacts = pgTable3(
2688
+ "sandbox_checkpoint_artifacts",
2689
+ {
2690
+ id: uuid3("id").primaryKey().defaultRandom(),
2691
+ accountId: uuid3("account_id").notNull(),
2692
+ workspaceId: uuid3("workspace_id").notNull(),
2693
+ sandboxGroupId: uuid3("sandbox_group_id").notNull(),
2694
+ sourceLeaseId: uuid3("source_lease_id").notNull(),
2695
+ sourceLeaseEpoch: integer2("source_lease_epoch").notNull(),
2696
+ sourceInstanceId: text3("source_instance_id"),
2697
+ sourceWorkspaceGeneration: integer2("source_workspace_generation"),
2698
+ provenance: text3("provenance", {
2699
+ enum: ["native_capture", "legacy_provider_adopted"]
2700
+ }).notNull(),
2701
+ providerBackend: text3("provider_backend").notNull(),
2702
+ providerBindingKey: text3("provider_binding_key").notNull(),
2703
+ providerBinding: jsonb2("provider_binding").$type().notNull(),
2704
+ objectKind: text3("object_kind", {
2705
+ enum: ["modal_filesystem_snapshot", "modal_directory_snapshot"]
2706
+ }).notNull(),
2707
+ objectId: text3("object_id").notNull(),
2708
+ archiveBase64: text3("archive_base64").notNull(),
2709
+ archiveSha256: text3("archive_sha256").notNull(),
2710
+ archiveBytes: integer2("archive_bytes").notNull(),
2711
+ descriptor: jsonb2("descriptor").$type().notNull(),
2712
+ descriptorRevision: text3("descriptor_revision").notNull(),
2713
+ state: text3("state", { enum: sandboxCheckpointArtifactStateValues }).notNull().default("candidate"),
2714
+ deleteAfter: timestamp3("delete_after", { withTimezone: true }),
2715
+ deleteAttempts: integer2("delete_attempts").notNull().default(0),
2716
+ deleteClaimId: uuid3("delete_claim_id"),
2717
+ deleteClaimedAt: timestamp3("delete_claimed_at", { withTimezone: true }),
2718
+ lastDeleteError: text3("last_delete_error"),
2719
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
2720
+ publishedAt: timestamp3("published_at", { withTimezone: true }),
2721
+ deletedAt: timestamp3("deleted_at", { withTimezone: true }),
2722
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
2723
+ },
2724
+ (table) => ({
2725
+ providerObject: uniqueIndex3("sandbox_checkpoint_artifacts_provider_object_uq").on(
2726
+ table.providerBackend,
2727
+ table.providerBindingKey,
2728
+ table.objectId
2729
+ ),
2730
+ gc: index3("sandbox_checkpoint_artifacts_gc_idx").on(table.deleteAfter, table.createdAt, table.id).where(
2731
+ sql3`${table.state} in (
2732
+ 'candidate', 'current', 'previous',
2733
+ 'delete_pending', 'delete_failed', 'deleting'
2734
+ )`
2735
+ ),
2736
+ source: index3("sandbox_checkpoint_artifacts_source_idx").on(
2737
+ table.workspaceId,
2738
+ table.sandboxGroupId,
2739
+ table.sourceLeaseId
2740
+ ),
2741
+ sourceValid: check3(
2742
+ "sandbox_checkpoint_artifacts_source_check",
2743
+ sql3`${table.sourceLeaseEpoch} >= 0
2744
+ and (
2745
+ (
2746
+ ${table.provenance} = 'native_capture'
2747
+ and ${table.sourceWorkspaceGeneration} is not null
2748
+ and ${table.sourceWorkspaceGeneration} >= 0
2749
+ and ${table.sourceInstanceId} is not null
2750
+ and octet_length(${table.sourceInstanceId}) between 1 and 512
2751
+ )
2752
+ or (
2753
+ ${table.provenance} = 'legacy_provider_adopted'
2754
+ and ${table.sourceWorkspaceGeneration} is null
2755
+ and ${table.sourceInstanceId} is null
2756
+ )
2757
+ )`
2758
+ ),
2759
+ providerValid: check3(
2760
+ "sandbox_checkpoint_artifacts_provider_check",
2761
+ sql3`${table.providerBackend} = 'modal'
2762
+ and octet_length(${table.providerBindingKey}) between 1 and 1024
2763
+ and jsonb_typeof(${table.providerBinding}) = 'object'
2764
+ and ${table.providerBindingKey}::jsonb = ${table.providerBinding}
2765
+ and ${table.objectKind} in ('modal_filesystem_snapshot', 'modal_directory_snapshot')
2766
+ and octet_length(${table.objectId}) between 1 and 1024`
2767
+ ),
2768
+ archiveValid: check3(
2769
+ "sandbox_checkpoint_artifacts_archive_check",
2770
+ sql3`${table.archiveBytes} > 0
2771
+ and octet_length(${table.archiveBase64}) > 0
2772
+ and ${table.archiveSha256} ~ '^[0-9a-f]{64}$'
2773
+ and jsonb_typeof(${table.descriptor}) = 'object'
2774
+ and octet_length(${table.descriptorRevision}) between 1 and 256`
2775
+ ),
2776
+ stateValid: check3(
2777
+ "sandbox_checkpoint_artifacts_state_check",
2778
+ sql3`${table.state} in (
2779
+ 'candidate', 'current', 'previous', 'delete_pending',
2780
+ 'deleting', 'delete_failed', 'deleted'
2781
+ )`
2782
+ ),
2783
+ deleteClaimValid: check3(
2784
+ "sandbox_checkpoint_artifacts_delete_claim_check",
2785
+ sql3`(${table.state} = 'deleting'
2786
+ and ${table.deleteClaimId} is not null
2787
+ and ${table.deleteClaimedAt} is not null)
2788
+ or (${table.state} <> 'deleting'
2789
+ and ${table.deleteClaimId} is null
2790
+ and ${table.deleteClaimedAt} is null)`
2791
+ )
2792
+ })
2793
+ );
2794
+ var sandboxLeaseLivenessValues = ["cold", "warming", "warm", "draining"];
2795
+ var sandboxLeases = pgTable3(
2796
+ "sandbox_leases",
2797
+ {
2798
+ id: uuid3("id").primaryKey().defaultRandom(),
2799
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2800
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2801
+ sandboxGroupId: uuid3("sandbox_group_id").notNull(),
2802
+ liveness: text3("liveness", { enum: sandboxLeaseLivenessValues }).notNull().default("cold"),
2803
+ refcount: integer2("refcount").notNull().default(0),
2804
+ turnHolders: integer2("turn_holders").notNull().default(0),
2805
+ viewerHolders: integer2("viewer_holders").notNull().default(0),
2806
+ instanceId: text3("instance_id"),
2807
+ backend: text3("backend").notNull(),
2808
+ os: text3("os").notNull().default("linux"),
2809
+ // The container IMAGE the group box runs (Modal image ref / docker image). A shared
2810
+ // box is SHARED STATE: all its sessions run the SAME filesystem, so they must run the
2811
+ // same image. This column stamps the image the live box was created with; a resume
2812
+ // whose resolved image DIFFERS is a conflict (B3): a solo holder requests a
2813
+ // capture-and-drain rotation; N-holders are rejected (SandboxImageConflictError). Nullable — a
2814
+ // legacy/cold row reads NULL = "image unknown", which never conflicts.
2815
+ image: text3("image"),
2816
+ // The frozen rig version the live box was created under (M3). Like `image`,
2817
+ // this is SHARED STATE: all the box's sessions run the same rig-baked setup,
2818
+ // so a resume resolving a DIFFERENT rig_version_id conflicts (a solo holder
2819
+ // requests capture-and-drain rotation; N-holders throw SandboxRigConflictError).
2820
+ // Nullable — a legacy/cold row or a rig-less session reads NULL = "rig
2821
+ // unknown", which never conflicts. No FK (symmetric with sandbox_group_id's
2822
+ // bare-uuid rationale: this lease outlives no single rig_versions row's RLS).
2823
+ rigVersionId: uuid3("rig_version_id"),
2824
+ dataPlaneUrl: text3("data_plane_url"),
2825
+ // The REAL PTY terminal (ttyd pty-ws) rides a SEPARATE provider tunnel (7681)
2826
+ // from the desktop noVNC (6080), so its resolved URL is cached independently.
2827
+ // Recorded under the epoch fence by recordLeaseTerminalDataPlaneUrl; reset to
2828
+ // null on every box re-key (warm-commit / fail / drain), symmetric with
2829
+ // data_plane_url.
2830
+ terminalDataPlaneUrl: text3("terminal_data_plane_url"),
2831
+ // integer (NOT bigint): the lease-epoch spike proved a raw int8 read returns a
2832
+ // JS STRING from postgres-js, breaking the strict epoch-fence comparison (it
2833
+ // was always-true → every turn fenced); int4 returns a JS number, the fix.
2834
+ // Epochs never approach 2^31, so the narrower type loses nothing.
2835
+ leaseEpoch: integer2("lease_epoch").notNull().default(0),
2836
+ // Monotonic mutation intent for the live workspace. Every acknowledged
2837
+ // filesystem-writing operation advances this under the exact lease epoch +
2838
+ // provider-instance fence BEFORE it reaches the provider. A verified
2839
+ // archive fold copies the exact captured value into archive_generation in
2840
+ // the same row update; equality is the only durable completeness proof.
2841
+ workspaceGeneration: integer2("workspace_generation").notNull().default(0),
2842
+ archiveGeneration: integer2("archive_generation"),
2843
+ // Provider-native capture may pause the live box. The exact claim is
2844
+ // acquired before provider I/O and cleared only after that capture settles;
2845
+ // new holders and workspace mutations fence on it. The SQL constraint also
2846
+ // requires the claimed generation to remain current, so an unaware writer
2847
+ // cannot advance generation through an active capture.
2848
+ archiveCaptureId: uuid3("archive_capture_id"),
2849
+ archiveCaptureGeneration: integer2("archive_capture_generation"),
2850
+ archiveCaptureStartedAt: timestamp3("archive_capture_started_at", {
2851
+ withTimezone: true
2852
+ }),
2853
+ archiveCaptureDeadlineAt: timestamp3("archive_capture_deadline_at", {
2854
+ withTimezone: true
2855
+ }),
2856
+ // The group box-envelope (the "envelope split" Critical): the small recovery
2857
+ // descriptor to resume()-by-id the group's box without a per-session join.
2858
+ resumeBackendId: text3("resume_backend_id"),
2859
+ resumeState: jsonb2("resume_state").$type(),
2860
+ // Warm-time billing cursor: last_meter_at = accrual cursor; last_meter_tick =
2861
+ // idempotency tick (warm_seconds accrued idempotent on
2862
+ // (sandbox_group_id, lease_epoch, last_meter_tick) in P2.1).
2863
+ lastMeterAt: timestamp3("last_meter_at", { withTimezone: true }),
2864
+ lastMeterTick: integer2("last_meter_tick").notNull().default(0),
2865
+ providerCreatedAt: timestamp3("provider_created_at", { withTimezone: true }),
2866
+ providerDeadlineAt: timestamp3("provider_deadline_at", { withTimezone: true }),
2867
+ rotationRequestedAt: timestamp3("rotation_requested_at", { withTimezone: true }),
2868
+ rotationReason: text3("rotation_reason", {
2869
+ enum: ["provider_deadline", "operator"]
2870
+ }),
2871
+ // The SQL migration owns the two DEFERRABLE foreign keys and deferred
2872
+ // scope/state constraint triggers. Drizzle does not model deferrability, so
2873
+ // these remain bare UUIDs here rather than generating a stricter wrong FK.
2874
+ currentCheckpointArtifactId: uuid3("current_checkpoint_artifact_id"),
2875
+ previousCheckpointArtifactId: uuid3("previous_checkpoint_artifact_id"),
2876
+ expiresAt: timestamp3("expires_at", { withTimezone: true }).notNull(),
2877
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
2878
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
2879
+ },
2880
+ (table) => ({
2881
+ groupIdx: uniqueIndex3("sandbox_leases_group_idx").on(table.workspaceId, table.sandboxGroupId),
2882
+ scopedId: uniqueIndex3("sandbox_leases_scoped_id_uq").on(
2883
+ table.accountId,
2884
+ table.workspaceId,
2885
+ table.sandboxGroupId,
2886
+ table.id
2887
+ ),
2888
+ accountWorkspaceId: uniqueIndex3("sandbox_leases_account_workspace_id_uq").on(
2889
+ table.accountId,
2890
+ table.workspaceId,
2891
+ table.id
2892
+ ),
2893
+ reaperIdx: index3("sandbox_leases_reaper_idx").on(table.expiresAt).where(sql3`${table.liveness} in ('warming','warm','draining')`),
2894
+ expiredDrainingInventory: index3("sandbox_leases_expired_draining_inventory_idx").on(table.expiresAt, table.backend).where(sql3`${table.liveness} = 'draining'`),
2895
+ providerDeadline: index3("sandbox_leases_provider_deadline_idx").on(table.providerDeadlineAt, table.id).where(
2896
+ sql3`${table.backend} = 'modal'
2897
+ and ${table.liveness} in ('warming', 'warm')
2898
+ and ${table.rotationRequestedAt} is null`
2899
+ ),
2900
+ workspaceGenerationValid: check3(
2901
+ "sandbox_leases_workspace_generation_check",
2902
+ sql3`${table.workspaceGeneration} >= 0`
2903
+ ),
2904
+ archiveGenerationValid: check3(
2905
+ "sandbox_leases_archive_generation_check",
2906
+ sql3`${table.archiveGeneration} is null
2907
+ or (${table.archiveGeneration} >= 0
2908
+ and ${table.archiveGeneration} <= ${table.workspaceGeneration})`
2909
+ ),
2910
+ archiveCaptureValid: check3(
2911
+ "sandbox_leases_archive_capture_check",
2912
+ sql3`(
2913
+ ${table.archiveCaptureId} is null
2914
+ and ${table.archiveCaptureGeneration} is null
2915
+ and ${table.archiveCaptureStartedAt} is null
2916
+ and ${table.archiveCaptureDeadlineAt} is null
2917
+ ) or (
2918
+ ${table.archiveCaptureId} is not null
2919
+ and ${table.archiveCaptureGeneration} is not null
2920
+ and ${table.archiveCaptureGeneration} = ${table.workspaceGeneration}
2921
+ and ${table.archiveCaptureStartedAt} is not null
2922
+ and ${table.archiveCaptureDeadlineAt} > ${table.archiveCaptureStartedAt}
2923
+ )`
2924
+ ),
2925
+ archiveCaptureDeadline: index3("sandbox_leases_archive_capture_deadline_idx").on(table.archiveCaptureDeadlineAt, table.id).where(sql3`${table.archiveCaptureId} is not null`),
2926
+ providerDeadlineValid: check3(
2927
+ "sandbox_leases_provider_deadline_check",
2928
+ sql3`(${table.providerCreatedAt} is null and ${table.providerDeadlineAt} is null)
2929
+ or (${table.providerCreatedAt} is not null
2930
+ and ${table.providerDeadlineAt} is not null
2931
+ and ${table.providerDeadlineAt} > ${table.providerCreatedAt})`
2932
+ ),
2933
+ rotationValid: check3(
2934
+ "sandbox_leases_rotation_check",
2935
+ sql3`(${table.rotationRequestedAt} is null and ${table.rotationReason} is null)
2936
+ or (${table.rotationRequestedAt} is not null
2937
+ and ${table.rotationReason} in ('provider_deadline', 'operator'))`
2938
+ ),
2939
+ checkpointDistinct: check3(
2940
+ "sandbox_leases_checkpoint_distinct_check",
2941
+ sql3`${table.currentCheckpointArtifactId} is null
2942
+ or ${table.previousCheckpointArtifactId} is null
2943
+ or ${table.currentCheckpointArtifactId} <> ${table.previousCheckpointArtifactId}`
2944
+ )
2945
+ })
2946
+ );
2947
+ var sandboxLeaseHolders = pgTable3(
2948
+ "sandbox_lease_holders",
2949
+ {
2950
+ id: uuid3("id").primaryKey().defaultRandom(),
2951
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2952
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2953
+ leaseId: uuid3("lease_id").notNull().references(() => sandboxLeases.id, { onDelete: "cascade" }),
2954
+ kind: text3("kind", { enum: ["turn", "viewer", "direct", "process"] }).notNull(),
2955
+ holderId: text3("holder_id").notNull(),
2956
+ // The attributing session within the (possibly shared) group.
2957
+ subjectId: uuid3("subject_id"),
2958
+ lastHeartbeatAt: timestamp3("last_heartbeat_at", { withTimezone: true }).notNull().defaultNow(),
2959
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
2960
+ },
2961
+ (table) => ({
2962
+ leaseScope: foreignKey({
2963
+ name: "sandbox_lease_holders_lease_scope_fk",
2964
+ columns: [table.accountId, table.workspaceId, table.leaseId],
2965
+ foreignColumns: [sandboxLeases.accountId, sandboxLeases.workspaceId, sandboxLeases.id]
2966
+ }).onDelete("cascade"),
2967
+ holderIdx: uniqueIndex3("sandbox_lease_holders_holder_idx").on(
2968
+ table.leaseId,
2969
+ table.kind,
2970
+ table.holderId
2971
+ ),
2972
+ staleIdx: index3("sandbox_lease_holders_stale_idx").on(table.kind, table.lastHeartbeatAt),
2973
+ leaseIdx: index3("sandbox_lease_holders_lease_idx").on(table.leaseId)
2974
+ })
2975
+ );
2976
+ var sandboxWorkspaceMutationActorKindValues = ["turn", "direct", "process"];
2977
+ var sandboxWorkspaceMutationHolderKindValues = ["turn", "direct", "process"];
2978
+ var sandboxWorkspaceMutationAdmissions = pgTable3(
2979
+ "sandbox_workspace_mutation_admissions",
2980
+ {
2981
+ id: uuid3("id").primaryKey().defaultRandom(),
2982
+ accountId: uuid3("account_id").notNull(),
2983
+ workspaceId: uuid3("workspace_id").notNull(),
2984
+ leaseId: uuid3("lease_id").notNull().references(() => sandboxLeases.id, { onDelete: "cascade" }),
2985
+ sandboxGroupId: uuid3("sandbox_group_id").notNull(),
2986
+ sessionId: uuid3("session_id").notNull(),
2987
+ actorKind: text3("actor_kind", { enum: sandboxWorkspaceMutationActorKindValues }).notNull(),
2988
+ actorId: uuid3("actor_id").notNull(),
2989
+ // Exact turn authority is present only for actor_kind='turn'. Direct HTTP
2990
+ // requests and retained processes never invent a turn or quiescence owner.
2991
+ turnId: uuid3("turn_id"),
2992
+ attemptId: uuid3("attempt_id"),
2993
+ executionGeneration: integer2("execution_generation"),
2994
+ holderKind: text3("holder_kind", {
2995
+ enum: sandboxWorkspaceMutationHolderKindValues
2996
+ }).notNull(),
2997
+ holderId: text3("holder_id").notNull(),
2998
+ leaseEpoch: integer2("lease_epoch").notNull(),
2999
+ providerBackend: text3("provider_backend").notNull(),
3000
+ providerInstanceId: text3("provider_instance_id").notNull(),
3001
+ routeKind: text3("route_kind", { enum: ["home", "active"] }).notNull(),
3002
+ // null route target means the persistable home/group provider. A non-null
3003
+ // target is pinned together with the active pointer epoch observed when the
3004
+ // operation was admitted.
3005
+ routeTargetId: uuid3("route_target_id"),
3006
+ routeEpoch: integer2("route_epoch").notNull(),
3007
+ workspaceGeneration: integer2("workspace_generation").notNull(),
3008
+ operation: text3("operation").notNull(),
3009
+ providerOutcome: text3("provider_outcome", {
3010
+ enum: ["resolved", "rejected", "retained"]
3011
+ }),
3012
+ admittedAt: timestamp3("admitted_at", { withTimezone: true }).notNull().defaultNow(),
3013
+ settledAt: timestamp3("settled_at", { withTimezone: true })
3014
+ },
3015
+ (table) => ({
3016
+ workspaceAccount: foreignKey({
3017
+ name: "sandbox_workspace_mutation_admissions_workspace_account_fk",
3018
+ columns: [table.workspaceId, table.accountId],
3019
+ foreignColumns: [workspaces.id, workspaces.accountId]
3020
+ }).onDelete("cascade"),
3021
+ workspaceSession: foreignKey({
3022
+ name: "sandbox_workspace_mutation_admissions_workspace_session_fk",
3023
+ columns: [table.workspaceId, table.sessionId],
3024
+ foreignColumns: [sessions.workspaceId, sessions.id]
3025
+ }).onDelete("restrict"),
3026
+ workspaceTurn: foreignKey({
3027
+ name: "sandbox_workspace_mutation_admissions_workspace_turn_fk",
3028
+ columns: [table.workspaceId, table.turnId],
3029
+ foreignColumns: [sessionTurns.workspaceId, sessionTurns.id]
3030
+ }).onDelete("restrict"),
3031
+ workspaceAttempt: foreignKey({
3032
+ name: "sandbox_workspace_mutation_admissions_workspace_attempt_fk",
3033
+ columns: [table.workspaceId, table.attemptId],
3034
+ foreignColumns: [sessionTurnAttempts.workspaceId, sessionTurnAttempts.id]
3035
+ }).onDelete("restrict"),
3036
+ leaseGeneration: uniqueIndex3("sandbox_workspace_mutation_admissions_lease_generation_uq").on(
3037
+ table.leaseId,
3038
+ table.workspaceGeneration
3039
+ ),
3040
+ scopedId: uniqueIndex3("sandbox_workspace_mutation_admissions_scoped_id_uq").on(
3041
+ table.accountId,
3042
+ table.workspaceId,
3043
+ table.sessionId,
3044
+ table.leaseId,
3045
+ table.id
3046
+ ),
3047
+ blocking: index3("sandbox_workspace_mutation_admissions_blocking_idx").on(table.leaseId, table.workspaceGeneration).where(sql3`${table.settledAt} is null`),
3048
+ attempt: index3("sandbox_workspace_mutation_admissions_attempt_idx").on(
3049
+ table.workspaceId,
3050
+ table.attemptId
3051
+ ),
3052
+ actor: index3("sandbox_workspace_mutation_admissions_actor_idx").on(
3053
+ table.workspaceId,
3054
+ table.actorKind,
3055
+ table.actorId
3056
+ ),
3057
+ generationValid: check3(
3058
+ "sandbox_workspace_mutation_admissions_generation_check",
3059
+ sql3`${table.workspaceGeneration} > 0
3060
+ and ${table.leaseEpoch} >= 0
3061
+ and ${table.routeEpoch} >= 0
3062
+ and (${table.executionGeneration} is null or ${table.executionGeneration} > 0)`
3063
+ ),
3064
+ actorValid: check3(
3065
+ "sandbox_workspace_mutation_admissions_actor_check",
3066
+ sql3`(
3067
+ ${table.actorKind} = 'turn'
3068
+ and ${table.actorId} = ${table.attemptId}
3069
+ and ${table.turnId} is not null
3070
+ and ${table.attemptId} is not null
3071
+ and ${table.executionGeneration} is not null
3072
+ and ${table.holderKind} = 'turn'
3073
+ ) or (
3074
+ ${table.actorKind} = 'direct'
3075
+ and ${table.turnId} is null
3076
+ and ${table.attemptId} is null
3077
+ and ${table.executionGeneration} is null
3078
+ and ${table.holderKind} = 'direct'
3079
+ ) or (
3080
+ ${table.actorKind} = 'process'
3081
+ and ${table.turnId} is null
3082
+ and ${table.attemptId} is null
3083
+ and ${table.executionGeneration} is null
3084
+ and ${table.holderKind} = 'process'
3085
+ )`
3086
+ ),
3087
+ routeValid: check3(
3088
+ "sandbox_workspace_mutation_admissions_route_check",
3089
+ sql3`${table.actorKind} in ('turn', 'direct', 'process')
3090
+ and ${table.holderKind} in ('turn', 'direct', 'process')
3091
+ and octet_length(${table.holderId}) between 1 and 256
3092
+ and octet_length(${table.providerBackend}) between 1 and 64
3093
+ and octet_length(${table.providerInstanceId}) between 1 and 512
3094
+ and ${table.routeKind} in ('home', 'active')
3095
+ and (${table.routeKind} = 'active' or ${table.routeTargetId} is null)`
3096
+ ),
3097
+ operationValid: check3(
3098
+ "sandbox_workspace_mutation_admissions_operation_check",
3099
+ sql3`octet_length(${table.operation}) between 1 and 128`
3100
+ ),
3101
+ outcomeValid: check3(
3102
+ "sandbox_workspace_mutation_admissions_outcome_check",
3103
+ sql3`${table.providerOutcome} is null or ${table.providerOutcome} in ('resolved', 'rejected', 'retained')`
3104
+ ),
3105
+ settlementConsistent: check3(
3106
+ "sandbox_workspace_mutation_admissions_settlement_check",
3107
+ sql3`(${table.providerOutcome} is null and ${table.settledAt} is null)
3108
+ or (${table.providerOutcome} = 'retained' and ${table.settledAt} is null)
3109
+ or (${table.providerOutcome} in ('resolved', 'rejected') and ${table.settledAt} is not null)`
3110
+ )
3111
+ })
3112
+ );
3113
+ var sandboxRetainedProcessStateValues = ["active", "exited", "lost"];
3114
+ var sandboxRetainedProcesses = pgTable3(
3115
+ "sandbox_retained_processes",
3116
+ {
3117
+ id: uuid3("id").primaryKey().defaultRandom(),
3118
+ accountId: uuid3("account_id").notNull(),
3119
+ workspaceId: uuid3("workspace_id").notNull(),
3120
+ sessionId: uuid3("session_id").notNull(),
3121
+ leaseId: uuid3("lease_id").notNull(),
3122
+ sandboxGroupId: uuid3("sandbox_group_id").notNull(),
3123
+ parentAdmissionId: uuid3("parent_admission_id").notNull(),
3124
+ holderId: text3("holder_id").notNull(),
3125
+ ownerActorKind: text3("owner_actor_kind", { enum: ["turn", "direct"] }).notNull(),
3126
+ ownerActorId: uuid3("owner_actor_id").notNull(),
3127
+ ownerTurnId: uuid3("owner_turn_id"),
3128
+ ownerAttemptId: uuid3("owner_attempt_id"),
3129
+ ownerExecutionGeneration: integer2("owner_execution_generation"),
3130
+ leaseEpoch: integer2("lease_epoch").notNull(),
3131
+ providerBackend: text3("provider_backend").notNull(),
3132
+ providerInstanceId: text3("provider_instance_id").notNull(),
3133
+ // Provider object ids are namespace-scoped. New Modal processes bind the
3134
+ // exact authenticated workspace before execution; legacy rows remain null
3135
+ // until a positive lookup proves which namespace owns the historical box.
3136
+ providerBindingKey: text3("provider_binding_key"),
3137
+ providerBinding: jsonb2("provider_binding").$type(),
3138
+ routeKind: text3("route_kind", { enum: ["home", "active"] }).notNull(),
3139
+ routeTargetId: uuid3("route_target_id"),
3140
+ routeEpoch: integer2("route_epoch").notNull(),
3141
+ providerSessionId: integer2("provider_session_id").notNull(),
3142
+ state: text3("state", { enum: sandboxRetainedProcessStateValues }).notNull().default("active"),
3143
+ exitCode: integer2("exit_code"),
3144
+ settlementReason: text3("settlement_reason"),
3145
+ startedAt: timestamp3("started_at", { withTimezone: true }).notNull().defaultNow(),
3146
+ settledAt: timestamp3("settled_at", { withTimezone: true }),
3147
+ // Coordination state for bounded terminal-owner reconciliation. While a
3148
+ // claim is live, reconcileAfter is its expiry; otherwise it is the next
3149
+ // retry time. Becoming due only licenses an exact provider probe and is
3150
+ // never exit/loss proof.
3151
+ reconcileAfter: timestamp3("reconcile_after", { withTimezone: true }).notNull().defaultNow(),
3152
+ reconcileClaimId: uuid3("reconcile_claim_id"),
3153
+ reconcileClaimedAt: timestamp3("reconcile_claimed_at", { withTimezone: true }),
3154
+ reconcileAttempts: integer2("reconcile_attempts").notNull().default(0),
3155
+ lastReconcileOutcome: text3("last_reconcile_outcome"),
3156
+ reconcileProofOutcome: text3("reconcile_proof_outcome", { enum: ["exited", "lost"] }),
3157
+ reconcileProofExitCode: integer2("reconcile_proof_exit_code"),
3158
+ reconcileProofReason: text3("reconcile_proof_reason"),
3159
+ reconcileProofObservedAt: timestamp3("reconcile_proof_observed_at", { withTimezone: true })
3160
+ },
3161
+ (table) => ({
3162
+ workspaceAccount: foreignKey({
3163
+ name: "sandbox_retained_processes_workspace_account_fk",
3164
+ columns: [table.workspaceId, table.accountId],
3165
+ foreignColumns: [workspaces.id, workspaces.accountId]
3166
+ }).onDelete("cascade"),
3167
+ workspaceSession: foreignKey({
3168
+ name: "sandbox_retained_processes_workspace_session_fk",
3169
+ columns: [table.workspaceId, table.sessionId],
3170
+ foreignColumns: [sessions.workspaceId, sessions.id]
3171
+ }).onDelete("restrict"),
3172
+ parentAdmissionScope: foreignKey({
3173
+ name: "sandbox_retained_processes_parent_admission_scope_fk",
3174
+ columns: [
3175
+ table.accountId,
3176
+ table.workspaceId,
3177
+ table.sessionId,
3178
+ table.leaseId,
3179
+ table.parentAdmissionId
3180
+ ],
3181
+ foreignColumns: [
3182
+ sandboxWorkspaceMutationAdmissions.accountId,
3183
+ sandboxWorkspaceMutationAdmissions.workspaceId,
3184
+ sandboxWorkspaceMutationAdmissions.sessionId,
3185
+ sandboxWorkspaceMutationAdmissions.leaseId,
3186
+ sandboxWorkspaceMutationAdmissions.id
3187
+ ]
3188
+ }).onDelete("restrict"),
3189
+ scopedId: uniqueIndex3("sandbox_retained_processes_scoped_id_uq").on(
3190
+ table.accountId,
3191
+ table.workspaceId,
3192
+ table.sessionId,
3193
+ table.leaseId,
3194
+ table.id
3195
+ ),
3196
+ parentAdmission: uniqueIndex3("sandbox_retained_processes_parent_admission_uq").on(
3197
+ table.parentAdmissionId
3198
+ ),
3199
+ liveProviderSession: uniqueIndex3("sandbox_retained_processes_live_provider_session_uq").on(
3200
+ table.leaseId,
3201
+ table.leaseEpoch,
3202
+ table.providerInstanceId,
3203
+ table.routeEpoch,
3204
+ table.providerSessionId
3205
+ ).where(sql3`${table.state} = 'active'`),
3206
+ holder: uniqueIndex3("sandbox_retained_processes_holder_uq").on(table.leaseId, table.holderId),
3207
+ active: index3("sandbox_retained_processes_active_idx").on(table.workspaceId, table.sessionId, table.startedAt).where(sql3`${table.state} = 'active'`),
3208
+ reconcileDue: index3("sandbox_retained_processes_reconcile_due_idx").on(table.reconcileAfter, table.startedAt, table.id).where(sql3`${table.state} = 'active'`),
3209
+ activeInventory: index3("sandbox_retained_processes_active_inventory_idx").on(table.ownerActorKind, table.workspaceId, table.ownerTurnId, table.ownerAttemptId).where(sql3`${table.state} = 'active'`),
3210
+ identityValid: check3(
3211
+ "sandbox_retained_processes_identity_check",
3212
+ sql3`${table.leaseEpoch} >= 0
3213
+ and ${table.routeEpoch} >= 0
3214
+ and ${table.providerSessionId} > 0
3215
+ and octet_length(${table.holderId}) between 1 and 256
3216
+ and octet_length(${table.providerBackend}) between 1 and 64
3217
+ and octet_length(${table.providerInstanceId}) between 1 and 512
3218
+ and (${table.routeKind} = 'active' or ${table.routeTargetId} is null)`
3219
+ ),
3220
+ ownerValid: check3(
3221
+ "sandbox_retained_processes_owner_check",
3222
+ sql3`(
3223
+ ${table.ownerActorKind} = 'turn'
3224
+ and ${table.ownerActorId} = ${table.ownerAttemptId}
3225
+ and ${table.ownerTurnId} is not null
3226
+ and ${table.ownerAttemptId} is not null
3227
+ and ${table.ownerExecutionGeneration} > 0
3228
+ ) or (
3229
+ ${table.ownerActorKind} = 'direct'
3230
+ and ${table.ownerTurnId} is null
3231
+ and ${table.ownerAttemptId} is null
3232
+ and ${table.ownerExecutionGeneration} is null
3233
+ )`
3234
+ ),
3235
+ settlementValid: check3(
3236
+ "sandbox_retained_processes_settlement_check",
3237
+ sql3`(${table.state} = 'active' and ${table.settledAt} is null and ${table.exitCode} is null)
3238
+ or (${table.state} = 'exited' and ${table.settledAt} is not null)
3239
+ or (${table.state} = 'lost' and ${table.settledAt} is not null and ${table.exitCode} is null)`
3240
+ ),
3241
+ reasonValid: check3(
3242
+ "sandbox_retained_processes_reason_check",
3243
+ sql3`${table.settlementReason} is null
3244
+ or octet_length(${table.settlementReason}) between 1 and 512`
3245
+ ),
3246
+ providerBindingValid: check3(
3247
+ "sandbox_retained_processes_provider_binding_check",
3248
+ sql3`(
3249
+ ${table.providerBindingKey} is null
3250
+ and ${table.providerBinding} is null
3251
+ ) or (
3252
+ ${table.providerBackend} = 'modal'
3253
+ and octet_length(${table.providerBindingKey}) between 1 and 1024
3254
+ and jsonb_typeof(${table.providerBinding}) = 'object'
3255
+ and ${table.providerBindingKey}::jsonb = ${table.providerBinding}
3256
+ and ${table.providerBindingKey} = format(
3257
+ '{"version":1,"serverUrl":%s,"workspaceName":%s,"environment":%s}',
3258
+ to_jsonb(${table.providerBinding} ->> 'serverUrl')::text,
3259
+ to_jsonb(${table.providerBinding} ->> 'workspaceName')::text,
3260
+ to_jsonb(${table.providerBinding} ->> 'environment')::text
3261
+ )
3262
+ and ${table.providerBinding} = jsonb_build_object(
3263
+ 'version', 1,
3264
+ 'serverUrl', ${table.providerBinding} ->> 'serverUrl',
3265
+ 'workspaceName', ${table.providerBinding} ->> 'workspaceName',
3266
+ 'environment', ${table.providerBinding} ->> 'environment'
3267
+ )
3268
+ and coalesce(octet_length(${table.providerBinding} ->> 'serverUrl'), 0) > 0
3269
+ and coalesce(octet_length(${table.providerBinding} ->> 'workspaceName'), 0) > 0
3270
+ and ${table.providerBinding} ->> 'environment' is not null
3271
+ )`
3272
+ ),
3273
+ reconcileClaimValid: check3(
3274
+ "sandbox_retained_processes_reconcile_claim_check",
3275
+ sql3`(${table.reconcileClaimId} is null and ${table.reconcileClaimedAt} is null)
3276
+ or (${table.reconcileClaimId} is not null and ${table.reconcileClaimedAt} is not null)`
3277
+ ),
3278
+ reconcileAttemptsValid: check3(
3279
+ "sandbox_retained_processes_reconcile_attempts_check",
3280
+ sql3`${table.reconcileAttempts} >= 0`
3281
+ ),
3282
+ reconcileOutcomeValid: check3(
3283
+ "sandbox_retained_processes_reconcile_outcome_check",
3284
+ sql3`${table.lastReconcileOutcome} is null
3285
+ or octet_length(${table.lastReconcileOutcome}) between 1 and 64`
3286
+ ),
3287
+ reconcileProofValid: check3(
3288
+ "sandbox_retained_processes_reconcile_proof_check",
3289
+ sql3`(
3290
+ ${table.reconcileProofOutcome} is null
3291
+ and ${table.reconcileProofExitCode} is null
3292
+ and ${table.reconcileProofReason} is null
3293
+ and ${table.reconcileProofObservedAt} is null
3294
+ ) or (
3295
+ ${table.reconcileProofOutcome} = 'exited'
3296
+ and ${table.reconcileProofExitCode} is not null
3297
+ and ${table.reconcileProofReason} = 'provider_exit_banner'
3298
+ and ${table.reconcileProofObservedAt} is not null
3299
+ ) or (
3300
+ ${table.reconcileProofOutcome} = 'lost'
3301
+ and ${table.reconcileProofExitCode} is null
3302
+ and ${table.reconcileProofReason} in (
3303
+ 'provider_session_lost_banner', 'provider_instance_not_found',
3304
+ 'provider_instance_terminated'
3305
+ )
3306
+ and ${table.reconcileProofObservedAt} is not null
3307
+ )`
3308
+ )
3309
+ })
3310
+ );
3311
+ var sessionRecordingStateValues = [
3312
+ "recording",
3313
+ "finalizing",
3314
+ "available",
3315
+ "failed"
3316
+ ];
3317
+ var sessionRecordingModeValues = ["manual", "on-turn", "on-verify"];
3318
+ var sessionRecordingCodecValues = ["h264-mp4", "vp9-webm"];
3319
+ var sessionRecordings = pgTable3(
3320
+ "session_recordings",
3321
+ {
3322
+ id: uuid3("id").primaryKey().defaultRandom(),
3323
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3324
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3325
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
3326
+ turnId: uuid3("turn_id").references(() => sessionTurns.id, {
3327
+ onDelete: "set null"
3328
+ }),
3329
+ state: text3("state", { enum: sessionRecordingStateValues }).notNull(),
3330
+ mode: text3("mode", { enum: sessionRecordingModeValues }).notNull(),
3331
+ codec: text3("codec", { enum: sessionRecordingCodecValues }).notNull(),
3332
+ storageKey: text3("storage_key"),
3333
+ sizeBytes: bigint3("size_bytes", { mode: "number" }),
3334
+ durationSeconds: numeric("duration_seconds").$type(),
3335
+ width: integer2("width").notNull(),
3336
+ height: integer2("height").notNull(),
3337
+ reason: text3("reason"),
3338
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
3339
+ finalizedAt: timestamp3("finalized_at", { withTimezone: true })
3340
+ },
3341
+ (table) => ({
3342
+ sessionIdx: index3("session_recordings_session_idx").on(
3343
+ table.workspaceId,
3344
+ table.sessionId,
3345
+ table.createdAt
3346
+ )
3347
+ })
3348
+ );
3349
+ var workspaceCaptures = pgTable3(
3350
+ "workspace_captures",
3351
+ {
3352
+ id: uuid3("id").primaryKey().defaultRandom(),
3353
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3354
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3355
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
3356
+ turnId: uuid3("turn_id").references(() => sessionTurns.id, {
3357
+ onDelete: "set null"
3358
+ }),
3359
+ revision: bigint3("revision", { mode: "number" }).notNull(),
3360
+ leaseEpoch: integer2("lease_epoch").notNull(),
3361
+ // 'available' on a committed capture. 'failed' reserved for a future two-phase
3362
+ // write; the current synchronous capture only ever inserts 'available'.
3363
+ state: text3("state", { enum: ["available", "failed"] }).notNull().default("available"),
3364
+ // Single JSON manifest blob (tree index + repos + file refs) — the cold-paint payload.
3365
+ manifestKey: text3("manifest_key"),
3366
+ // The fs tree index blob, kept separate from the manifest so the API can inline
3367
+ // or sign it independently of the (usually small) manifest metadata.
3368
+ treeIndexKey: text3("tree_index_key"),
3369
+ // Content-addressed after-image blob keys this revision references (GC input).
3370
+ blobKeys: jsonb2("blob_keys").$type().notNull().default([]),
3371
+ sizeBytes: bigint3("size_bytes", { mode: "number" }),
3372
+ stats: jsonb2("stats").$type().notNull().default({}),
3373
+ capturedAt: timestamp3("captured_at", { withTimezone: true }).notNull().defaultNow()
3374
+ },
3375
+ (table) => ({
3376
+ sessionRevision: uniqueIndex3("workspace_captures_session_revision_idx").on(
3377
+ table.sessionId,
3378
+ table.revision
3379
+ ),
3380
+ latest: index3("workspace_captures_latest_idx").on(
3381
+ table.workspaceId,
3382
+ table.sessionId,
3383
+ table.revision
3384
+ )
3385
+ })
3386
+ );
3387
+ var sandboxPtySessions = pgTable3(
3388
+ "sandbox_pty_sessions",
3389
+ {
3390
+ id: uuid3("id").primaryKey().defaultRandom(),
3391
+ // == ptyId on the wire
3392
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3393
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3394
+ sessionId: uuid3("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
3395
+ leaseId: uuid3("lease_id"),
3396
+ sandboxGroupId: uuid3("sandbox_group_id"),
3397
+ retainedProcessId: uuid3("retained_process_id"),
3398
+ openAdmissionId: uuid3("open_admission_id"),
3399
+ // Copied provider locator for the adopted retained process.
3400
+ execSessionId: integer2("exec_session_id"),
3401
+ leaseEpoch: integer2("lease_epoch").notNull(),
3402
+ providerBackend: text3("provider_backend"),
3403
+ providerInstanceId: text3("provider_instance_id"),
3404
+ routeKind: text3("route_kind", { enum: ["home", "active"] }),
3405
+ routeTargetId: uuid3("route_target_id"),
3406
+ routeEpoch: integer2("route_epoch"),
3407
+ cols: integer2("cols").notNull(),
3408
+ rows: integer2("rows").notNull(),
3409
+ shell: text3("shell").notNull(),
3410
+ cwd: text3("cwd").notNull(),
3411
+ status: text3("status").notNull().default("open"),
3412
+ // 'open' | 'closed'
3413
+ // The viewer grant/subject that opened it (free-text — access subjects are not
3414
+ // always UUIDs, M5; so a text column, never a uuid NOT NULL).
3415
+ openedBy: text3("opened_by").notNull(),
3416
+ lastInputAt: timestamp3("last_input_at", { withTimezone: true }).notNull().defaultNow(),
3417
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
3418
+ closedAt: timestamp3("closed_at", { withTimezone: true })
3419
+ },
3420
+ (table) => ({
3421
+ retainedProcessScope: foreignKey({
3422
+ name: "sandbox_pty_sessions_retained_process_scope_fk",
3423
+ columns: [
3424
+ table.accountId,
3425
+ table.workspaceId,
3426
+ table.sessionId,
3427
+ table.leaseId,
3428
+ table.retainedProcessId
3429
+ ],
3430
+ foreignColumns: [
3431
+ sandboxRetainedProcesses.accountId,
3432
+ sandboxRetainedProcesses.workspaceId,
3433
+ sandboxRetainedProcesses.sessionId,
3434
+ sandboxRetainedProcesses.leaseId,
3435
+ sandboxRetainedProcesses.id
3436
+ ]
3437
+ }).onDelete("restrict"),
3438
+ openIdx: index3("sandbox_pty_sessions_session_idx").on(table.workspaceId, table.sessionId).where(sql3`${table.status} = 'open'`),
3439
+ processIdx: uniqueIndex3("sandbox_pty_sessions_open_process_uq").on(table.retainedProcessId).where(sql3`${table.status} = 'open'`),
3440
+ openIdentityValid: check3(
3441
+ "sandbox_pty_sessions_open_identity_check",
3442
+ sql3`${table.status} <> 'open' or (
3443
+ ${table.leaseId} is not null
3444
+ and ${table.sandboxGroupId} is not null
3445
+ and ${table.retainedProcessId} is not null
3446
+ and ${table.openAdmissionId} is not null
3447
+ and ${table.execSessionId} > 0
3448
+ and octet_length(${table.providerBackend}) between 1 and 64
3449
+ and octet_length(${table.providerInstanceId}) between 1 and 512
3450
+ and ${table.routeKind} in ('home', 'active')
3451
+ and (${table.routeKind} = 'active' or ${table.routeTargetId} is null)
3452
+ and ${table.routeEpoch} is not null
3453
+ and ${table.leaseEpoch} >= 0
3454
+ and ${table.routeEpoch} >= 0
3455
+ )`
3456
+ )
3457
+ })
3458
+ );
3459
+ var enrollmentExposureValues = ["whole-machine"];
3460
+ var enrollmentStatusValues = ["active", "revoked"];
3461
+ var enrollmentOsValues = ["linux", "macos", "windows"];
3462
+ var sandboxKindValues = ["modal", "selfhosted"];
3463
+ var enrollments = pgTable3(
3464
+ "enrollments",
3465
+ {
3466
+ id: uuid3("id").primaryKey().defaultRandom(),
3467
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3468
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3469
+ // The agent's ed25519 public key (the machine identity).
3470
+ pubkey: text3("pubkey").notNull(),
3471
+ exposure: text3("exposure", { enum: enrollmentExposureValues }).notNull().default("whole-machine"),
3472
+ hasDisplay: boolean2("has_display").notNull().default(false),
3473
+ // Refreshed from every connect Hello (Capabilities.op_stream); false for
3474
+ // agents predating the op-stream engine.
3475
+ opStream: boolean2("op_stream").notNull().default(false),
3476
+ // When the machine has a display it CANNOT capture (macOS Screen Recording / TCC
3477
+ // not granted), the agent reports has_display=false AND a human, actionable reason
3478
+ // here (e.g. "grant Screen Recording in System Settings"). NULL means capture is
3479
+ // permitted (has_display=true) or the machine is genuinely headless — the reason
3480
+ // distinguishes "display present but capture not granted" from plain "no display"
3481
+ // so the Machines dashboard / VM picker can surface the specific hint. Refreshed
3482
+ // from every connect Hello alongside has_display.
3483
+ desktopUnavailableReason: text3("desktop_unavailable_reason"),
3484
+ allowScreenControl: boolean2("allow_screen_control").notNull().default(false),
3485
+ status: text3("status", { enum: enrollmentStatusValues }).notNull().default("active"),
3486
+ os: text3("os", { enum: enrollmentOsValues }).notNull().default("linux"),
3487
+ arch: text3("arch").notNull().default("x86_64"),
3488
+ // Heartbeat liveness cursor. Null until the first connect.
3489
+ lastSeenAt: timestamp3("last_seen_at", { withTimezone: true }),
3490
+ // Clean going-offline marker (migration 0049). Set when the machine announces a
3491
+ // typed GoingOffline (user-stop / self-update / host-shutdown); the liveness
3492
+ // derivation reads an un-cleared marker as OFFLINE immediately, regardless of a
3493
+ // still-fresh last_seen. Any newer liveness signal (a reconnect Hello or a
3494
+ // fresher heartbeat via touchEnrollmentLastSeen) clears BOTH back to NULL. NULL
3495
+ // (the default) ⇒ no goodbye pending — today's last_seen-aging behavior.
3496
+ wentOfflineAt: timestamp3("went_offline_at", { withTimezone: true }),
3497
+ wentOfflineReason: text3("went_offline_reason"),
3498
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
3499
+ revokedAt: timestamp3("revoked_at", { withTimezone: true }),
3500
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
3501
+ },
3502
+ (table) => ({
3503
+ // One enrollment per (workspace, pubkey): a re-enroll is an idempotent upsert.
3504
+ workspacePubkey: uniqueIndex3("enrollments_workspace_pubkey_idx").on(
3505
+ table.workspaceId,
3506
+ table.pubkey
3507
+ ),
3508
+ // List a workspace's ACTIVE machines without scanning revoked rows.
3509
+ workspaceStatus: index3("enrollments_workspace_status_idx").on(table.workspaceId, table.status)
3510
+ })
3511
+ );
3512
+ var deviceEnrollmentStatusValues = ["pending", "approved", "denied", "consumed"];
3513
+ var deviceEnrollmentRequests = pgTable3(
3514
+ "device_enrollment_requests",
3515
+ {
3516
+ id: uuid3("id").primaryKey().defaultRandom(),
3517
+ // The opaque code the agent polls with (unguessable, single-use). Unique.
3518
+ deviceCode: text3("device_code").notNull(),
3519
+ // The short human-typed code (e.g. "WDJB-MJHT"). Unique among LIVE (pending)
3520
+ // rows via a partial unique index so a recycled code never collides with a
3521
+ // terminal row.
3522
+ userCode: text3("user_code").notNull(),
3523
+ // The workspace this request was started for (resolved from the deployment-edge
3524
+ // request context — the agent presents the access key, the flow binds to the
3525
+ // single managed workspace OR a workspace hint). account_id rides along for RLS.
3526
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3527
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3528
+ // The agent's ed25519 public key (the machine identity the enrollment binds to).
3529
+ pubkey: text3("pubkey").notNull(),
3530
+ os: text3("os", { enum: enrollmentOsValues }).notNull().default("linux"),
3531
+ arch: text3("arch").notNull().default("x86_64"),
3532
+ machineName: text3("machine_name"),
3533
+ // The exposure the agent REQUESTED (whole-machine in v1; loudly consented at
3534
+ // approve). Mirrors the enrollment column domain.
3535
+ requestedExposure: text3("requested_exposure", {
3536
+ enum: enrollmentExposureValues
3537
+ }).notNull().default("whole-machine"),
3538
+ // The agent CAN offer a display (a real screen / Xvfb is available) — gates
3539
+ // whether screen-control consent is even meaningful. has_display on the
3540
+ // resulting enrollment is derived from this.
3541
+ canOfferDisplay: boolean2("can_offer_display").notNull().default(false),
3542
+ // The agent REQUESTS screen control (computer-use). The user's allow_screen_control
3543
+ // at approve is the AUTHORITATIVE consent; this is only the agent's request.
3544
+ requestsScreenControl: boolean2("requests_screen_control").notNull().default(false),
3545
+ status: text3("status", { enum: deviceEnrollmentStatusValues }).notNull().default("pending"),
3546
+ // ── LOUD CONSENT capture (who/when/what), stamped at approve ──────────────
3547
+ approvedBySubjectId: text3("approved_by_subject_id"),
3548
+ approvedBySubjectLabel: text3("approved_by_subject_label"),
3549
+ // The user's screen-control consent decision (whole-machine is mandatory at
3550
+ // approve; screen-control is opt-in per this flag).
3551
+ allowScreenControl: boolean2("allow_screen_control").notNull().default(false),
3552
+ approvedAt: timestamp3("approved_at", { withTimezone: true }),
3553
+ // The enrollment + sandbox the approve produced (acceptance #2: an enrollment
3554
+ // row AND a sandbox row appear). Null until approved.
3555
+ enrollmentId: uuid3("enrollment_id").references(() => enrollments.id, {
3556
+ onDelete: "set null"
3557
+ }),
3558
+ sandboxId: uuid3("sandbox_id").references(() => sandboxes.id, {
3559
+ onDelete: "set null"
3560
+ }),
3561
+ // The short-TTL expiry; a pending row past this is EXPIRED on poll.
3562
+ expiresAt: timestamp3("expires_at", { withTimezone: true }).notNull(),
3563
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
3564
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
3565
+ },
3566
+ (table) => ({
3567
+ // The device_code is the agent's poll key — globally unique + indexed.
3568
+ deviceCode: uniqueIndex3("device_enrollment_requests_device_code_idx").on(table.deviceCode),
3569
+ // The user_code must be unique among LIVE (pending) rows so the approve lookup
3570
+ // is unambiguous; a terminal row's code may be recycled.
3571
+ userCodePending: uniqueIndex3("device_enrollment_requests_user_code_pending_idx").on(table.userCode).where(sql3`${table.status} = 'pending'`),
3572
+ workspaceCreated: index3("device_enrollment_requests_workspace_created_idx").on(
3573
+ table.workspaceId,
3574
+ table.createdAt
3575
+ ),
3576
+ expires: index3("device_enrollment_requests_expires_idx").on(table.expiresAt)
3577
+ })
3578
+ );
3579
+ var sandboxes = pgTable3(
3580
+ "sandboxes",
3581
+ {
3582
+ id: uuid3("id").primaryKey().defaultRandom(),
3583
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3584
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3585
+ kind: text3("kind", { enum: sandboxKindValues }).notNull(),
3586
+ name: text3("name").notNull(),
3587
+ enrollmentId: uuid3("enrollment_id").references(() => enrollments.id, {
3588
+ onDelete: "set null"
3589
+ }),
3590
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
3591
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
3592
+ },
3593
+ (table) => ({
3594
+ workspaceCreated: index3("sandboxes_workspace_created_idx").on(
3595
+ table.workspaceId,
3596
+ table.createdAt
3597
+ ),
3598
+ enrollment: index3("sandboxes_enrollment_idx").on(table.enrollmentId).where(sql3`${table.enrollmentId} is not null`)
3599
+ })
3600
+ );
3601
+ var machineMetricsLatest = pgTable3(
3602
+ "machine_metrics_latest",
3603
+ {
3604
+ enrollmentId: uuid3("enrollment_id").primaryKey().references(() => enrollments.id, { onDelete: "cascade" }),
3605
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3606
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3607
+ cpuPercent: numeric("cpu_percent").$type(),
3608
+ load1: numeric("load1").$type(),
3609
+ load5: numeric("load5").$type(),
3610
+ load15: numeric("load15").$type(),
3611
+ memUsedBytes: bigint3("mem_used_bytes", { mode: "number" }),
3612
+ memTotalBytes: bigint3("mem_total_bytes", { mode: "number" }),
3613
+ diskUsedBytes: bigint3("disk_used_bytes", { mode: "number" }),
3614
+ diskTotalBytes: bigint3("disk_total_bytes", { mode: "number" }),
3615
+ gpuUtilPercent: numeric("gpu_util_percent").$type(),
3616
+ gpuMemUsedBytes: bigint3("gpu_mem_used_bytes", { mode: "number" }),
3617
+ gpuMemTotalBytes: bigint3("gpu_mem_total_bytes", { mode: "number" }),
3618
+ contention: numeric("contention").$type(),
3619
+ sampledAt: timestamp3("sampled_at", { withTimezone: true }).notNull(),
3620
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
3621
+ },
3622
+ (table) => ({
3623
+ workspace: index3("machine_metrics_latest_workspace_idx").on(table.workspaceId)
3624
+ })
3625
+ );
3626
+ var machineMetricsSeries = pgTable3(
3627
+ "machine_metrics_series",
3628
+ {
3629
+ id: uuid3("id").primaryKey().defaultRandom(),
3630
+ enrollmentId: uuid3("enrollment_id").notNull().references(() => enrollments.id, { onDelete: "cascade" }),
3631
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3632
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3633
+ cpuPercent: numeric("cpu_percent").$type(),
3634
+ load1: numeric("load1").$type(),
3635
+ load5: numeric("load5").$type(),
3636
+ load15: numeric("load15").$type(),
3637
+ memUsedBytes: bigint3("mem_used_bytes", { mode: "number" }),
3638
+ memTotalBytes: bigint3("mem_total_bytes", { mode: "number" }),
3639
+ diskUsedBytes: bigint3("disk_used_bytes", { mode: "number" }),
3640
+ diskTotalBytes: bigint3("disk_total_bytes", { mode: "number" }),
3641
+ gpuUtilPercent: numeric("gpu_util_percent").$type(),
3642
+ gpuMemUsedBytes: bigint3("gpu_mem_used_bytes", { mode: "number" }),
3643
+ gpuMemTotalBytes: bigint3("gpu_mem_total_bytes", { mode: "number" }),
3644
+ contention: numeric("contention").$type(),
3645
+ sampledAt: timestamp3("sampled_at", { withTimezone: true }).notNull(),
3646
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
3647
+ },
3648
+ (table) => ({
3649
+ enrollmentSampled: index3("machine_metrics_series_enrollment_sampled_idx").on(
3650
+ table.enrollmentId,
3651
+ table.sampledAt
3652
+ ),
3653
+ sampled: index3("machine_metrics_series_sampled_idx").on(table.sampledAt)
3654
+ })
3655
+ );
3656
+ var scheduledTasks = pgTable3(
3657
+ "scheduled_tasks",
3658
+ {
3659
+ id: uuid3("id").primaryKey().defaultRandom(),
3660
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3661
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3662
+ name: text3("name").notNull(),
3663
+ status: text3("status").notNull().default("active"),
3664
+ schedule: jsonb2("schedule").$type().notNull(),
3665
+ temporalScheduleId: text3("temporal_schedule_id").notNull(),
3666
+ runMode: text3("run_mode").notNull().default("new_session_per_run"),
3667
+ overlapPolicy: text3("overlap_policy").notNull().default("allow_concurrent"),
3668
+ agentConfig: jsonb2("agent_config").$type().notNull(),
3669
+ reusableSessionId: uuid3("reusable_session_id").references(() => sessions.id, {
3670
+ onDelete: "set null"
3671
+ }),
3672
+ variableSetId: uuid3("variable_set_id").references(() => workspaceVariableSets.id, {
3673
+ onDelete: "restrict"
3674
+ }),
3675
+ // The rig this task's runs ride; the active version is resolved per fire
3676
+ // (migration 0047). NULL ⇒ no rig. FK (-> rigs(id) ON DELETE SET NULL) lives
3677
+ // in migration 0047 (forward-reference pattern). Consumed in M3.
3678
+ rigId: uuid3("rig_id"),
3679
+ metadata: jsonb2("metadata").$type().notNull().default({}),
3680
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
3681
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
3682
+ },
3683
+ (table) => ({
3684
+ temporalScheduleId: uniqueIndex3("scheduled_tasks_workspace_temporal_schedule_id_idx").on(
3685
+ table.workspaceId,
3686
+ table.temporalScheduleId
3687
+ ),
3688
+ status: index3("scheduled_tasks_workspace_status_idx").on(table.workspaceId, table.status),
3689
+ variableSet: index3("scheduled_tasks_variable_set_idx").on(
3690
+ table.workspaceId,
3691
+ table.variableSetId
3692
+ )
3693
+ })
3694
+ );
3695
+ var scheduledTaskRuns = pgTable3(
3696
+ "scheduled_task_runs",
3697
+ {
3698
+ id: uuid3("id").primaryKey().defaultRandom(),
3699
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3700
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3701
+ taskId: uuid3("task_id").notNull().references(() => scheduledTasks.id, { onDelete: "cascade" }),
3702
+ status: text3("status").notNull().default("queued"),
3703
+ triggerType: text3("trigger_type").notNull(),
3704
+ scheduledAt: timestamp3("scheduled_at", { withTimezone: true }),
3705
+ firedAt: timestamp3("fired_at", { withTimezone: true }).notNull().defaultNow(),
3706
+ sessionId: uuid3("session_id").references(() => sessions.id, {
3707
+ onDelete: "set null"
3708
+ }),
3709
+ triggerEventId: uuid3("trigger_event_id"),
3710
+ // Stable Temporal producer identity. Activity replay/re-dispatch returns
3711
+ // the exact run instead of allocating a second schedule source row.
3712
+ producerKey: text3("producer_key"),
3713
+ error: text3("error"),
3714
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
3715
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
3716
+ },
3717
+ (table) => ({
3718
+ taskCreated: index3("scheduled_task_runs_workspace_task_created_idx").on(
3719
+ table.workspaceId,
3720
+ table.taskId,
3721
+ table.createdAt
3722
+ ),
3723
+ session: index3("scheduled_task_runs_workspace_session_idx").on(
3724
+ table.workspaceId,
3725
+ table.sessionId
3726
+ ),
3727
+ producer: uniqueIndex3("scheduled_task_runs_producer_key_uq").on(table.workspaceId, table.producerKey).where(sql3`${table.producerKey} is not null`)
3728
+ })
3729
+ );
3730
+ var githubInstallations = pgTable3(
3731
+ "github_installations",
3732
+ {
3733
+ id: uuid3("id").primaryKey().defaultRandom(),
3734
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3735
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3736
+ installationId: integer2("installation_id").notNull(),
3737
+ githubAccountId: bigint3("github_account_id", { mode: "number" }),
3738
+ accountLogin: text3("account_login"),
3739
+ accountType: text3("account_type"),
3740
+ repositoryScope: text3("repository_scope").notNull().default("all"),
3741
+ linkedBySubjectId: text3("linked_by_subject_id"),
3742
+ githubActorId: bigint3("github_actor_id", { mode: "number" }),
3743
+ githubActorLogin: text3("github_actor_login"),
3744
+ authorityKind: text3("authority_kind"),
3745
+ authorityCheckedAt: timestamp3("authority_checked_at", { withTimezone: true }),
3746
+ authorityExpiresAt: timestamp3("authority_expires_at", { withTimezone: true }),
3747
+ authorityNonce: text3("authority_nonce"),
3748
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
3749
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
3750
+ },
3751
+ (table) => ({
3752
+ workspaceInstallation: uniqueIndex3("github_installations_workspace_installation_idx").on(
3753
+ table.workspaceId,
3754
+ table.installationId
3755
+ ),
3756
+ installation: index3("github_installations_installation_idx").on(table.installationId),
3757
+ workspace: index3("github_installations_workspace_idx").on(table.workspaceId),
3758
+ repositoryScopeCheck: check3(
3759
+ "github_installations_repository_scope_check",
3760
+ sql3`${table.repositoryScope} in ('all', 'selected')`
3761
+ ),
3762
+ authorityKindCheck: check3(
3763
+ "github_installations_authority_kind_check",
3764
+ sql3`
3765
+ (
3766
+ ${table.githubAccountId} is null
3767
+ and ${table.githubActorId} is null
3768
+ and ${table.githubActorLogin} is null
3769
+ and ${table.authorityKind} is null
3770
+ and ${table.authorityCheckedAt} is null
3771
+ and ${table.authorityExpiresAt} is null
3772
+ and ${table.authorityNonce} is null
3773
+ )
3774
+ or (
3775
+ ${table.githubAccountId} is not null
3776
+ and ${table.githubAccountId} > 0
3777
+ and ${table.githubActorId} is not null
3778
+ and ${table.githubActorId} > 0
3779
+ and ${table.githubActorLogin} is not null
3780
+ and length(${table.githubActorLogin}) > 0
3781
+ and ${table.accountLogin} is not null
3782
+ and length(${table.accountLogin}) > 0
3783
+ and ${table.accountType} is not null
3784
+ and ${table.linkedBySubjectId} is not null
3785
+ and length(${table.linkedBySubjectId}) > 0
3786
+ and ${table.authorityKind} is not null
3787
+ and ${table.authorityCheckedAt} is not null
3788
+ and ${table.authorityExpiresAt} is not null
3789
+ and ${table.authorityCheckedAt} < ${table.authorityExpiresAt}
3790
+ and ${table.authorityExpiresAt} <= ${table.authorityCheckedAt} + interval '10 minutes'
3791
+ and ${table.authorityNonce} is not null
3792
+ and length(${table.authorityNonce}) > 0
3793
+ and ${table.repositoryScope} = 'selected'
3794
+ and (
3795
+ (
3796
+ ${table.authorityKind} = 'personal_owner'
3797
+ and ${table.accountType} = 'User'
3798
+ and ${table.githubActorId} = ${table.githubAccountId}
3799
+ )
3800
+ or (
3801
+ ${table.authorityKind} = 'organization_owner'
3802
+ and ${table.accountType} = 'Organization'
3803
+ )
3804
+ )
3805
+ )
3806
+ `
3807
+ ),
3808
+ authorityNonce: uniqueIndex3("github_installations_authority_nonce_uq").on(table.authorityNonce).where(sql3`${table.authorityNonce} is not null`)
3809
+ })
3810
+ );
3811
+ var githubInstallationRepositories = pgTable3(
3812
+ "github_installation_repositories",
3813
+ {
3814
+ id: uuid3("id").primaryKey().defaultRandom(),
3815
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3816
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3817
+ installationId: integer2("installation_id").notNull(),
3818
+ repositoryId: bigint3("repository_id", { mode: "number" }).notNull(),
3819
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
3820
+ },
3821
+ (table) => ({
3822
+ installationRepository: uniqueIndex3("github_install_repo_workspace_installation_repo_idx").on(
3823
+ table.workspaceId,
3824
+ table.installationId,
3825
+ table.repositoryId
3826
+ ),
3827
+ workspaceInstallation: index3("github_install_repo_workspace_installation_idx").on(
3828
+ table.workspaceId,
3829
+ table.installationId
3830
+ ),
3831
+ workspaceAccount: foreignKey({
3832
+ columns: [table.workspaceId, table.accountId],
3833
+ foreignColumns: [workspaces.id, workspaces.accountId],
3834
+ name: "github_installation_repositories_workspace_account_fk"
3835
+ }).onDelete("cascade"),
3836
+ installationBinding: foreignKey({
3837
+ columns: [table.workspaceId, table.installationId],
3838
+ foreignColumns: [githubInstallations.workspaceId, githubInstallations.installationId],
3839
+ name: "github_installation_repositories_installation_fk"
3840
+ }).onDelete("cascade")
3841
+ })
3842
+ );
3843
+ var usageEvents = pgTable3(
3844
+ "usage_events",
3845
+ {
3846
+ id: uuid3("id").primaryKey().defaultRandom(),
3847
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3848
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3849
+ subjectId: text3("subject_id"),
3850
+ eventType: text3("event_type").notNull(),
3851
+ quantity: bigint3("quantity", { mode: "number" }).notNull(),
3852
+ unit: text3("unit").notNull(),
3853
+ sourceResourceType: text3("source_resource_type"),
3854
+ sourceResourceId: text3("source_resource_id"),
3855
+ // Exact execution source for host usage export. These are deliberately
3856
+ // validated soft references rather than cascading foreign keys: usage is
3857
+ // an immutable billing/audit fact and must retain its source identity after
3858
+ // a session or turn is deleted.
3859
+ sessionId: uuid3("session_id"),
3860
+ turnId: uuid3("turn_id"),
3861
+ turnAttemptId: uuid3("turn_attempt_id"),
3862
+ initiatorKind: text3("initiator_kind"),
3863
+ initiatorSubjectId: text3("initiator_subject_id"),
3864
+ initiatorContext: jsonb2("initiator_context").$type().notNull().default({}),
3865
+ origin: text3("origin"),
3866
+ idempotencyKey: text3("idempotency_key").notNull(),
3867
+ occurredAt: timestamp3("occurred_at", { withTimezone: true }).notNull(),
3868
+ recordedAt: timestamp3("recorded_at", { withTimezone: true }).notNull().defaultNow(),
3869
+ exportedToBillingAt: timestamp3("exported_to_billing_at", {
3870
+ withTimezone: true
3871
+ }),
3872
+ billingProviderEventId: text3("billing_provider_event_id")
3873
+ },
3874
+ (table) => ({
3875
+ idempotency: uniqueIndex3("usage_events_idempotency_idx").on(table.idempotencyKey),
3876
+ workspaceMetric: index3("usage_events_workspace_metric_idx").on(
3877
+ table.workspaceId,
3878
+ table.eventType,
3879
+ table.occurredAt
3880
+ ),
3881
+ accountMetric: index3("usage_events_account_metric_idx").on(
3882
+ table.accountId,
3883
+ table.eventType,
3884
+ table.occurredAt
3885
+ ),
3886
+ workspaceSession: index3("usage_events_workspace_session_idx").on(
3887
+ table.workspaceId,
3888
+ table.sessionId,
3889
+ table.occurredAt
3890
+ ),
3891
+ contextHierarchy: check3(
3892
+ "usage_events_context_hierarchy_check",
3893
+ sql3`(${table.turnId} is null or ${table.sessionId} is not null)
3894
+ and (${table.turnAttemptId} is null or ${table.turnId} is not null)`
3895
+ ),
3896
+ initiatorConsistent: check3(
3897
+ "usage_events_initiator_check",
3898
+ sql3`(${table.initiatorKind} is null and ${table.initiatorSubjectId} is null)
3899
+ or (${table.initiatorKind} in ('subject', 'service')
3900
+ and ${table.initiatorSubjectId} is not null
3901
+ and octet_length(${table.initiatorSubjectId}) between 1 and 1024)`
3902
+ ),
3903
+ attributionContextBytes: check3(
3904
+ "usage_events_initiator_context_bytes_check",
3905
+ sql3`octet_length(${table.initiatorContext}::text) <= 4096`
3906
+ ),
3907
+ originValid: check3(
3908
+ "usage_events_origin_check",
3909
+ sql3`${table.origin} is null or ${table.origin} in (
3910
+ 'user', 'scheduled_task', 'api', 'goal', 'system', 'compaction'
3911
+ )`
3912
+ )
3913
+ })
3914
+ );
3915
+ var modelCallFacts = pgTable3(
3916
+ "model_call_facts",
3917
+ {
3918
+ id: uuid3("id").primaryKey().defaultRandom(),
3919
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3920
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3921
+ sessionId: uuid3("session_id").notNull(),
3922
+ turnId: uuid3("turn_id").notNull(),
3923
+ turnAttemptId: uuid3("turn_attempt_id"),
3924
+ sourceKey: text3("source_key").notNull(),
3925
+ provider: text3("provider").notNull(),
3926
+ providerApi: text3("provider_api").notNull(),
3927
+ model: text3("model").notNull(),
3928
+ billingPath: text3("billing_path").notNull(),
3929
+ turnSource: text3("turn_source"),
3930
+ initiatorKind: text3("initiator_kind"),
3931
+ initiatorSubjectId: text3("initiator_subject_id"),
3932
+ scheduledTaskId: uuid3("scheduled_task_id"),
3933
+ inputTokens: bigint3("input_tokens", { mode: "number" }),
3934
+ outputTokens: bigint3("output_tokens", { mode: "number" }),
3935
+ cachedTokens: bigint3("cached_tokens", { mode: "number" }),
3936
+ cacheWriteTokens: bigint3("cache_write_tokens", { mode: "number" }),
3937
+ reasoningTokens: bigint3("reasoning_tokens", { mode: "number" }),
3938
+ totalTokens: bigint3("total_tokens", { mode: "number" }),
3939
+ pricedCostMicros: bigint3("priced_cost_micros", { mode: "number" }).notNull().default(0),
3940
+ occurredAt: timestamp3("occurred_at", { withTimezone: true }).notNull(),
3941
+ recordedAt: timestamp3("recorded_at", { withTimezone: true }).notNull().defaultNow()
3942
+ },
3943
+ (table) => ({
3944
+ workspaceTurnSource: uniqueIndex3("model_call_facts_workspace_turn_source_uq").on(
3945
+ table.workspaceId,
3946
+ table.turnId,
3947
+ table.sourceKey
3948
+ ),
3949
+ workspaceOccurred: index3("model_call_facts_workspace_occurred_idx").on(
3950
+ table.workspaceId,
3951
+ table.occurredAt
3952
+ ),
3953
+ workspaceProviderModelOccurred: index3(
3954
+ "model_call_facts_workspace_provider_model_occurred_idx"
3955
+ ).on(table.workspaceId, table.provider, table.model, table.occurredAt),
3956
+ workspaceSessionOccurred: index3("model_call_facts_workspace_session_occurred_idx").on(
3957
+ table.workspaceId,
3958
+ table.sessionId,
3959
+ table.occurredAt
3960
+ ),
3961
+ workspaceScheduledTaskOccurred: index3("model_call_facts_workspace_scheduled_task_occurred_idx").on(table.workspaceId, table.scheduledTaskId, table.occurredAt).where(sql3`${table.scheduledTaskId} is not null`),
3962
+ workspaceAccount: foreignKey({
3963
+ name: "model_call_facts_workspace_account_fk",
3964
+ columns: [table.workspaceId, table.accountId],
3965
+ foreignColumns: [workspaces.id, workspaces.accountId]
3966
+ }).onDelete("cascade"),
3967
+ billingPathValid: check3(
3968
+ "model_call_facts_billing_path_check",
3969
+ sql3`${table.billingPath} in ('opengeni_credits', 'external')`
3970
+ ),
3971
+ pricedCostNonNegative: check3(
3972
+ "model_call_facts_priced_cost_check",
3973
+ sql3`${table.pricedCostMicros} >= 0`
3974
+ ),
3975
+ initiatorConsistent: check3(
3976
+ "model_call_facts_initiator_check",
3977
+ sql3`(${table.initiatorKind} is null and ${table.initiatorSubjectId} is null)
3978
+ or (${table.initiatorKind} in ('subject', 'service')
3979
+ and ${table.initiatorSubjectId} is not null
3980
+ and octet_length(${table.initiatorSubjectId}) between 1 and 1024)`
3981
+ ),
3982
+ sourceKeyBytes: check3(
3983
+ "model_call_facts_source_key_bytes_check",
3984
+ sql3`octet_length(${table.sourceKey}) between 1 and 1024`
3985
+ ),
3986
+ providerBytes: check3(
3987
+ "model_call_facts_provider_bytes_check",
3988
+ sql3`octet_length(${table.provider}) between 1 and 256`
3989
+ ),
3990
+ providerApiBytes: check3(
3991
+ "model_call_facts_provider_api_bytes_check",
3992
+ sql3`octet_length(${table.providerApi}) between 1 and 256`
3993
+ ),
3994
+ modelBytes: check3(
3995
+ "model_call_facts_model_bytes_check",
3996
+ sql3`octet_length(${table.model}) between 1 and 512`
3997
+ )
3998
+ })
3999
+ );
4000
+ var hostExportConfig = pgTable3(
4001
+ "host_export_config",
4002
+ {
4003
+ id: integer2("id").primaryKey().default(1),
4004
+ sessionEventsEnabled: boolean2("session_events_enabled").notNull().default(false),
4005
+ usageEventsEnabled: boolean2("usage_events_enabled").notNull().default(false),
4006
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4007
+ },
4008
+ (table) => ({
4009
+ singleton: check3("host_export_config_singleton_check", sql3`${table.id} = 1`)
4010
+ })
4011
+ );
4012
+ var hostExportOutbox = pgTable3(
4013
+ "host_export_outbox",
4014
+ {
4015
+ id: uuid3("id").primaryKey().defaultRandom(),
4016
+ exportKind: text3("export_kind").notNull(),
4017
+ exportCursor: bigint3("export_cursor", { mode: "bigint" }),
4018
+ sourceId: uuid3("source_id").notNull(),
4019
+ accountId: uuid3("account_id").notNull(),
4020
+ workspaceId: uuid3("workspace_id").notNull(),
4021
+ sessionId: uuid3("session_id"),
4022
+ rootSessionId: uuid3("root_session_id"),
4023
+ turnId: uuid3("turn_id"),
4024
+ turnGeneration: integer2("turn_generation"),
4025
+ turnAttemptId: uuid3("turn_attempt_id"),
4026
+ sessionSequence: integer2("session_sequence"),
4027
+ clientEventId: text3("client_event_id"),
4028
+ turnAssociation: text3("turn_association"),
4029
+ duplicateOfEventId: uuid3("duplicate_of_event_id"),
4030
+ duplicateReason: text3("duplicate_reason"),
4031
+ eventType: text3("event_type").notNull(),
4032
+ idempotencyKey: text3("idempotency_key").notNull(),
4033
+ initiator: jsonb2("initiator").$type(),
4034
+ initiatorContext: jsonb2("initiator_context").$type().notNull().default({}),
4035
+ origin: text3("origin"),
4036
+ payload: jsonb2("payload").$type().notNull(),
4037
+ envelopeBytes: integer2("envelope_bytes").notNull(),
4038
+ occurredAt: timestamp3("occurred_at", { withTimezone: true }).notNull(),
4039
+ sourceRecordedAt: timestamp3("source_recorded_at", { withTimezone: true }).notNull(),
4040
+ enqueuedAt: timestamp3("enqueued_at", { withTimezone: true }).notNull()
4041
+ },
4042
+ (table) => ({
4043
+ kindValid: check3(
4044
+ "host_export_outbox_kind_check",
4045
+ sql3`${table.exportKind} in ('session_event', 'usage_event')`
4046
+ ),
4047
+ rootSessionCaptured: check3(
4048
+ "host_export_outbox_root_session_check",
4049
+ sql3`${table.sessionId} is null or ${table.rootSessionId} is not null`
4050
+ ),
4051
+ sourceUnique: uniqueIndex3("host_export_outbox_source_uq").on(table.exportKind, table.sourceId),
4052
+ cursorUnique: uniqueIndex3("host_export_outbox_cursor_uq").on(table.exportKind, table.exportCursor).where(sql3`${table.exportCursor} is not null`),
4053
+ unassigned: index3("host_export_outbox_unassigned_idx").on(table.exportKind, table.enqueuedAt, table.id).where(sql3`${table.exportCursor} is null`),
4054
+ unassignedSession: index3("host_export_outbox_unassigned_session_idx").on(table.exportKind, table.sessionId, table.sessionSequence).where(sql3`${table.exportCursor} is null and ${table.sessionId} is not null`),
4055
+ contextBytes: check3(
4056
+ "host_export_outbox_context_bytes_check",
4057
+ sql3`octet_length(${table.initiatorContext}::text) <= 4096`
4058
+ ),
4059
+ originValid: check3(
4060
+ "host_export_outbox_origin_check",
4061
+ sql3`${table.origin} is null or ${table.origin} in (
4062
+ 'user', 'scheduled_task', 'api', 'goal', 'system', 'compaction'
4063
+ )`
4064
+ )
4065
+ })
4066
+ );
4067
+ var hostExportCursorState = pgTable3(
4068
+ "host_export_cursor_state",
4069
+ {
4070
+ exportKind: text3("export_kind").primaryKey(),
4071
+ nextCursor: bigint3("next_cursor", { mode: "bigint" }).notNull().default(1n),
4072
+ prunedThrough: bigint3("pruned_through", { mode: "bigint" }).notNull().default(0n),
4073
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4074
+ },
4075
+ (table) => ({
4076
+ kindValid: check3(
4077
+ "host_export_cursor_state_kind_check",
4078
+ sql3`${table.exportKind} in ('session_event', 'usage_event')`
4079
+ ),
4080
+ cursorValid: check3(
4081
+ "host_export_cursor_state_next_check",
4082
+ sql3`${table.nextCursor} > 0 and ${table.prunedThrough} >= 0
4083
+ and ${table.prunedThrough} < ${table.nextCursor}`
4084
+ )
4085
+ })
4086
+ );
4087
+ var hostExportConsumers = pgTable3(
4088
+ "host_export_consumers",
4089
+ {
4090
+ id: uuid3("id").primaryKey().defaultRandom(),
4091
+ consumerId: text3("consumer_id").notNull(),
4092
+ exportKind: text3("export_kind").notNull(),
4093
+ checkpoint: bigint3("checkpoint", { mode: "bigint" }).notNull().default(0n),
4094
+ enabled: boolean2("enabled").notNull().default(true),
4095
+ leaseToken: uuid3("lease_token"),
4096
+ leaseHolderId: text3("lease_holder_id"),
4097
+ leaseExpiresAt: timestamp3("lease_expires_at", { withTimezone: true }),
4098
+ leaseFrom: bigint3("lease_from", { mode: "bigint" }),
4099
+ leaseThrough: bigint3("lease_through", { mode: "bigint" }),
4100
+ consecutiveFailures: integer2("consecutive_failures").notNull().default(0),
4101
+ nextAttemptAt: timestamp3("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
4102
+ lastError: text3("last_error"),
4103
+ lastErrorAt: timestamp3("last_error_at", { withTimezone: true }),
4104
+ blockedAt: timestamp3("blocked_at", { withTimezone: true }),
4105
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
4106
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4107
+ },
4108
+ (table) => ({
4109
+ consumerKind: uniqueIndex3("host_export_consumers_kind_id_uq").on(
4110
+ table.exportKind,
4111
+ table.consumerId
4112
+ ),
4113
+ kindValid: check3(
4114
+ "host_export_consumers_kind_check",
4115
+ sql3`${table.exportKind} in ('session_event', 'usage_event')`
4116
+ ),
4117
+ checkpointValid: check3("host_export_consumers_checkpoint_check", sql3`${table.checkpoint} >= 0`),
4118
+ due: index3("host_export_consumers_due_idx").on(
4119
+ table.enabled,
4120
+ table.blockedAt,
4121
+ table.nextAttemptAt
4122
+ )
4123
+ })
4124
+ );
4125
+ var hostExportDeadLetters = pgTable3(
4126
+ "host_export_dead_letters",
4127
+ {
4128
+ id: uuid3("id").primaryKey().defaultRandom(),
4129
+ consumerId: text3("consumer_id").notNull(),
4130
+ exportKind: text3("export_kind").notNull(),
4131
+ exportCursor: bigint3("export_cursor", { mode: "bigint" }).notNull(),
4132
+ sourceId: uuid3("source_id").notNull(),
4133
+ reason: text3("reason").notNull(),
4134
+ envelope: jsonb2("envelope").$type().notNull(),
4135
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
4136
+ },
4137
+ (table) => ({
4138
+ consumerCursor: uniqueIndex3("host_export_dead_letters_consumer_cursor_uq").on(
4139
+ table.exportKind,
4140
+ table.consumerId,
4141
+ table.exportCursor
4142
+ ),
4143
+ kindValid: check3(
4144
+ "host_export_dead_letters_kind_check",
4145
+ sql3`${table.exportKind} in ('session_event', 'usage_event')`
4146
+ ),
4147
+ reasonValid: check3(
4148
+ "host_export_dead_letters_reason_check",
4149
+ sql3`length(${table.reason}) between 1 and 500`
4150
+ ),
4151
+ envelopeBytes: check3(
4152
+ "host_export_dead_letters_envelope_bytes_check",
4153
+ sql3`pg_column_size(${table.envelope}) <= 114688`
4154
+ )
4155
+ })
4156
+ );
4157
+ var creditLedgerEntries = pgTable3(
4158
+ "credit_ledger_entries",
4159
+ {
4160
+ id: uuid3("id").primaryKey().defaultRandom(),
4161
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4162
+ workspaceId: uuid3("workspace_id").references(() => workspaces.id, {
4163
+ onDelete: "set null"
4164
+ }),
4165
+ type: text3("type").notNull(),
4166
+ amountMicros: bigint3("amount_micros", { mode: "number" }).notNull(),
4167
+ currency: text3("currency").notNull().default("usd"),
4168
+ sourceType: text3("source_type"),
4169
+ sourceId: text3("source_id"),
4170
+ idempotencyKey: text3("idempotency_key").notNull(),
4171
+ metadata: jsonb2("metadata").$type().notNull().default({}),
4172
+ occurredAt: timestamp3("occurred_at", { withTimezone: true }).notNull().defaultNow(),
4173
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
4174
+ },
4175
+ (table) => ({
4176
+ idempotency: uniqueIndex3("credit_ledger_entries_idempotency_idx").on(table.idempotencyKey),
4177
+ accountCreated: index3("credit_ledger_entries_account_created_idx").on(
4178
+ table.accountId,
4179
+ table.createdAt
4180
+ )
4181
+ })
4182
+ );
4183
+ var billingCustomers = pgTable3(
4184
+ "billing_customers",
4185
+ {
4186
+ id: uuid3("id").primaryKey().defaultRandom(),
4187
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4188
+ provider: text3("provider").notNull().default("stripe"),
4189
+ providerCustomerId: text3("provider_customer_id").notNull(),
4190
+ email: text3("email"),
4191
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
4192
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4193
+ },
4194
+ (table) => ({
4195
+ accountProvider: uniqueIndex3("billing_customers_account_provider_idx").on(
4196
+ table.accountId,
4197
+ table.provider
4198
+ ),
4199
+ providerCustomer: uniqueIndex3("billing_customers_provider_customer_idx").on(
4200
+ table.provider,
4201
+ table.providerCustomerId
4202
+ )
4203
+ })
4204
+ );
4205
+ var stripeWebhookEvents = pgTable3("stripe_webhook_events", {
4206
+ id: text3("id").primaryKey(),
4207
+ type: text3("type").notNull(),
4208
+ livemode: text3("livemode").notNull().default("false"),
4209
+ payload: jsonb2("payload").$type().notNull(),
4210
+ processedAt: timestamp3("processed_at", { withTimezone: true }),
4211
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
4212
+ });
4213
+ var auditEvents = pgTable3(
4214
+ "audit_events",
4215
+ {
4216
+ id: uuid3("id").primaryKey().defaultRandom(),
4217
+ accountId: uuid3("account_id").references(() => managedAccounts.id, {
4218
+ onDelete: "set null"
4219
+ }),
4220
+ workspaceId: uuid3("workspace_id").references(() => workspaces.id, {
4221
+ onDelete: "set null"
4222
+ }),
4223
+ subjectId: text3("subject_id"),
4224
+ action: text3("action").notNull(),
4225
+ targetType: text3("target_type"),
4226
+ targetId: text3("target_id"),
4227
+ metadata: jsonb2("metadata").$type().notNull().default({}),
4228
+ occurredAt: timestamp3("occurred_at", { withTimezone: true }).notNull().defaultNow()
4229
+ },
4230
+ (table) => ({
4231
+ accountCreated: index3("audit_events_account_created_idx").on(table.accountId, table.occurredAt),
4232
+ workspaceCreated: index3("audit_events_workspace_created_idx").on(
4233
+ table.workspaceId,
4234
+ table.occurredAt
4235
+ )
4236
+ })
4237
+ );
4238
+ var packInstallations = pgTable3(
4239
+ "pack_installations",
4240
+ {
4241
+ id: uuid3("id").primaryKey().defaultRandom(),
4242
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4243
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4244
+ packId: text3("pack_id").notNull(),
4245
+ status: text3("status").notNull().default("active"),
4246
+ metadata: jsonb2("metadata").$type().notNull().default({}),
4247
+ enabledAt: timestamp3("enabled_at", { withTimezone: true }).notNull().defaultNow(),
4248
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4249
+ },
4250
+ (table) => ({
4251
+ workspacePack: uniqueIndex3("pack_installations_workspace_pack_idx").on(
4252
+ table.workspaceId,
4253
+ table.packId
4254
+ ),
4255
+ status: index3("pack_installations_workspace_status_idx").on(table.workspaceId, table.status)
4256
+ })
4257
+ );
4258
+ var workspacePacks = pgTable3(
4259
+ "workspace_packs",
4260
+ {
4261
+ id: uuid3("id").primaryKey().defaultRandom(),
4262
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4263
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4264
+ packId: text3("pack_id").notNull(),
4265
+ manifest: jsonb2("manifest").$type().notNull(),
4266
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
4267
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4268
+ },
4269
+ (table) => ({
4270
+ workspacePack: uniqueIndex3("workspace_packs_workspace_pack_idx").on(
4271
+ table.workspaceId,
4272
+ table.packId
4273
+ )
4274
+ })
4275
+ );
4276
+ var importBatches = pgTable3(
4277
+ "import_batches",
4278
+ {
4279
+ id: uuid3("id").primaryKey().defaultRandom(),
4280
+ source: text3("source").notNull(),
4281
+ snapshotDate: timestamp3("snapshot_date", { withTimezone: true }).notNull(),
4282
+ snapshotRef: text3("snapshot_ref"),
4283
+ attributionNote: text3("attribution_note").notNull(),
4284
+ importedCount: integer2("imported_count").notNull().default(0),
4285
+ skippedCount: integer2("skipped_count").notNull().default(0),
4286
+ quarantinedCount: integer2("quarantined_count").notNull().default(0),
4287
+ logoFailureCount: integer2("logo_failure_count").notNull().default(0),
4288
+ staleCount: integer2("stale_count").notNull().default(0),
4289
+ details: jsonb2("details").$type().notNull().default({}),
4290
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
4291
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4292
+ },
4293
+ (table) => ({
4294
+ sourceSnapshot: index3("import_batches_source_snapshot_idx").on(
4295
+ table.source,
4296
+ table.snapshotDate
4297
+ ),
4298
+ createdAt: index3("import_batches_created_at_idx").on(table.createdAt)
4299
+ })
4300
+ );
4301
+ var capabilityCatalogItems = pgTable3(
4302
+ "capability_catalog_items",
4303
+ {
4304
+ id: text3("id").notNull(),
4305
+ accountId: uuid3("account_id").references(() => managedAccounts.id, {
4306
+ onDelete: "cascade"
4307
+ }),
4308
+ workspaceId: uuid3("workspace_id").references(() => workspaces.id, {
4309
+ onDelete: "cascade"
4310
+ }),
4311
+ kind: text3("kind").notNull(),
4312
+ source: text3("source").notNull().default("manual"),
4313
+ name: text3("name").notNull(),
4314
+ description: text3("description"),
4315
+ category: text3("category").notNull().default("custom"),
4316
+ tags: jsonb2("tags").$type().notNull().default([]),
4317
+ homepageUrl: text3("homepage_url"),
4318
+ endpointUrl: text3("endpoint_url"),
4319
+ installUrl: text3("install_url"),
4320
+ authModel: text3("auth_model"),
4321
+ providerDomain: text3("provider_domain"),
4322
+ surfaceType: text3("surface_type"),
4323
+ transport: text3("transport"),
4324
+ mcpUrl: text3("mcp_url"),
4325
+ authKind: text3("auth_kind"),
4326
+ credentialFacts: jsonb2("credential_facts").$type().notNull().default([]),
4327
+ tier: text3("tier"),
4328
+ provenance: text3("provenance"),
4329
+ logoAssetPath: text3("logo_asset_path"),
4330
+ importBatchId: uuid3("import_batch_id").references(() => importBatches.id, {
4331
+ onDelete: "set null"
4332
+ }),
4333
+ stale: boolean2("stale").notNull().default(false),
4334
+ staleAt: timestamp3("stale_at", { withTimezone: true }),
4335
+ metadata: jsonb2("metadata").$type().notNull().default({}),
4336
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
4337
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4338
+ },
4339
+ (table) => ({
4340
+ workspaceCapability: uniqueIndex3("capability_catalog_items_workspace_capability_idx").on(
4341
+ table.workspaceId,
4342
+ table.id
4343
+ ),
4344
+ registrySurface: uniqueIndex3("capability_catalog_items_registry_surface_idx").on(
4345
+ table.source,
4346
+ table.providerDomain,
4347
+ table.mcpUrl
4348
+ ),
4349
+ globalCapability: uniqueIndex3("capability_catalog_items_global_capability_idx").on(table.id).where(sql3`${table.workspaceId} is null`),
4350
+ kind: index3("capability_catalog_items_workspace_kind_idx").on(table.workspaceId, table.kind),
4351
+ category: index3("capability_catalog_items_workspace_category_idx").on(
4352
+ table.workspaceId,
4353
+ table.category
4354
+ ),
4355
+ source: index3("capability_catalog_items_workspace_source_idx").on(
4356
+ table.workspaceId,
4357
+ table.source
4358
+ ),
4359
+ providerDomain: index3("capability_catalog_items_provider_domain_idx").on(table.providerDomain),
4360
+ importBatch: index3("capability_catalog_items_import_batch_idx").on(table.importBatchId),
4361
+ stale: index3("capability_catalog_items_source_stale_idx").on(table.source, table.stale)
4362
+ })
4363
+ );
4364
+ var capabilityInstallations = pgTable3(
4365
+ "capability_installations",
4366
+ {
4367
+ id: uuid3("id").primaryKey().defaultRandom(),
4368
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4369
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4370
+ capabilityId: text3("capability_id").notNull(),
4371
+ kind: text3("kind").notNull(),
4372
+ status: text3("status").notNull().default("active"),
4373
+ config: jsonb2("config").$type().notNull().default({}),
4374
+ metadata: jsonb2("metadata").$type().notNull().default({}),
4375
+ enabledAt: timestamp3("enabled_at", { withTimezone: true }).notNull().defaultNow(),
4376
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4377
+ },
4378
+ (table) => ({
4379
+ workspaceCapability: uniqueIndex3("capability_installations_workspace_capability_idx").on(
4380
+ table.workspaceId,
4381
+ table.capabilityId
4382
+ ),
4383
+ kind: index3("capability_installations_workspace_kind_idx").on(table.workspaceId, table.kind),
4384
+ status: index3("capability_installations_workspace_status_idx").on(
4385
+ table.workspaceId,
4386
+ table.status
4387
+ )
4388
+ })
4389
+ );
4390
+ var socialConnections = pgTable3(
4391
+ "social_connections",
4392
+ {
4393
+ id: uuid3("id").primaryKey().defaultRandom(),
4394
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4395
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4396
+ provider: text3("provider").notNull(),
4397
+ accountHandle: text3("account_handle").notNull(),
4398
+ accountName: text3("account_name"),
4399
+ externalAccountId: text3("external_account_id"),
4400
+ status: text3("status").notNull().default("connected"),
4401
+ scopes: jsonb2("scopes").$type().notNull().default([]),
4402
+ credentialRef: text3("credential_ref"),
4403
+ tokenMetadata: jsonb2("token_metadata").$type().notNull().default({}),
4404
+ metadata: jsonb2("metadata").$type().notNull().default({}),
4405
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
4406
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4407
+ },
4408
+ (table) => ({
4409
+ workspaceProviderHandle: uniqueIndex3("social_connections_workspace_provider_handle_idx").on(
4410
+ table.workspaceId,
4411
+ table.provider,
4412
+ table.accountHandle
4413
+ ),
4414
+ providerStatus: index3("social_connections_workspace_provider_status_idx").on(
4415
+ table.workspaceId,
4416
+ table.provider,
4417
+ table.status
4418
+ )
4419
+ })
4420
+ );
4421
+ var socialPosts = pgTable3(
4422
+ "social_posts",
4423
+ {
4424
+ id: uuid3("id").primaryKey().defaultRandom(),
4425
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4426
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4427
+ connectionId: uuid3("connection_id").notNull().references(() => socialConnections.id, { onDelete: "cascade" }),
4428
+ provider: text3("provider").notNull(),
4429
+ externalPostId: text3("external_post_id"),
4430
+ url: text3("url"),
4431
+ authorHandle: text3("author_handle"),
4432
+ text: text3("text").notNull(),
4433
+ publishedAt: timestamp3("published_at", { withTimezone: true }).notNull(),
4434
+ metrics: jsonb2("metrics").$type().notNull().default({}),
4435
+ raw: jsonb2("raw").$type().notNull().default({}),
4436
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
4437
+ },
4438
+ (table) => ({
4439
+ connectionExternalPost: uniqueIndex3("social_posts_workspace_connection_external_post_idx").on(
4440
+ table.workspaceId,
4441
+ table.connectionId,
4442
+ table.externalPostId
4443
+ ),
4444
+ connectionPublished: index3("social_posts_workspace_connection_published_idx").on(
4445
+ table.workspaceId,
4446
+ table.connectionId,
4447
+ table.publishedAt
4448
+ ),
4449
+ providerPublished: index3("social_posts_workspace_provider_published_idx").on(
4450
+ table.workspaceId,
4451
+ table.provider,
4452
+ table.publishedAt
4453
+ )
4454
+ })
4455
+ );
4456
+ var rigs = pgTable3(
4457
+ "rigs",
4458
+ {
4459
+ id: uuid3("id").primaryKey().defaultRandom(),
4460
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4461
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4462
+ name: text3("name").notNull(),
4463
+ description: text3("description"),
4464
+ // Attribution string: 'user:<subject>' | 'session:<id>' | 'system'.
4465
+ createdBy: text3("created_by"),
4466
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
4467
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4468
+ },
4469
+ (table) => ({
4470
+ workspaceName: uniqueIndex3("rigs_workspace_name_idx").on(table.workspaceId, table.name),
4471
+ workspaceCreated: index3("rigs_workspace_created_idx").on(table.workspaceId, table.createdAt)
4472
+ })
4473
+ );
4474
+ var rigVersions = pgTable3(
4475
+ "rig_versions",
4476
+ {
4477
+ id: uuid3("id").primaryKey().defaultRandom(),
4478
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4479
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4480
+ rigId: uuid3("rig_id").notNull().references(() => rigs.id, { onDelete: "cascade" }),
4481
+ version: integer2("version").notNull(),
4482
+ image: text3("image"),
4483
+ setupScript: text3("setup_script"),
4484
+ // Self-declared health checks: [{ name, command }].
4485
+ checks: jsonb2("checks").$type().notNull().default([]),
4486
+ // Registered credential-hook names (resolved to hook implementations in M3).
4487
+ credentialHooks: jsonb2("credential_hooks").$type().notNull().default([]),
4488
+ // Variable-set ids layered below the session's variable set at run time (M3).
4489
+ defaultVariableSetIds: jsonb2("default_variable_set_ids").$type().notNull().default([]),
4490
+ changelog: text3("changelog"),
4491
+ createdBy: text3("created_by"),
4492
+ active: boolean2("active").notNull().default(false),
4493
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
4494
+ },
4495
+ (table) => ({
4496
+ rigVersion: uniqueIndex3("rig_versions_rig_version_idx").on(table.rigId, table.version),
4497
+ // At most one active version per rig — the single-active invariant, in the DB.
4498
+ rigActive: uniqueIndex3("rig_versions_rig_active_idx").on(table.rigId).where(sql3`${table.active}`),
4499
+ workspaceRig: index3("rig_versions_workspace_rig_idx").on(
4500
+ table.workspaceId,
4501
+ table.rigId,
4502
+ table.version
4503
+ )
4504
+ })
4505
+ );
4506
+ var rigChanges = pgTable3(
4507
+ "rig_changes",
4508
+ {
4509
+ id: uuid3("id").primaryKey().defaultRandom(),
4510
+ accountId: uuid3("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4511
+ workspaceId: uuid3("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4512
+ rigId: uuid3("rig_id").notNull().references(() => rigs.id, { onDelete: "cascade" }),
4513
+ baseVersionId: uuid3("base_version_id").references(() => rigVersions.id, {
4514
+ onDelete: "set null"
4515
+ }),
4516
+ // 'setup_append' | 'definition_edit' (CHECK in migration 0047).
4517
+ kind: text3("kind").notNull(),
4518
+ payload: jsonb2("payload").$type().notNull(),
4519
+ // 'proposed' | 'verifying' | 'merged' | 'rejected' | 'failed' (CHECK in 0047).
4520
+ status: text3("status").notNull().default("proposed"),
4521
+ proposedBy: text3("proposed_by"),
4522
+ verification: jsonb2("verification").$type(),
4523
+ resultVersionId: uuid3("result_version_id").references(() => rigVersions.id, {
4524
+ onDelete: "set null"
4525
+ }),
4526
+ createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
4527
+ updatedAt: timestamp3("updated_at", { withTimezone: true }).notNull().defaultNow()
4528
+ },
4529
+ (table) => ({
4530
+ workspaceRig: index3("rig_changes_workspace_rig_idx").on(
4531
+ table.workspaceId,
4532
+ table.rigId,
4533
+ table.createdAt
4534
+ ),
4535
+ workspaceStatus: index3("rig_changes_workspace_status_idx").on(table.workspaceId, table.status)
4536
+ })
4537
+ );
4538
+
4539
+ export {
4540
+ workspaceInstructionPolicyRevisions,
4541
+ workspaceInstructionPolicyHeads,
4542
+ workspaceInstructionPolicyActivationEvents,
4543
+ preferenceRegistryPreferences,
4544
+ preferenceRegistryRevisions,
4545
+ preferenceRegistryEvents,
4546
+ preferenceRegistrySnapshots,
4547
+ managedAccounts,
4548
+ workspaces,
4549
+ nestedAgentDepthConfiguration,
4550
+ workspaceInferenceControls,
4551
+ workspaceSessionActivityRevisions,
4552
+ workspaceMemberships,
4553
+ apiKeys,
4554
+ workspaceVariableSets,
4555
+ workspaceVariableSetVariables,
4556
+ codexSubscriptionCredentials,
4557
+ codexResetRedemptionAttempts,
4558
+ connections,
4559
+ slackBotPostOperations,
4560
+ slackBotDeleteOperations,
4561
+ integrationOauthClients,
4562
+ integrationOauthStateNonces,
4563
+ codexRotationSettings,
4564
+ workspaceModelPolicies,
4565
+ codexCredentialLeases,
4566
+ sessions,
4567
+ sessionSpawnDenials,
4568
+ sessionPins,
4569
+ sessionListSnapshots,
4570
+ sessionMcpServers,
4571
+ files,
4572
+ fileUploads,
4573
+ documentBases,
4574
+ documents,
4575
+ documentChunks,
4576
+ knowledgeMemories,
4577
+ sessionTurns,
4578
+ sessionTurnAttempts,
4579
+ sessionCommandReceipts,
4580
+ workspaceControlEvents,
4581
+ sessionAttemptInterruptions,
4582
+ composerDrafts,
4583
+ newSessionDrafts,
4584
+ sessionSystemUpdates,
4585
+ sessionSystemUpdateOutbox,
4586
+ sessionWorkflowWakeOutbox,
4587
+ sessionGoals,
4588
+ codexCapacityWaiters,
4589
+ sessionEvents,
4590
+ agentRunStates,
4591
+ sessionHumanInputRequests,
4592
+ sessionHistoryItems,
4593
+ sessionPendingToolCalls,
4594
+ sandboxSessionEnvelopes,
4595
+ sandboxCheckpointArtifactStateValues,
4596
+ sandboxCheckpointArtifacts,
4597
+ sandboxLeaseLivenessValues,
4598
+ sandboxLeases,
4599
+ sandboxLeaseHolders,
4600
+ sandboxWorkspaceMutationActorKindValues,
4601
+ sandboxWorkspaceMutationHolderKindValues,
4602
+ sandboxWorkspaceMutationAdmissions,
4603
+ sandboxRetainedProcessStateValues,
4604
+ sandboxRetainedProcesses,
4605
+ sessionRecordingStateValues,
4606
+ sessionRecordingModeValues,
4607
+ sessionRecordingCodecValues,
4608
+ sessionRecordings,
4609
+ workspaceCaptures,
4610
+ sandboxPtySessions,
4611
+ enrollmentExposureValues,
4612
+ enrollmentStatusValues,
4613
+ enrollmentOsValues,
4614
+ sandboxKindValues,
4615
+ enrollments,
4616
+ deviceEnrollmentStatusValues,
4617
+ deviceEnrollmentRequests,
4618
+ sandboxes,
4619
+ machineMetricsLatest,
4620
+ machineMetricsSeries,
4621
+ scheduledTasks,
4622
+ scheduledTaskRuns,
4623
+ githubInstallations,
4624
+ githubInstallationRepositories,
4625
+ usageEvents,
4626
+ modelCallFacts,
4627
+ hostExportConfig,
4628
+ hostExportOutbox,
4629
+ hostExportCursorState,
4630
+ hostExportConsumers,
4631
+ hostExportDeadLetters,
4632
+ creditLedgerEntries,
4633
+ billingCustomers,
4634
+ stripeWebhookEvents,
4635
+ auditEvents,
4636
+ packInstallations,
4637
+ workspacePacks,
4638
+ importBatches,
4639
+ capabilityCatalogItems,
4640
+ capabilityInstallations,
4641
+ socialConnections,
4642
+ socialPosts,
4643
+ rigs,
4644
+ rigVersions,
4645
+ rigChanges,
4646
+ schema_exports
4647
+ };
4648
+ //# sourceMappingURL=chunk-HZD7KVAR.js.map