@opengeni/db 0.22.2 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/{chunk-CYGFLLMN.js → chunk-7WTDI7Y3.js} +764 -283
  2. package/dist/chunk-7WTDI7Y3.js.map +1 -0
  3. package/dist/{chunk-BNGEN5QZ.js → chunk-KW6U54V2.js} +26 -2
  4. package/dist/chunk-KW6U54V2.js.map +1 -0
  5. package/dist/connection-token-resolver.d.ts +24 -2
  6. package/dist/index.d.ts +107 -5
  7. package/dist/index.js +7857 -3898
  8. package/dist/index.js.map +1 -1
  9. package/dist/preference-registry.d.ts +14 -0
  10. package/dist/provision-roles.js +1 -1
  11. package/dist/runtime-posture.d.ts +3 -3
  12. package/dist/schema.d.ts +1659 -77
  13. package/dist/schema.js +13 -1
  14. package/dist/session-control.d.ts +7 -1
  15. package/dist/session-queue-commands.d.ts +8 -0
  16. package/dist/session-realtime-context.d.ts +56 -0
  17. package/dist/session-realtime-ledger.d.ts +188 -0
  18. package/dist/session-realtime-mirror.d.ts +51 -0
  19. package/dist/session-realtime-state.d.ts +2 -0
  20. package/dist/session-realtime-terminal.d.ts +40 -0
  21. package/dist/session-realtime.d.ts +59 -0
  22. package/dist/workspace-instruction-policies-schema.d.ts +307 -0
  23. package/dist/workspace-instruction-policies.d.ts +97 -7
  24. package/drizzle/0156_slack_reaction_trigger.sql +49 -0
  25. package/drizzle/0157_session_policy_role_snapshots.sql +1146 -0
  26. package/drizzle/0158_session_realtime_mode.sql +88 -0
  27. package/drizzle/0159_session_realtime_ledger.sql +198 -0
  28. package/drizzle/0160_session_realtime_delegation_terminal.sql +38 -0
  29. package/drizzle/0161_session_realtime_context_projection.sql +82 -0
  30. package/drizzle/0162_session_realtime_connection_promotion.sql +53 -0
  31. package/drizzle/0163_session_realtime_delegation_progress.sql +35 -0
  32. package/drizzle/0164_session_realtime_models.sql +28 -0
  33. package/drizzle/0165_document_authority_foundation.sql +259 -0
  34. package/drizzle/0166_connection_disconnect_idempotency.sql +49 -0
  35. package/drizzle/0167_document_index_replay_authority.sql +61 -0
  36. package/drizzle/0168_workspace_instruction_policy_operation_receipts.sql +44 -0
  37. package/package.json +4 -4
  38. package/src/connection-token-resolver.ts +79 -16
  39. package/src/index.ts +1033 -101
  40. package/src/preference-registry.ts +114 -6
  41. package/src/provision-roles.ts +12 -0
  42. package/src/runtime-posture.ts +12 -0
  43. package/src/schema.ts +486 -43
  44. package/src/session-control.ts +643 -21
  45. package/src/session-queue-commands.ts +121 -18
  46. package/src/session-realtime-context.ts +393 -0
  47. package/src/session-realtime-ledger.ts +1790 -0
  48. package/src/session-realtime-mirror.ts +276 -0
  49. package/src/session-realtime-state.ts +25 -0
  50. package/src/session-realtime-terminal.ts +306 -0
  51. package/src/session-realtime.ts +659 -0
  52. package/src/workspace-instruction-policies-schema.ts +71 -0
  53. package/src/workspace-instruction-policies.ts +568 -25
  54. package/dist/chunk-BNGEN5QZ.js.map +0 -1
  55. package/dist/chunk-CYGFLLMN.js.map +0 -1
package/src/schema.ts CHANGED
@@ -557,16 +557,12 @@ export const codexSubscriptionCredentials = pgTable(
557
557
  // continues to own `version`; quota/cache writes own neither counter.
558
558
  allocatorVersion: integer("allocator_version").notNull().default(1),
559
559
  allocatorUpdatedBySubjectId: text("allocator_updated_by_subject_id"),
560
- allocatorUpdatedAt: timestamp("allocator_updated_at", {
561
- withTimezone: true,
562
- }),
560
+ allocatorUpdatedAt: timestamp("allocator_updated_at", { withTimezone: true }),
563
561
  // Authoritative count-only summary cached from /wham/usage. Detailed rows
564
562
  // are never persisted as redemption authority; every first POST preflights
565
563
  // the provider's fresh detail endpoint.
566
564
  resetCreditAvailableCount: integer("reset_credit_available_count"),
567
- resetCreditsCheckedAt: timestamp("reset_credits_checked_at", {
568
- withTimezone: true,
569
- }),
565
+ resetCreditsCheckedAt: timestamp("reset_credits_checked_at", { withTimezone: true }),
570
566
  // Set only by a direct Better Auth cookie connection/reconnection. Legacy,
571
567
  // configured, delegated, API-key, and agent-created rows remain view-only.
572
568
  connectedBySubjectId: text("connected_by_subject_id"),
@@ -616,9 +612,7 @@ export const codexResetRedemptionAttempts = pgTable(
616
612
  outcome: text("outcome"),
617
613
  claimHolderId: uuid("claim_holder_id"),
618
614
  claimExpiresAt: timestamp("claim_expires_at", { withTimezone: true }),
619
- confirmationExpiresAt: timestamp("confirmation_expires_at", {
620
- withTimezone: true,
621
- }).notNull(),
615
+ confirmationExpiresAt: timestamp("confirmation_expires_at", { withTimezone: true }).notNull(),
622
616
  providerStartedAt: timestamp("provider_started_at", { withTimezone: true }),
623
617
  completedAt: timestamp("completed_at", { withTimezone: true }),
624
618
  lastFailureKind: text("last_failure_kind"),
@@ -726,6 +720,45 @@ export const connections = pgTable(
726
720
  }),
727
721
  );
728
722
 
723
+ export const connectionDisconnectOperations = pgTable(
724
+ "connection_disconnect_operations",
725
+ {
726
+ id: uuid("id").primaryKey().defaultRandom(),
727
+ accountId: uuid("account_id")
728
+ .notNull()
729
+ .references(() => managedAccounts.id, { onDelete: "cascade" }),
730
+ workspaceId: uuid("workspace_id")
731
+ .notNull()
732
+ .references(() => workspaces.id, { onDelete: "cascade" }),
733
+ connectionId: uuid("connection_id")
734
+ .notNull()
735
+ .references(() => connections.id, { onDelete: "cascade" }),
736
+ subjectId: text("subject_id").notNull(),
737
+ idempotencyKey: text("idempotency_key").notNull(),
738
+ expectedVersion: integer("expected_version").notNull(),
739
+ resultVersion: integer("result_version").notNull(),
740
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
741
+ },
742
+ (table) => ({
743
+ workspaceSubjectKey: uniqueIndex("connection_disconnect_operations_subject_key_uq").on(
744
+ table.workspaceId,
745
+ table.subjectId,
746
+ table.idempotencyKey,
747
+ ),
748
+ connectionGeneration: uniqueIndex(
749
+ "connection_disconnect_operations_connection_generation_uq",
750
+ ).on(table.workspaceId, table.connectionId, table.expectedVersion),
751
+ identityValid: check(
752
+ "connection_disconnect_operations_identity_check",
753
+ sql`length(${table.subjectId}) between 1 and 512
754
+ and length(${table.idempotencyKey}) between 1 and 200
755
+ and ${table.idempotencyKey} = btrim(${table.idempotencyKey})
756
+ and ${table.expectedVersion} > 0
757
+ and ${table.resultVersion} = ${table.expectedVersion} + 1`,
758
+ ),
759
+ }),
760
+ );
761
+
729
762
  export const connectorActionPolicies = pgTable(
730
763
  "connector_action_policies",
731
764
  {
@@ -826,7 +859,9 @@ export const slackInteractionInbox = pgTable(
826
859
  slackMessageTs: text("slack_message_ts").notNull(),
827
860
  slackThreadTs: text("slack_thread_ts"),
828
861
  triggerKind: text("trigger_kind")
829
- .$type<"app_mention" | "dm" | "slash_command" | "message_shortcut" | "thread_reply">()
862
+ .$type<
863
+ "app_mention" | "dm" | "reaction" | "slash_command" | "message_shortcut" | "thread_reply"
864
+ >()
830
865
  .notNull(),
831
866
  text: text("text").notNull(),
832
867
  status: text("status")
@@ -838,6 +873,7 @@ export const slackInteractionInbox = pgTable(
838
873
  attemptCount: integer("attempt_count").notNull().default(0),
839
874
  retryAt: timestamp("retry_at", { withTimezone: true }),
840
875
  lastErrorCode: text("last_error_code"),
876
+ reactionContextCheckpoint: jsonb("reaction_context_checkpoint").$type<unknown>(),
841
877
  processedAt: timestamp("processed_at", { withTimezone: true }),
842
878
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
843
879
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
@@ -1310,6 +1346,11 @@ export const sessions = pgTable(
1310
1346
  // Composed system-level AFTER the workspace agentInstructions; never emitted
1311
1347
  // as a timeline event.
1312
1348
  instructions: text("instructions"),
1349
+ // Immutable normalized prompt-policy role. This is deliberately separate
1350
+ // from workspace membership roles and memory selectors. Existing rows keep
1351
+ // NULL and use the bounded metadata.role compatibility fallback at the
1352
+ // attempt-snapshot boundary.
1353
+ policyRole: text("policy_role"),
1313
1354
  resources: jsonb("resources").$type<unknown[]>().notNull().default([]),
1314
1355
  skills: jsonb("skills").$type<unknown[]>().notNull().default([]),
1315
1356
  tools: jsonb("tools").$type<unknown[]>().notNull().default([]),
@@ -1517,6 +1558,323 @@ export const sessions = pgTable(
1517
1558
  }),
1518
1559
  );
1519
1560
 
1561
+ // One temporary realtime owner for an ordinary session. Terminal rows remain
1562
+ // as lifecycle evidence; the partial unique index admits only one active owner.
1563
+ export const sessionRealtimeModes = pgTable(
1564
+ "session_realtime_modes",
1565
+ {
1566
+ id: uuid("id").primaryKey().defaultRandom(),
1567
+ accountId: uuid("account_id").notNull(),
1568
+ workspaceId: uuid("workspace_id").notNull(),
1569
+ sessionId: uuid("session_id").notNull(),
1570
+ operationId: uuid("operation_id").notNull(),
1571
+ ownerSubjectId: text("owner_subject_id").notNull(),
1572
+ browserInstanceId: text("browser_instance_id").notNull(),
1573
+ ownerKeyHash: text("owner_key_hash").notNull(),
1574
+ model: text("model").notNull(),
1575
+ state: text("state").notNull().default("active"),
1576
+ version: integer("version").notNull().default(1),
1577
+ connectionEpoch: integer("connection_epoch").notNull().default(1),
1578
+ leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }).notNull(),
1579
+ lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true }).notNull(),
1580
+ startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(),
1581
+ endedAt: timestamp("ended_at", { withTimezone: true }),
1582
+ endReason: text("end_reason"),
1583
+ // The rolling migration owns this forward reference. End commits at most
1584
+ // one canonical transcript-tail Steer and binds its audit projection here.
1585
+ contextProjectionId: uuid("context_projection_id"),
1586
+ contextProjectedAt: timestamp("context_projected_at", { withTimezone: true }),
1587
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1588
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1589
+ },
1590
+ (table) => ({
1591
+ workspaceAccount: foreignKey({
1592
+ name: "session_realtime_modes_workspace_account_fk",
1593
+ columns: [table.workspaceId, table.accountId],
1594
+ foreignColumns: [workspaces.id, workspaces.accountId],
1595
+ }).onDelete("cascade"),
1596
+ workspaceSession: foreignKey({
1597
+ name: "session_realtime_modes_workspace_session_fk",
1598
+ columns: [table.workspaceId, table.sessionId],
1599
+ foreignColumns: [sessions.workspaceId, sessions.id],
1600
+ }).onDelete("cascade"),
1601
+ operation: uniqueIndex("session_realtime_modes_operation_uq").on(
1602
+ table.workspaceId,
1603
+ table.sessionId,
1604
+ table.operationId,
1605
+ ),
1606
+ oneActive: uniqueIndex("session_realtime_modes_one_active_uq")
1607
+ .on(table.workspaceId, table.sessionId)
1608
+ .where(sql`${table.state} = 'active'`),
1609
+ activeLease: index("session_realtime_modes_active_lease_idx")
1610
+ .on(table.leaseExpiresAt, table.workspaceId, table.sessionId)
1611
+ .where(sql`${table.state} = 'active'`),
1612
+ stateValid: check(
1613
+ "session_realtime_modes_state_check",
1614
+ sql`${table.state} in ('active', 'ended')`,
1615
+ ),
1616
+ modelValid: check(
1617
+ "session_realtime_modes_model_check",
1618
+ sql`${table.model} in (
1619
+ 'gpt-live-1-boulder-alpha',
1620
+ 'opengeni-gateway/openai/gpt-realtime-2.1',
1621
+ 'opengeni-gateway/openai/gpt-realtime-mini',
1622
+ 'opengeni-gateway/xai/grok-voice-think-fast-2.0',
1623
+ 'workspace-gateway/openai/gpt-realtime-2.1',
1624
+ 'workspace-gateway/openai/gpt-realtime-mini',
1625
+ 'workspace-gateway/xai/grok-voice-think-fast-2.0'
1626
+ )`,
1627
+ ),
1628
+ endReasonValid: check(
1629
+ "session_realtime_modes_end_reason_check",
1630
+ sql`${table.endReason} is null or ${table.endReason} in ('user_stop', 'browser_unload', 'lease_expired')`,
1631
+ ),
1632
+ versionValid: check("session_realtime_modes_version_check", sql`${table.version} >= 1`),
1633
+ epochValid: check("session_realtime_modes_epoch_check", sql`${table.connectionEpoch} >= 1`),
1634
+ ownerSubjectValid: check(
1635
+ "session_realtime_modes_owner_subject_check",
1636
+ sql`octet_length(${table.ownerSubjectId}) between 1 and 1024`,
1637
+ ),
1638
+ browserInstanceValid: check(
1639
+ "session_realtime_modes_browser_instance_check",
1640
+ sql`octet_length(${table.browserInstanceId}) between 1 and 256`,
1641
+ ),
1642
+ ownerKeyHashValid: check(
1643
+ "session_realtime_modes_owner_key_hash_check",
1644
+ sql`${table.ownerKeyHash} ~ '^[0-9a-f]{64}$'`,
1645
+ ),
1646
+ leaseValid: check(
1647
+ "session_realtime_modes_lease_check",
1648
+ sql`${table.leaseExpiresAt} > ${table.lastHeartbeatAt}`,
1649
+ ),
1650
+ terminalValid: check(
1651
+ "session_realtime_modes_terminal_check",
1652
+ sql`(${table.state} = 'active' and ${table.endedAt} is null and ${table.endReason} is null)
1653
+ or (${table.state} = 'ended' and ${table.endedAt} is not null and ${table.endReason} is not null)`,
1654
+ ),
1655
+ }),
1656
+ );
1657
+
1658
+ export const sessionRealtimeConnections = pgTable(
1659
+ "session_realtime_connections",
1660
+ {
1661
+ id: uuid("id").primaryKey().defaultRandom(),
1662
+ accountId: uuid("account_id").notNull(),
1663
+ workspaceId: uuid("workspace_id").notNull(),
1664
+ sessionId: uuid("session_id").notNull(),
1665
+ realtimeId: uuid("realtime_id")
1666
+ .notNull()
1667
+ .references(() => sessionRealtimeModes.id, { onDelete: "cascade" }),
1668
+ operationId: uuid("operation_id").notNull(),
1669
+ connectionEpoch: integer("connection_epoch").notNull(),
1670
+ startupFenceSequence: integer("startup_fence_sequence").notNull().default(0),
1671
+ promotionMode: text("promotion_mode").notNull().default("legacy"),
1672
+ state: text("state").notNull().default("negotiating"),
1673
+ sdpAnswer: text("sdp_answer"),
1674
+ failureCode: text("failure_code"),
1675
+ providerSessionId: text("provider_session_id"),
1676
+ startupEventId: text("startup_event_id"),
1677
+ startupAcknowledgedAt: timestamp("startup_acknowledged_at", { withTimezone: true }),
1678
+ negotiatedAt: timestamp("negotiated_at", { withTimezone: true }),
1679
+ closedAt: timestamp("closed_at", { withTimezone: true }),
1680
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1681
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1682
+ },
1683
+ (table) => ({
1684
+ workspaceAccount: foreignKey({
1685
+ name: "session_realtime_connections_workspace_account_fk",
1686
+ columns: [table.workspaceId, table.accountId],
1687
+ foreignColumns: [workspaces.id, workspaces.accountId],
1688
+ }).onDelete("cascade"),
1689
+ workspaceSession: foreignKey({
1690
+ name: "session_realtime_connections_workspace_session_fk",
1691
+ columns: [table.workspaceId, table.sessionId],
1692
+ foreignColumns: [sessions.workspaceId, sessions.id],
1693
+ }).onDelete("cascade"),
1694
+ operation: uniqueIndex("session_realtime_connections_operation_uq").on(
1695
+ table.realtimeId,
1696
+ table.operationId,
1697
+ ),
1698
+ epoch: uniqueIndex("session_realtime_connections_epoch_uq").on(
1699
+ table.realtimeId,
1700
+ table.connectionEpoch,
1701
+ ),
1702
+ oneActive: uniqueIndex("session_realtime_connections_one_active_uq")
1703
+ .on(table.realtimeId)
1704
+ .where(
1705
+ sql`(${table.promotionMode} = 'legacy' and ${table.state} in ('negotiating', 'ready', 'active'))
1706
+ or (${table.promotionMode} = 'staged' and ${table.state} = 'active')`,
1707
+ ),
1708
+ onePreparing: uniqueIndex("session_realtime_connections_one_preparing_uq")
1709
+ .on(table.realtimeId)
1710
+ .where(
1711
+ sql`(${table.promotionMode} = 'legacy' and ${table.state} in ('negotiating', 'ready', 'active'))
1712
+ or (${table.promotionMode} = 'staged' and ${table.state} in ('negotiating', 'ready'))`,
1713
+ ),
1714
+ epochValid: check(
1715
+ "session_realtime_connections_epoch_check",
1716
+ sql`${table.connectionEpoch} >= 1`,
1717
+ ),
1718
+ startupFenceValid: check(
1719
+ "session_realtime_connections_startup_fence_check",
1720
+ sql`${table.startupFenceSequence} >= 0`,
1721
+ ),
1722
+ promotionModeValid: check(
1723
+ "session_realtime_connections_promotion_mode_check",
1724
+ sql`${table.promotionMode} in ('legacy', 'staged')`,
1725
+ ),
1726
+ stateValid: check(
1727
+ "session_realtime_connections_state_check",
1728
+ sql`${table.state} in ('negotiating', 'ready', 'active', 'failed', 'closed')`,
1729
+ ),
1730
+ sdpValid: check(
1731
+ "session_realtime_connections_sdp_check",
1732
+ sql`${table.sdpAnswer} is null or octet_length(${table.sdpAnswer}) between 1 and 1048576`,
1733
+ ),
1734
+ failureValid: check(
1735
+ "session_realtime_connections_failure_check",
1736
+ sql`${table.failureCode} is null or octet_length(${table.failureCode}) between 1 and 128`,
1737
+ ),
1738
+ providerSessionValid: check(
1739
+ "session_realtime_connections_provider_session_check",
1740
+ sql`${table.providerSessionId} is null or octet_length(${table.providerSessionId}) between 1 and 1024`,
1741
+ ),
1742
+ startupEventValid: check(
1743
+ "session_realtime_connections_startup_event_check",
1744
+ sql`${table.startupEventId} is null or octet_length(${table.startupEventId}) between 1 and 1024`,
1745
+ ),
1746
+ startupAckValid: check(
1747
+ "session_realtime_connections_startup_ack_check",
1748
+ sql`(${table.startupAcknowledgedAt} is null and ${table.providerSessionId} is null and ${table.startupEventId} is null)
1749
+ or (${table.startupAcknowledgedAt} is not null and ${table.providerSessionId} is not null)`,
1750
+ ),
1751
+ terminalValid: check(
1752
+ "session_realtime_connections_terminal_check",
1753
+ sql`(${table.state} = 'negotiating' and ${table.sdpAnswer} is null and ${table.failureCode} is null and ${table.negotiatedAt} is null and ${table.closedAt} is null)
1754
+ or (${table.state} = 'ready' and ${table.sdpAnswer} is not null and ${table.failureCode} is null and ${table.negotiatedAt} is not null and ${table.closedAt} is null)
1755
+ or (${table.state} = 'active' and ${table.sdpAnswer} is not null and ${table.failureCode} is null and ${table.negotiatedAt} is not null and ${table.closedAt} is null)
1756
+ or (${table.state} = 'failed' and ${table.sdpAnswer} is null and ${table.failureCode} is not null and ${table.closedAt} is not null)
1757
+ or (${table.state} = 'closed' and ${table.closedAt} is not null)`,
1758
+ ),
1759
+ }),
1760
+ );
1761
+
1762
+ export const sessionRealtimeEntries = pgTable(
1763
+ "session_realtime_entries",
1764
+ {
1765
+ id: uuid("id").primaryKey().defaultRandom(),
1766
+ accountId: uuid("account_id").notNull(),
1767
+ workspaceId: uuid("workspace_id").notNull(),
1768
+ sessionId: uuid("session_id").notNull(),
1769
+ realtimeId: uuid("realtime_id")
1770
+ .notNull()
1771
+ .references(() => sessionRealtimeModes.id, { onDelete: "cascade" }),
1772
+ operationId: uuid("operation_id").notNull(),
1773
+ connectionEpoch: integer("connection_epoch").notNull(),
1774
+ sequence: integer("sequence").notNull(),
1775
+ direction: text("direction").notNull(),
1776
+ kind: text("kind").notNull(),
1777
+ role: text("role"),
1778
+ providerEventId: text("provider_event_id"),
1779
+ delegationItemId: text("delegation_item_id"),
1780
+ // The referenced tables are declared later in this schema module; the
1781
+ // rolling migration owns all three ON DELETE SET NULL foreign keys.
1782
+ sourceUpdateId: uuid("source_update_id"),
1783
+ historyItemId: uuid("history_item_id"),
1784
+ // The rolling migration owns this ON DELETE SET NULL foreign key because
1785
+ // sessionTurns is declared later in this schema module. A non-null value
1786
+ // links the accepted provider call and its one terminal outbound
1787
+ // result/error to the same ordinary turn. It never denotes a child/fork
1788
+ // session.
1789
+ turnId: uuid("turn_id"),
1790
+ text: text("text"),
1791
+ payload: jsonb("payload").$type<Record<string, unknown>>().notNull().default({}),
1792
+ clientAckedAt: timestamp("client_acked_at", { withTimezone: true }),
1793
+ providerAckedAt: timestamp("provider_acked_at", { withTimezone: true }),
1794
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
1795
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
1796
+ },
1797
+ (table) => ({
1798
+ workspaceAccount: foreignKey({
1799
+ name: "session_realtime_entries_workspace_account_fk",
1800
+ columns: [table.workspaceId, table.accountId],
1801
+ foreignColumns: [workspaces.id, workspaces.accountId],
1802
+ }).onDelete("cascade"),
1803
+ workspaceSession: foreignKey({
1804
+ name: "session_realtime_entries_workspace_session_fk",
1805
+ columns: [table.workspaceId, table.sessionId],
1806
+ foreignColumns: [sessions.workspaceId, sessions.id],
1807
+ }).onDelete("cascade"),
1808
+ operation: uniqueIndex("session_realtime_entries_operation_uq").on(
1809
+ table.realtimeId,
1810
+ table.operationId,
1811
+ ),
1812
+ sequence: uniqueIndex("session_realtime_entries_sequence_uq").on(
1813
+ table.realtimeId,
1814
+ table.sequence,
1815
+ ),
1816
+ sourceUpdate: uniqueIndex("session_realtime_entries_source_update_uq")
1817
+ .on(table.realtimeId, table.sourceUpdateId)
1818
+ .where(sql`${table.sourceUpdateId} is not null`),
1819
+ delegationTurn: uniqueIndex("session_realtime_entries_delegation_turn_uq")
1820
+ .on(table.turnId)
1821
+ .where(sql`${table.kind} = 'delegation_call' and ${table.turnId} is not null`),
1822
+ delegationTerminal: uniqueIndex("session_realtime_entries_delegation_terminal_uq")
1823
+ .on(table.turnId)
1824
+ .where(
1825
+ sql`${table.direction} = 'provider_out' and ${table.kind} in ('delegation_result', 'error') and ${table.turnId} is not null`,
1826
+ ),
1827
+ delegationCall: uniqueIndex("session_realtime_entries_delegation_call_uq")
1828
+ .on(table.realtimeId, table.delegationItemId)
1829
+ .where(sql`${table.kind} = 'delegation_call' and ${table.delegationItemId} is not null`),
1830
+ outboundPending: index("session_realtime_entries_outbound_pending_idx")
1831
+ .on(table.realtimeId, table.sequence)
1832
+ .where(sql`${table.direction} = 'provider_out' and ${table.providerAckedAt} is null`),
1833
+ epochValid: check("session_realtime_entries_epoch_check", sql`${table.connectionEpoch} >= 1`),
1834
+ sequenceValid: check("session_realtime_entries_sequence_check", sql`${table.sequence} >= 1`),
1835
+ directionValid: check(
1836
+ "session_realtime_entries_direction_check",
1837
+ sql`${table.direction} in ('provider_in', 'provider_out')`,
1838
+ ),
1839
+ kindValid: check(
1840
+ "session_realtime_entries_kind_check",
1841
+ sql`${table.kind} in ('user_transcript', 'assistant_transcript', 'delegation_call', 'delegation_progress', 'delegation_result', 'interruption', 'session_update', 'error')`,
1842
+ ),
1843
+ roleValid: check(
1844
+ "session_realtime_entries_role_check",
1845
+ sql`${table.role} is null or ${table.role} in ('user', 'assistant')`,
1846
+ ),
1847
+ providerEventValid: check(
1848
+ "session_realtime_entries_provider_event_check",
1849
+ sql`${table.providerEventId} is null or octet_length(${table.providerEventId}) between 1 and 1024`,
1850
+ ),
1851
+ delegationItemValid: check(
1852
+ "session_realtime_entries_delegation_item_check",
1853
+ sql`${table.delegationItemId} is null or octet_length(${table.delegationItemId}) between 1 and 1024`,
1854
+ ),
1855
+ textValid: check(
1856
+ "session_realtime_entries_text_check",
1857
+ sql`${table.text} is null or octet_length(${table.text}) <= 131072`,
1858
+ ),
1859
+ payloadValid: check(
1860
+ "session_realtime_entries_payload_check",
1861
+ sql`octet_length(${table.payload}::text) <= 131072`,
1862
+ ),
1863
+ turnValid: check(
1864
+ "session_realtime_entries_turn_check",
1865
+ sql`${table.turnId} is null
1866
+ or (${table.kind} = 'delegation_call' and ${table.direction} = 'provider_in')
1867
+ or (${table.kind} in ('delegation_progress', 'delegation_result', 'error') and ${table.direction} = 'provider_out')`,
1868
+ ),
1869
+ transcriptValid: check(
1870
+ "session_realtime_entries_transcript_check",
1871
+ sql`(${table.kind} = 'user_transcript' and ${table.role} = 'user' and ${table.text} is not null)
1872
+ or (${table.kind} = 'assistant_transcript' and ${table.role} = 'assistant' and ${table.text} is not null)
1873
+ or (${table.kind} not in ('user_transcript', 'assistant_transcript') and ${table.role} is null)`,
1874
+ ),
1875
+ }),
1876
+ );
1877
+
1520
1878
  // A denied session create is durable evidence, not a mutable session/resource
1521
1879
  // artifact. It has its own workspace-scoped idempotency key so retries replay
1522
1880
  // the same denial without creating a session or billing/run rows.
@@ -1831,6 +2189,11 @@ export const documents = pgTable(
1831
2189
  sourceUpdatedAt: timestamp("source_updated_at", { withTimezone: true }),
1832
2190
  sourceVersion: text("source_version"),
1833
2191
  aclTags: jsonb("acl_tags").$type<string[]>().notNull().default([]),
2192
+ // Durable authorization tuple. The workspace_id above remains ingestion
2193
+ // provenance; organization authority deliberately has no workspace owner.
2194
+ authorityKind: text("authority_kind").notNull().default("workspace"),
2195
+ authorityWorkspaceId: uuid("authority_workspace_id"),
2196
+ authoritySubjectId: text("authority_subject_id"),
1834
2197
  // Per-document access controls. visibility 'private' restricts human reads to
1835
2198
  // created_by (a grant subject id, not a uuid); agent_access=false hides the
1836
2199
  // document from agent retrieval surfaces (docs MCP) while humans keep REST.
@@ -1868,6 +2231,28 @@ export const documents = pgTable(
1868
2231
  table.workspaceId,
1869
2232
  table.curationStatus,
1870
2233
  ),
2234
+ authority: index("documents_authority_idx").on(
2235
+ table.accountId,
2236
+ table.authorityKind,
2237
+ table.authorityWorkspaceId,
2238
+ table.authoritySubjectId,
2239
+ table.status,
2240
+ ),
2241
+ authorityWorkspaceAccount: foreignKey({
2242
+ name: "documents_authority_workspace_fk",
2243
+ columns: [table.authorityWorkspaceId, table.accountId],
2244
+ foreignColumns: [workspaces.id, workspaces.accountId],
2245
+ }).onDelete("restrict"),
2246
+ authorityState: check(
2247
+ "documents_authority_chk",
2248
+ sql`(${table.authorityKind} = 'organization' and ${table.authorityWorkspaceId} is null and ${table.authoritySubjectId} is null)
2249
+ or (${table.authorityKind} = 'workspace' and ${table.authorityWorkspaceId} = ${table.workspaceId} and ${table.authoritySubjectId} is null)
2250
+ or (${table.authorityKind} = 'personal' and ${table.authorityWorkspaceId} = ${table.workspaceId} and nullif(btrim(${table.authoritySubjectId}), '') is not null and octet_length(convert_to(${table.authoritySubjectId}, 'UTF8')) <= 1024 and ${table.authoritySubjectId} = ${table.createdBy})`,
2251
+ ),
2252
+ authorityVisibility: check(
2253
+ "documents_authority_visibility_chk",
2254
+ sql`(${table.authorityKind} = 'personal') = (${table.visibility} = 'private')`,
2255
+ ),
1871
2256
  visibilityState: check(
1872
2257
  "documents_visibility_chk",
1873
2258
  sql`${table.visibility} in ('workspace', 'private')`,
@@ -1910,6 +2295,9 @@ export const documentChunks = pgTable(
1910
2295
  chunkIndex: integer("chunk_index").notNull(),
1911
2296
  text: text("text").notNull(),
1912
2297
  metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
2298
+ authorityKind: text("authority_kind").notNull().default("workspace"),
2299
+ authorityWorkspaceId: uuid("authority_workspace_id"),
2300
+ authoritySubjectId: text("authority_subject_id"),
1913
2301
  embedding: vector("embedding").notNull(),
1914
2302
  embeddingModel: text("embedding_model").notNull(),
1915
2303
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
@@ -1921,6 +2309,23 @@ export const documentChunks = pgTable(
1921
2309
  table.chunkIndex,
1922
2310
  ),
1923
2311
  base: index("document_chunks_workspace_base_idx").on(table.workspaceId, table.baseId),
2312
+ authority: index("document_chunks_authority_idx").on(
2313
+ table.accountId,
2314
+ table.authorityKind,
2315
+ table.authorityWorkspaceId,
2316
+ table.authoritySubjectId,
2317
+ ),
2318
+ authorityWorkspaceAccount: foreignKey({
2319
+ name: "document_chunks_authority_workspace_fk",
2320
+ columns: [table.authorityWorkspaceId, table.accountId],
2321
+ foreignColumns: [workspaces.id, workspaces.accountId],
2322
+ }).onDelete("restrict"),
2323
+ authorityState: check(
2324
+ "document_chunks_authority_chk",
2325
+ sql`(${table.authorityKind} = 'organization' and ${table.authorityWorkspaceId} is null and ${table.authoritySubjectId} is null)
2326
+ or (${table.authorityKind} = 'workspace' and ${table.authorityWorkspaceId} = ${table.workspaceId} and ${table.authoritySubjectId} is null)
2327
+ or (${table.authorityKind} = 'personal' and ${table.authorityWorkspaceId} = ${table.workspaceId} and nullif(btrim(${table.authoritySubjectId}), '') is not null and octet_length(convert_to(${table.authoritySubjectId}, 'UTF8')) <= 1024)`,
2328
+ ),
1924
2329
  }),
1925
2330
  );
1926
2331
 
@@ -2082,6 +2487,11 @@ export const sessionTurns = pgTable(
2082
2487
  .$type<Record<string, unknown>>()
2083
2488
  .notNull()
2084
2489
  .default({ backfill: true }),
2490
+ // Immutable human authority for exact-attempt governance. Human turns bind
2491
+ // their own subject; trusted continuations/compactions may inherit the
2492
+ // causal turn's value while retaining a service initiator. Null means the
2493
+ // turn has no human preference authority.
2494
+ initiatingHumanSubjectId: text("initiating_human_subject_id"),
2085
2495
  // Immutable exact personal MCP authority for this logical turn. Recovery,
2086
2496
  // approval, retries, and Toolspace reuse this row; no runtime may infer
2087
2497
  // broader authority from the session creator or mutable session state.
@@ -2121,6 +2531,61 @@ export const sessionTurns = pgTable(
2121
2531
  }),
2122
2532
  );
2123
2533
 
2534
+ // One bounded audit/idempotency projection of an ended mode's transcript-tail
2535
+ // wrapper, bound to the exact ordinary Steer turn that durably carries it.
2536
+ export const sessionRealtimeContextProjections = pgTable(
2537
+ "session_realtime_context_projections",
2538
+ {
2539
+ id: uuid("id").primaryKey().defaultRandom(),
2540
+ accountId: uuid("account_id").notNull(),
2541
+ workspaceId: uuid("workspace_id").notNull(),
2542
+ sessionId: uuid("session_id").notNull(),
2543
+ turnId: uuid("turn_id").notNull(),
2544
+ context: text("context"),
2545
+ sourceModeCount: integer("source_mode_count").notNull(),
2546
+ sourceEntryCount: integer("source_entry_count").notNull(),
2547
+ includedEntryCount: integer("included_entry_count").notNull(),
2548
+ omittedEntryCount: integer("omitted_entry_count").notNull(),
2549
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
2550
+ },
2551
+ (table) => ({
2552
+ workspaceAccount: foreignKey({
2553
+ name: "session_realtime_context_projections_workspace_account_fk",
2554
+ columns: [table.workspaceId, table.accountId],
2555
+ foreignColumns: [workspaces.id, workspaces.accountId],
2556
+ }).onDelete("cascade"),
2557
+ workspaceSession: foreignKey({
2558
+ name: "session_realtime_context_projections_workspace_session_fk",
2559
+ columns: [table.workspaceId, table.sessionId],
2560
+ foreignColumns: [sessions.workspaceId, sessions.id],
2561
+ }).onDelete("cascade"),
2562
+ workspaceTurn: foreignKey({
2563
+ name: "session_realtime_context_projections_workspace_turn_fk",
2564
+ columns: [table.workspaceId, table.turnId],
2565
+ foreignColumns: [sessionTurns.workspaceId, sessionTurns.id],
2566
+ }).onDelete("cascade"),
2567
+ turn: uniqueIndex("session_realtime_context_projections_turn_uq").on(
2568
+ table.workspaceId,
2569
+ table.sessionId,
2570
+ table.turnId,
2571
+ ),
2572
+ contextValid: check(
2573
+ "session_realtime_context_projections_context_check",
2574
+ sql`${table.context} is null or octet_length(${table.context}) between 1 and 65536`,
2575
+ ),
2576
+ countsValid: check(
2577
+ "session_realtime_context_projections_counts_check",
2578
+ sql`${table.sourceModeCount} >= 1
2579
+ and ${table.sourceEntryCount} >= 0
2580
+ and ${table.includedEntryCount} >= 0
2581
+ and ${table.omittedEntryCount} >= 0
2582
+ and ${table.includedEntryCount} + ${table.omittedEntryCount} = ${table.sourceEntryCount}
2583
+ and ((${table.sourceEntryCount} = 0 and ${table.context} is null)
2584
+ or (${table.sourceEntryCount} > 0 and ${table.context} is not null))`,
2585
+ ),
2586
+ }),
2587
+ );
2588
+
2124
2589
  // First-class ownership for one accepted execution attempt. A workflow may
2125
2590
  // preallocate id, but this row is inserted only by the activity transaction
2126
2591
  // that actually claims the logical turn and registers its exact dispatch.
@@ -2849,14 +3314,10 @@ export const sessionGoals = pgTable(
2849
3314
  // update, timeline events, usage row, and workflow-wake outbox row.
2850
3315
  // Temporal signals and workflow history are replaceable nudges over these
2851
3316
  // monotonic revisions.
2852
- continuationWakeRevision: bigint("continuation_wake_revision", {
2853
- mode: "number",
2854
- })
3317
+ continuationWakeRevision: bigint("continuation_wake_revision", { mode: "number" })
2855
3318
  .notNull()
2856
3319
  .default(0),
2857
- continuationObservedRevision: bigint("continuation_observed_revision", {
2858
- mode: "number",
2859
- })
3320
+ continuationObservedRevision: bigint("continuation_observed_revision", { mode: "number" })
2860
3321
  .notNull()
2861
3322
  .default(0),
2862
3323
  metadata: jsonb("metadata").$type<Record<string, unknown>>().notNull().default({}),
@@ -3640,9 +4101,7 @@ export const sandboxLeaseHolders = pgTable(
3640
4101
  leaseId: uuid("lease_id")
3641
4102
  .notNull()
3642
4103
  .references(() => sandboxLeases.id, { onDelete: "cascade" }),
3643
- kind: text("kind", {
3644
- enum: ["turn", "viewer", "direct", "process"],
3645
- }).notNull(),
4104
+ kind: text("kind", { enum: ["turn", "viewer", "direct", "process"] }).notNull(),
3646
4105
  holderId: text("holder_id").notNull(),
3647
4106
  // The attributing session within the (possibly shared) group.
3648
4107
  subjectId: uuid("subject_id"),
@@ -3687,9 +4146,7 @@ export const sandboxWorkspaceMutationAdmissions = pgTable(
3687
4146
  .references(() => sandboxLeases.id, { onDelete: "cascade" }),
3688
4147
  sandboxGroupId: uuid("sandbox_group_id").notNull(),
3689
4148
  sessionId: uuid("session_id").notNull(),
3690
- actorKind: text("actor_kind", {
3691
- enum: sandboxWorkspaceMutationActorKindValues,
3692
- }).notNull(),
4149
+ actorKind: text("actor_kind", { enum: sandboxWorkspaceMutationActorKindValues }).notNull(),
3693
4150
  actorId: uuid("actor_id").notNull(),
3694
4151
  // Exact turn authority is present only for actor_kind='turn'. Direct HTTP
3695
4152
  // requests and retained processes never invent a turn or quiescence owner.
@@ -3836,9 +4293,7 @@ export const sandboxRetainedProcesses = pgTable(
3836
4293
  sandboxGroupId: uuid("sandbox_group_id").notNull(),
3837
4294
  parentAdmissionId: uuid("parent_admission_id").notNull(),
3838
4295
  holderId: text("holder_id").notNull(),
3839
- ownerActorKind: text("owner_actor_kind", {
3840
- enum: ["turn", "direct"],
3841
- }).notNull(),
4296
+ ownerActorKind: text("owner_actor_kind", { enum: ["turn", "direct"] }).notNull(),
3842
4297
  ownerActorId: uuid("owner_actor_id").notNull(),
3843
4298
  ownerTurnId: uuid("owner_turn_id"),
3844
4299
  ownerAttemptId: uuid("owner_attempt_id"),
@@ -3866,19 +4321,13 @@ export const sandboxRetainedProcesses = pgTable(
3866
4321
  // never exit/loss proof.
3867
4322
  reconcileAfter: timestamp("reconcile_after", { withTimezone: true }).notNull().defaultNow(),
3868
4323
  reconcileClaimId: uuid("reconcile_claim_id"),
3869
- reconcileClaimedAt: timestamp("reconcile_claimed_at", {
3870
- withTimezone: true,
3871
- }),
4324
+ reconcileClaimedAt: timestamp("reconcile_claimed_at", { withTimezone: true }),
3872
4325
  reconcileAttempts: integer("reconcile_attempts").notNull().default(0),
3873
4326
  lastReconcileOutcome: text("last_reconcile_outcome"),
3874
- reconcileProofOutcome: text("reconcile_proof_outcome", {
3875
- enum: ["exited", "lost"],
3876
- }),
4327
+ reconcileProofOutcome: text("reconcile_proof_outcome", { enum: ["exited", "lost"] }),
3877
4328
  reconcileProofExitCode: integer("reconcile_proof_exit_code"),
3878
4329
  reconcileProofReason: text("reconcile_proof_reason"),
3879
- reconcileProofObservedAt: timestamp("reconcile_proof_observed_at", {
3880
- withTimezone: true,
3881
- }),
4330
+ reconcileProofObservedAt: timestamp("reconcile_proof_observed_at", { withTimezone: true }),
3882
4331
  },
3883
4332
  (table) => ({
3884
4333
  workspaceAccount: foreignKey({
@@ -4640,12 +5089,8 @@ export const githubInstallations = pgTable(
4640
5089
  githubActorId: bigint("github_actor_id", { mode: "number" }),
4641
5090
  githubActorLogin: text("github_actor_login"),
4642
5091
  authorityKind: text("authority_kind"),
4643
- authorityCheckedAt: timestamp("authority_checked_at", {
4644
- withTimezone: true,
4645
- }),
4646
- authorityExpiresAt: timestamp("authority_expires_at", {
4647
- withTimezone: true,
4648
- }),
5092
+ authorityCheckedAt: timestamp("authority_checked_at", { withTimezone: true }),
5093
+ authorityExpiresAt: timestamp("authority_expires_at", { withTimezone: true }),
4649
5094
  authorityNonce: text("authority_nonce"),
4650
5095
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
4651
5096
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
@@ -4975,9 +5420,7 @@ export const hostExportOutbox = pgTable(
4975
5420
  payload: jsonb("payload").$type<unknown>().notNull(),
4976
5421
  envelopeBytes: integer("envelope_bytes").notNull(),
4977
5422
  occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),
4978
- sourceRecordedAt: timestamp("source_recorded_at", {
4979
- withTimezone: true,
4980
- }).notNull(),
5423
+ sourceRecordedAt: timestamp("source_recorded_at", { withTimezone: true }).notNull(),
4981
5424
  enqueuedAt: timestamp("enqueued_at", { withTimezone: true }).notNull(),
4982
5425
  },
4983
5426
  (table) => ({