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