@opengeni/db 0.28.1 → 0.28.9

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 (52) hide show
  1. package/dist/{chunk-HT5T62CC.js → chunk-P6CUHXQZ.js} +651 -206
  2. package/dist/chunk-P6CUHXQZ.js.map +1 -0
  3. package/dist/{chunk-DBS5HPEW.js → chunk-VHBFHMPC.js} +7 -1
  4. package/dist/chunk-VHBFHMPC.js.map +1 -0
  5. package/dist/environment-crypto.d.ts +8 -4
  6. package/dist/index.d.ts +265 -20
  7. package/dist/index.js +3966 -2185
  8. package/dist/index.js.map +1 -1
  9. package/dist/lossless-columns.d.ts +58 -0
  10. package/dist/lossless-json.d.ts +39 -0
  11. package/dist/memory-domain.d.ts +3 -6
  12. package/dist/persistence-errors.d.ts +7 -14
  13. package/dist/provision-roles.js +1 -1
  14. package/dist/runtime-posture.d.ts +2 -2
  15. package/dist/schema.d.ts +1419 -271
  16. package/dist/schema.js +9 -1
  17. package/dist/session-realtime-terminal.d.ts +7 -0
  18. package/dist/transcription-recordings-schema.d.ts +44 -6
  19. package/dist/transcription-recordings.d.ts +1 -1
  20. package/drizzle/0065_enrollment_credential_generation.sql +10 -0
  21. package/drizzle/0140_retained_screenshot_artifacts.sql +192 -0
  22. package/drizzle/0176_lossless_canonical_json.sql +975 -0
  23. package/drizzle/0177_session_events_workspace_turn_type_index.sql +5 -0
  24. package/drizzle/0178_permissioned_secret_reads.sql +14 -0
  25. package/drizzle/0179_slack_private_shortcut_delivery_gate.sql +85 -0
  26. package/drizzle/0180_retained_screenshot_lifecycle_fences.sql +273 -0
  27. package/drizzle/0181_connected_machine_removal.sql +52 -0
  28. package/drizzle/0182_connected_machine_remove_session_default.sql +77 -0
  29. package/package.json +4 -4
  30. package/src/database.ts +7 -1
  31. package/src/environment-crypto.ts +22 -9
  32. package/src/index.ts +4253 -1601
  33. package/src/lossless-columns.ts +35 -0
  34. package/src/lossless-json.ts +322 -0
  35. package/src/memory-domain.ts +5 -44
  36. package/src/persistence-errors.ts +29 -34
  37. package/src/runtime-posture.ts +6 -0
  38. package/src/schema.ts +260 -38
  39. package/src/session-control.ts +125 -76
  40. package/src/session-queue-commands.ts +325 -234
  41. package/src/session-realtime-context.ts +18 -5
  42. package/src/session-realtime-ledger.ts +29 -7
  43. package/src/session-realtime-mirror.ts +4 -2
  44. package/src/session-realtime-terminal.ts +89 -21
  45. package/src/session-realtime.ts +3 -2
  46. package/src/session-tool-call-settlement.ts +29 -15
  47. package/src/transcription-recordings-schema.ts +5 -2
  48. package/src/transcription-recordings.ts +70 -40
  49. package/dist/chunk-DBS5HPEW.js.map +0 -1
  50. package/dist/chunk-HT5T62CC.js.map +0 -1
  51. package/dist/event-payload-sanitizer.d.ts +0 -32
  52. package/src/event-payload-sanitizer.ts +0 -377
@@ -65,6 +65,8 @@ __export(schema_exports, {
65
65
  knowledgeSyncRuns: () => knowledgeSyncRuns,
66
66
  machineMetricsLatest: () => machineMetricsLatest,
67
67
  machineMetricsSeries: () => machineMetricsSeries,
68
+ machineRemovalOperationOutcomeValues: () => machineRemovalOperationOutcomeValues,
69
+ machineRemovalOperations: () => machineRemovalOperations,
68
70
  managedAccounts: () => managedAccounts,
69
71
  modelCallFacts: () => modelCallFacts,
70
72
  nestedAgentDepthConfiguration: () => nestedAgentDepthConfiguration,
@@ -74,6 +76,7 @@ __export(schema_exports, {
74
76
  preferenceRegistryPreferences: () => preferenceRegistryPreferences,
75
77
  preferenceRegistryRevisions: () => preferenceRegistryRevisions,
76
78
  preferenceRegistrySnapshots: () => preferenceRegistrySnapshots,
79
+ retainedScreenshotArtifacts: () => retainedScreenshotArtifacts,
77
80
  rigChanges: () => rigChanges,
78
81
  rigVersions: () => rigVersions,
79
82
  rigs: () => rigs,
@@ -150,6 +153,7 @@ __export(schema_exports, {
150
153
  workspaceMemberships: () => workspaceMemberships,
151
154
  workspaceModelPolicies: () => workspaceModelPolicies,
152
155
  workspacePacks: () => workspacePacks,
156
+ workspaceScreenshotQuotas: () => workspaceScreenshotQuotas,
153
157
  workspaceSessionActivityRevisions: () => workspaceSessionActivityRevisions,
154
158
  workspaceVariableSetVariables: () => workspaceVariableSetVariables,
155
159
  workspaceVariableSets: () => workspaceVariableSets,
@@ -160,26 +164,280 @@ import {
160
164
  bigint as bigint4,
161
165
  boolean as boolean4,
162
166
  check as check5,
167
+ customType as customType2,
163
168
  foreignKey,
164
169
  index as index6,
165
- integer as integer6,
170
+ integer as integer7,
166
171
  jsonb as jsonb6,
167
172
  numeric,
168
173
  pgTable as pgTable6,
169
174
  text as text6,
170
175
  timestamp as timestamp6,
171
176
  uniqueIndex as uniqueIndex6,
172
- uuid as uuid6,
173
- customType
177
+ uuid as uuid6
174
178
  } from "drizzle-orm/pg-core";
175
179
 
180
+ // src/lossless-columns.ts
181
+ import { customType, integer } from "drizzle-orm/pg-core";
182
+
183
+ // src/lossless-json.ts
184
+ var JSON_STRING_PREFIX = "opengeni_lossless_json_string_v2_81f06e15:";
185
+ var JSON_KEY_PREFIX = "opengeni_lossless_json_key_v2_7ca6071d:";
186
+ var TEXT_PREFIX = "opengeni_lossless_text_v2_c4100a62:";
187
+ var MAX_JSON_DEPTH = 512;
188
+ var LOSSLESS_CONTENT_CODEC_VERSION = 1;
189
+ var LOSSLESS_CONTENT_WRITER_APPLICATION_NAME = "opengeni-lossless-v1";
190
+ function withLosslessContentWriteVersion(value, contentKey, versionKey) {
191
+ const stamp = (entry) => {
192
+ if (!Object.hasOwn(entry, contentKey)) {
193
+ throw new Error(`Lossless content write omitted ${contentKey}`);
194
+ }
195
+ return { ...entry, [versionKey]: LOSSLESS_CONTENT_CODEC_VERSION };
196
+ };
197
+ return Array.isArray(value) ? value.map(stamp) : stamp(value);
198
+ }
199
+ var LOSSLESS_TEXT_PREFIX = TEXT_PREFIX;
200
+ var UnsupportedCanonicalValueError = class extends TypeError {
201
+ name = "UnsupportedCanonicalValueError";
202
+ };
203
+ function toPostgresLosslessJson(value) {
204
+ return encodeJsonValue(value, /* @__PURE__ */ new Set(), 0).value;
205
+ }
206
+ function fromPostgresLosslessJson(value, codecVersion) {
207
+ return codecVersion === LOSSLESS_CONTENT_CODEC_VERSION ? decodeJsonValue(value, 0).value : value;
208
+ }
209
+ function toPostgresLosslessText(value) {
210
+ if (isPostgresSafeString(value) && !value.includes(TEXT_PREFIX)) return value;
211
+ let stored = "";
212
+ for (let index7 = 0; index7 < value.length; index7 += 1) {
213
+ const code = value.charCodeAt(index7);
214
+ if (value.startsWith(TEXT_PREFIX, index7)) {
215
+ stored += encodeTextCodeUnit(code);
216
+ continue;
217
+ }
218
+ if (code === 0 || code >= 56320 && code <= 57343) {
219
+ stored += encodeTextCodeUnit(code);
220
+ continue;
221
+ }
222
+ if (code >= 55296 && code <= 56319) {
223
+ const next = index7 + 1 < value.length ? value.charCodeAt(index7 + 1) : 0;
224
+ if (next < 56320 || next > 57343) {
225
+ stored += encodeTextCodeUnit(code);
226
+ continue;
227
+ }
228
+ stored += value.slice(index7, index7 + 2);
229
+ index7 += 1;
230
+ continue;
231
+ }
232
+ stored += value[index7];
233
+ }
234
+ return stored;
235
+ }
236
+ function fromPostgresLosslessText(value, codecVersion) {
237
+ return codecVersion === LOSSLESS_CONTENT_CODEC_VERSION ? value.replaceAll(
238
+ new RegExp(` ${TEXT_PREFIX}([0-9a-f]{4}); `, "g"),
239
+ (_match, encoded) => String.fromCharCode(Number.parseInt(encoded, 16))
240
+ ) : value;
241
+ }
242
+ function encodeTextCodeUnit(code) {
243
+ return ` ${TEXT_PREFIX}${code.toString(16).padStart(4, "0")}; `;
244
+ }
245
+ function encodeJsonValue(value, ancestors, depth) {
246
+ if (depth > MAX_JSON_DEPTH) {
247
+ throw new UnsupportedCanonicalValueError(
248
+ `Canonical JSON exceeds the maximum supported depth of ${MAX_JSON_DEPTH}`
249
+ );
250
+ }
251
+ if (value === null || typeof value === "boolean") return { value, changed: false };
252
+ if (typeof value === "string") {
253
+ if (isPostgresSafeString(value) && !value.startsWith(JSON_STRING_PREFIX)) {
254
+ return { value, changed: false };
255
+ }
256
+ return { value: `${JSON_STRING_PREFIX}${encodeUtf16(value)}`, changed: true };
257
+ }
258
+ if (typeof value === "number") {
259
+ if (!Number.isFinite(value) || Object.is(value, -0)) {
260
+ throw new UnsupportedCanonicalValueError(
261
+ "Canonical JSON requires finite non-negative-zero numbers"
262
+ );
263
+ }
264
+ return { value, changed: false };
265
+ }
266
+ if (typeof value === "undefined" || typeof value === "bigint" || typeof value === "function" || typeof value === "symbol") {
267
+ throw new UnsupportedCanonicalValueError(`Canonical JSON cannot contain ${typeof value}`);
268
+ }
269
+ if (!isPlainObject(value) && !Array.isArray(value)) {
270
+ throw new UnsupportedCanonicalValueError("Canonical JSON requires arrays and plain objects");
271
+ }
272
+ if (ancestors.has(value)) {
273
+ throw new UnsupportedCanonicalValueError("Canonical JSON cannot contain cyclic references");
274
+ }
275
+ if (Object.getOwnPropertySymbols(value).length > 0) {
276
+ throw new UnsupportedCanonicalValueError("Canonical JSON cannot contain symbol keys");
277
+ }
278
+ ancestors.add(value);
279
+ try {
280
+ if (Array.isArray(value)) {
281
+ const descriptors2 = Object.getOwnPropertyDescriptors(value);
282
+ const propertyNames = Object.getOwnPropertyNames(descriptors2);
283
+ const indexNames = propertyNames.filter((name) => name !== "length");
284
+ if (indexNames.length !== value.length || indexNames.some((name) => {
285
+ const index7 = Number(name);
286
+ return !Number.isInteger(index7) || index7 < 0 || index7 >= value.length || String(index7) !== name;
287
+ })) {
288
+ throw new UnsupportedCanonicalValueError(
289
+ "Canonical JSON arrays cannot contain non-index properties or holes"
290
+ );
291
+ }
292
+ const output2 = [];
293
+ let changed2 = false;
294
+ for (let index7 = 0; index7 < value.length; index7 += 1) {
295
+ const descriptor = descriptors2[String(index7)];
296
+ if (!descriptor || !descriptor.enumerable || !("value" in descriptor)) {
297
+ throw new UnsupportedCanonicalValueError(
298
+ "Canonical JSON arrays cannot contain holes, accessors, or hidden elements"
299
+ );
300
+ }
301
+ const encoded = encodeJsonValue(descriptor.value, ancestors, depth + 1);
302
+ output2.push(encoded.value);
303
+ changed2 ||= encoded.changed;
304
+ }
305
+ return changed2 ? { value: output2, changed: true } : { value, changed: false };
306
+ }
307
+ const descriptors = Object.getOwnPropertyDescriptors(value);
308
+ const output = {};
309
+ let changed = false;
310
+ for (const [key, descriptor] of Object.entries(descriptors)) {
311
+ if (!descriptor.enumerable || !("value" in descriptor)) {
312
+ throw new UnsupportedCanonicalValueError(
313
+ "Canonical JSON objects cannot contain accessors or hidden properties"
314
+ );
315
+ }
316
+ const encodedKey = isPostgresSafeString(key) && !key.startsWith(JSON_KEY_PREFIX) ? key : `${JSON_KEY_PREFIX}${encodeUtf16(key)}`;
317
+ if (Object.prototype.hasOwnProperty.call(output, encodedKey)) {
318
+ throw new UnsupportedCanonicalValueError("Canonical JSON key encoding collided");
319
+ }
320
+ const encodedValue = encodeJsonValue(descriptor.value, ancestors, depth + 1);
321
+ defineJsonDataProperty(output, encodedKey, encodedValue.value);
322
+ changed ||= encodedKey !== key || encodedValue.changed;
323
+ }
324
+ return changed ? { value: output, changed: true } : { value, changed: false };
325
+ } finally {
326
+ ancestors.delete(value);
327
+ }
328
+ }
329
+ function decodeJsonValue(value, depth) {
330
+ if (depth > MAX_JSON_DEPTH) return { value, changed: false };
331
+ if (typeof value === "string") {
332
+ const decoded = decodeTaggedString(value, JSON_STRING_PREFIX);
333
+ return decoded === null ? { value, changed: false } : { value: decoded, changed: true };
334
+ }
335
+ if (!value || typeof value !== "object") return { value, changed: false };
336
+ if (Array.isArray(value)) {
337
+ const output2 = [];
338
+ let changed2 = false;
339
+ for (const entry of value) {
340
+ const decoded = decodeJsonValue(entry, depth + 1);
341
+ output2.push(decoded.value);
342
+ changed2 ||= decoded.changed;
343
+ }
344
+ return changed2 ? { value: output2, changed: true } : { value, changed: false };
345
+ }
346
+ if (!isPlainObject(value)) return { value, changed: false };
347
+ const output = {};
348
+ let changed = false;
349
+ for (const [key, entry] of Object.entries(value)) {
350
+ const decodedKey = decodeTaggedString(key, JSON_KEY_PREFIX) ?? key;
351
+ if (Object.prototype.hasOwnProperty.call(output, decodedKey)) {
352
+ return { value, changed: false };
353
+ }
354
+ const decodedValue = decodeJsonValue(entry, depth + 1);
355
+ defineJsonDataProperty(output, decodedKey, decodedValue.value);
356
+ changed ||= decodedKey !== key || decodedValue.changed;
357
+ }
358
+ return changed ? { value: output, changed: true } : { value, changed: false };
359
+ }
360
+ function defineJsonDataProperty(target, key, value) {
361
+ Object.defineProperty(target, key, {
362
+ value,
363
+ enumerable: true,
364
+ configurable: true,
365
+ writable: true
366
+ });
367
+ }
368
+ function encodeUtf16(value) {
369
+ const bytes = Buffer.allocUnsafe(value.length * 2);
370
+ for (let index7 = 0; index7 < value.length; index7 += 1) {
371
+ bytes.writeUInt16LE(value.charCodeAt(index7), index7 * 2);
372
+ }
373
+ return bytes.toString("base64");
374
+ }
375
+ function decodeTaggedString(value, prefix) {
376
+ if (!value.startsWith(prefix)) return null;
377
+ const encoded = value.slice(prefix.length);
378
+ if (encoded.length === 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return null;
379
+ const bytes = Buffer.from(encoded, "base64");
380
+ if (bytes.byteLength % 2 !== 0 || bytes.toString("base64") !== encoded) return null;
381
+ let decoded = "";
382
+ for (let offset = 0; offset < bytes.byteLength; offset += 2) {
383
+ decoded += String.fromCharCode(bytes.readUInt16LE(offset));
384
+ }
385
+ return decoded;
386
+ }
387
+ function isPostgresSafeString(value) {
388
+ for (let index7 = 0; index7 < value.length; index7 += 1) {
389
+ const code = value.charCodeAt(index7);
390
+ if (code === 0) return false;
391
+ if (code >= 55296 && code <= 56319) {
392
+ const next = index7 + 1 < value.length ? value.charCodeAt(index7 + 1) : 0;
393
+ if (next < 56320 || next > 57343) return false;
394
+ index7 += 1;
395
+ continue;
396
+ }
397
+ if (code >= 56320 && code <= 57343) return false;
398
+ }
399
+ return true;
400
+ }
401
+ function isPlainObject(value) {
402
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
403
+ const prototype = Object.getPrototypeOf(value);
404
+ return prototype === Object.prototype || prototype === null;
405
+ }
406
+
407
+ // src/lossless-columns.ts
408
+ function losslessCodecVersion(name) {
409
+ return integer(name);
410
+ }
411
+ var losslessJsonb = customType({
412
+ dataType() {
413
+ return "jsonb";
414
+ },
415
+ toDriver(value) {
416
+ return JSON.stringify(toPostgresLosslessJson(value));
417
+ },
418
+ fromDriver(value) {
419
+ return typeof value === "string" ? JSON.parse(value) : value;
420
+ }
421
+ });
422
+ var losslessText = customType({
423
+ dataType() {
424
+ return "text";
425
+ },
426
+ toDriver(value) {
427
+ return toPostgresLosslessText(value);
428
+ },
429
+ fromDriver(value) {
430
+ return value;
431
+ }
432
+ });
433
+
176
434
  // src/workspace-instruction-policies-schema.ts
177
435
  import { sql } from "drizzle-orm";
178
436
  import {
179
437
  bigint,
180
438
  check,
181
439
  index,
182
- integer,
440
+ integer as integer2,
183
441
  jsonb,
184
442
  pgTable,
185
443
  text,
@@ -340,7 +598,7 @@ var workspaceInstructionPolicyOnboardingProposals = pgTable(
340
598
  roleKey: text("role_key"),
341
599
  sourceId: text("source_id").notNull(),
342
600
  sourceVersion: text("source_version").notNull(),
343
- confidenceBps: integer("confidence_bps").notNull(),
601
+ confidenceBps: integer2("confidence_bps").notNull(),
344
602
  baselineRevisionId: uuid("baseline_revision_id"),
345
603
  baselineRevision: bigint("baseline_revision", { mode: "number" }),
346
604
  baselineContentHash: text("baseline_content_hash"),
@@ -421,7 +679,7 @@ var workspaceInstructionPolicySnapshots = pgTable(
421
679
  sessionId: uuid("session_id").notNull(),
422
680
  turnId: uuid("turn_id").notNull(),
423
681
  attemptId: uuid("attempt_id").notNull(),
424
- executionGeneration: integer("execution_generation").notNull(),
682
+ executionGeneration: integer2("execution_generation").notNull(),
425
683
  policyRole: text("policy_role"),
426
684
  roleSource: text("role_source").notNull(),
427
685
  entries: jsonb("entries").$type().notNull(),
@@ -457,7 +715,7 @@ import {
457
715
  boolean,
458
716
  check as check2,
459
717
  index as index2,
460
- integer as integer2,
718
+ integer as integer3,
461
719
  jsonb as jsonb2,
462
720
  pgTable as pgTable2,
463
721
  text as text2,
@@ -475,8 +733,8 @@ var preferenceRegistryPreferences = pgTable2(
475
733
  scopeWorkspaceId: uuid2("scope_workspace_id"),
476
734
  scopeSubjectId: text2("scope_subject_id"),
477
735
  status: text2("status").notNull().default("proposed"),
478
- scopeVersion: integer2("scope_version").notNull().default(1),
479
- activationVersion: integer2("activation_version").notNull().default(0),
736
+ scopeVersion: integer3("scope_version").notNull().default(1),
737
+ activationVersion: integer3("activation_version").notNull().default(0),
480
738
  activeRevisionId: uuid2("active_revision_id"),
481
739
  activeRevision: bigint2("active_revision", { mode: "number" }),
482
740
  activeContentHash: text2("active_content_hash"),
@@ -518,7 +776,7 @@ var preferenceRegistryRevisions = pgTable2(
518
776
  description: text2("description").notNull(),
519
777
  content: text2("content").notNull(),
520
778
  contentHash: text2("content_hash").notNull(),
521
- precedenceRank: integer2("precedence_rank").notNull().default(0),
779
+ precedenceRank: integer3("precedence_rank").notNull().default(0),
522
780
  conflictStrategy: text2("conflict_strategy").notNull(),
523
781
  conflictsWith: jsonb2("conflicts_with").$type().notNull().default([]),
524
782
  provenanceSource: text2("provenance_source").notNull(),
@@ -547,7 +805,7 @@ var preferenceRegistryEvents = pgTable2(
547
805
  accountId: uuid2("account_id").notNull(),
548
806
  preferenceId: uuid2("preference_id").notNull(),
549
807
  type: text2("type").notNull(),
550
- version: integer2("version").notNull(),
808
+ version: integer3("version").notNull(),
551
809
  oldRevisionId: uuid2("old_revision_id"),
552
810
  newRevisionId: uuid2("new_revision_id"),
553
811
  oldScope: text2("old_scope"),
@@ -582,7 +840,7 @@ var preferenceRegistrySnapshots = pgTable2(
582
840
  sessionId: uuid2("session_id").notNull(),
583
841
  turnId: uuid2("turn_id").notNull(),
584
842
  attemptId: uuid2("attempt_id").notNull(),
585
- executionGeneration: integer2("execution_generation").notNull(),
843
+ executionGeneration: integer3("execution_generation").notNull(),
586
844
  initiatingHumanSubjectId: text2("initiating_human_subject_id").notNull(),
587
845
  descriptors: jsonb2("descriptors").$type().notNull(),
588
846
  descriptorHash: text2("descriptor_hash").notNull(),
@@ -612,7 +870,7 @@ import { sql as sql3 } from "drizzle-orm";
612
870
  import {
613
871
  check as check3,
614
872
  index as index3,
615
- integer as integer3,
873
+ integer as integer4,
616
874
  jsonb as jsonb3,
617
875
  pgTable as pgTable3,
618
876
  text as text3,
@@ -629,7 +887,7 @@ var knowledgeMemoryRelationships = pgTable3(
629
887
  sourceMemoryId: uuid3("source_memory_id").notNull(),
630
888
  targetMemoryId: uuid3("target_memory_id").notNull(),
631
889
  relationshipType: text3("relationship_type").notNull(),
632
- version: integer3("version").notNull().default(1),
890
+ version: integer4("version").notNull().default(1),
633
891
  createdByEventId: uuid3("created_by_event_id").notNull(),
634
892
  removedByEventId: uuid3("removed_by_event_id"),
635
893
  createdAt: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -694,7 +952,7 @@ var knowledgeMemoryLifecycleEvents = pgTable3(
694
952
  actorSessionId: uuid3("actor_session_id"),
695
953
  actorTurnId: uuid3("actor_turn_id"),
696
954
  actorAttemptId: uuid3("actor_attempt_id"),
697
- actorExecutionGeneration: integer3("actor_execution_generation"),
955
+ actorExecutionGeneration: integer4("actor_execution_generation"),
698
956
  planHash: text3("plan_hash").notNull(),
699
957
  beforeState: jsonb3("before_state").$type().notNull(),
700
958
  afterState: jsonb3("after_state").$type().notNull(),
@@ -766,7 +1024,7 @@ import {
766
1024
  bigint as bigint3,
767
1025
  boolean as boolean2,
768
1026
  index as index4,
769
- integer as integer4,
1027
+ integer as integer5,
770
1028
  jsonb as jsonb4,
771
1029
  pgTable as pgTable4,
772
1030
  text as text4,
@@ -1186,7 +1444,7 @@ var knowledgeClaims = pgTable4(
1186
1444
  ...tenantScopeColumns(),
1187
1445
  factId: uuid4("fact_id").notNull(),
1188
1446
  origin: text4("origin").notNull(),
1189
- confidenceBps: integer4("confidence_bps").notNull(),
1447
+ confidenceBps: integer5("confidence_bps").notNull(),
1190
1448
  effectiveAt: timestamp4("effective_at", { withTimezone: true }).notNull(),
1191
1449
  expiresAt: timestamp4("expires_at", { withTimezone: true }),
1192
1450
  extractionMethod: text4("extraction_method").notNull(),
@@ -1247,7 +1505,7 @@ var knowledgeClaimEvidence = pgTable4(
1247
1505
  documentVersionId: uuid4("document_version_id").notNull(),
1248
1506
  polarity: text4("polarity").notNull(),
1249
1507
  documentChunkId: uuid4("document_chunk_id"),
1250
- chunkIndex: integer4("chunk_index"),
1508
+ chunkIndex: integer5("chunk_index"),
1251
1509
  locator: text4("locator"),
1252
1510
  quoteHash: text4("quote_hash"),
1253
1511
  contentHash: text4("content_hash").notNull(),
@@ -1340,7 +1598,7 @@ import {
1340
1598
  boolean as boolean3,
1341
1599
  check as check4,
1342
1600
  index as index5,
1343
- integer as integer5,
1601
+ integer as integer6,
1344
1602
  jsonb as jsonb5,
1345
1603
  pgTable as pgTable5,
1346
1604
  primaryKey,
@@ -1376,18 +1634,19 @@ var transcriptionRecordings = pgTable5(
1376
1634
  subjectId: text5("subject_id").notNull(),
1377
1635
  mimeType: text5("mime_type").notNull(),
1378
1636
  state: text5("state", { enum: transcriptionRecordingStateValues }).notNull().default("uploading"),
1379
- nextChunkNumber: integer5("next_chunk_number").notNull().default(0),
1380
- chunkCount: integer5("chunk_count").notNull().default(0),
1381
- totalBytes: integer5("total_bytes").notNull().default(0),
1382
- totalDurationMilliseconds: integer5("total_duration_milliseconds").notNull().default(0),
1383
- segmentCount: integer5("segment_count").notNull().default(0),
1384
- completedSegmentCount: integer5("completed_segment_count").notNull().default(0),
1385
- transcriptText: text5("transcript_text"),
1637
+ nextChunkNumber: integer6("next_chunk_number").notNull().default(0),
1638
+ chunkCount: integer6("chunk_count").notNull().default(0),
1639
+ totalBytes: integer6("total_bytes").notNull().default(0),
1640
+ totalDurationMilliseconds: integer6("total_duration_milliseconds").notNull().default(0),
1641
+ segmentCount: integer6("segment_count").notNull().default(0),
1642
+ completedSegmentCount: integer6("completed_segment_count").notNull().default(0),
1643
+ transcriptText: losslessText("transcript_text"),
1644
+ transcriptTextCodecVersion: losslessCodecVersion("transcript_text_codec_version"),
1386
1645
  languages: jsonb5("languages").$type().notNull().default([]),
1387
1646
  errorCode: text5("error_code"),
1388
1647
  retryable: boolean3("retryable").notNull().default(false),
1389
1648
  providerId: text5("provider_id"),
1390
- processingGeneration: integer5("processing_generation").notNull().default(0),
1649
+ processingGeneration: integer6("processing_generation").notNull().default(0),
1391
1650
  processingOwner: uuid5("processing_owner"),
1392
1651
  processingStartedAt: timestamp5("processing_started_at", { withTimezone: true }),
1393
1652
  objectsCleanedAt: timestamp5("objects_cleaned_at", { withTimezone: true }),
@@ -1475,12 +1734,12 @@ var transcriptionRecordingChunks = pgTable5(
1475
1734
  workspaceId: uuid5("workspace_id").notNull(),
1476
1735
  subjectId: text5("subject_id").notNull(),
1477
1736
  recordingId: uuid5("recording_id").notNull(),
1478
- chunkNumber: integer5("chunk_number").notNull(),
1737
+ chunkNumber: integer6("chunk_number").notNull(),
1479
1738
  state: text5("state", { enum: transcriptionRecordingChunkStateValues }).notNull().default("uploading"),
1480
- byteLength: integer5("byte_length").notNull(),
1739
+ byteLength: integer6("byte_length").notNull(),
1481
1740
  sha256: text5("sha256").notNull(),
1482
- startMilliseconds: integer5("start_milliseconds").notNull(),
1483
- durationMilliseconds: integer5("duration_milliseconds").notNull(),
1741
+ startMilliseconds: integer6("start_milliseconds").notNull(),
1742
+ durationMilliseconds: integer6("duration_milliseconds").notNull(),
1484
1743
  objectKey: text5("object_key").notNull(),
1485
1744
  createdAt: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
1486
1745
  completedAt: timestamp5("completed_at", { withTimezone: true })
@@ -1518,18 +1777,19 @@ var transcriptionRecordingSegments = pgTable5(
1518
1777
  workspaceId: uuid5("workspace_id").notNull(),
1519
1778
  subjectId: text5("subject_id").notNull(),
1520
1779
  recordingId: uuid5("recording_id").notNull(),
1521
- segmentNumber: integer5("segment_number").notNull(),
1522
- generation: integer5("generation").notNull(),
1780
+ segmentNumber: integer6("segment_number").notNull(),
1781
+ generation: integer6("generation").notNull(),
1523
1782
  state: text5("state", { enum: transcriptionRecordingSegmentStateValues }).notNull().default("preparing"),
1524
- byteLength: integer5("byte_length").notNull(),
1783
+ byteLength: integer6("byte_length").notNull(),
1525
1784
  sha256: text5("sha256").notNull(),
1526
- startMilliseconds: integer5("start_milliseconds").notNull(),
1527
- durationMilliseconds: integer5("duration_milliseconds").notNull(),
1785
+ startMilliseconds: integer6("start_milliseconds").notNull(),
1786
+ durationMilliseconds: integer6("duration_milliseconds").notNull(),
1528
1787
  objectKey: text5("object_key").notNull(),
1529
1788
  attemptId: uuid5("attempt_id"),
1530
1789
  attemptStartedAt: timestamp5("attempt_started_at", { withTimezone: true }),
1531
1790
  attemptDeadlineAt: timestamp5("attempt_deadline_at", { withTimezone: true }),
1532
- transcriptText: text5("transcript_text"),
1791
+ transcriptText: losslessText("transcript_text"),
1792
+ transcriptTextCodecVersion: losslessCodecVersion("transcript_text_codec_version"),
1533
1793
  languages: jsonb5("languages").$type().notNull().default([]),
1534
1794
  providerId: text5("provider_id"),
1535
1795
  errorCode: text5("error_code"),
@@ -1570,7 +1830,7 @@ var transcriptionRecordingSegments = pgTable5(
1570
1830
  );
1571
1831
 
1572
1832
  // src/schema.ts
1573
- var vector = customType({
1833
+ var vector = customType2({
1574
1834
  dataType() {
1575
1835
  return "vector(3072)";
1576
1836
  },
@@ -1685,16 +1945,16 @@ var workspaceArtifactVersions = pgTable6(
1685
1945
  accountId: uuid6("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
1686
1946
  workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
1687
1947
  artifactId: uuid6("artifact_id").notNull(),
1688
- revision: integer6("revision").notNull(),
1948
+ revision: integer7("revision").notNull(),
1689
1949
  contentKey: text6("content_key").notNull(),
1690
1950
  contentType: text6("content_type").$type().notNull().default("text/html"),
1691
1951
  contentSha256: text6("content_sha256").notNull(),
1692
- sizeBytes: integer6("size_bytes").notNull(),
1952
+ sizeBytes: integer7("size_bytes").notNull(),
1693
1953
  operationKey: text6("operation_key").notNull(),
1694
1954
  sourceSessionId: uuid6("source_session_id"),
1695
1955
  sourceTurnId: uuid6("source_turn_id"),
1696
1956
  sourceAttemptId: uuid6("source_attempt_id"),
1697
- sourceExecutionGeneration: integer6("source_execution_generation"),
1957
+ sourceExecutionGeneration: integer7("source_execution_generation"),
1698
1958
  createdBySubjectId: text6("created_by_subject_id").notNull(),
1699
1959
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow()
1700
1960
  },
@@ -1752,7 +2012,7 @@ var workspaceArtifactEvents = pgTable6(
1752
2012
  sourceSessionId: uuid6("source_session_id"),
1753
2013
  sourceTurnId: uuid6("source_turn_id"),
1754
2014
  sourceAttemptId: uuid6("source_attempt_id"),
1755
- sourceExecutionGeneration: integer6("source_execution_generation"),
2015
+ sourceExecutionGeneration: integer7("source_execution_generation"),
1756
2016
  actorSubjectId: text6("actor_subject_id").notNull(),
1757
2017
  reason: text6("reason").notNull(),
1758
2018
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow()
@@ -1797,7 +2057,7 @@ var nestedAgentDepthConfiguration = pgTable6(
1797
2057
  "nested_agent_depth_configuration",
1798
2058
  {
1799
2059
  singleton: boolean4("singleton").primaryKey().notNull().default(true),
1800
- maxNestedAgentDepth: integer6("max_nested_agent_depth").notNull(),
2060
+ maxNestedAgentDepth: integer7("max_nested_agent_depth").notNull(),
1801
2061
  policySource: text6("policy_source").$type().notNull(),
1802
2062
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
1803
2063
  },
@@ -1955,7 +2215,7 @@ var workspaceVariableSetVariables = pgTable6(
1955
2215
  name: text6("name").notNull(),
1956
2216
  // Format: v1:<base64 iv>:<base64 ciphertext||gcm-tag>. Never returned by any API.
1957
2217
  valueEncrypted: text6("value_encrypted").notNull(),
1958
- version: integer6("version").notNull().default(1),
2218
+ version: integer7("version").notNull().default(1),
1959
2219
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
1960
2220
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
1961
2221
  },
@@ -1991,7 +2251,7 @@ var codexSubscriptionCredentials = pgTable6(
1991
2251
  status: text6("status").notNull().default("active"),
1992
2252
  // active | needs_relogin | error
1993
2253
  lastError: text6("last_error"),
1994
- version: integer6("version").notNull().default(1),
2254
+ version: integer7("version").notNull().default(1),
1995
2255
  label: text6("label"),
1996
2256
  // user-chosen nickname; null ⇒ derive from email/plan/account
1997
2257
  accountEmail: text6("account_email"),
@@ -1999,9 +2259,9 @@ var codexSubscriptionCredentials = pgTable6(
1999
2259
  // P2 usage cache (plaintext metadata; NEVER a token). Snapshotted from
2000
2260
  // GET /wham/usage; drives the quota bars + the cache TTL. primary = 5h window
2001
2261
  // (limit_window_seconds 18000), secondary = weekly (604800).
2002
- primaryUsedPercent: integer6("primary_used_percent"),
2262
+ primaryUsedPercent: integer7("primary_used_percent"),
2003
2263
  primaryResetAt: timestamp6("primary_reset_at", { withTimezone: true }),
2004
- secondaryUsedPercent: integer6("secondary_used_percent"),
2264
+ secondaryUsedPercent: integer7("secondary_used_percent"),
2005
2265
  secondaryResetAt: timestamp6("secondary_reset_at", { withTimezone: true }),
2006
2266
  usageCheckedAt: timestamp6("usage_checked_at", { withTimezone: true }),
2007
2267
  // snapshot freshness → cache TTL clock
@@ -2018,18 +2278,18 @@ var codexSubscriptionCredentials = pgTable6(
2018
2278
  allocatorEnabled: boolean4("allocator_enabled").notNull().default(true),
2019
2279
  // Independent OCC/audit sequence for the allocator toggle. Token refresh
2020
2280
  // continues to own `version`; quota/cache writes own neither counter.
2021
- allocatorVersion: integer6("allocator_version").notNull().default(1),
2281
+ allocatorVersion: integer7("allocator_version").notNull().default(1),
2022
2282
  allocatorUpdatedBySubjectId: text6("allocator_updated_by_subject_id"),
2023
2283
  allocatorUpdatedAt: timestamp6("allocator_updated_at", { withTimezone: true }),
2024
2284
  // Authoritative count-only summary cached from /wham/usage. Detailed rows
2025
2285
  // are never persisted as redemption authority; every first POST preflights
2026
2286
  // the provider's fresh detail endpoint.
2027
- resetCreditAvailableCount: integer6("reset_credit_available_count"),
2287
+ resetCreditAvailableCount: integer7("reset_credit_available_count"),
2028
2288
  resetCreditsCheckedAt: timestamp6("reset_credits_checked_at", { withTimezone: true }),
2029
2289
  // Set only by a direct Better Auth cookie connection/reconnection. Legacy,
2030
2290
  // configured, delegated, API-key, and agent-created rows remain view-only.
2031
2291
  connectedBySubjectId: text6("connected_by_subject_id"),
2032
- selectionCount: integer6("selection_count").notNull().default(0),
2292
+ selectionCount: integer7("selection_count").notNull().default(0),
2033
2293
  lastSelectedAt: timestamp6("last_selected_at", { withTimezone: true }),
2034
2294
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
2035
2295
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
@@ -2059,7 +2319,7 @@ var codexAppsSettings = pgTable6(
2059
2319
  accountId: uuid6("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2060
2320
  workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2061
2321
  credentialId: uuid6("credential_id"),
2062
- version: integer6("version").notNull().default(1),
2322
+ version: integer7("version").notNull().default(1),
2063
2323
  designatedAt: timestamp6("designated_at", { withTimezone: true }),
2064
2324
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
2065
2325
  },
@@ -2108,7 +2368,7 @@ var codexResetRedemptionAttempts = pgTable6(
2108
2368
  providerStartedAt: timestamp6("provider_started_at", { withTimezone: true }),
2109
2369
  completedAt: timestamp6("completed_at", { withTimezone: true }),
2110
2370
  lastFailureKind: text6("last_failure_kind"),
2111
- retryCount: integer6("retry_count").notNull().default(0),
2371
+ retryCount: integer7("retry_count").notNull().default(0),
2112
2372
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
2113
2373
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
2114
2374
  },
@@ -2168,13 +2428,13 @@ var connections = pgTable6(
2168
2428
  lastRefreshAt: timestamp6("last_refresh_at", { withTimezone: true }),
2169
2429
  lastUsedAt: timestamp6("last_used_at", { withTimezone: true }),
2170
2430
  lastError: text6("last_error"),
2171
- version: integer6("version").notNull().default(1),
2431
+ version: integer7("version").notNull().default(1),
2172
2432
  // Server-owned proof that the dedicated install route verified the exact
2173
2433
  // credential at this connection version. Generic/legacy writers cannot set
2174
2434
  // these columns, and migration 0131 clears them when protected fields change
2175
2435
  // without a fresh verification in the same statement.
2176
2436
  verifiedInstallAt: timestamp6("verified_install_at", { withTimezone: true }),
2177
- verifiedInstallVersion: integer6("verified_install_version"),
2437
+ verifiedInstallVersion: integer7("verified_install_version"),
2178
2438
  metadata: jsonb6("metadata").$type().notNull().default({}),
2179
2439
  createdBySubjectId: text6("created_by_subject_id"),
2180
2440
  updatedBySubjectId: text6("updated_by_subject_id"),
@@ -2208,8 +2468,8 @@ var connectionDisconnectOperations = pgTable6(
2208
2468
  connectionId: uuid6("connection_id").notNull().references(() => connections.id, { onDelete: "cascade" }),
2209
2469
  subjectId: text6("subject_id").notNull(),
2210
2470
  idempotencyKey: text6("idempotency_key").notNull(),
2211
- expectedVersion: integer6("expected_version").notNull(),
2212
- resultVersion: integer6("result_version").notNull(),
2471
+ expectedVersion: integer7("expected_version").notNull(),
2472
+ resultVersion: integer7("result_version").notNull(),
2213
2473
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow()
2214
2474
  },
2215
2475
  (table) => ({
@@ -2242,7 +2502,7 @@ var connectorActionPolicies = pgTable6(
2242
2502
  toolName: text6("tool_name").notNull(),
2243
2503
  actionName: text6("action_name").notNull(),
2244
2504
  policy: text6("policy").$type().notNull(),
2245
- version: integer6("version").notNull().default(1),
2505
+ version: integer7("version").notNull().default(1),
2246
2506
  createdBySubjectId: text6("created_by_subject_id").notNull(),
2247
2507
  updatedBySubjectId: text6("updated_by_subject_id").notNull(),
2248
2508
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -2317,7 +2577,7 @@ var slackInteractionInbox = pgTable6(
2317
2577
  status: text6("status").$type().notNull().default("pending"),
2318
2578
  claimHolderId: uuid6("claim_holder_id"),
2319
2579
  claimExpiresAt: timestamp6("claim_expires_at", { withTimezone: true }),
2320
- attemptCount: integer6("attempt_count").notNull().default(0),
2580
+ attemptCount: integer7("attempt_count").notNull().default(0),
2321
2581
  retryAt: timestamp6("retry_at", { withTimezone: true }),
2322
2582
  lastErrorCode: text6("last_error_code"),
2323
2583
  reactionContextCheckpoint: jsonb6("reaction_context_checkpoint").$type(),
@@ -2360,16 +2620,16 @@ var slackInteractions = pgTable6(
2360
2620
  sessionId: uuid6("session_id").references(() => sessions.id, {
2361
2621
  onDelete: "cascade"
2362
2622
  }),
2363
- lastDeliveredSessionEventSequence: integer6("last_delivered_session_event_sequence").notNull().default(0),
2623
+ lastDeliveredSessionEventSequence: integer7("last_delivered_session_event_sequence").notNull().default(0),
2364
2624
  deliveryClaimHolderId: uuid6("delivery_claim_holder_id"),
2365
2625
  deliveryClaimExpiresAt: timestamp6("delivery_claim_expires_at", {
2366
2626
  withTimezone: true
2367
2627
  }),
2368
- deliveryAttemptCount: integer6("delivery_attempt_count").notNull().default(0),
2628
+ deliveryAttemptCount: integer7("delivery_attempt_count").notNull().default(0),
2369
2629
  deliveryRetryAt: timestamp6("delivery_retry_at", { withTimezone: true }),
2370
2630
  deliveryLastErrorCode: text6("delivery_last_error_code"),
2371
2631
  ackSlackMessageTs: text6("ack_slack_message_ts"),
2372
- progressCount: integer6("progress_count").notNull().default(0),
2632
+ progressCount: integer7("progress_count").notNull().default(0),
2373
2633
  terminalDeliveryState: text6("terminal_delivery_state").$type().notNull().default("open"),
2374
2634
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
2375
2635
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
@@ -2401,8 +2661,8 @@ var slackInteractionProgressDeliveries = pgTable6(
2401
2661
  accountId: uuid6("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2402
2662
  workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2403
2663
  interactionId: uuid6("interaction_id").notNull(),
2404
- sessionEventSequence: integer6("session_event_sequence").notNull(),
2405
- slot: integer6("slot").notNull(),
2664
+ sessionEventSequence: integer7("session_event_sequence").notNull(),
2665
+ slot: integer7("slot").notNull(),
2406
2666
  operationId: uuid6("operation_id").notNull(),
2407
2667
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow()
2408
2668
  },
@@ -2445,7 +2705,7 @@ var slackBotPostOperations = pgTable6(
2445
2705
  status: text6("status").$type().notNull(),
2446
2706
  claimHolderId: uuid6("claim_holder_id"),
2447
2707
  claimExpiresAt: timestamp6("claim_expires_at", { withTimezone: true }),
2448
- attemptCount: integer6("attempt_count").notNull().default(0),
2708
+ attemptCount: integer7("attempt_count").notNull().default(0),
2449
2709
  lastFailureCode: text6("last_failure_code"),
2450
2710
  slackChannelId: text6("slack_channel_id"),
2451
2711
  slackMessageTimestamp: text6("slack_message_timestamp"),
@@ -2515,7 +2775,7 @@ var slackBotDeleteOperations = pgTable6(
2515
2775
  status: text6("status").$type().notNull(),
2516
2776
  claimHolderId: uuid6("claim_holder_id"),
2517
2777
  claimExpiresAt: timestamp6("claim_expires_at", { withTimezone: true }),
2518
- attemptCount: integer6("attempt_count").notNull().default(0),
2778
+ attemptCount: integer7("attempt_count").notNull().default(0),
2519
2779
  lastFailureCode: text6("last_failure_code"),
2520
2780
  slackChannelId: text6("slack_channel_id"),
2521
2781
  slackMessageTimestamp: text6("slack_message_timestamp"),
@@ -2654,7 +2914,7 @@ var codexCredentialLeases = pgTable6(
2654
2914
  // durable turn replaces holderId and increments generation atomically;
2655
2915
  // stale/zombie heartbeats and releases must match both values.
2656
2916
  holderId: text6("holder_id").notNull(),
2657
- generation: integer6("generation").notNull().default(1),
2917
+ generation: integer7("generation").notNull().default(1),
2658
2918
  leasedUntil: timestamp6("leased_until", { withTimezone: true }).notNull(),
2659
2919
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
2660
2920
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
@@ -2679,7 +2939,8 @@ var sessions = pgTable6(
2679
2939
  accountId: uuid6("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
2680
2940
  workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
2681
2941
  status: text6("status").notNull().default("queued"),
2682
- initialMessage: text6("initial_message").notNull(),
2942
+ initialMessage: losslessText("initial_message").notNull(),
2943
+ initialMessageCodecVersion: losslessCodecVersion("initial_message_codec_version"),
2683
2944
  // Invisible host context frozen with the winning session create. The
2684
2945
  // initial turn copies this value so an idempotent repair can never adopt a
2685
2946
  // retrying caller's different instructions.
@@ -2736,7 +2997,7 @@ var sessions = pgTable6(
2736
2997
  // in-flight op fenced by a stale active_epoch retries against the new active
2737
2998
  // sandbox. integer (NOT bigint) — the lease-epoch spike: int8 reads back as a
2738
2999
  // JS string and breaks the strict fence; int4 returns a number.
2739
- activeEpoch: integer6("active_epoch").notNull().default(0),
3000
+ activeEpoch: integer7("active_epoch").notNull().default(0),
2740
3001
  // The session's WORKING DIRECTORY — the path/cwd base the (selfhosted) box's
2741
3002
  // agent/terminal/file-dock operate under. A launch-workspace_root-relative
2742
3003
  // subdir or an absolute machine path; surfaced alongside the active-sandbox
@@ -2770,7 +3031,7 @@ var sessions = pgTable6(
2770
3031
  // representation so every session has one explicit policy mode.
2771
3032
  toolPolicy: jsonb6("tool_policy").$type().notNull(),
2772
3033
  // Optimistic-concurrency fence for durable session tool-policy writes.
2773
- toolPolicyVersion: integer6("tool_policy_version").notNull().default(1),
3034
+ toolPolicyVersion: integer7("tool_policy_version").notNull().default(1),
2774
3035
  // The manager session that spawned this one via session_create. Set only
2775
3036
  // when the creating grant carried a worker-signed sessionId claim (a session
2776
3037
  // spawning a worker); null for direct API creates and scheduled-task runs.
@@ -2794,9 +3055,9 @@ var sessions = pgTable6(
2794
3055
  // populated by the database admission boundary and never re-derived from
2795
3056
  // a live workspace setting for an existing session.
2796
3057
  rootSessionId: uuid6("root_session_id").notNull(),
2797
- nestedAgentDepth: integer6("nested_agent_depth").notNull(),
2798
- maxNestedAgentDepthOverride: integer6("max_nested_agent_depth_override"),
2799
- effectiveMaxNestedAgentDepth: integer6("effective_max_nested_agent_depth").notNull(),
3058
+ nestedAgentDepth: integer7("nested_agent_depth").notNull(),
3059
+ maxNestedAgentDepthOverride: integer7("max_nested_agent_depth_override"),
3060
+ effectiveMaxNestedAgentDepth: integer7("effective_max_nested_agent_depth").notNull(),
2800
3061
  nestedAgentDepthPolicySource: text6("nested_agent_depth_policy_source").notNull(),
2801
3062
  nestedAgentDepthPolicySessionId: uuid6("nested_agent_depth_policy_session_id"),
2802
3063
  temporalWorkflowId: text6("temporal_workflow_id"),
@@ -2804,13 +3065,13 @@ var sessions = pgTable6(
2804
3065
  // Actual input tokens reported for the latest authoritative ordinary model
2805
3066
  // call. Compaction/context clearing invalidates it to null; local history
2806
3067
  // estimates must never be stored here.
2807
- lastInputTokens: integer6("last_input_tokens"),
3068
+ lastInputTokens: integer7("last_input_tokens"),
2808
3069
  // Operator /compact request flag. The API sets
2809
3070
  // it true; the worker honors it BEFORE the next turn's model call by forcing
2810
3071
  // a compaction, then clears it. A durable flag (not a transient signal) so
2811
3072
  // the trigger survives a worker restart and converges before the next turn.
2812
3073
  compactRequested: boolean4("compact_requested").notNull().default(false),
2813
- queueVersion: integer6("queue_version").notNull().default(0),
3074
+ queueVersion: integer7("queue_version").notNull().default(0),
2814
3075
  queueHeadPosition: bigint4("queue_head_position", { mode: "number" }).notNull().default(0),
2815
3076
  queueTailPosition: bigint4("queue_tail_position", { mode: "number" }).notNull().default(0),
2816
3077
  directControlState: text6("direct_control_state").notNull().default("active"),
@@ -2824,7 +3085,7 @@ var sessions = pgTable6(
2824
3085
  directControlChangedAt: timestamp6("direct_control_changed_at", {
2825
3086
  withTimezone: true
2826
3087
  }),
2827
- lastSequence: integer6("last_sequence").notNull().default(0),
3088
+ lastSequence: integer7("last_sequence").notNull().default(0),
2828
3089
  // The session's PINNED Codex account (manual override from the in-session
2829
3090
  // switcher). NULL ⇒ follow the workspace active pointer. FK declared in the
2830
3091
  // migration with ON DELETE SET NULL (a disconnected pin degrades to "follow
@@ -2908,8 +3169,8 @@ var sessionRealtimeModes = pgTable6(
2908
3169
  ownerKeyHash: text6("owner_key_hash").notNull(),
2909
3170
  model: text6("model").notNull(),
2910
3171
  state: text6("state").notNull().default("active"),
2911
- version: integer6("version").notNull().default(1),
2912
- connectionEpoch: integer6("connection_epoch").notNull().default(1),
3172
+ version: integer7("version").notNull().default(1),
3173
+ connectionEpoch: integer7("connection_epoch").notNull().default(1),
2913
3174
  leaseExpiresAt: timestamp6("lease_expires_at", { withTimezone: true }).notNull(),
2914
3175
  lastHeartbeatAt: timestamp6("last_heartbeat_at", { withTimezone: true }).notNull(),
2915
3176
  startedAt: timestamp6("started_at", { withTimezone: true }).notNull().defaultNow(),
@@ -2994,8 +3255,8 @@ var sessionRealtimeConnections = pgTable6(
2994
3255
  sessionId: uuid6("session_id").notNull(),
2995
3256
  realtimeId: uuid6("realtime_id").notNull().references(() => sessionRealtimeModes.id, { onDelete: "cascade" }),
2996
3257
  operationId: uuid6("operation_id").notNull(),
2997
- connectionEpoch: integer6("connection_epoch").notNull(),
2998
- startupFenceSequence: integer6("startup_fence_sequence").notNull().default(0),
3258
+ connectionEpoch: integer7("connection_epoch").notNull(),
3259
+ startupFenceSequence: integer7("startup_fence_sequence").notNull().default(0),
2999
3260
  promotionMode: text6("promotion_mode").notNull().default("legacy"),
3000
3261
  state: text6("state").notNull().default("negotiating"),
3001
3262
  sdpAnswer: text6("sdp_answer"),
@@ -3091,8 +3352,8 @@ var sessionRealtimeEntries = pgTable6(
3091
3352
  sessionId: uuid6("session_id").notNull(),
3092
3353
  realtimeId: uuid6("realtime_id").notNull().references(() => sessionRealtimeModes.id, { onDelete: "cascade" }),
3093
3354
  operationId: uuid6("operation_id").notNull(),
3094
- connectionEpoch: integer6("connection_epoch").notNull(),
3095
- sequence: integer6("sequence").notNull(),
3355
+ connectionEpoch: integer7("connection_epoch").notNull(),
3356
+ sequence: integer7("sequence").notNull(),
3096
3357
  direction: text6("direction").notNull(),
3097
3358
  kind: text6("kind").notNull(),
3098
3359
  role: text6("role"),
@@ -3108,8 +3369,10 @@ var sessionRealtimeEntries = pgTable6(
3108
3369
  // result/error to the same ordinary turn. It never denotes a child/fork
3109
3370
  // session.
3110
3371
  turnId: uuid6("turn_id"),
3111
- text: text6("text"),
3112
- payload: jsonb6("payload").$type().notNull().default({}),
3372
+ text: losslessText("text"),
3373
+ textCodecVersion: losslessCodecVersion("text_codec_version"),
3374
+ payload: losslessJsonb("payload").$type().notNull().default({}),
3375
+ payloadCodecVersion: losslessCodecVersion("payload_codec_version"),
3113
3376
  clientAckedAt: timestamp6("client_acked_at", { withTimezone: true }),
3114
3377
  providerAckedAt: timestamp6("provider_acked_at", { withTimezone: true }),
3115
3378
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -3163,14 +3426,6 @@ var sessionRealtimeEntries = pgTable6(
3163
3426
  "session_realtime_entries_delegation_item_check",
3164
3427
  sql6`${table.delegationItemId} is null or octet_length(${table.delegationItemId}) between 1 and 1024`
3165
3428
  ),
3166
- textValid: check5(
3167
- "session_realtime_entries_text_check",
3168
- sql6`${table.text} is null or octet_length(${table.text}) <= 131072`
3169
- ),
3170
- payloadValid: check5(
3171
- "session_realtime_entries_payload_check",
3172
- sql6`octet_length(${table.payload}::text) <= 131072`
3173
- ),
3174
3429
  turnValid: check5(
3175
3430
  "session_realtime_entries_turn_check",
3176
3431
  sql6`${table.turnId} is null
@@ -3193,10 +3448,10 @@ var sessionSpawnDenials = pgTable6(
3193
3448
  workspaceId: uuid6("workspace_id").notNull(),
3194
3449
  parentSessionId: uuid6("parent_session_id"),
3195
3450
  rootSessionId: uuid6("root_session_id"),
3196
- currentDepth: integer6("current_depth").notNull(),
3451
+ currentDepth: integer7("current_depth").notNull(),
3197
3452
  attemptedDepth: bigint4("attempted_depth", { mode: "number" }).notNull(),
3198
- effectiveMaxNestedAgentDepth: integer6("effective_max_nested_agent_depth").notNull(),
3199
- requestedMaxNestedAgentDepthOverride: integer6("requested_max_nested_agent_depth_override"),
3453
+ effectiveMaxNestedAgentDepth: integer7("effective_max_nested_agent_depth").notNull(),
3454
+ requestedMaxNestedAgentDepthOverride: integer7("requested_max_nested_agent_depth_override"),
3200
3455
  policySource: text6("policy_source").notNull(),
3201
3456
  policySessionId: uuid6("policy_session_id"),
3202
3457
  subjectId: text6("subject_id"),
@@ -3240,7 +3495,7 @@ var sessionPins = pgTable6(
3240
3495
  // unpin+re-pin that would otherwise recreate version 1.
3241
3496
  pinned: boolean4("pinned").notNull().default(true),
3242
3497
  pinnedAt: timestamp6("pinned_at", { withTimezone: true }).defaultNow(),
3243
- version: integer6("version").notNull().default(1)
3498
+ version: integer7("version").notNull().default(1)
3244
3499
  },
3245
3500
  (table) => ({
3246
3501
  subjectNonempty: check5(
@@ -3326,7 +3581,7 @@ var sessionMcpServers = pgTable6(
3326
3581
  name: text6("name"),
3327
3582
  url: text6("url").notNull(),
3328
3583
  allowedTools: jsonb6("allowed_tools").$type(),
3329
- timeoutMs: integer6("timeout_ms"),
3584
+ timeoutMs: integer7("timeout_ms"),
3330
3585
  cacheToolsList: boolean4("cache_tools_list").notNull().default(false),
3331
3586
  // Human-approval policy: `true` = every tool requires approval, a string[] of
3332
3587
  // UNPREFIXED tool names = only those require it, null/absent = auto-run.
@@ -3337,7 +3592,7 @@ var sessionMcpServers = pgTable6(
3337
3592
  // Map of header name -> AES-GCM ciphertext. Values are decrypted only by the
3338
3593
  // worker's run-preparation path and never returned by API helpers.
3339
3594
  headersEncrypted: jsonb6("headers_encrypted").$type().notNull().default({}),
3340
- credentialVersion: integer6("credential_version").notNull().default(1),
3595
+ credentialVersion: integer7("credential_version").notNull().default(1),
3341
3596
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
3342
3597
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
3343
3598
  },
@@ -3392,6 +3647,114 @@ var fileUploads = pgTable6(
3392
3647
  status: index6("file_uploads_status_idx").on(table.status)
3393
3648
  })
3394
3649
  );
3650
+ var workspaceScreenshotQuotas = pgTable6(
3651
+ "workspace_screenshot_quotas",
3652
+ {
3653
+ workspaceId: uuid6("workspace_id").primaryKey().references(() => workspaces.id, { onDelete: "cascade" }),
3654
+ accountId: uuid6("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3655
+ reservedBytes: bigint4("reserved_bytes", { mode: "number" }).notNull().default(0),
3656
+ readyBytes: bigint4("ready_bytes", { mode: "number" }).notNull().default(0),
3657
+ updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
3658
+ },
3659
+ (table) => ({
3660
+ workspaceAccount: foreignKey({
3661
+ columns: [table.workspaceId, table.accountId],
3662
+ foreignColumns: [workspaces.id, workspaces.accountId],
3663
+ name: "workspace_screenshot_quotas_workspace_account_fk"
3664
+ }).onDelete("cascade"),
3665
+ nonnegative: check5(
3666
+ "workspace_screenshot_quotas_nonnegative_chk",
3667
+ sql6`${table.reservedBytes} >= 0 and ${table.readyBytes} >= 0`
3668
+ )
3669
+ })
3670
+ );
3671
+ var retainedScreenshotArtifacts = pgTable6(
3672
+ "retained_screenshot_artifacts",
3673
+ {
3674
+ // The composite file FK is RESTRICT in migration 0176: only the retained
3675
+ // screenshot lifecycle may remove its backing file after provider cleanup.
3676
+ artifactId: uuid6("artifact_id").primaryKey(),
3677
+ accountId: uuid6("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
3678
+ workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
3679
+ sessionId: uuid6("session_id").references(() => sessions.id, { onDelete: "set null" }),
3680
+ // Turn/attempt foreign keys are installed by migrations 0140/0176.
3681
+ // Those tables are declared later in this monolithic schema module, so
3682
+ // referencing them here would create an eager initialization cycle.
3683
+ turnId: uuid6("turn_id"),
3684
+ attemptId: uuid6("attempt_id"),
3685
+ settlementKey: text6("settlement_key").notNull(),
3686
+ toolCallId: text6("tool_call_id").notNull(),
3687
+ toolOutputId: text6("tool_output_id").notNull(),
3688
+ status: text6("status").$type().notNull().default("pending"),
3689
+ quotaState: text6("quota_state").$type().notNull().default("reserved"),
3690
+ mediaType: text6("media_type").notNull(),
3691
+ sizeBytes: bigint4("size_bytes", { mode: "number" }).notNull(),
3692
+ sha256: text6("sha256").notNull(),
3693
+ width: integer7("width").notNull(),
3694
+ height: integer7("height").notNull(),
3695
+ retentionExpiresAt: timestamp6("retention_expires_at", { withTimezone: true }).notNull(),
3696
+ readyAt: timestamp6("ready_at", { withTimezone: true }),
3697
+ cleanupReason: text6("cleanup_reason"),
3698
+ lastError: text6("last_error"),
3699
+ maintenanceClaimId: uuid6("maintenance_claim_id"),
3700
+ maintenanceClaimedAt: timestamp6("maintenance_claimed_at", { withTimezone: true }),
3701
+ createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
3702
+ updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
3703
+ },
3704
+ (table) => ({
3705
+ settlementKey: uniqueIndex6("retained_screenshot_artifacts_settlement_key_uq").on(
3706
+ table.settlementKey
3707
+ ),
3708
+ sessionCreated: index6("retained_screenshot_artifacts_session_created_idx").on(
3709
+ table.workspaceId,
3710
+ table.sessionId,
3711
+ table.createdAt,
3712
+ table.artifactId
3713
+ ),
3714
+ readyExpiry: index6("retained_screenshot_artifacts_ready_expiry_idx").on(table.retentionExpiresAt, table.artifactId).where(sql6`${table.status} = 'ready'`),
3715
+ pendingReconcile: index6("retained_screenshot_artifacts_pending_reconcile_idx").on(table.updatedAt, table.artifactId).where(
3716
+ sql6`${table.status} in ('pending', 'reconciling', 'cleanup_queued', 'cleanup_pending')`
3717
+ ),
3718
+ workspaceAccount: foreignKey({
3719
+ columns: [table.workspaceId, table.accountId],
3720
+ foreignColumns: [workspaces.id, workspaces.accountId],
3721
+ name: "retained_screenshot_artifacts_workspace_account_fk"
3722
+ }).onDelete("cascade"),
3723
+ workspaceFile: foreignKey({
3724
+ columns: [table.workspaceId, table.artifactId],
3725
+ foreignColumns: [files.workspaceId, files.id],
3726
+ name: "retained_screenshot_artifacts_workspace_file_fk"
3727
+ }).onDelete("restrict"),
3728
+ statusValid: check5(
3729
+ "retained_screenshot_artifacts_status_chk",
3730
+ sql6`${table.status} in ('pending', 'reconciling', 'ready', 'cleanup_queued', 'cleanup_pending', 'failed', 'expired', 'deleted')`
3731
+ ),
3732
+ quotaStateValid: check5(
3733
+ "retained_screenshot_artifacts_quota_state_chk",
3734
+ sql6`${table.quotaState} in ('reserved', 'ready', 'released')`
3735
+ ),
3736
+ statusQuotaValid: check5(
3737
+ "retained_screenshot_artifacts_status_quota_chk",
3738
+ sql6`(${table.status} in ('pending', 'reconciling') and ${table.quotaState} = 'reserved')
3739
+ or (${table.status} = 'ready' and ${table.quotaState} = 'ready')
3740
+ or (${table.status} in ('cleanup_queued', 'cleanup_pending') and ${table.quotaState} in ('reserved', 'ready'))
3741
+ or (${table.status} in ('failed', 'expired', 'deleted') and ${table.quotaState} = 'released')`
3742
+ ),
3743
+ claimShapeValid: check5(
3744
+ "retained_screenshot_artifacts_claim_shape_chk",
3745
+ sql6`(${table.status} in ('reconciling', 'cleanup_pending')
3746
+ and ${table.maintenanceClaimId} is not null
3747
+ and ${table.maintenanceClaimedAt} is not null)
3748
+ or (${table.status} not in ('reconciling', 'cleanup_pending')
3749
+ and ${table.maintenanceClaimId} is null
3750
+ and ${table.maintenanceClaimedAt} is null)`
3751
+ ),
3752
+ dimensionsValid: check5(
3753
+ "retained_screenshot_artifacts_dimensions_chk",
3754
+ sql6`${table.width} between 1 and 16384 and ${table.height} between 1 and 16384 and (${table.width}::bigint * ${table.height}::bigint) <= 67108864`
3755
+ )
3756
+ })
3757
+ );
3395
3758
  var documentBases = pgTable6(
3396
3759
  "document_bases",
3397
3760
  {
@@ -3422,7 +3785,7 @@ var documents = pgTable6(
3422
3785
  status: text6("status").notNull().default("queued"),
3423
3786
  title: text6("title").notNull(),
3424
3787
  parser: text6("parser").notNull().default("liteparse"),
3425
- chunkCount: integer6("chunk_count").notNull().default(0),
3788
+ chunkCount: integer7("chunk_count").notNull().default(0),
3426
3789
  error: text6("error"),
3427
3790
  sourceKind: text6("source_kind").notNull().default("manual_upload"),
3428
3791
  sourceUri: text6("source_uri"),
@@ -3525,7 +3888,7 @@ var documentChunks = pgTable6(
3525
3888
  documentId: uuid6("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
3526
3889
  baseId: uuid6("base_id").notNull().references(() => documentBases.id, { onDelete: "cascade" }),
3527
3890
  fileId: uuid6("file_id").notNull().references(() => files.id, { onDelete: "restrict" }),
3528
- chunkIndex: integer6("chunk_index").notNull(),
3891
+ chunkIndex: integer7("chunk_index").notNull(),
3529
3892
  text: text6("text").notNull(),
3530
3893
  metadata: jsonb6("metadata").$type().notNull().default({}),
3531
3894
  authorityKind: text6("authority_kind").notNull().default("workspace"),
@@ -3570,9 +3933,10 @@ var knowledgeMemories = pgTable6(
3570
3933
  status: text6("status").notNull().default("proposed"),
3571
3934
  kind: text6("kind").notNull().default("semantic"),
3572
3935
  scope: text6("scope").notNull().default("workspace"),
3573
- text: text6("text").notNull(),
3936
+ text: losslessText("text").notNull(),
3937
+ textCodecVersion: losslessCodecVersion("text_codec_version"),
3574
3938
  sourceRefs: jsonb6("source_refs").$type().notNull().default([]),
3575
- confidence: integer6("confidence").notNull().default(50),
3939
+ confidence: integer7("confidence").notNull().default(50),
3576
3940
  metadata: jsonb6("metadata").$type().notNull().default({}),
3577
3941
  createdBySessionId: uuid6("created_by_session_id").references(() => sessions.id, {
3578
3942
  onDelete: "set null"
@@ -3584,7 +3948,7 @@ var knowledgeMemories = pgTable6(
3584
3948
  embedding: vector("embedding"),
3585
3949
  embeddingModel: text6("embedding_model"),
3586
3950
  pinned: boolean4("pinned").notNull().default(false),
3587
- usageCount: integer6("usage_count").notNull().default(0),
3951
+ usageCount: integer7("usage_count").notNull().default(0),
3588
3952
  lastUsedAt: timestamp6("last_used_at", { withTimezone: true }),
3589
3953
  // Self-referential supersession chain. FKs live in migration 0045 (ON DELETE SET
3590
3954
  // NULL); declared here as plain columns like the migration-only composite FK.
@@ -3600,7 +3964,7 @@ var knowledgeMemories = pgTable6(
3600
3964
  scopeSessionId: uuid6("scope_session_id"),
3601
3965
  namespace: text6("namespace_key").notNull().default("general"),
3602
3966
  labels: text6("labels").array().notNull().default([]),
3603
- memoryVersion: integer6("memory_version").notNull().default(1),
3967
+ memoryVersion: integer7("memory_version").notNull().default(1),
3604
3968
  createdByKind: text6("created_by_kind").notNull().default("service"),
3605
3969
  createdBySubjectId: text6("created_by_subject_id").notNull().default("unattributed-legacy"),
3606
3970
  createdByContext: jsonb6("created_by_context").$type().notNull().default({ backfill: true }),
@@ -3667,7 +4031,8 @@ var sessionTurns = pgTable6(
3667
4031
  status: text6("status").notNull(),
3668
4032
  source: text6("source").notNull().default("user"),
3669
4033
  position: bigint4("position", { mode: "number" }).notNull(),
3670
- prompt: text6("prompt").notNull(),
4034
+ prompt: losslessText("prompt").notNull(),
4035
+ promptCodecVersion: losslessCodecVersion("prompt_codec_version"),
3671
4036
  // Host context for this exact turn. System-level at runtime and deliberately
3672
4037
  // separate from the visible prompt/event payload.
3673
4038
  turnInstructions: text6("turn_instructions"),
@@ -3685,8 +4050,8 @@ var sessionTurns = pgTable6(
3685
4050
  // constrained to the SandboxOs enum (or NULL) in migration 0018.
3686
4051
  sandboxOs: text6("sandbox_os"),
3687
4052
  metadata: jsonb6("metadata").$type().notNull().default({}),
3688
- version: integer6("version").notNull().default(1),
3689
- executionGeneration: integer6("execution_generation").notNull().default(0),
4053
+ version: integer7("version").notNull().default(1),
4054
+ executionGeneration: integer7("execution_generation").notNull().default(0),
3690
4055
  // Composite FK to session_turn_attempts is installed by migration 0063.
3691
4056
  // It lives in SQL because attempts carry the reciprocal turn FK and because
3692
4057
  // the claim transaction preallocates this ID before inserting the attempt;
@@ -3712,7 +4077,7 @@ var sessionTurns = pgTable6(
3712
4077
  // Atomic per-turn toolspace call budget counter (migration 0043). Incremented
3713
4078
  // by a single conditional UPDATE at tools/call time; the row lock serializes
3714
4079
  // concurrent reservations so exactly `toolspaceMaxCallsPerTurn` succeed.
3715
- toolspaceCallCount: integer6("toolspace_call_count").notNull().default(0),
4080
+ toolspaceCallCount: integer7("toolspace_call_count").notNull().default(0),
3716
4081
  startedAt: timestamp6("started_at", { withTimezone: true }),
3717
4082
  finishedAt: timestamp6("finished_at", { withTimezone: true }),
3718
4083
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -3745,10 +4110,10 @@ var sessionRealtimeContextProjections = pgTable6(
3745
4110
  sessionId: uuid6("session_id").notNull(),
3746
4111
  turnId: uuid6("turn_id").notNull(),
3747
4112
  context: text6("context"),
3748
- sourceModeCount: integer6("source_mode_count").notNull(),
3749
- sourceEntryCount: integer6("source_entry_count").notNull(),
3750
- includedEntryCount: integer6("included_entry_count").notNull(),
3751
- omittedEntryCount: integer6("omitted_entry_count").notNull(),
4113
+ sourceModeCount: integer7("source_mode_count").notNull(),
4114
+ sourceEntryCount: integer7("source_entry_count").notNull(),
4115
+ includedEntryCount: integer7("included_entry_count").notNull(),
4116
+ omittedEntryCount: integer7("omitted_entry_count").notNull(),
3752
4117
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow()
3753
4118
  },
3754
4119
  (table) => ({
@@ -3796,7 +4161,7 @@ var sessionTurnAttempts = pgTable6(
3796
4161
  workspaceId: uuid6("workspace_id").notNull(),
3797
4162
  sessionId: uuid6("session_id").notNull(),
3798
4163
  turnId: uuid6("turn_id").notNull(),
3799
- executionGeneration: integer6("execution_generation").notNull(),
4164
+ executionGeneration: integer7("execution_generation").notNull(),
3800
4165
  state: text6("state").notNull().default("claimed"),
3801
4166
  outcome: text6("outcome"),
3802
4167
  temporalWorkflowId: text6("temporal_workflow_id").notNull(),
@@ -3890,20 +4255,20 @@ var connectorActionRequests = pgTable6(
3890
4255
  sessionId: uuid6("session_id").notNull(),
3891
4256
  turnId: uuid6("turn_id").notNull(),
3892
4257
  creationAttemptId: uuid6("creation_attempt_id").notNull(),
3893
- creationExecutionGeneration: integer6("creation_execution_generation").notNull(),
4258
+ creationExecutionGeneration: integer7("creation_execution_generation").notNull(),
3894
4259
  executionAttemptId: uuid6("execution_attempt_id"),
3895
- executionAttemptGeneration: integer6("execution_attempt_generation"),
4260
+ executionAttemptGeneration: integer7("execution_attempt_generation"),
3896
4261
  approvalId: text6("approval_id").notNull(),
3897
4262
  initiatorKind: text6("initiator_kind").$type().notNull(),
3898
4263
  initiatorSubjectId: text6("initiator_subject_id").notNull(),
3899
4264
  connectionId: text6("connection_id").notNull(),
3900
- connectionVersion: integer6("connection_version"),
4265
+ connectionVersion: integer7("connection_version"),
3901
4266
  serverId: text6("server_id").notNull(),
3902
4267
  toolName: text6("tool_name").notNull(),
3903
4268
  actionName: text6("action_name").notNull(),
3904
4269
  // Attempt-frozen provenance intentionally survives policy deletion.
3905
4270
  policyId: uuid6("policy_id"),
3906
- policyVersion: integer6("policy_version"),
4271
+ policyVersion: integer7("policy_version"),
3907
4272
  policySource: text6("policy_source").$type().notNull(),
3908
4273
  policyDecision: text6("policy_decision").$type().notNull(),
3909
4274
  actionFingerprint: text6("action_fingerprint").notNull(),
@@ -4000,8 +4365,8 @@ var sessionCommandReceipts = pgTable6(
4000
4365
  appliedControlRevision: bigint4("applied_control_revision", {
4001
4366
  mode: "number"
4002
4367
  }),
4003
- appliedQueueVersion: integer6("applied_queue_version"),
4004
- appliedTurnVersion: integer6("applied_turn_version"),
4368
+ appliedQueueVersion: integer7("applied_queue_version"),
4369
+ appliedTurnVersion: integer7("applied_turn_version"),
4005
4370
  appliedDraftRevision: bigint4("applied_draft_revision", { mode: "number" }),
4006
4371
  result: jsonb6("result").$type().notNull().default({}),
4007
4372
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -4064,11 +4429,11 @@ var workspaceControlEvents = pgTable6(
4064
4429
  action: text6("action").notNull(),
4065
4430
  automatic: boolean4("automatic").notNull().default(false),
4066
4431
  reason: text6("reason"),
4067
- reasonOriginalBytes: integer6("reason_original_bytes"),
4432
+ reasonOriginalBytes: integer7("reason_original_bytes"),
4068
4433
  actor: text6("actor").notNull(),
4069
4434
  // Null is the rolling-upgrade shape for untouched, already-bounded legacy
4070
4435
  // rows. New writes and rewritten poison rows carry exact source byte facts.
4071
- actorOriginalBytes: integer6("actor_original_bytes"),
4436
+ actorOriginalBytes: integer7("actor_original_bytes"),
4072
4437
  occurredAt: timestamp6("occurred_at", { withTimezone: true }).notNull().defaultNow()
4073
4438
  },
4074
4439
  (table) => ({
@@ -4168,7 +4533,7 @@ var composerDrafts = pgTable6(
4168
4533
  reasoningEffort: text6("reasoning_effort").notNull(),
4169
4534
  latencyMode: text6("latency_mode").notNull().default("standard"),
4170
4535
  sourceTurnId: uuid6("source_turn_id"),
4171
- sourceTurnVersion: integer6("source_turn_version"),
4536
+ sourceTurnVersion: integer7("source_turn_version"),
4172
4537
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
4173
4538
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
4174
4539
  },
@@ -4254,8 +4619,10 @@ var sessionSystemUpdates = pgTable6(
4254
4619
  classification: text6("classification").notNull().default("info"),
4255
4620
  sourceId: text6("source_id").notNull(),
4256
4621
  dedupeKey: text6("dedupe_key").notNull(),
4257
- summary: text6("summary").notNull(),
4258
- payload: jsonb6("payload").$type().notNull().default({}),
4622
+ summary: losslessText("summary").notNull(),
4623
+ summaryCodecVersion: losslessCodecVersion("summary_codec_version"),
4624
+ payload: losslessJsonb("payload").$type().notNull().default({}),
4625
+ payloadCodecVersion: losslessCodecVersion("payload_codec_version"),
4259
4626
  lineage: jsonb6("lineage").$type().notNull().default({}),
4260
4627
  // Private immutable authority frozen when this machine input is accepted.
4261
4628
  // Public projections intentionally omit connection ids and owner subjects.
@@ -4319,14 +4686,16 @@ var sessionSystemUpdateOutbox = pgTable6(
4319
4686
  kind: text6("kind").notNull(),
4320
4687
  classification: text6("classification").notNull(),
4321
4688
  sourceId: text6("source_id").notNull(),
4322
- summary: text6("summary").notNull(),
4323
- payload: jsonb6("payload").$type().notNull().default({}),
4689
+ summary: losslessText("summary").notNull(),
4690
+ summaryCodecVersion: losslessCodecVersion("summary_codec_version"),
4691
+ payload: losslessJsonb("payload").$type().notNull().default({}),
4692
+ payloadCodecVersion: losslessCodecVersion("payload_codec_version"),
4324
4693
  lineage: jsonb6("lineage").$type().notNull().default({}),
4325
4694
  // Exact private authority copied from the causal parent turn in the source
4326
4695
  // terminal transaction. Delivery retries cannot replace this snapshot.
4327
4696
  personalConnectionDelegations: jsonb6("personal_connection_delegations").$type().notNull().default([]),
4328
4697
  status: text6("status").notNull().default("pending"),
4329
- attempts: integer6("attempts").notNull().default(0),
4698
+ attempts: integer7("attempts").notNull().default(0),
4330
4699
  updateId: uuid6("update_id"),
4331
4700
  lastError: text6("last_error"),
4332
4701
  deliveredAt: timestamp6("delivered_at", { withTimezone: true }),
@@ -4360,7 +4729,7 @@ var sessionWorkflowWakeOutbox = pgTable6(
4360
4729
  deliveredRevision: bigint4("delivered_revision", { mode: "number" }).notNull().default(0),
4361
4730
  controlRevision: bigint4("control_revision", { mode: "number" }).notNull().default(0),
4362
4731
  reason: text6("reason").notNull(),
4363
- attempts: integer6("attempts").notNull().default(0),
4732
+ attempts: integer7("attempts").notNull().default(0),
4364
4733
  nextAttemptAt: timestamp6("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
4365
4734
  lastError: text6("last_error"),
4366
4735
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -4415,14 +4784,14 @@ var sessionGoals = pgTable6(
4415
4784
  // agent | user_pause | api | no_progress | max_auto_continuations | limits
4416
4785
  createdBy: text6("created_by").notNull().default("api"),
4417
4786
  // api | agent | scheduled_task
4418
- version: integer6("version").notNull().default(1),
4787
+ version: integer7("version").notNull().default(1),
4419
4788
  // bumped on every set/update; progress signal
4420
- autoContinuations: integer6("auto_continuations").notNull().default(0),
4421
- noProgressStreak: integer6("no_progress_streak").notNull().default(0),
4422
- maxAutoContinuations: integer6("max_auto_continuations"),
4789
+ autoContinuations: integer7("auto_continuations").notNull().default(0),
4790
+ noProgressStreak: integer7("no_progress_streak").notNull().default(0),
4791
+ maxAutoContinuations: integer7("max_auto_continuations"),
4423
4792
  // per-goal override; a configured settings cap (if any) remains the hard ceiling
4424
4793
  lastContinuationTurnId: uuid6("last_continuation_turn_id"),
4425
- versionAtLastContinuation: integer6("version_at_last_continuation"),
4794
+ versionAtLastContinuation: integer7("version_at_last_continuation"),
4426
4795
  // Postgres owns the continuation obligation. Terminal settlement advances
4427
4796
  // wakeRevision in the same transaction that makes the session idle;
4428
4797
  // materialization advances observedRevision only alongside the one typed
@@ -4460,23 +4829,23 @@ var codexCapacityWaiters = pgTable6(
4460
4829
  sessionId: uuid6("session_id").notNull(),
4461
4830
  goalId: uuid6("goal_id"),
4462
4831
  blockedTurnId: uuid6("blocked_turn_id").notNull(),
4463
- blockedTurnGeneration: integer6("blocked_turn_generation").notNull(),
4832
+ blockedTurnGeneration: integer7("blocked_turn_generation").notNull(),
4464
4833
  workflowId: text6("workflow_id").notNull(),
4465
- generation: integer6("generation").notNull().default(1),
4834
+ generation: integer7("generation").notNull().default(1),
4466
4835
  status: text6("status").notNull().default("waiting"),
4467
4836
  // waiting | resumed | superseded
4468
- goalVersion: integer6("goal_version"),
4837
+ goalVersion: integer7("goal_version"),
4469
4838
  policyHash: text6("policy_hash"),
4470
4839
  earliestResetAt: timestamp6("earliest_reset_at", { withTimezone: true }),
4471
4840
  nextCheckAt: timestamp6("next_check_at", { withTimezone: true }).notNull(),
4472
4841
  resetKind: text6("reset_kind").notNull(),
4473
4842
  // authoritative | bounded_refresh
4474
- refreshAttempt: integer6("refresh_attempt").notNull().default(0),
4843
+ refreshAttempt: integer7("refresh_attempt").notNull().default(0),
4475
4844
  // Coalescing outbox generation. Every eligibility-affecting mutation bumps
4476
4845
  // wakeRevision. Duplicate/lost Temporal signals are harmless because only
4477
4846
  // the row-locked evaluator moves observedWakeRevision and may enqueue work.
4478
- wakeRevision: integer6("wake_revision").notNull().default(1),
4479
- observedWakeRevision: integer6("observed_wake_revision").notNull().default(0),
4847
+ wakeRevision: integer7("wake_revision").notNull().default(1),
4848
+ observedWakeRevision: integer7("observed_wake_revision").notNull().default(0),
4480
4849
  lastWakeReason: text6("last_wake_reason").notNull().default("capacity_wait_armed"),
4481
4850
  resumedUpdateId: uuid6("resumed_update_id"),
4482
4851
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -4511,17 +4880,18 @@ var sessionEvents = pgTable6(
4511
4880
  workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4512
4881
  sessionId: uuid6("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
4513
4882
  turnId: uuid6("turn_id"),
4514
- turnGeneration: integer6("turn_generation"),
4883
+ turnGeneration: integer7("turn_generation"),
4515
4884
  turnAttemptId: uuid6("turn_attempt_id"),
4516
4885
  turnAssociation: text6("turn_association"),
4517
4886
  duplicateOfEventId: uuid6("duplicate_of_event_id"),
4518
4887
  duplicateReason: text6("duplicate_reason"),
4519
- sequence: integer6("sequence").notNull(),
4888
+ sequence: integer7("sequence").notNull(),
4520
4889
  type: text6("type").notNull(),
4521
- payload: jsonb6("payload").$type().notNull().default({}),
4890
+ payload: losslessJsonb("payload").$type().notNull().default({}),
4891
+ payloadCodecVersion: losslessCodecVersion("payload_codec_version"),
4522
4892
  clientEventId: text6("client_event_id"),
4523
4893
  producerId: text6("producer_id"),
4524
- producerSeq: integer6("producer_seq"),
4894
+ producerSeq: integer7("producer_seq"),
4525
4895
  occurredAt: timestamp6("occurred_at", { withTimezone: true }).notNull().defaultNow(),
4526
4896
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow()
4527
4897
  },
@@ -4549,14 +4919,11 @@ var sessionEvents = pgTable6(
4549
4919
  table.type,
4550
4920
  table.sequence
4551
4921
  ),
4922
+ workspaceTurnType: index6("session_events_workspace_turn_type_idx").on(table.workspaceId, table.turnId, table.type).where(sql6`${table.turnId} is not null`),
4552
4923
  monitoringTail: index6("session_events_workspace_session_monitoring_tail_idx").on(table.workspaceId, table.sessionId, table.sequence).where(
4553
4924
  sql6`${table.type} not in ('agent.message.delta', 'agent.reasoning.delta', 'sandbox.command.output.delta', 'terminal.pty.output.delta')`
4554
4925
  ),
4555
4926
  duplicateOfEvent: index6("session_events_duplicate_of_event_idx").on(table.duplicateOfEventId),
4556
- payloadBytes: check5(
4557
- "session_events_payload_bytes_check",
4558
- sql6`octet_length(${table.payload}::text) <= 65536`
4559
- ),
4560
4927
  typeBytes: check5(
4561
4928
  "session_events_type_bytes_check",
4562
4929
  sql6`octet_length(${table.type}) <= 256 and position(E'\n' in ${table.type}) = 0 and position(E'\r' in ${table.type}) = 0`
@@ -4587,9 +4954,11 @@ var agentRunStates = pgTable6("agent_run_states", {
4587
4954
  turnId: uuid6("turn_id").references(() => sessionTurns.id, {
4588
4955
  onDelete: "set null"
4589
4956
  }),
4590
- stateVersion: integer6("state_version").notNull(),
4591
- serializedRunState: text6("serialized_run_state").notNull(),
4592
- pendingApprovals: jsonb6("pending_approvals").$type().notNull().default([]),
4957
+ stateVersion: integer7("state_version").notNull(),
4958
+ serializedRunState: losslessText("serialized_run_state").notNull(),
4959
+ serializedRunStateCodecVersion: losslessCodecVersion("serialized_run_state_codec_version"),
4960
+ pendingApprovals: losslessJsonb("pending_approvals").$type().notNull().default([]),
4961
+ pendingApprovalsCodecVersion: losslessCodecVersion("pending_approvals_codec_version"),
4593
4962
  // Exact provider rejection marks the latest current-turn receipt only when it
4594
4963
  // was part of the rejected request. The serialized receipt remains durable;
4595
4964
  // recovery builds a temporary view without unusable opaque artifacts.
@@ -4608,7 +4977,7 @@ var sessionHumanInputRequests = pgTable6(
4608
4977
  workspaceId: uuid6("workspace_id").notNull(),
4609
4978
  sessionId: uuid6("session_id").notNull(),
4610
4979
  turnId: uuid6("turn_id").notNull(),
4611
- turnGeneration: integer6("turn_generation").notNull(),
4980
+ turnGeneration: integer7("turn_generation").notNull(),
4612
4981
  creationAttemptId: uuid6("creation_attempt_id").notNull(),
4613
4982
  toolCallId: text6("tool_call_id").notNull(),
4614
4983
  status: text6("status").notNull().default("pending"),
@@ -4690,7 +5059,8 @@ var sessionHistoryItems = pgTable6(
4690
5059
  // positions; only the summary uses the half-step. `mode: "number"` maps the
4691
5060
  // postgres.js string back to a JS number so every reader stays numeric.
4692
5061
  position: numeric("position", { mode: "number" }).notNull(),
4693
- item: jsonb6("item").$type().notNull(),
5062
+ item: losslessJsonb("item").$type().notNull(),
5063
+ itemCodecVersion: losslessCodecVersion("item_codec_version"),
4694
5064
  // Live-row flag for client-side context compaction. The read path selects
4695
5065
  // only active rows; a compaction supersedes the summarized prefix (sets this
4696
5066
  // false — never deletes, so the full transcript stays as an audit trail) and
@@ -4725,13 +5095,15 @@ var sessionPendingToolCalls = pgTable6(
4725
5095
  workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4726
5096
  sessionId: uuid6("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
4727
5097
  turnId: uuid6("turn_id").notNull().references(() => sessionTurns.id, { onDelete: "cascade" }),
4728
- executionGeneration: integer6("execution_generation").notNull(),
5098
+ executionGeneration: integer7("execution_generation").notNull(),
4729
5099
  attemptId: uuid6("attempt_id").notNull(),
4730
5100
  callId: text6("call_id").notNull(),
4731
5101
  callType: text6("call_type").notNull(),
4732
- callItem: jsonb6("call_item").$type().notNull(),
4733
- modelToolOutputTruncationTokens: integer6("model_tool_output_truncation_tokens"),
4734
- resultItem: jsonb6("result_item").$type(),
5102
+ callItem: losslessJsonb("call_item").$type().notNull(),
5103
+ callItemCodecVersion: losslessCodecVersion("call_item_codec_version"),
5104
+ modelToolOutputTruncationTokens: integer7("model_tool_output_truncation_tokens"),
5105
+ resultItem: losslessJsonb("result_item").$type(),
5106
+ resultItemCodecVersion: losslessCodecVersion("result_item_codec_version"),
4735
5107
  resultRecordedAt: timestamp6("result_recorded_at", { withTimezone: true }),
4736
5108
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow()
4737
5109
  },
@@ -4760,7 +5132,8 @@ var sandboxSessionEnvelopes = pgTable6(
4760
5132
  accountId: uuid6("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
4761
5133
  workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4762
5134
  sessionId: uuid6("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
4763
- envelope: jsonb6("envelope").$type().notNull(),
5135
+ envelope: losslessJsonb("envelope").$type().notNull(),
5136
+ envelopeCodecVersion: losslessCodecVersion("envelope_codec_version"),
4764
5137
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
4765
5138
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
4766
5139
  },
@@ -4788,9 +5161,9 @@ var sandboxCheckpointArtifacts = pgTable6(
4788
5161
  workspaceId: uuid6("workspace_id").notNull(),
4789
5162
  sandboxGroupId: uuid6("sandbox_group_id").notNull(),
4790
5163
  sourceLeaseId: uuid6("source_lease_id").notNull(),
4791
- sourceLeaseEpoch: integer6("source_lease_epoch").notNull(),
5164
+ sourceLeaseEpoch: integer7("source_lease_epoch").notNull(),
4792
5165
  sourceInstanceId: text6("source_instance_id"),
4793
- sourceWorkspaceGeneration: integer6("source_workspace_generation"),
5166
+ sourceWorkspaceGeneration: integer7("source_workspace_generation"),
4794
5167
  provenance: text6("provenance", {
4795
5168
  enum: ["native_capture", "legacy_provider_adopted"]
4796
5169
  }).notNull(),
@@ -4803,12 +5176,12 @@ var sandboxCheckpointArtifacts = pgTable6(
4803
5176
  objectId: text6("object_id").notNull(),
4804
5177
  archiveBase64: text6("archive_base64").notNull(),
4805
5178
  archiveSha256: text6("archive_sha256").notNull(),
4806
- archiveBytes: integer6("archive_bytes").notNull(),
5179
+ archiveBytes: integer7("archive_bytes").notNull(),
4807
5180
  descriptor: jsonb6("descriptor").$type().notNull(),
4808
5181
  descriptorRevision: text6("descriptor_revision").notNull(),
4809
5182
  state: text6("state", { enum: sandboxCheckpointArtifactStateValues }).notNull().default("candidate"),
4810
5183
  deleteAfter: timestamp6("delete_after", { withTimezone: true }),
4811
- deleteAttempts: integer6("delete_attempts").notNull().default(0),
5184
+ deleteAttempts: integer7("delete_attempts").notNull().default(0),
4812
5185
  deleteClaimId: uuid6("delete_claim_id"),
4813
5186
  deleteClaimedAt: timestamp6("delete_claimed_at", { withTimezone: true }),
4814
5187
  lastDeleteError: text6("last_delete_error"),
@@ -4896,9 +5269,9 @@ var sandboxLeases = pgTable6(
4896
5269
  workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
4897
5270
  sandboxGroupId: uuid6("sandbox_group_id").notNull(),
4898
5271
  liveness: text6("liveness", { enum: sandboxLeaseLivenessValues }).notNull().default("cold"),
4899
- refcount: integer6("refcount").notNull().default(0),
4900
- turnHolders: integer6("turn_holders").notNull().default(0),
4901
- viewerHolders: integer6("viewer_holders").notNull().default(0),
5272
+ refcount: integer7("refcount").notNull().default(0),
5273
+ turnHolders: integer7("turn_holders").notNull().default(0),
5274
+ viewerHolders: integer7("viewer_holders").notNull().default(0),
4902
5275
  instanceId: text6("instance_id"),
4903
5276
  backend: text6("backend").notNull(),
4904
5277
  os: text6("os").notNull().default("linux"),
@@ -4928,21 +5301,21 @@ var sandboxLeases = pgTable6(
4928
5301
  // JS STRING from postgres-js, breaking the strict epoch-fence comparison (it
4929
5302
  // was always-true → every turn fenced); int4 returns a JS number, the fix.
4930
5303
  // Epochs never approach 2^31, so the narrower type loses nothing.
4931
- leaseEpoch: integer6("lease_epoch").notNull().default(0),
5304
+ leaseEpoch: integer7("lease_epoch").notNull().default(0),
4932
5305
  // Monotonic mutation intent for the live workspace. Every acknowledged
4933
5306
  // filesystem-writing operation advances this under the exact lease epoch +
4934
5307
  // provider-instance fence BEFORE it reaches the provider. A verified
4935
5308
  // archive fold copies the exact captured value into archive_generation in
4936
5309
  // the same row update; equality is the only durable completeness proof.
4937
- workspaceGeneration: integer6("workspace_generation").notNull().default(0),
4938
- archiveGeneration: integer6("archive_generation"),
5310
+ workspaceGeneration: integer7("workspace_generation").notNull().default(0),
5311
+ archiveGeneration: integer7("archive_generation"),
4939
5312
  // Provider-native capture may pause the live box. The exact claim is
4940
5313
  // acquired before provider I/O and cleared only after that capture settles;
4941
5314
  // new holders and workspace mutations fence on it. The SQL constraint also
4942
5315
  // requires the claimed generation to remain current, so an unaware writer
4943
5316
  // cannot advance generation through an active capture.
4944
5317
  archiveCaptureId: uuid6("archive_capture_id"),
4945
- archiveCaptureGeneration: integer6("archive_capture_generation"),
5318
+ archiveCaptureGeneration: integer7("archive_capture_generation"),
4946
5319
  archiveCaptureStartedAt: timestamp6("archive_capture_started_at", {
4947
5320
  withTimezone: true
4948
5321
  }),
@@ -4957,7 +5330,7 @@ var sandboxLeases = pgTable6(
4957
5330
  // idempotency tick (warm_seconds accrued idempotent on
4958
5331
  // (sandbox_group_id, lease_epoch, last_meter_tick) in P2.1).
4959
5332
  lastMeterAt: timestamp6("last_meter_at", { withTimezone: true }),
4960
- lastMeterTick: integer6("last_meter_tick").notNull().default(0),
5333
+ lastMeterTick: integer7("last_meter_tick").notNull().default(0),
4961
5334
  providerCreatedAt: timestamp6("provider_created_at", { withTimezone: true }),
4962
5335
  providerDeadlineAt: timestamp6("provider_deadline_at", {
4963
5336
  withTimezone: true
@@ -5090,12 +5463,12 @@ var sandboxWorkspaceMutationAdmissions = pgTable6(
5090
5463
  // requests and retained processes never invent a turn or quiescence owner.
5091
5464
  turnId: uuid6("turn_id"),
5092
5465
  attemptId: uuid6("attempt_id"),
5093
- executionGeneration: integer6("execution_generation"),
5466
+ executionGeneration: integer7("execution_generation"),
5094
5467
  holderKind: text6("holder_kind", {
5095
5468
  enum: sandboxWorkspaceMutationHolderKindValues
5096
5469
  }).notNull(),
5097
5470
  holderId: text6("holder_id").notNull(),
5098
- leaseEpoch: integer6("lease_epoch").notNull(),
5471
+ leaseEpoch: integer7("lease_epoch").notNull(),
5099
5472
  providerBackend: text6("provider_backend").notNull(),
5100
5473
  providerInstanceId: text6("provider_instance_id").notNull(),
5101
5474
  routeKind: text6("route_kind", { enum: ["home", "active"] }).notNull(),
@@ -5103,8 +5476,8 @@ var sandboxWorkspaceMutationAdmissions = pgTable6(
5103
5476
  // target is pinned together with the active pointer epoch observed when the
5104
5477
  // operation was admitted.
5105
5478
  routeTargetId: uuid6("route_target_id"),
5106
- routeEpoch: integer6("route_epoch").notNull(),
5107
- workspaceGeneration: integer6("workspace_generation").notNull(),
5479
+ routeEpoch: integer7("route_epoch").notNull(),
5480
+ workspaceGeneration: integer7("workspace_generation").notNull(),
5108
5481
  operation: text6("operation").notNull(),
5109
5482
  providerOutcome: text6("provider_outcome", {
5110
5483
  enum: ["resolved", "rejected", "retained"]
@@ -5226,8 +5599,8 @@ var sandboxRetainedProcesses = pgTable6(
5226
5599
  ownerActorId: uuid6("owner_actor_id").notNull(),
5227
5600
  ownerTurnId: uuid6("owner_turn_id"),
5228
5601
  ownerAttemptId: uuid6("owner_attempt_id"),
5229
- ownerExecutionGeneration: integer6("owner_execution_generation"),
5230
- leaseEpoch: integer6("lease_epoch").notNull(),
5602
+ ownerExecutionGeneration: integer7("owner_execution_generation"),
5603
+ leaseEpoch: integer7("lease_epoch").notNull(),
5231
5604
  providerBackend: text6("provider_backend").notNull(),
5232
5605
  providerInstanceId: text6("provider_instance_id").notNull(),
5233
5606
  // Provider object ids are namespace-scoped. New Modal processes bind the
@@ -5237,10 +5610,10 @@ var sandboxRetainedProcesses = pgTable6(
5237
5610
  providerBinding: jsonb6("provider_binding").$type(),
5238
5611
  routeKind: text6("route_kind", { enum: ["home", "active"] }).notNull(),
5239
5612
  routeTargetId: uuid6("route_target_id"),
5240
- routeEpoch: integer6("route_epoch").notNull(),
5241
- providerSessionId: integer6("provider_session_id").notNull(),
5613
+ routeEpoch: integer7("route_epoch").notNull(),
5614
+ providerSessionId: integer7("provider_session_id").notNull(),
5242
5615
  state: text6("state", { enum: sandboxRetainedProcessStateValues }).notNull().default("active"),
5243
- exitCode: integer6("exit_code"),
5616
+ exitCode: integer7("exit_code"),
5244
5617
  settlementReason: text6("settlement_reason"),
5245
5618
  startedAt: timestamp6("started_at", { withTimezone: true }).notNull().defaultNow(),
5246
5619
  settledAt: timestamp6("settled_at", { withTimezone: true }),
@@ -5251,10 +5624,10 @@ var sandboxRetainedProcesses = pgTable6(
5251
5624
  reconcileAfter: timestamp6("reconcile_after", { withTimezone: true }).notNull().defaultNow(),
5252
5625
  reconcileClaimId: uuid6("reconcile_claim_id"),
5253
5626
  reconcileClaimedAt: timestamp6("reconcile_claimed_at", { withTimezone: true }),
5254
- reconcileAttempts: integer6("reconcile_attempts").notNull().default(0),
5627
+ reconcileAttempts: integer7("reconcile_attempts").notNull().default(0),
5255
5628
  lastReconcileOutcome: text6("last_reconcile_outcome"),
5256
5629
  reconcileProofOutcome: text6("reconcile_proof_outcome", { enum: ["exited", "lost"] }),
5257
- reconcileProofExitCode: integer6("reconcile_proof_exit_code"),
5630
+ reconcileProofExitCode: integer7("reconcile_proof_exit_code"),
5258
5631
  reconcileProofReason: text6("reconcile_proof_reason"),
5259
5632
  reconcileProofObservedAt: timestamp6("reconcile_proof_observed_at", { withTimezone: true })
5260
5633
  },
@@ -5432,9 +5805,10 @@ var sessionRecordings = pgTable6(
5432
5805
  storageKey: text6("storage_key"),
5433
5806
  sizeBytes: bigint4("size_bytes", { mode: "number" }),
5434
5807
  durationSeconds: numeric("duration_seconds").$type(),
5435
- width: integer6("width").notNull(),
5436
- height: integer6("height").notNull(),
5437
- reason: text6("reason"),
5808
+ width: integer7("width").notNull(),
5809
+ height: integer7("height").notNull(),
5810
+ reason: losslessText("reason"),
5811
+ reasonCodecVersion: losslessCodecVersion("reason_codec_version"),
5438
5812
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
5439
5813
  finalizedAt: timestamp6("finalized_at", { withTimezone: true })
5440
5814
  },
@@ -5457,7 +5831,7 @@ var workspaceCaptures = pgTable6(
5457
5831
  onDelete: "set null"
5458
5832
  }),
5459
5833
  revision: bigint4("revision", { mode: "number" }).notNull(),
5460
- leaseEpoch: integer6("lease_epoch").notNull(),
5834
+ leaseEpoch: integer7("lease_epoch").notNull(),
5461
5835
  // 'available' on a committed capture. 'failed' reserved for a future two-phase
5462
5836
  // write; the current synchronous capture only ever inserts 'available'.
5463
5837
  state: text6("state", { enum: ["available", "failed"] }).notNull().default("available"),
@@ -5497,15 +5871,15 @@ var sandboxPtySessions = pgTable6(
5497
5871
  retainedProcessId: uuid6("retained_process_id"),
5498
5872
  openAdmissionId: uuid6("open_admission_id"),
5499
5873
  // Copied provider locator for the adopted retained process.
5500
- execSessionId: integer6("exec_session_id"),
5501
- leaseEpoch: integer6("lease_epoch").notNull(),
5874
+ execSessionId: integer7("exec_session_id"),
5875
+ leaseEpoch: integer7("lease_epoch").notNull(),
5502
5876
  providerBackend: text6("provider_backend"),
5503
5877
  providerInstanceId: text6("provider_instance_id"),
5504
5878
  routeKind: text6("route_kind", { enum: ["home", "active"] }),
5505
5879
  routeTargetId: uuid6("route_target_id"),
5506
- routeEpoch: integer6("route_epoch"),
5507
- cols: integer6("cols").notNull(),
5508
- rows: integer6("rows").notNull(),
5880
+ routeEpoch: integer7("route_epoch"),
5881
+ cols: integer7("cols").notNull(),
5882
+ rows: integer7("rows").notNull(),
5509
5883
  shell: text6("shell").notNull(),
5510
5884
  cwd: text6("cwd").notNull(),
5511
5885
  status: text6("status").notNull().default("open"),
@@ -5583,6 +5957,10 @@ var enrollments = pgTable6(
5583
5957
  desktopUnavailableReason: text6("desktop_unavailable_reason"),
5584
5958
  allowScreenControl: boolean4("allow_screen_control").notNull().default(false),
5585
5959
  status: text6("status", { enum: enrollmentStatusValues }).notNull().default("active"),
5960
+ // Credential-family fence. Existing rows/migration-era bearers are generation
5961
+ // 1; every successful re-enrollment increments this atomically before a new
5962
+ // bearer is signed. Auth and self-revoke require an exact row/claim match.
5963
+ credentialGeneration: integer7("credential_generation").notNull().default(1),
5586
5964
  os: text6("os", { enum: enrollmentOsValues }).notNull().default("linux"),
5587
5965
  arch: text6("arch").notNull().default("x86_64"),
5588
5966
  // Heartbeat liveness cursor. Null until the first connect.
@@ -5609,6 +5987,55 @@ var enrollments = pgTable6(
5609
5987
  workspaceStatus: index6("enrollments_workspace_status_idx").on(table.workspaceId, table.status)
5610
5988
  })
5611
5989
  );
5990
+ var machineRemovalOperationOutcomeValues = [
5991
+ "removed",
5992
+ "already_removed",
5993
+ "blocked"
5994
+ ];
5995
+ var machineRemovalOperations = pgTable6(
5996
+ "machine_removal_operations",
5997
+ {
5998
+ id: uuid6("id").primaryKey().defaultRandom(),
5999
+ accountId: uuid6("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
6000
+ workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
6001
+ enrollmentId: uuid6("enrollment_id").notNull().references(() => enrollments.id, { onDelete: "restrict" }),
6002
+ operationKey: text6("operation_key").notNull(),
6003
+ requestFingerprint: text6("request_fingerprint").notNull(),
6004
+ outcome: text6("outcome", { enum: machineRemovalOperationOutcomeValues }).notNull(),
6005
+ result: jsonb6("result").$type().notNull().default({}),
6006
+ createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
6007
+ updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
6008
+ },
6009
+ (table) => ({
6010
+ workspaceAccount: foreignKey({
6011
+ name: "machine_removal_operations_workspace_account_fk",
6012
+ columns: [table.workspaceId, table.accountId],
6013
+ foreignColumns: [workspaces.id, workspaces.accountId]
6014
+ }).onDelete("cascade"),
6015
+ workspaceOperation: uniqueIndex6("machine_removal_operations_workspace_operation_uq").on(
6016
+ table.workspaceId,
6017
+ table.operationKey
6018
+ ),
6019
+ workspaceIdentity: uniqueIndex6("machine_removal_operations_workspace_id_uq").on(
6020
+ table.workspaceId,
6021
+ table.id
6022
+ ),
6023
+ enrollmentTimeline: index6("machine_removal_operations_enrollment_created_idx").on(
6024
+ table.workspaceId,
6025
+ table.enrollmentId,
6026
+ table.createdAt
6027
+ ),
6028
+ requestFingerprintValid: check5(
6029
+ "machine_removal_operations_request_fingerprint_chk",
6030
+ sql6`${table.requestFingerprint} ~ '^[0-9a-f]{64}$'`
6031
+ ),
6032
+ operationKeyValid: check5(
6033
+ "machine_removal_operations_operation_key_chk",
6034
+ sql6`length(btrim(${table.operationKey})) between 1 and 200
6035
+ and ${table.operationKey} = btrim(${table.operationKey})`
6036
+ )
6037
+ })
6038
+ );
5612
6039
  var deviceEnrollmentStatusValues = ["pending", "approved", "denied", "consumed"];
5613
6040
  var deviceEnrollmentRequests = pgTable6(
5614
6041
  "device_enrollment_requests",
@@ -5837,7 +6264,7 @@ var githubInstallations = pgTable6(
5837
6264
  id: uuid6("id").primaryKey().defaultRandom(),
5838
6265
  accountId: uuid6("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
5839
6266
  workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
5840
- installationId: integer6("installation_id").notNull(),
6267
+ installationId: integer7("installation_id").notNull(),
5841
6268
  githubAccountId: bigint4("github_account_id", { mode: "number" }),
5842
6269
  accountLogin: text6("account_login"),
5843
6270
  accountType: text6("account_type"),
@@ -5918,7 +6345,7 @@ var githubInstallationRepositories = pgTable6(
5918
6345
  id: uuid6("id").primaryKey().defaultRandom(),
5919
6346
  accountId: uuid6("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
5920
6347
  workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
5921
- installationId: integer6("installation_id").notNull(),
6348
+ installationId: integer7("installation_id").notNull(),
5922
6349
  repositoryId: bigint4("repository_id", { mode: "number" }).notNull(),
5923
6350
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow()
5924
6351
  },
@@ -6104,7 +6531,7 @@ var modelCallFacts = pgTable6(
6104
6531
  var hostExportConfig = pgTable6(
6105
6532
  "host_export_config",
6106
6533
  {
6107
- id: integer6("id").primaryKey().default(1),
6534
+ id: integer7("id").primaryKey().default(1),
6108
6535
  sessionEventsEnabled: boolean4("session_events_enabled").notNull().default(false),
6109
6536
  usageEventsEnabled: boolean4("usage_events_enabled").notNull().default(false),
6110
6537
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
@@ -6125,9 +6552,9 @@ var hostExportOutbox = pgTable6(
6125
6552
  sessionId: uuid6("session_id"),
6126
6553
  rootSessionId: uuid6("root_session_id"),
6127
6554
  turnId: uuid6("turn_id"),
6128
- turnGeneration: integer6("turn_generation"),
6555
+ turnGeneration: integer7("turn_generation"),
6129
6556
  turnAttemptId: uuid6("turn_attempt_id"),
6130
- sessionSequence: integer6("session_sequence"),
6557
+ sessionSequence: integer7("session_sequence"),
6131
6558
  clientEventId: text6("client_event_id"),
6132
6559
  turnAssociation: text6("turn_association"),
6133
6560
  duplicateOfEventId: uuid6("duplicate_of_event_id"),
@@ -6138,7 +6565,8 @@ var hostExportOutbox = pgTable6(
6138
6565
  initiatorContext: jsonb6("initiator_context").$type().notNull().default({}),
6139
6566
  origin: text6("origin"),
6140
6567
  payload: jsonb6("payload").$type().notNull(),
6141
- envelopeBytes: integer6("envelope_bytes").notNull(),
6568
+ payloadCodecVersion: losslessCodecVersion("payload_codec_version"),
6569
+ envelopeBytes: integer7("envelope_bytes").notNull(),
6142
6570
  occurredAt: timestamp6("occurred_at", { withTimezone: true }).notNull(),
6143
6571
  sourceRecordedAt: timestamp6("source_recorded_at", { withTimezone: true }).notNull(),
6144
6572
  enqueuedAt: timestamp6("enqueued_at", { withTimezone: true }).notNull()
@@ -6201,9 +6629,10 @@ var hostExportConsumers = pgTable6(
6201
6629
  leaseExpiresAt: timestamp6("lease_expires_at", { withTimezone: true }),
6202
6630
  leaseFrom: bigint4("lease_from", { mode: "bigint" }),
6203
6631
  leaseThrough: bigint4("lease_through", { mode: "bigint" }),
6204
- consecutiveFailures: integer6("consecutive_failures").notNull().default(0),
6632
+ consecutiveFailures: integer7("consecutive_failures").notNull().default(0),
6205
6633
  nextAttemptAt: timestamp6("next_attempt_at", { withTimezone: true }).notNull().defaultNow(),
6206
6634
  lastError: text6("last_error"),
6635
+ lastErrorCodecVersion: losslessCodecVersion("last_error_codec_version"),
6207
6636
  lastErrorAt: timestamp6("last_error_at", { withTimezone: true }),
6208
6637
  blockedAt: timestamp6("blocked_at", { withTimezone: true }),
6209
6638
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -6235,7 +6664,9 @@ var hostExportDeadLetters = pgTable6(
6235
6664
  exportCursor: bigint4("export_cursor", { mode: "bigint" }).notNull(),
6236
6665
  sourceId: uuid6("source_id").notNull(),
6237
6666
  reason: text6("reason").notNull(),
6238
- envelope: jsonb6("envelope").$type().notNull(),
6667
+ envelope: losslessJsonb("envelope").$type().notNull(),
6668
+ envelopeCodecVersion: losslessCodecVersion("envelope_codec_version"),
6669
+ eventPayloadCodecVersion: losslessCodecVersion("event_payload_codec_version"),
6239
6670
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow()
6240
6671
  },
6241
6672
  (table) => ({
@@ -6328,7 +6759,8 @@ var auditEvents = pgTable6(
6328
6759
  action: text6("action").notNull(),
6329
6760
  targetType: text6("target_type"),
6330
6761
  targetId: text6("target_id"),
6331
- metadata: jsonb6("metadata").$type().notNull().default({}),
6762
+ metadata: losslessJsonb("metadata").$type().notNull().default({}),
6763
+ metadataCodecVersion: losslessCodecVersion("metadata_codec_version"),
6332
6764
  occurredAt: timestamp6("occurred_at", { withTimezone: true }).notNull().defaultNow()
6333
6765
  },
6334
6766
  (table) => ({
@@ -6385,11 +6817,11 @@ var importBatches = pgTable6(
6385
6817
  snapshotDate: timestamp6("snapshot_date", { withTimezone: true }).notNull(),
6386
6818
  snapshotRef: text6("snapshot_ref"),
6387
6819
  attributionNote: text6("attribution_note").notNull(),
6388
- importedCount: integer6("imported_count").notNull().default(0),
6389
- skippedCount: integer6("skipped_count").notNull().default(0),
6390
- quarantinedCount: integer6("quarantined_count").notNull().default(0),
6391
- logoFailureCount: integer6("logo_failure_count").notNull().default(0),
6392
- staleCount: integer6("stale_count").notNull().default(0),
6820
+ importedCount: integer7("imported_count").notNull().default(0),
6821
+ skippedCount: integer7("skipped_count").notNull().default(0),
6822
+ quarantinedCount: integer7("quarantined_count").notNull().default(0),
6823
+ logoFailureCount: integer7("logo_failure_count").notNull().default(0),
6824
+ staleCount: integer7("stale_count").notNull().default(0),
6393
6825
  details: jsonb6("details").$type().notNull().default({}),
6394
6826
  createdAt: timestamp6("created_at", { withTimezone: true }).notNull().defaultNow(),
6395
6827
  updatedAt: timestamp6("updated_at", { withTimezone: true }).notNull().defaultNow()
@@ -6590,7 +7022,7 @@ var rigVersions = pgTable6(
6590
7022
  accountId: uuid6("account_id").notNull().references(() => managedAccounts.id, { onDelete: "cascade" }),
6591
7023
  workspaceId: uuid6("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
6592
7024
  rigId: uuid6("rig_id").notNull().references(() => rigs.id, { onDelete: "cascade" }),
6593
- version: integer6("version").notNull(),
7025
+ version: integer7("version").notNull(),
6594
7026
  image: text6("image"),
6595
7027
  setupScript: text6("setup_script"),
6596
7028
  // Self-declared health checks: [{ name, command }].
@@ -6627,11 +7059,13 @@ var rigChanges = pgTable6(
6627
7059
  }),
6628
7060
  // 'setup_append' | 'definition_edit' (CHECK in migration 0047).
6629
7061
  kind: text6("kind").notNull(),
6630
- payload: jsonb6("payload").$type().notNull(),
7062
+ payload: losslessJsonb("payload").$type().notNull(),
7063
+ payloadCodecVersion: losslessCodecVersion("payload_codec_version"),
6631
7064
  // 'proposed' | 'verifying' | 'merged' | 'rejected' | 'failed' (CHECK in 0047).
6632
7065
  status: text6("status").notNull().default("proposed"),
6633
7066
  proposedBy: text6("proposed_by"),
6634
- verification: jsonb6("verification").$type(),
7067
+ verification: losslessJsonb("verification").$type(),
7068
+ verificationCodecVersion: losslessCodecVersion("verification_codec_version"),
6635
7069
  resultVersionId: uuid6("result_version_id").references(() => rigVersions.id, {
6636
7070
  onDelete: "set null"
6637
7071
  }),
@@ -6649,6 +7083,13 @@ var rigChanges = pgTable6(
6649
7083
  );
6650
7084
 
6651
7085
  export {
7086
+ LOSSLESS_CONTENT_CODEC_VERSION,
7087
+ LOSSLESS_CONTENT_WRITER_APPLICATION_NAME,
7088
+ withLosslessContentWriteVersion,
7089
+ LOSSLESS_TEXT_PREFIX,
7090
+ fromPostgresLosslessJson,
7091
+ toPostgresLosslessText,
7092
+ fromPostgresLosslessText,
6652
7093
  workspaceInstructionPolicyRevisions,
6653
7094
  workspaceInstructionPolicyHeads,
6654
7095
  workspaceInstructionPolicyActivationEvents,
@@ -6723,6 +7164,8 @@ export {
6723
7164
  sessionMcpServers,
6724
7165
  files,
6725
7166
  fileUploads,
7167
+ workspaceScreenshotQuotas,
7168
+ retainedScreenshotArtifacts,
6726
7169
  documentBases,
6727
7170
  documents,
6728
7171
  documentChunks,
@@ -6768,6 +7211,8 @@ export {
6768
7211
  enrollmentOsValues,
6769
7212
  sandboxKindValues,
6770
7213
  enrollments,
7214
+ machineRemovalOperationOutcomeValues,
7215
+ machineRemovalOperations,
6771
7216
  deviceEnrollmentStatusValues,
6772
7217
  deviceEnrollmentRequests,
6773
7218
  sandboxes,
@@ -6800,4 +7245,4 @@ export {
6800
7245
  rigChanges,
6801
7246
  schema_exports
6802
7247
  };
6803
- //# sourceMappingURL=chunk-HT5T62CC.js.map
7248
+ //# sourceMappingURL=chunk-P6CUHXQZ.js.map