@opengeni/db 0.36.1 → 3.1.0-canary.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 (274) hide show
  1. package/dist/attached-browser-devices.d.ts +7 -0
  2. package/dist/automations.d.ts +154 -0
  3. package/dist/canonical-human-identities.js +3 -3
  4. package/dist/capability-integrations.d.ts +13 -0
  5. package/dist/child-lifecycle-notices.d.ts +68 -0
  6. package/dist/{chunk-GYO7ED2Q.js → chunk-EULAN2NP.js} +2 -2
  7. package/dist/{chunk-VTPRIXKG.js → chunk-NJVZPWXY.js} +3 -3
  8. package/dist/{chunk-HSOWSYOX.js → chunk-NMUBV7Z5.js} +19 -11
  9. package/dist/chunk-NMUBV7Z5.js.map +1 -0
  10. package/dist/chunk-OF5OBB76.js +4457 -0
  11. package/dist/chunk-OF5OBB76.js.map +1 -0
  12. package/dist/{chunk-5KTIEDX7.js → chunk-PR2WMLOQ.js} +7714 -4443
  13. package/dist/chunk-PR2WMLOQ.js.map +1 -0
  14. package/dist/{chunk-Z7VYMNPZ.js → chunk-SCPUJS53.js} +41 -4
  15. package/dist/chunk-SCPUJS53.js.map +1 -0
  16. package/dist/{chunk-SK7YYHBI.js → chunk-SIBYBA2D.js} +46 -1
  17. package/dist/chunk-SIBYBA2D.js.map +1 -0
  18. package/dist/chunk-TIKF3KTI.js +383 -0
  19. package/dist/chunk-TIKF3KTI.js.map +1 -0
  20. package/dist/chunk-ZZ5LJEFX.js +516 -0
  21. package/dist/chunk-ZZ5LJEFX.js.map +1 -0
  22. package/dist/codemode-operations.d.ts +1 -6
  23. package/dist/company-brain-context-selection-schema.d.ts +705 -0
  24. package/dist/company-brain-context-selection.d.ts +94 -0
  25. package/dist/company-brain-governed-writes.d.ts +24 -0
  26. package/dist/company-brain.d.ts +55 -0
  27. package/dist/company-profile-agent-admin.d.ts +15 -0
  28. package/dist/company-profile-schema.d.ts +619 -2
  29. package/dist/company-profile.d.ts +9 -4
  30. package/dist/connection-authority.d.ts +95 -0
  31. package/dist/connection-scopes.d.ts +8 -0
  32. package/dist/connection-tenancy-backfill.d.ts +41 -0
  33. package/dist/connection-token-resolver.d.ts +30 -1
  34. package/dist/database.d.ts +19 -0
  35. package/dist/editable-artifact-durable-export.d.ts +10 -0
  36. package/dist/editable-artifact-durable-export.js +18 -3
  37. package/dist/editable-artifact-durable-export.js.map +1 -1
  38. package/dist/editable-artifacts.d.ts +2 -2
  39. package/dist/editable-artifacts.js +3 -3
  40. package/dist/governed-learning-activation-schema.d.ts +984 -0
  41. package/dist/governed-learning-activation.d.ts +98 -0
  42. package/dist/governed-learning-evaluator-schema.d.ts +633 -0
  43. package/dist/governed-learning-evaluator.d.ts +28 -0
  44. package/dist/index.d.ts +1633 -87
  45. package/dist/index.js +22004 -8109
  46. package/dist/index.js.map +1 -1
  47. package/dist/insights.d.ts +18 -0
  48. package/dist/integration-bindings.d.ts +1 -0
  49. package/dist/integration-facets.d.ts +30 -0
  50. package/dist/interaction-placement-loss.d.ts +22 -0
  51. package/dist/knowledge-source-sync-schema.d.ts +730 -0
  52. package/dist/knowledge-source-sync.d.ts +60 -0
  53. package/dist/managed-human-provisioning.d.ts +25 -0
  54. package/dist/memory-domain.d.ts +3 -3
  55. package/dist/migrate.d.ts +11 -1
  56. package/dist/migrate.js +1 -1
  57. package/dist/new-session-drafts.d.ts +43 -5
  58. package/dist/organization-membership-backfill.d.ts +174 -0
  59. package/dist/organization-membership-lifecycle.d.ts +162 -0
  60. package/dist/pr-review.d.ts +107 -0
  61. package/dist/preference-registry-schema.d.ts +2 -0
  62. package/dist/preference-registry.d.ts +2 -0
  63. package/dist/provision-roles.js +1 -1
  64. package/dist/runtime-posture.d.ts +23 -9
  65. package/dist/schema.d.ts +24925 -13697
  66. package/dist/schema.js +103 -1
  67. package/dist/scoped-knowledge-schema.d.ts +52 -1
  68. package/dist/session-background-commands.d.ts +125 -0
  69. package/dist/session-background-commands.js +34 -0
  70. package/dist/session-background-commands.js.map +1 -0
  71. package/dist/session-control.d.ts +156 -3
  72. package/dist/session-goal-pacing.d.ts +68 -0
  73. package/dist/session-queue-commands.d.ts +42 -5
  74. package/dist/session-realtime-ledger.d.ts +3 -0
  75. package/dist/session-tenancy.d.ts +71 -1
  76. package/dist/session-tenancy.js +25 -3
  77. package/dist/session-tool-call-settlement.d.ts +9 -4
  78. package/dist/slack-routing-personal-workspace.d.ts +23 -0
  79. package/dist/slack-routing.d.ts +153 -0
  80. package/dist/slack-task-policy-schema.d.ts +34 -0
  81. package/dist/slack-task-policy.d.ts +8 -0
  82. package/dist/slack-user-link-access.d.ts +1 -0
  83. package/dist/task-notes-schema.d.ts +594 -0
  84. package/dist/task-notes.d.ts +39 -0
  85. package/dist/turn-initiator.d.ts +2 -0
  86. package/dist/user-resource-authority.d.ts +109 -0
  87. package/dist/video-generation.js +3 -3
  88. package/dist/workspace-authority.d.ts +81 -0
  89. package/dist/workspace-instruction-policies-schema.d.ts +279 -0
  90. package/dist/workspace-instruction-policies.d.ts +62 -0
  91. package/dist/workspace-learning-policy.d.ts +1 -0
  92. package/dist/workspace-membership-permissions.d.ts +2 -0
  93. package/drizzle/0240_enrollment_connection_authority.sql +39 -0
  94. package/drizzle/0240_model_context_user_messages.sql +204 -0
  95. package/drizzle/0241_atomic_personal_resource_delegation.sql +1000 -0
  96. package/drizzle/0241_enrollment_agent_runtime.sql +70 -0
  97. package/drizzle/0243_google_drive_object_acl_authority.sql +554 -0
  98. package/drizzle/0244_slack_app_home_refresh_queue.sql +120 -0
  99. package/drizzle/0245_model_context_contribution_facts.sql +88 -0
  100. package/drizzle/0246_integration_personal_instance_authority.sql +70 -0
  101. package/drizzle/0247_terraform_stacks_provenance_repair.sql +428 -0
  102. package/drizzle/0248_terraform_stacks_component_resolution_fence.sql +83 -0
  103. package/drizzle/0249_personal_resource_delegation_authority_correction.sql +662 -0
  104. package/drizzle/0250_direct_retained_process_owner_liveness.sql +199 -0
  105. package/drizzle/0251_connected_machine_operation_policy.sql +45 -0
  106. package/drizzle/0252_scheduled_personal_resource_delegation.sql +1867 -0
  107. package/drizzle/0253_common_user_resource_authority_lifecycle.sql +1555 -0
  108. package/drizzle/0254_scoped_variable_set_authority.sql +1255 -0
  109. package/drizzle/0255_company_brain_governed_write_proposals.sql +524 -0
  110. package/drizzle/0256_connection_authority_delegation.sql +703 -0
  111. package/drizzle/0257_goal_revision_decisions_and_root_constraints.sql +436 -0
  112. package/drizzle/0258_three_scope_document_knowledge_authority.sql +1273 -0
  113. package/drizzle/0259_company_brain_context_selection_receipts.sql +869 -0
  114. package/drizzle/0260_task_note_knowledge_promotion.sql +820 -0
  115. package/drizzle/0261_preference_knowledge_proposal_actor_binding.sql +471 -0
  116. package/drizzle/0262_scoped_connected_machines_and_rigs.sql +1700 -0
  117. package/drizzle/0263_organization_membership_lifecycle.sql +3284 -0
  118. package/drizzle/0264_connection_authority_runtime_activation.sql +1084 -0
  119. package/drizzle/0266_company_brain_context_receipt_inspection.sql +156 -0
  120. package/drizzle/0268_governed_learning_decision_receipts.sql +825 -0
  121. package/drizzle/0269_governed_learning_activation_controller.sql +1874 -0
  122. package/drizzle/0270_governed_learning_history_inspection.sql +170 -0
  123. package/drizzle/0271_company_brain_retrieval_only_default.sql +524 -0
  124. package/drizzle/0272_human_confirmed_learning_activation.sql +591 -0
  125. package/drizzle/0273_scheduled_variable_set_materialization.sql +268 -0
  126. package/drizzle/0274_human_confirmed_knowledge_review.sql +310 -0
  127. package/drizzle/0275_scheduled_connection_authority.sql +5527 -0
  128. package/drizzle/0276_onboarding_proposal_initiating_human_guc.sql +198 -0
  129. package/drizzle/0277_workspace_writer_authority_attribution.sql +393 -0
  130. package/drizzle/0278_workspace_membership_removal_fencing.sql +1174 -0
  131. package/drizzle/0279_workspace_connection_use_lane.sql +343 -0
  132. package/drizzle/0280_connection_and_variable_set_audit_attribution.sql +773 -0
  133. package/drizzle/0281_viewer_holder_authority_claims.sql +52 -0
  134. package/drizzle/0282_variable_set_session_attach_attribution.sql +178 -0
  135. package/drizzle/0283_editable_spreadsheet_authored_state.sql +82 -0
  136. package/drizzle/0284_truthful_human_confirmed_review_reason.sql +930 -0
  137. package/drizzle/0285_organization_tenancy_inventory.sql +329 -0
  138. package/drizzle/0286_widen_task_note_expiry_ceiling.sql +391 -0
  139. package/drizzle/0287_open_suffix_pending_tool_calls.sql +18 -0
  140. package/drizzle/0288_attached_browser_reenrollment.sql +64 -0
  141. package/drizzle/0289_session_composer_policy_authority.sql +597 -0
  142. package/drizzle/0290_organization_membership_backfill.sql +268 -0
  143. package/drizzle/0291_resource_authority_classification_assertion.sql +371 -0
  144. package/drizzle/0292_truthful_tenancy_inventory_counters.sql +291 -0
  145. package/drizzle/0293_confirm_time_rule_rebaseline.sql +615 -0
  146. package/drizzle/0294_preference_activation_authority.sql +237 -0
  147. package/drizzle/0295_retire_legacy_standing_memory_mode.sql +476 -0
  148. package/drizzle/0296_force_rls_backfill_noop_repair.sql +215 -0
  149. package/drizzle/0297_session_ownership_classification_and_backfill.sql +752 -0
  150. package/drizzle/0298_organization_tenancy_parity.sql +609 -0
  151. package/drizzle/0299_organization_membership_lock_order.sql +291 -0
  152. package/drizzle/0300_tenancy_backfill_ledger.sql +459 -0
  153. package/drizzle/0301_session_snapshot_and_pin_visibility.sql +181 -0
  154. package/drizzle/0302_personal_workspace_session_ownership.sql +303 -0
  155. package/drizzle/0303_session_tenancy_product_activation.sql +919 -0
  156. package/drizzle/0304_personal_workspace_private_session_reads.sql +97 -0
  157. package/drizzle/0305_personal_resource_grant_management.sql +584 -0
  158. package/drizzle/0306_atomic_personal_resource_attachments.sql +1374 -0
  159. package/drizzle/0307_session_attention_state.sql +51 -0
  160. package/drizzle/0308_session_archives.sql +35 -0
  161. package/drizzle/0309_channel_project_pins.sql +6 -0
  162. package/drizzle/0310_channel_project_order.sql +27 -0
  163. package/drizzle/0311_company_scope_and_private_session_create.sql +656 -0
  164. package/drizzle/0312_quiescent_session_tree_deletion.sql +39 -0
  165. package/drizzle/0313_private_child_session_authority.sql +365 -0
  166. package/drizzle/0314_unregistered_organization_invitations.sql +606 -0
  167. package/drizzle/0315_personal_github_repository_selection.sql +624 -0
  168. package/drizzle/0316_human_confirmed_activation_resumed_generation.sql +869 -0
  169. package/drizzle/0317_session_goal_continuation_hold.sql +64 -0
  170. package/drizzle/0318_session_turn_startup_milestones.sql +115 -0
  171. package/drizzle/0319_event_triggered_automations.sql +254 -0
  172. package/drizzle/0320_pr_review_pack.sql +113 -0
  173. package/drizzle/0321_slack_bot_environment_display_name.sql +15 -0
  174. package/drizzle/0322_session_turns_unclaimed_prompt_trigger_index.sql +5 -0
  175. package/drizzle/0323_organization_private_session_enablement.sql +489 -0
  176. package/drizzle/0324_human_confirmed_company_profile_agent_admin.sql +856 -0
  177. package/drizzle/0325_child_lifecycle_notices.sql +44 -0
  178. package/drizzle/0326_interaction_operation_error_codes.sql +62 -0
  179. package/drizzle/0327_slack_first_task_hint.sql +29 -0
  180. package/drizzle/0328_session_background_commands.sql +590 -0
  181. package/drizzle/0329_slack_orchestration_delivery_events.sql +91 -0
  182. package/drizzle/0330_api_key_descriptions.sql +20 -0
  183. package/drizzle/0331_managed_organization_creation.sql +163 -0
  184. package/drizzle/0332_organization_shared_workspace_control_plane.sql +539 -0
  185. package/drizzle/0333_session_turn_prompt_routing.sql +45 -0
  186. package/drizzle/0334_connected_machine_workspace_root.sql +99 -0
  187. package/drizzle/0335_slack_workspace_routing.sql +460 -0
  188. package/drizzle/0336_atomic_session_fork_visibility.sql +667 -0
  189. package/drizzle/0337_slack_routed_action_handles.sql +189 -0
  190. package/drizzle/0338_atomic_connected_machine_attachments.sql +410 -0
  191. package/drizzle/0339_document_authority_reclassification.sql +1153 -0
  192. package/drizzle/0340_tenancy_backfill_activation_evidence.sql +1347 -0
  193. package/drizzle/0341_slack_routing_probe_organization_fence.sql +109 -0
  194. package/package.json +10 -6
  195. package/src/attached-browser-devices.ts +233 -5
  196. package/src/automations.ts +911 -0
  197. package/src/browser-sessions.ts +10 -0
  198. package/src/capability-integrations.ts +175 -1
  199. package/src/child-lifecycle-notices.ts +241 -0
  200. package/src/codemode-operations.ts +1 -35
  201. package/src/company-brain-context-selection-schema.ts +100 -0
  202. package/src/company-brain-context-selection.ts +359 -0
  203. package/src/company-brain-governed-writes.ts +1170 -0
  204. package/src/company-brain.ts +309 -0
  205. package/src/company-profile-agent-admin.ts +225 -0
  206. package/src/company-profile-schema.ts +121 -1
  207. package/src/company-profile.ts +21 -0
  208. package/src/computer-sessions.ts +10 -1
  209. package/src/connection-authority.ts +290 -0
  210. package/src/connection-scopes.ts +20 -0
  211. package/src/connection-tenancy-backfill.ts +81 -0
  212. package/src/connection-token-resolver.ts +263 -31
  213. package/src/database.ts +75 -2
  214. package/src/editable-artifact-durable-export.ts +27 -0
  215. package/src/editable-artifacts-schema.ts +10 -5
  216. package/src/editable-artifacts.ts +21 -11
  217. package/src/governed-learning-activation-schema.ts +121 -0
  218. package/src/governed-learning-activation.ts +588 -0
  219. package/src/governed-learning-evaluator-schema.ts +72 -0
  220. package/src/governed-learning-evaluator.ts +217 -0
  221. package/src/index.ts +12001 -1699
  222. package/src/insights.ts +107 -0
  223. package/src/integration-bindings.ts +88 -6
  224. package/src/integration-facets.ts +287 -84
  225. package/src/interaction-placement-loss.ts +234 -0
  226. package/src/knowledge-source-sync-schema.ts +83 -0
  227. package/src/knowledge-source-sync.ts +530 -0
  228. package/src/managed-human-provisioning.ts +116 -0
  229. package/src/memory-domain.ts +27 -32
  230. package/src/migrate.ts +77 -1
  231. package/src/new-session-drafts.ts +229 -35
  232. package/src/organization-membership-backfill.ts +735 -0
  233. package/src/organization-membership-lifecycle.ts +985 -0
  234. package/src/pr-review.ts +890 -0
  235. package/src/preference-registry.ts +31 -1
  236. package/src/provision-roles.ts +931 -24
  237. package/src/runtime-posture-cli.ts +2 -0
  238. package/src/runtime-posture.ts +1315 -52
  239. package/src/schema.ts +3336 -438
  240. package/src/scoped-knowledge-schema.ts +16 -8
  241. package/src/scoped-knowledge.ts +1 -1
  242. package/src/session-background-commands.ts +759 -0
  243. package/src/session-control.ts +640 -74
  244. package/src/session-goal-pacing.ts +126 -0
  245. package/src/session-queue-commands.ts +450 -98
  246. package/src/session-realtime-context.ts +19 -3
  247. package/src/session-realtime-ledger.ts +75 -12
  248. package/src/session-realtime-mirror.ts +1 -1
  249. package/src/session-tenancy.ts +403 -49
  250. package/src/session-tool-call-settlement.ts +38 -29
  251. package/src/slack-routing-personal-workspace.ts +67 -0
  252. package/src/slack-routing.ts +469 -0
  253. package/src/slack-task-policy-schema.ts +5 -0
  254. package/src/slack-task-policy.ts +18 -0
  255. package/src/slack-user-link-access.ts +17 -1
  256. package/src/task-notes-schema.ts +74 -0
  257. package/src/task-notes.ts +124 -2
  258. package/src/turn-initiator.ts +8 -0
  259. package/src/user-resource-authority.ts +377 -0
  260. package/src/workspace-authority.ts +160 -0
  261. package/src/workspace-instruction-policies-schema.ts +53 -1
  262. package/src/workspace-instruction-policies.ts +528 -77
  263. package/src/workspace-learning-policy.ts +21 -5
  264. package/src/workspace-membership-permissions.ts +9 -0
  265. package/dist/chunk-5KTIEDX7.js.map +0 -1
  266. package/dist/chunk-FPVAD4CO.js +0 -117
  267. package/dist/chunk-FPVAD4CO.js.map +0 -1
  268. package/dist/chunk-HSOWSYOX.js.map +0 -1
  269. package/dist/chunk-SK7YYHBI.js.map +0 -1
  270. package/dist/chunk-VKLB2ZGI.js +0 -2389
  271. package/dist/chunk-VKLB2ZGI.js.map +0 -1
  272. package/dist/chunk-Z7VYMNPZ.js.map +0 -1
  273. /package/dist/{chunk-GYO7ED2Q.js.map → chunk-EULAN2NP.js.map} +0 -0
  274. /package/dist/{chunk-VTPRIXKG.js.map → chunk-NJVZPWXY.js.map} +0 -0
@@ -0,0 +1,4457 @@
1
+ // src/provision-roles.ts
2
+ import postgres from "postgres";
3
+
4
+ // src/runtime-posture.ts
5
+ import { sql } from "drizzle-orm";
6
+
7
+ // src/role-relationships.ts
8
+ function roleRelationshipsCatalogQuery(targetRole) {
9
+ return `
10
+ with recursive target_role(oid, rolname) as (
11
+ select oid, rolname
12
+ from pg_roles
13
+ where rolname = ${targetRole}
14
+ ), inherited_roles(oid, rolname) as (
15
+ select parent.oid, parent.rolname
16
+ from pg_auth_members membership
17
+ join target_role target on target.oid = membership.member
18
+ join pg_roles parent on parent.oid = membership.roleid
19
+ union
20
+ select parent.oid, parent.rolname
21
+ from inherited_roles inherited
22
+ join pg_auth_members membership on membership.member = inherited.oid
23
+ join pg_roles parent on parent.oid = membership.roleid
24
+ ), relationships as (
25
+ select
26
+ ('inherits:' || inherited.rolname)::text as relationship,
27
+ 'inherits'::text as direction,
28
+ null::boolean as admin_option,
29
+ null::boolean as inherit_option,
30
+ null::boolean as set_option,
31
+ null::boolean as member_is_superuser,
32
+ null::boolean as member_can_create_role,
33
+ null::text as grantor_role,
34
+ null::boolean as grantor_is_superuser
35
+ from inherited_roles inherited
36
+ union all
37
+ select
38
+ ('member:' || member.rolname)::text as relationship,
39
+ 'member'::text as direction,
40
+ membership.admin_option,
41
+ case
42
+ when current_setting('server_version_num')::integer >= 160000
43
+ then (to_jsonb(membership) ->> 'inherit_option')::boolean
44
+ else null::boolean
45
+ end as inherit_option,
46
+ case
47
+ when current_setting('server_version_num')::integer >= 160000
48
+ then (to_jsonb(membership) ->> 'set_option')::boolean
49
+ else null::boolean
50
+ end as set_option,
51
+ member.rolsuper as member_is_superuser,
52
+ member.rolcreaterole as member_can_create_role,
53
+ grantor.rolname::text as grantor_role,
54
+ grantor.rolsuper as grantor_is_superuser
55
+ from pg_auth_members membership
56
+ join target_role target on target.oid = membership.roleid
57
+ join pg_roles member on member.oid = membership.member
58
+ left join pg_roles grantor on grantor.oid = membership.grantor
59
+ )
60
+ select
61
+ relationship,
62
+ direction,
63
+ current_setting('server_version_num')::integer as server_version_num,
64
+ admin_option,
65
+ inherit_option,
66
+ set_option,
67
+ member_is_superuser,
68
+ member_can_create_role,
69
+ grantor_role,
70
+ grantor_is_superuser
71
+ from relationships
72
+ order by relationship, direction, grantor_role nulls first
73
+ `;
74
+ }
75
+ function isManagementOnlyRoleRelationship(row) {
76
+ return row.direction === "member" && row.server_version_num >= 16e4 && row.admin_option === true && row.inherit_option === false && row.set_option === false && row.member_is_superuser === false && row.member_can_create_role === true && row.grantor_is_superuser === true;
77
+ }
78
+ function sortedUnique(values) {
79
+ return [...new Set(values)].sort((a, b) => a.localeCompare(b));
80
+ }
81
+ function classifyRoleRelationships(rows) {
82
+ const managementOnlyRows = rows.filter(isManagementOnlyRoleRelationship);
83
+ const unsafeRows = rows.filter((row) => !isManagementOnlyRoleRelationship(row));
84
+ return {
85
+ relationships: sortedUnique(rows.map((row) => row.relationship)),
86
+ managementOnlyRelationships: sortedUnique(managementOnlyRows.map((row) => row.relationship)),
87
+ unsafeRelationships: sortedUnique(unsafeRows.map((row) => row.relationship))
88
+ };
89
+ }
90
+
91
+ // src/runtime-posture.ts
92
+ var ARTIFACT_OUTBOX_CAPABILITY_ROUTINES = [
93
+ "claim_editable_artifact_live_outbox(text, integer, integer, name)",
94
+ "mark_editable_artifact_live_outbox_published(text, text, integer, name)",
95
+ "renew_editable_artifact_live_outbox(text, text, integer, integer, name)",
96
+ "retry_editable_artifact_live_outbox(text, text, integer, integer, text, name)",
97
+ "dead_letter_editable_artifact_live_outbox(text, text, integer, text, name)",
98
+ "release_editable_artifact_live_outbox(text, text, integer, name)"
99
+ ];
100
+ var ARTIFACT_MATERIALIZER_CAPABILITY_ROUTINES = [
101
+ "claim_editable_artifact_materializations(text, integer, integer, name)",
102
+ "renew_editable_artifact_materialization(uuid, uuid, text, text, text, integer, integer, name)",
103
+ "succeed_editable_artifact_materialization(uuid, uuid, text, text, text, integer, text, text, text, bigint, text, text, timestamp with time zone, name)",
104
+ "fail_editable_artifact_materialization(uuid, uuid, text, text, text, integer, text, name)"
105
+ ];
106
+ var ARTIFACT_LIVE_TICKET_CAPABILITY_ROUTINES = [
107
+ "put_editable_artifact_live_ticket(text, uuid, uuid, text, text, text, text, text, text, text, text, integer, text, boolean, integer, timestamp with time zone, timestamp with time zone, name)",
108
+ "consume_editable_artifact_live_ticket(text, name)",
109
+ "cleanup_expired_editable_artifact_live_tickets(integer, name)"
110
+ ];
111
+ var ARTIFACT_LIVE_TICKET_INTERNAL_ROUTINES = [
112
+ "resolve_editable_artifact_ticket_data_schema(name)"
113
+ ];
114
+ var ARTIFACT_AUTHORIZATION_CAPABILITY_ROUTINES = [
115
+ "authorize_editable_artifact_actor(uuid, uuid, text, text, text, text, text, text, integer, text, text, name)"
116
+ ];
117
+ var DEDICATED_ARTIFACT_CAPABILITY_ROUTINES = /* @__PURE__ */ new Set([
118
+ ...ARTIFACT_OUTBOX_CAPABILITY_ROUTINES,
119
+ ...ARTIFACT_MATERIALIZER_CAPABILITY_ROUTINES,
120
+ ...ARTIFACT_LIVE_TICKET_INTERNAL_ROUTINES
121
+ ]);
122
+ var KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_ROUTINE = "knowledge_source_sync_lock_authority(uuid, uuid, uuid)";
123
+ var GOOGLE_DRIVE_FILE_AUTHORIZATION_ROUTINE = "google_drive_file_authorized(uuid, uuid, text, uuid)";
124
+ var GOOGLE_DRIVE_DOCUMENT_CITATION_ROUTINE = "google_drive_document_citation(uuid, uuid, text, uuid, uuid)";
125
+ var GOOGLE_DRIVE_AUTHORITY_TABLES = [
126
+ "connections",
127
+ "files",
128
+ "google_drive_object_acl_evidence",
129
+ "google_drive_object_acl_principals",
130
+ "knowledge_document_versions",
131
+ "knowledge_providers",
132
+ "knowledge_source_objects",
133
+ "knowledge_source_sync_index_obligations",
134
+ "knowledge_source_sync_states",
135
+ "knowledge_sources"
136
+ ];
137
+ var KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_TABLES = [
138
+ "knowledge_sources",
139
+ "knowledge_source_objects"
140
+ ];
141
+ var MANAGED_HUMAN_PERSONAL_WORKSPACE_ROUTINE = "ensure_managed_human_personal_workspace(uuid, text, uuid)";
142
+ var ORGANIZATION_MEMBERSHIP_LIFECYCLE_ROUTINES = [
143
+ "list_self_organization_memberships(text)",
144
+ "list_self_organization_invitations(text)",
145
+ "list_self_organization_invitations(text, uuid, integer)",
146
+ "get_self_organization_invitation(text, uuid)",
147
+ "list_organization_invitations(uuid, text, uuid, integer)",
148
+ "list_organization_members(uuid, text)",
149
+ "get_organization_administration_overview(uuid, text)",
150
+ "create_managed_organization(text, text, text, uuid)",
151
+ "assert_organization_shared_workspace_administrator(uuid, uuid, text)",
152
+ "open_organization_shared_workspace_administration_capability(uuid, uuid, text)",
153
+ "close_organization_shared_workspace_administration_capability(uuid)",
154
+ "create_organization_shared_workspace(uuid, text, text, text, text, uuid)",
155
+ "upsert_organization_shared_workspace_member(uuid, uuid, text, uuid, text, text, jsonb, boolean)",
156
+ "update_organization_name(uuid, text, text, timestamp with time zone, uuid)",
157
+ "create_organization_invitation_v2(jsonb)",
158
+ "bind_pending_organization_invitations_for_verified_email(text, text)",
159
+ "has_pending_organization_invitation_for_subject(text)",
160
+ "accept_organization_invitation_v2(jsonb)",
161
+ "organization_membership_command(jsonb)",
162
+ "prepare_organization_membership_protocol_settlements(jsonb)",
163
+ "assert_active_managed_human_organization_membership(uuid, text)",
164
+ "resolve_workspace_writer_grant_identity(uuid, text)",
165
+ "prepare_workspace_membership_removal_settlements(jsonb)",
166
+ "workspace_membership_removal_command(jsonb)",
167
+ "get_organization_retention_policy(uuid, text)",
168
+ "preview_organization_retention_deletions(uuid, integer)",
169
+ "claim_organization_retention_deletion(uuid, uuid, uuid[])",
170
+ "list_organization_retention_deletion_objects(uuid, uuid, uuid, text, integer)",
171
+ "record_organization_retention_object_deleted(uuid, uuid, uuid, text, text, text, text)",
172
+ "fail_organization_retention_deletion(uuid, uuid, uuid, text)",
173
+ "finalize_organization_retention_deletion(uuid, uuid, uuid, text)",
174
+ "complete_organization_retention_deletion(uuid, uuid, uuid, text)"
175
+ ];
176
+ var ORGANIZATION_MEMBERSHIP_LIFECYCLE_AUTHORITY_TABLES = [
177
+ "organization_invitation_binding_events",
178
+ "organization_membership_invitations",
179
+ "organization_membership_lifecycle_events",
180
+ "organization_membership_operation_receipts",
181
+ "organization_memberships",
182
+ "organization_profile_events",
183
+ "organization_shared_workspace_administration_capabilities",
184
+ "organization_user_resource_authorities",
185
+ "organization_user_resource_grants",
186
+ "organization_user_retention_deletion_events",
187
+ "organization_user_retention_deletions",
188
+ "organization_user_retention_object_deletion_receipts",
189
+ "organization_user_retention_object_obligations",
190
+ "organization_user_retention_policies"
191
+ ];
192
+ var PRIVATE_SESSION_CREATE_POLICY_ROUTINE = "get_private_session_create_policy(uuid, uuid, text)";
193
+ var ORGANIZATION_PRIVATE_SESSION_SETTINGS_READ_ROUTINE = "get_organization_private_session_settings(uuid, text)";
194
+ var ORGANIZATION_PRIVATE_SESSION_SETTINGS_UPDATE_ROUTINE = "update_organization_private_session_settings(uuid, text, boolean, bigint, uuid)";
195
+ var ORGANIZATION_PRIVATE_SESSION_ROUTINE_AUTHORITY_TABLES = {
196
+ [PRIVATE_SESSION_CREATE_POLICY_ROUTINE]: [
197
+ "organization_memberships",
198
+ "organization_private_session_settings",
199
+ "session_tenancy_activations",
200
+ "workspace_memberships",
201
+ "workspaces"
202
+ ],
203
+ [ORGANIZATION_PRIVATE_SESSION_SETTINGS_READ_ROUTINE]: [
204
+ "managed_accounts",
205
+ "organization_memberships",
206
+ "organization_private_session_settings",
207
+ "session_tenancy_activations"
208
+ ],
209
+ [ORGANIZATION_PRIVATE_SESSION_SETTINGS_UPDATE_ROUTINE]: [
210
+ "managed_accounts",
211
+ "organization_memberships",
212
+ "organization_private_session_setting_events",
213
+ "organization_private_session_settings",
214
+ "session_tenancy_activations"
215
+ ]
216
+ };
217
+ var ORGANIZATION_PRIVATE_SESSION_ROUTINES = Object.keys(
218
+ ORGANIZATION_PRIVATE_SESSION_ROUTINE_AUTHORITY_TABLES
219
+ );
220
+ var ORGANIZATION_PRIVATE_SESSIONS_ENABLED_ROUTINE = "organization_private_sessions_enabled(uuid)";
221
+ var PREFERENCE_KNOWLEDGE_PROPOSAL_ROUTINE = "preference_registry_create_knowledge_proposal_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, text, uuid, text, text, text, text, integer, text, jsonb, timestamp with time zone, text)";
222
+ var PREFERENCE_KNOWLEDGE_PROPOSAL_AUTHORITY_TABLES = [
223
+ "company_brain_preference_proposal_receipts",
224
+ "knowledge_change_proposals",
225
+ "knowledge_claim_evidence",
226
+ "knowledge_claim_reviews",
227
+ "knowledge_claims",
228
+ "preference_registry_events",
229
+ "preference_registry_preferences",
230
+ "preference_registry_revisions",
231
+ "session_attempt_interruptions",
232
+ "session_turn_attempts",
233
+ "session_turns",
234
+ "sessions",
235
+ "workspaces"
236
+ ];
237
+ var MANAGED_HUMAN_PERSONAL_WORKSPACE_AUTHORITY_TABLES = [
238
+ "organization_memberships",
239
+ "organization_user_retention_policies",
240
+ "organization_user_resource_authorities",
241
+ "organization_user_resource_grants"
242
+ ];
243
+ var PERSONAL_RESOURCE_ATTEMPT_RESOLVER_ROUTINE = "resolve_session_attempt_personal_resources(uuid, uuid, uuid)";
244
+ var USER_RESOURCE_LIFECYCLE_ROUTINES = [
245
+ "accept_turn_personal_resource_attachment(uuid, uuid, uuid, uuid, text, integer, boolean, integer)",
246
+ "list_self_user_resource_authorities(uuid, uuid, text, uuid, integer)",
247
+ "issue_self_user_resource_grant(uuid, uuid, uuid, text, text, text, uuid, integer, boolean)",
248
+ "revoke_self_user_resource_grant(uuid, uuid, uuid)",
249
+ "authorize_session_attempt_personal_resource_reads(uuid, uuid, uuid)"
250
+ ];
251
+ var CONNECTION_AUTHORITY_ROUTINES = [
252
+ "resolve_personal_connection_authority_selection(uuid, uuid, text, uuid, jsonb)",
253
+ "resolve_accepted_connection_use(uuid, uuid, uuid, uuid, uuid, integer, uuid, text, text, uuid, text, text, text, text)",
254
+ "resolve_connection_use_authority(uuid, uuid, uuid, jsonb)"
255
+ ];
256
+ var PERSONAL_GITHUB_REPOSITORY_AUTHORITY_ROUTINES = [
257
+ "get_self_personal_github_repository_selection(uuid, uuid, text, uuid)",
258
+ "mutate_self_personal_github_repository_selection(uuid, uuid, text, uuid, bigint, bigint, text, jsonb, boolean)"
259
+ ];
260
+ var PERSONAL_GITHUB_REPOSITORY_AUTHORITY_TABLES = [
261
+ "personal_github_repository_selection_heads",
262
+ "personal_github_repository_selection_operations",
263
+ "personal_github_repository_selections"
264
+ ];
265
+ var SCHEDULED_PERSONAL_RESOURCE_ROUTINES = [
266
+ "freeze_scheduled_task_personal_resources(uuid, uuid, uuid, bigint)",
267
+ "clone_scheduled_task_personal_resource_authority(uuid, uuid, uuid, bigint, bigint)",
268
+ "refresh_scheduled_task_personal_resources_clone_connections(uuid, uuid, uuid, bigint, bigint)",
269
+ "create_scheduled_agent_run_with_admission(uuid, uuid, uuid, uuid, bigint, text, text, text, timestamp with time zone, timestamp with time zone, jsonb)",
270
+ "materialize_scheduled_task_reusable_session_from_run(uuid, uuid, uuid, uuid, uuid, bigint, text)",
271
+ "scheduled_task_run_personal_resource_authority(uuid, uuid, uuid)",
272
+ "scheduled_task_run_connection_authority_subject(uuid, uuid, uuid)",
273
+ "scheduled_task_personal_resource_authority_subject(uuid, uuid, uuid, bigint)",
274
+ "record_scheduled_task_revision_authority(uuid, uuid, uuid, bigint)",
275
+ "clone_scheduled_task_revision_authority(uuid, uuid, uuid, bigint, bigint)",
276
+ "scheduled_task_revision_authority_subject(uuid, uuid, uuid, bigint)",
277
+ "scheduled_task_revision_authority_snapshot(uuid, uuid, uuid, bigint)",
278
+ "validate_scheduled_agent_run_live_authority(uuid, uuid, uuid)",
279
+ "scheduled_scoped_rig_version_metadata(uuid, uuid, text, uuid, uuid)",
280
+ "scheduled_variable_set_expected_generation_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid)",
281
+ "bind_scheduled_task_run_session(uuid, uuid, uuid, uuid)",
282
+ "transition_scheduled_agent_run(uuid, uuid, uuid, uuid, uuid, text, text)"
283
+ ];
284
+ var PERSONAL_RESOURCE_CAPABILITY_PREDICATE_ROUTINE = "personal_resource_delegation_capability_active(text)";
285
+ var PERSONAL_RESOURCE_CAPABILITY_TABLE = "personal_resource_delegation_capabilities";
286
+ var SCHEDULED_PERSONAL_RESOURCE_CAPABILITY_PREDICATE_ROUTINE = "scheduled_personal_resource_capability_active(text)";
287
+ var SCHEDULED_PERSONAL_RESOURCE_CAPABILITY_TABLE = "scheduled_personal_resource_capabilities";
288
+ var VARIABLE_SET_CAPABILITY_PREDICATE_ROUTINE = "variable_set_authority_capability_active(text)";
289
+ var VARIABLE_SET_CAPABILITY_TABLE = "variable_set_authority_capabilities";
290
+ var PERSONAL_DOCUMENT_CAPABILITY_PREDICATE_ROUTINE = "personal_document_authority_capability_active(text)";
291
+ var PERSONAL_DOCUMENT_CAPABILITY_TABLE = "personal_document_authority_capabilities";
292
+ var PERSONAL_DOCUMENT_AUTHORITY_ROUTINES = [
293
+ "create_personal_document_authority(uuid, uuid, uuid)",
294
+ "resolve_document_original_file(uuid, uuid, text, uuid)",
295
+ "resolve_session_attempt_personal_document_reads(uuid, uuid, uuid, uuid)"
296
+ ];
297
+ var DOCUMENT_MIGRATION_CAPABILITY_PREDICATE_ROUTINE = "document_migration_capability_active(text)";
298
+ var DOCUMENT_MIGRATION_CAPABILITY_TABLE = "document_migration_capabilities";
299
+ var DOCUMENT_MIGRATION_AUTHORITY_ROUTINES = [
300
+ "list_document_authority_reclassifications(uuid, uuid, text, uuid, integer, timestamp with time zone, uuid)",
301
+ "reclassify_document_authority(jsonb)",
302
+ "run_document_default_collection_backfill(jsonb)"
303
+ ];
304
+ var VARIABLE_SET_AUTHORITY_ROUTINES = [
305
+ "create_scoped_variable_set(uuid, uuid, text, text, text, jsonb, boolean)",
306
+ "list_scoped_variable_sets(uuid, uuid, uuid, text, text)",
307
+ "count_scoped_variable_sets(uuid, uuid, text)",
308
+ "mutate_scoped_variable_set(uuid, uuid, uuid, text, text, boolean, text, boolean, text, text, boolean)",
309
+ "read_scoped_variable_set_secret(uuid, uuid, uuid, text, text, text, uuid, uuid, uuid, integer)",
310
+ "materialize_scoped_variable_set_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid)",
311
+ "materialize_scoped_variable_set_for_session(uuid, uuid, uuid, uuid)"
312
+ ];
313
+ var SCOPED_COMPUTE_CAPABILITY_PREDICATE_ROUTINE = "scoped_compute_capability_active(text)";
314
+ var SCOPED_COMPUTE_CAPABILITY_TABLE = "scoped_compute_capabilities";
315
+ var CONNECTION_TENANCY_BACKFILL_CAPABILITY_TABLE = "connection_tenancy_backfill_capabilities";
316
+ var CONNECTION_TENANCY_BACKFILL_CAPABILITY_PREDICATE_ROUTINE = "connection_tenancy_backfill_capability_active(uuid)";
317
+ var SCOPED_COMPUTE_AUTHORITY_ROUTINES = [
318
+ "create_scoped_rig(uuid, uuid, text, text, text, text, jsonb, boolean)",
319
+ "list_scoped_rigs(uuid, uuid, uuid, text, text)",
320
+ "count_scoped_rigs(uuid, uuid, text)",
321
+ "mutate_scoped_rig(uuid, uuid, uuid, text, text, boolean, text, boolean, boolean)",
322
+ "finalize_scoped_enrollment(uuid, uuid, text, text, boolean, boolean, text, text, text, boolean)",
323
+ "list_scoped_enrollments(uuid, uuid, uuid, text)",
324
+ "get_scoped_sandbox(uuid, uuid, uuid)",
325
+ "authorize_scoped_sandbox_attach(uuid, uuid, uuid)",
326
+ "materialize_scoped_rig_version_for_attempt(uuid, uuid, uuid, uuid, uuid, integer)",
327
+ "authorize_session_attempt_personal_machine(uuid, uuid, uuid, uuid, uuid, integer, uuid)",
328
+ "assert_session_attempt_personal_machine(uuid, uuid, uuid, uuid, uuid, integer, uuid, boolean)",
329
+ "list_scoped_machine_dependent_sessions(uuid, uuid, uuid)",
330
+ "detach_scoped_machine_dependent_sessions(uuid, uuid, uuid)"
331
+ ];
332
+ var CANONICAL_HUMAN_IDENTITY_ROUTINES = [
333
+ "ensure_canonical_human_identity(text, text)",
334
+ "validate_canonical_human_session(text, text, boolean)",
335
+ "get_canonical_human_identity_projection(text)",
336
+ "apply_canonical_human_identity_operation(uuid, text, bigint, text, uuid, text, text, text)"
337
+ ];
338
+ var CANONICAL_HUMAN_IDENTITY_AUTHORITY_TABLES = [
339
+ "canonical_human_identities",
340
+ "canonical_human_identity_subjects",
341
+ "canonical_human_login_bindings",
342
+ "canonical_human_identity_operations"
343
+ ];
344
+ var SESSION_PRIVATE_ACTOR_VISIBLE_ROUTINE = "session_private_actor_visible(uuid, uuid, uuid, text)";
345
+ var SESSION_REFERENCE_VISIBLE_ROUTINE = "session_reference_visible(uuid, uuid, uuid)";
346
+ var TASK_NOTE_CAPABILITY_ROUTINES = [
347
+ "create_task_note_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, text, text, integer)",
348
+ "archive_task_note_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, uuid, integer, text)",
349
+ "list_task_notes_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, boolean, integer)",
350
+ "replace_task_note_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, uuid, uuid, uuid, integer, text, text, integer, text)",
351
+ "resolve_task_note_knowledge_promotion_source(uuid, uuid, uuid, uuid, uuid, integer, uuid, integer, text, text, text)"
352
+ ];
353
+ var COMPANY_BRAIN_CONTEXT_SELECTION_ROUTINE = "company_brain_context_get_or_create_selection(uuid, uuid, uuid, uuid, uuid, integer)";
354
+ var COMPANY_BRAIN_CONTEXT_INSPECTION_ROUTINE = "company_brain_inspect_context_receipts(uuid, uuid, text, uuid, timestamp with time zone, uuid, integer)";
355
+ var GOVERNED_LEARNING_EVALUATION_ROUTINE = "evaluate_governed_learning_proposal(uuid, uuid, uuid, uuid, uuid, integer, uuid, uuid, uuid, uuid, uuid)";
356
+ var GOVERNED_LEARNING_ACTIVATION_ROUTINES = [
357
+ "activate_governed_learning_decision(uuid, uuid, uuid, uuid)",
358
+ "activate_human_confirmed_learning_decision(uuid, uuid, uuid, uuid, uuid)",
359
+ "confirm_remember_knowledge_claim(uuid, uuid, uuid, uuid, integer, uuid, uuid, uuid)",
360
+ "undo_governed_learning_activation(uuid, uuid, uuid, uuid)"
361
+ ];
362
+ var GOVERNED_LEARNING_INSPECTION_ROUTINES = [
363
+ "inspect_governed_learning_decisions(uuid, uuid, text, integer)",
364
+ "inspect_governed_learning_activations(uuid, uuid, text, integer)",
365
+ "inspect_governed_learning_activation_undos(uuid, uuid, text, integer)"
366
+ ];
367
+ var GOVERNED_LEARNING_INSPECTION_AUTHORITY_TABLES = [
368
+ "governed_learning_decision_receipts",
369
+ "governed_learning_activation_receipts",
370
+ "governed_learning_activation_undo_receipts",
371
+ "sessions"
372
+ ];
373
+ var COMPANY_PROFILE_AGENT_ADMIN_ROUTINES = [
374
+ "propose_company_profile_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, text, text, text)",
375
+ "confirm_company_profile_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, uuid, uuid)"
376
+ ];
377
+ var COMPANY_PROFILE_AGENT_ADMIN_AUTHORITY_TABLES = [
378
+ "company_profile_activation_events",
379
+ "company_profile_agent_confirmation_receipts",
380
+ "company_profile_agent_proposal_receipts",
381
+ "company_profile_heads",
382
+ "company_profile_revisions",
383
+ "managed_accounts",
384
+ "organization_memberships",
385
+ "session_human_input_requests",
386
+ "session_turn_attempts",
387
+ "session_turns",
388
+ "sessions",
389
+ "workspaces"
390
+ ];
391
+ var GOVERNED_LEARNING_EVALUATION_AUTHORITY_TABLES = [
392
+ "document_chunks",
393
+ "documents",
394
+ "governed_learning_decision_receipts",
395
+ "knowledge_change_proposals",
396
+ "knowledge_claim_evidence",
397
+ "knowledge_claim_relations",
398
+ "knowledge_claim_reviews",
399
+ "knowledge_claims",
400
+ "knowledge_document_versions",
401
+ "knowledge_providers",
402
+ "knowledge_source_acl_versions",
403
+ "knowledge_source_objects",
404
+ "knowledge_sources",
405
+ "session_attempt_interruptions",
406
+ "session_turn_attempts",
407
+ "session_turns",
408
+ "sessions",
409
+ "task_notes",
410
+ "workspace_learning_policy_snapshots",
411
+ "workspaces"
412
+ ];
413
+ var GOVERNED_LEARNING_ACTIVATION_AUTHORITY_TABLES = [
414
+ ...GOVERNED_LEARNING_EVALUATION_AUTHORITY_TABLES,
415
+ "company_brain_preference_proposal_receipts",
416
+ "governed_learning_activation_receipts",
417
+ "governed_learning_activation_undo_receipts",
418
+ "preference_registry_events",
419
+ "preference_registry_preferences",
420
+ "preference_registry_revisions",
421
+ "remember_knowledge_confirmation_receipts",
422
+ "session_human_input_requests",
423
+ "workspace_instruction_policy_activation_events",
424
+ "workspace_instruction_policy_deactivation_events",
425
+ "workspace_instruction_policy_heads",
426
+ "workspace_instruction_policy_onboarding_proposals",
427
+ "workspace_instruction_policy_revisions",
428
+ "workspace_learning_policy_heads",
429
+ "workspace_learning_policy_revisions"
430
+ ];
431
+ var TRANSITION_SESSION_VISIBILITY_ROUTINE = "transition_session_visibility(uuid, uuid, uuid, text, text, integer, text, text, integer)";
432
+ var LEGACY_FORK_SESSION_CONTENT_ROUTINE = "fork_session_content(uuid, uuid, uuid, text, uuid, text, text, text, integer)";
433
+ var FORK_SESSION_CONTENT_ROUTINE = "fork_session_content(uuid, uuid, uuid, text, uuid, text, boolean, text, text, integer)";
434
+ var REPLAY_APPLIED_SESSION_FORK_ROUTINE = "replay_applied_session_fork(uuid, uuid, uuid, text, uuid, text, boolean, text, text, integer)";
435
+ var SESSION_TENANCY_ACTIVATED_ROUTINE = "session_tenancy_product_activated(uuid, integer)";
436
+ var SESSION_TENANCY_ANY_ACTIVATION_ROUTINE = "session_tenancy_any_product_activation()";
437
+ var SESSION_TENANCY_QUIESCENCE_ROUTINE = "assert_session_tenancy_quiescent(uuid, uuid, uuid, boolean)";
438
+ var TENANCY_BACKFILL_ACTIVATION_EVIDENCE_ROUTINE = "check_tenancy_backfill_activation_evidence(uuid)";
439
+ var SESSION_VISIBILITY_LIFECYCLE_CAPABILITY_ROUTINE = "session_visibility_lifecycle_capability_held()";
440
+ var PRIVATE_SESSION_CREATE_CAPABILITY_ROUTINES = [
441
+ "open_private_session_create_capability(uuid, uuid, uuid, text)",
442
+ "open_private_child_session_create_capability(uuid, uuid, uuid, uuid, uuid, uuid, integer)",
443
+ "close_private_session_create_capability(uuid)"
444
+ ];
445
+ var SESSION_AUTHORITY_ROUTINES = /* @__PURE__ */ new Set([
446
+ LEGACY_FORK_SESSION_CONTENT_ROUTINE,
447
+ FORK_SESSION_CONTENT_ROUTINE,
448
+ REPLAY_APPLIED_SESSION_FORK_ROUTINE,
449
+ SESSION_TENANCY_ACTIVATED_ROUTINE,
450
+ SESSION_TENANCY_ANY_ACTIVATION_ROUTINE,
451
+ SESSION_TENANCY_QUIESCENCE_ROUTINE,
452
+ PERSONAL_RESOURCE_ATTEMPT_RESOLVER_ROUTINE,
453
+ ...USER_RESOURCE_LIFECYCLE_ROUTINES,
454
+ ...CONNECTION_AUTHORITY_ROUTINES,
455
+ ...SCHEDULED_PERSONAL_RESOURCE_ROUTINES,
456
+ SESSION_PRIVATE_ACTOR_VISIBLE_ROUTINE,
457
+ SESSION_REFERENCE_VISIBLE_ROUTINE,
458
+ SESSION_VISIBILITY_LIFECYCLE_CAPABILITY_ROUTINE,
459
+ ...PRIVATE_SESSION_CREATE_CAPABILITY_ROUTINES,
460
+ TRANSITION_SESSION_VISIBILITY_ROUTINE,
461
+ ...TASK_NOTE_CAPABILITY_ROUTINES,
462
+ COMPANY_BRAIN_CONTEXT_SELECTION_ROUTINE,
463
+ COMPANY_BRAIN_CONTEXT_INSPECTION_ROUTINE
464
+ ]);
465
+ var XAI_CREATE_CREDENTIAL_ROUTINE = "create_xai_subscription_credential(uuid, uuid, text, text, text, text, text, text, text, timestamp with time zone)";
466
+ var XAI_DISCONNECT_CREDENTIAL_ROUTINE = "disconnect_xai_subscription_credential(uuid, uuid, text, uuid, jsonb)";
467
+ var XAI_SNAPSHOT_VALIDATOR_ROUTINE = "xai_provider_account_authority_snapshot_v1_valid(jsonb)";
468
+ var XAI_AUTHORITY_LIVE_ROUTINE = "xai_subscription_authority_live(uuid, uuid, text, uuid, text, uuid, uuid, bigint)";
469
+ var XAI_POOL_VISIBLE_ROUTINE = "xai_subscription_pool_visible(uuid, uuid, text, text, uuid)";
470
+ var XAI_RESOLVE_POOL_ROUTINE = "resolve_xai_authority_pool(uuid, uuid, text, jsonb)";
471
+ var XAI_REVALIDATE_CREDENTIAL_ROUTINE = "revalidate_xai_subscription_authority(uuid, text, uuid, jsonb)";
472
+ var XAI_AUTHORITY_TABLES = [
473
+ "organization_memberships",
474
+ "organization_user_resource_authorities",
475
+ "workspace_memberships",
476
+ "xai_subscription_credentials"
477
+ ];
478
+ var RUNTIME_TARGET_SCHEMA_CAPABILITY_ROUTINES = [
479
+ COMPANY_BRAIN_CONTEXT_INSPECTION_ROUTINE,
480
+ COMPANY_BRAIN_CONTEXT_SELECTION_ROUTINE,
481
+ ...COMPANY_PROFILE_AGENT_ADMIN_ROUTINES,
482
+ GOVERNED_LEARNING_EVALUATION_ROUTINE,
483
+ ...GOVERNED_LEARNING_ACTIVATION_ROUTINES,
484
+ ...GOVERNED_LEARNING_INSPECTION_ROUTINES,
485
+ FORK_SESSION_CONTENT_ROUTINE,
486
+ LEGACY_FORK_SESSION_CONTENT_ROUTINE,
487
+ REPLAY_APPLIED_SESSION_FORK_ROUTINE,
488
+ SESSION_TENANCY_ACTIVATED_ROUTINE,
489
+ SESSION_TENANCY_ANY_ACTIVATION_ROUTINE,
490
+ XAI_AUTHORITY_LIVE_ROUTINE,
491
+ XAI_CREATE_CREDENTIAL_ROUTINE,
492
+ XAI_DISCONNECT_CREDENTIAL_ROUTINE,
493
+ GOOGLE_DRIVE_DOCUMENT_CITATION_ROUTINE,
494
+ GOOGLE_DRIVE_FILE_AUTHORIZATION_ROUTINE,
495
+ KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_ROUTINE,
496
+ MANAGED_HUMAN_PERSONAL_WORKSPACE_ROUTINE,
497
+ ...ORGANIZATION_MEMBERSHIP_LIFECYCLE_ROUTINES,
498
+ ...ORGANIZATION_PRIVATE_SESSION_ROUTINES,
499
+ ...PRIVATE_SESSION_CREATE_CAPABILITY_ROUTINES,
500
+ PERSONAL_RESOURCE_ATTEMPT_RESOLVER_ROUTINE,
501
+ ...USER_RESOURCE_LIFECYCLE_ROUTINES,
502
+ PREFERENCE_KNOWLEDGE_PROPOSAL_ROUTINE,
503
+ ...VARIABLE_SET_AUTHORITY_ROUTINES,
504
+ ...CONNECTION_AUTHORITY_ROUTINES,
505
+ ...PERSONAL_GITHUB_REPOSITORY_AUTHORITY_ROUTINES,
506
+ ...PERSONAL_DOCUMENT_AUTHORITY_ROUTINES,
507
+ ...DOCUMENT_MIGRATION_AUTHORITY_ROUTINES,
508
+ ...SCOPED_COMPUTE_AUTHORITY_ROUTINES,
509
+ ...SCHEDULED_PERSONAL_RESOURCE_ROUTINES,
510
+ ...CANONICAL_HUMAN_IDENTITY_ROUTINES,
511
+ ...TASK_NOTE_CAPABILITY_ROUTINES,
512
+ SESSION_PRIVATE_ACTOR_VISIBLE_ROUTINE,
513
+ SESSION_REFERENCE_VISIBLE_ROUTINE,
514
+ SESSION_VISIBILITY_LIFECYCLE_CAPABILITY_ROUTINE,
515
+ TRANSITION_SESSION_VISIBILITY_ROUTINE,
516
+ XAI_POOL_VISIBLE_ROUTINE,
517
+ XAI_RESOLVE_POOL_ROUTINE,
518
+ XAI_REVALIDATE_CREDENTIAL_ROUTINE,
519
+ XAI_SNAPSHOT_VALIDATOR_ROUTINE
520
+ ];
521
+ var RUNTIME_TARGET_SCHEMA_FORBIDDEN_ROUTINES = [
522
+ ORGANIZATION_PRIVATE_SESSIONS_ENABLED_ROUTINE,
523
+ SESSION_TENANCY_QUIESCENCE_ROUTINE,
524
+ TENANCY_BACKFILL_ACTIVATION_EVIDENCE_ROUTINE
525
+ ];
526
+ var RUNTIME_TARGET_SCHEMA_INVOKER_ROUTINES = [
527
+ SESSION_REFERENCE_VISIBLE_ROUTINE,
528
+ XAI_SNAPSHOT_VALIDATOR_ROUTINE
529
+ ];
530
+ var RUNTIME_TARGET_SCHEMA_INVOKER_ROUTINE_SET = new Set(
531
+ RUNTIME_TARGET_SCHEMA_INVOKER_ROUTINES
532
+ );
533
+ var FORCE_RLS_TABLES = [
534
+ "agent_run_states",
535
+ "api_keys",
536
+ "attached_browser_devices",
537
+ "attached_browser_inventories",
538
+ "audit_events",
539
+ "auth_runs",
540
+ "automation_run_event_links",
541
+ "automation_runs",
542
+ "automation_sources",
543
+ "automation_trigger_events",
544
+ "automation_trigger_revisions",
545
+ "automation_triggers",
546
+ "billing_customers",
547
+ "browser_identities",
548
+ "browser_revision_components",
549
+ "browser_revisions",
550
+ "browser_session_associations",
551
+ "browser_sessions",
552
+ "browser_state_artifacts",
553
+ "browser_state_uploads",
554
+ "canonical_human_identities",
555
+ "canonical_human_identity_operations",
556
+ "canonical_human_identity_subjects",
557
+ "canonical_human_login_bindings",
558
+ "capability_api_facets",
559
+ "capability_catalog_items",
560
+ "capability_component_owners",
561
+ "capability_facet_installations",
562
+ "capability_facets",
563
+ "capability_installations",
564
+ "capability_integration_facets",
565
+ "capability_mcp_facets",
566
+ "capability_operations",
567
+ "capability_plugin_installations",
568
+ "capability_plugin_versions",
569
+ "capability_plugins",
570
+ "capability_skill_facets",
571
+ "capability_skill_files",
572
+ "channels",
573
+ "codex_apps_settings",
574
+ "codex_capacity_waiters",
575
+ "codex_credential_leases",
576
+ "codex_reset_redemption_attempts",
577
+ "codex_rotation_settings",
578
+ "codex_subscription_credentials",
579
+ "company_brain_context_selection_receipts",
580
+ "company_brain_preference_proposal_receipts",
581
+ "company_brain_turn_context_snapshots",
582
+ "company_profile_activation_events",
583
+ "company_profile_agent_confirmation_receipts",
584
+ "company_profile_agent_proposal_receipts",
585
+ "company_profile_heads",
586
+ "company_profile_revisions",
587
+ "company_profile_snapshots",
588
+ "composer_drafts",
589
+ "computer_session_associations",
590
+ "computer_sessions",
591
+ "connection_disconnect_operations",
592
+ "connection_use_audit_facts",
593
+ "connection_use_once_consumption_receipts",
594
+ "connections",
595
+ "connector_action_policies",
596
+ "connector_action_requests",
597
+ "credit_ledger_entries",
598
+ "device_enrollment_requests",
599
+ "document_authority_reclassifications",
600
+ "document_bases",
601
+ "document_chunks",
602
+ "document_default_collection_backfill_operations",
603
+ "document_default_collection_backfill_receipts",
604
+ "document_default_collection_backfill_runs",
605
+ "documents",
606
+ "editable_artifact_blob_refs",
607
+ "editable_artifact_idempotency_receipts",
608
+ "editable_artifact_live_outbox",
609
+ "editable_artifact_live_tickets",
610
+ "editable_artifact_materialization_jobs",
611
+ "editable_artifact_materialization_results",
612
+ "editable_artifact_operations",
613
+ "editable_artifact_replica_leases",
614
+ "editable_artifact_scope_authorization_heads",
615
+ "editable_artifact_sequence_checkpoints",
616
+ "editable_artifact_session_links",
617
+ "editable_artifact_snapshots",
618
+ "editable_artifact_transactions",
619
+ "editable_artifact_undo_claims",
620
+ "editable_artifact_versions",
621
+ "editable_artifacts",
622
+ "enrollments",
623
+ "file_uploads",
624
+ "files",
625
+ "generated_image_artifacts",
626
+ "generated_video_artifacts",
627
+ "github_installation_repositories",
628
+ "github_installations",
629
+ "google_drive_object_acl_evidence",
630
+ "google_drive_object_acl_principals",
631
+ "governed_learning_activation_receipts",
632
+ "governed_learning_activation_undo_receipts",
633
+ "governed_learning_decision_receipts",
634
+ "host_export_config",
635
+ "host_export_consumers",
636
+ "host_export_cursor_state",
637
+ "host_export_dead_letters",
638
+ "host_export_outbox",
639
+ "image_generation_operations",
640
+ "import_batches",
641
+ "integration_facet_binding_owners",
642
+ "integration_facet_bindings",
643
+ "integration_facet_definitions",
644
+ "integration_oauth_state_nonces",
645
+ "integration_spec_revisions",
646
+ "integration_tools",
647
+ "interaction_interventions",
648
+ "interaction_operations",
649
+ "interaction_resource_operations",
650
+ "knowledge_change_proposals",
651
+ "knowledge_claim_evidence",
652
+ "knowledge_claim_relations",
653
+ "knowledge_claim_reviews",
654
+ "knowledge_claims",
655
+ "knowledge_document_versions",
656
+ "knowledge_entities",
657
+ "knowledge_entity_aliases",
658
+ "knowledge_facts",
659
+ "knowledge_lifecycle_events",
660
+ "knowledge_memories",
661
+ "knowledge_memory_lifecycle_events",
662
+ "knowledge_memory_relationships",
663
+ "knowledge_operation_receipts",
664
+ "knowledge_providers",
665
+ "knowledge_source_acl_versions",
666
+ "knowledge_source_objects",
667
+ "knowledge_source_sync_index_obligations",
668
+ "knowledge_source_sync_item_outcomes",
669
+ "knowledge_source_sync_object_observations",
670
+ "knowledge_source_sync_states",
671
+ "knowledge_source_sync_wakes",
672
+ "knowledge_sources",
673
+ "knowledge_sync_runs",
674
+ "machine_metrics_latest",
675
+ "machine_metrics_series",
676
+ "machine_removal_operations",
677
+ "memory_slack_publication_configurations",
678
+ "memory_slack_publication_receipts",
679
+ "memory_slack_publications",
680
+ "model_call_facts",
681
+ "network_routes",
682
+ "new_session_drafts",
683
+ "organization_invitation_binding_events",
684
+ "organization_membership_invitations",
685
+ "organization_membership_lifecycle_events",
686
+ "organization_membership_operation_receipts",
687
+ "organization_memberships",
688
+ "organization_private_session_setting_events",
689
+ "organization_private_session_settings",
690
+ "organization_profile_events",
691
+ "organization_shared_workspace_administration_capabilities",
692
+ "organization_user_resource_authorities",
693
+ "organization_user_resource_grants",
694
+ "organization_user_retention_deletion_events",
695
+ "organization_user_retention_deletions",
696
+ "organization_user_retention_object_deletion_receipts",
697
+ "organization_user_retention_object_obligations",
698
+ "organization_user_retention_policies",
699
+ "pack_installation_components",
700
+ "pack_installations",
701
+ "personal_document_once_consumption_receipts",
702
+ "personal_github_repository_selection_heads",
703
+ "personal_github_repository_selection_operations",
704
+ "personal_github_repository_selections",
705
+ "personal_resource_once_consumption_receipts",
706
+ "pr_review_app_registrations",
707
+ "pr_review_repository_bindings",
708
+ "preference_registry_events",
709
+ "preference_registry_preferences",
710
+ "preference_registry_revisions",
711
+ "preference_registry_snapshots",
712
+ "private_session_create_capabilities",
713
+ "remember_knowledge_confirmation_receipts",
714
+ "retained_screenshot_artifacts",
715
+ "rig_changes",
716
+ "rig_versions",
717
+ "rigs",
718
+ "sandbox_checkpoint_artifacts",
719
+ "sandbox_lease_holders",
720
+ "sandbox_leases",
721
+ "sandbox_pty_sessions",
722
+ "sandbox_retained_processes",
723
+ "sandbox_session_envelopes",
724
+ "sandbox_workspace_mutation_admissions",
725
+ "sandboxes",
726
+ "scheduled_task_connection_authority_snapshots",
727
+ "scheduled_task_personal_resource_authorities",
728
+ "scheduled_task_personal_resource_snapshots",
729
+ "scheduled_task_reusable_connection_materializations",
730
+ "scheduled_task_revision_authorities",
731
+ "scheduled_task_run_connection_authority_snapshots",
732
+ "scheduled_task_run_personal_resource_admissions",
733
+ "scheduled_task_run_personal_resource_once_receipts",
734
+ "scheduled_task_run_personal_resource_snapshots",
735
+ "scheduled_task_runs",
736
+ "scheduled_tasks",
737
+ "session_attempt_codemode_calls",
738
+ "session_attempt_connected_machine_authorizations",
739
+ "session_attempt_interruptions",
740
+ "session_attempt_personal_document_admissions",
741
+ "session_attempt_personal_document_snapshots",
742
+ "session_attempt_personal_resource_admissions",
743
+ "session_attempt_personal_resource_snapshots",
744
+ "session_attempt_tool_catalogs",
745
+ "session_background_commands",
746
+ "session_command_receipts",
747
+ "session_events",
748
+ "session_goal_revisions",
749
+ "session_goals",
750
+ "session_history_items",
751
+ "session_human_input_requests",
752
+ "session_list_snapshots",
753
+ "session_mcp_servers",
754
+ "session_pending_tool_calls",
755
+ "session_pins",
756
+ "session_realtime_connections",
757
+ "session_realtime_context_projections",
758
+ "session_realtime_entries",
759
+ "session_realtime_modes",
760
+ "session_recordings",
761
+ "session_spawn_denials",
762
+ "session_stream_acknowledgments",
763
+ "session_system_update_outbox",
764
+ "session_system_updates",
765
+ "session_tenancy_activations",
766
+ "session_turn_attempts",
767
+ "session_turn_startup_milestones",
768
+ "session_turns",
769
+ "session_visibility_write_capabilities",
770
+ "session_workflow_wake_outbox",
771
+ "sessions",
772
+ "site_auth_connections",
773
+ "slack_app_home_refreshes",
774
+ "slack_bot_delete_operations",
775
+ "slack_bot_post_operations",
776
+ "slack_bot_update_operations",
777
+ "slack_bot_user_links",
778
+ "slack_channel_routes",
779
+ "slack_installation_bindings",
780
+ "slack_interaction_action_handles",
781
+ "slack_interaction_inbox",
782
+ "slack_interaction_progress_deliveries",
783
+ "slack_interactions",
784
+ "slack_route_prompt_options",
785
+ "slack_route_prompts",
786
+ "slack_shared_task_origins",
787
+ "slack_task_policy_activation_events",
788
+ "slack_task_policy_heads",
789
+ "slack_task_policy_revisions",
790
+ "slack_user_dm_routes",
791
+ "slack_user_link_access_request_operations",
792
+ "slack_user_link_access_requests",
793
+ "social_connections",
794
+ "social_posts",
795
+ "task_note_events",
796
+ "task_note_knowledge_promotion_capabilities",
797
+ "task_note_replacement_receipts",
798
+ "task_note_write_capabilities",
799
+ "task_notes",
800
+ "temporal_schedule_cleanup_outbox",
801
+ "tenancy_backfill_receipts",
802
+ "tenancy_backfill_unresolved_rows",
803
+ "transcription_recording_chunks",
804
+ "transcription_recording_objects",
805
+ "transcription_recording_segments",
806
+ "transcription_recordings",
807
+ "turn_connection_authority_snapshots",
808
+ "turn_personal_resource_attachment_receipts",
809
+ "turn_personal_resource_once_receipts",
810
+ "turn_personal_resource_snapshots",
811
+ "usage_events",
812
+ "video_generation_operations",
813
+ "video_generation_references",
814
+ "workspace_artifact_events",
815
+ "workspace_artifact_versions",
816
+ "workspace_artifacts",
817
+ "workspace_captures",
818
+ "workspace_control_events",
819
+ "workspace_inference_controls",
820
+ "workspace_instruction_policy_activation_events",
821
+ "workspace_instruction_policy_deactivation_events",
822
+ "workspace_instruction_policy_heads",
823
+ "workspace_instruction_policy_onboarding_proposals",
824
+ "workspace_instruction_policy_revisions",
825
+ "workspace_instruction_policy_snapshots",
826
+ "workspace_interaction_revisions",
827
+ "workspace_learning_policy_activation_events",
828
+ "workspace_learning_policy_heads",
829
+ "workspace_learning_policy_revisions",
830
+ "workspace_learning_policy_snapshots",
831
+ "workspace_model_policies",
832
+ "workspace_packs",
833
+ "workspace_screenshot_quotas",
834
+ "workspace_session_activity_revisions",
835
+ "workspace_variable_set_variables",
836
+ "workspace_variable_sets",
837
+ "workspace_video_generation_policies",
838
+ "workspace_video_generation_quotas",
839
+ "xai_capacity_waiters",
840
+ "xai_credential_leases",
841
+ "xai_rotation_settings",
842
+ "xai_session_account_pins",
843
+ "xai_subscription_credentials"
844
+ ];
845
+ var NON_RLS_RUNTIME_TABLES = [
846
+ "auth_identities",
847
+ "auth_rate_limits",
848
+ "auth_sessions",
849
+ "auth_users",
850
+ "auth_verifications",
851
+ "automation_webhook_endpoints",
852
+ "integration_oauth_clients",
853
+ "managed_accounts",
854
+ "nested_agent_depth_configuration",
855
+ "stripe_webhook_events",
856
+ "workspace_memberships",
857
+ "workspaces"
858
+ ];
859
+ var RUNTIME_FULL_DML_TABLES = [
860
+ "agent_run_states",
861
+ "api_keys",
862
+ "audit_events",
863
+ "auth_identities",
864
+ "auth_rate_limits",
865
+ "auth_sessions",
866
+ "auth_users",
867
+ "auth_verifications",
868
+ "automation_run_event_links",
869
+ "automation_runs",
870
+ "automation_sources",
871
+ "automation_trigger_events",
872
+ "automation_trigger_revisions",
873
+ "automation_triggers",
874
+ "automation_webhook_endpoints",
875
+ "billing_customers",
876
+ "browser_session_associations",
877
+ "capability_catalog_items",
878
+ "capability_component_owners",
879
+ "capability_facet_installations",
880
+ "capability_installations",
881
+ "capability_operations",
882
+ "capability_plugin_installations",
883
+ "channels",
884
+ "codex_apps_settings",
885
+ "codex_capacity_waiters",
886
+ "codex_credential_leases",
887
+ "codex_reset_redemption_attempts",
888
+ "codex_rotation_settings",
889
+ "codex_subscription_credentials",
890
+ "composer_drafts",
891
+ "computer_session_associations",
892
+ "connection_disconnect_operations",
893
+ "connections",
894
+ "connector_action_policies",
895
+ "connector_action_requests",
896
+ "credit_ledger_entries",
897
+ "device_enrollment_requests",
898
+ "document_bases",
899
+ "document_chunks",
900
+ "documents",
901
+ "editable_artifact_replica_leases",
902
+ "enrollments",
903
+ "file_uploads",
904
+ "files",
905
+ "generated_image_artifacts",
906
+ "generated_video_artifacts",
907
+ "github_installation_repositories",
908
+ "github_installations",
909
+ "image_generation_operations",
910
+ "import_batches",
911
+ "integration_facet_binding_owners",
912
+ "integration_facet_bindings",
913
+ "integration_oauth_clients",
914
+ "integration_oauth_state_nonces",
915
+ "knowledge_memories",
916
+ "knowledge_source_sync_index_obligations",
917
+ "knowledge_source_sync_item_outcomes",
918
+ "knowledge_source_sync_object_observations",
919
+ "knowledge_source_sync_states",
920
+ "knowledge_source_sync_wakes",
921
+ "machine_metrics_latest",
922
+ "machine_metrics_series",
923
+ "machine_removal_operations",
924
+ "managed_accounts",
925
+ "memory_slack_publication_configurations",
926
+ "memory_slack_publication_receipts",
927
+ "memory_slack_publications",
928
+ "model_call_facts",
929
+ "new_session_drafts",
930
+ "pack_installation_components",
931
+ "pack_installations",
932
+ "pr_review_app_registrations",
933
+ "pr_review_repository_bindings",
934
+ "retained_screenshot_artifacts",
935
+ "rig_changes",
936
+ "rig_versions",
937
+ "rigs",
938
+ "sandbox_checkpoint_artifacts",
939
+ "sandbox_lease_holders",
940
+ "sandbox_leases",
941
+ "sandbox_pty_sessions",
942
+ "sandbox_retained_processes",
943
+ "sandbox_session_envelopes",
944
+ "sandbox_workspace_mutation_admissions",
945
+ "sandboxes",
946
+ "session_attempt_interruptions",
947
+ "session_background_commands",
948
+ "session_command_receipts",
949
+ "session_events",
950
+ "session_goals",
951
+ "session_history_items",
952
+ "session_human_input_requests",
953
+ "session_list_snapshots",
954
+ "session_mcp_servers",
955
+ "session_pending_tool_calls",
956
+ "session_pins",
957
+ "session_realtime_connections",
958
+ "session_realtime_context_projections",
959
+ "session_realtime_entries",
960
+ "session_realtime_modes",
961
+ "session_recordings",
962
+ "session_stream_acknowledgments",
963
+ "session_system_update_outbox",
964
+ "session_system_updates",
965
+ "session_turn_attempts",
966
+ "session_turns",
967
+ "session_workflow_wake_outbox",
968
+ "sessions",
969
+ "slack_app_home_refreshes",
970
+ "slack_bot_delete_operations",
971
+ "slack_bot_post_operations",
972
+ "slack_bot_update_operations",
973
+ "slack_bot_user_links",
974
+ "slack_channel_routes",
975
+ "slack_interaction_action_handles",
976
+ "slack_interaction_inbox",
977
+ "slack_interaction_progress_deliveries",
978
+ "slack_interactions",
979
+ "slack_route_prompt_options",
980
+ "slack_route_prompts",
981
+ "slack_user_dm_routes",
982
+ "social_connections",
983
+ "social_posts",
984
+ "stripe_webhook_events",
985
+ "transcription_recording_chunks",
986
+ "transcription_recording_objects",
987
+ "transcription_recording_segments",
988
+ "transcription_recordings",
989
+ "usage_events",
990
+ "video_generation_operations",
991
+ "video_generation_references",
992
+ "workspace_artifacts",
993
+ "workspace_captures",
994
+ "workspace_control_events",
995
+ "workspace_inference_controls",
996
+ "workspace_instruction_policy_heads",
997
+ "workspace_memberships",
998
+ "workspace_model_policies",
999
+ "workspace_packs",
1000
+ "workspace_screenshot_quotas",
1001
+ "workspace_video_generation_policies",
1002
+ "workspace_video_generation_quotas",
1003
+ "workspaces",
1004
+ "xai_capacity_waiters",
1005
+ "xai_credential_leases",
1006
+ "xai_rotation_settings",
1007
+ "xai_session_account_pins",
1008
+ "xai_subscription_credentials"
1009
+ ];
1010
+ var RUNTIME_READ_ONLY_TABLES = [
1011
+ "company_profile_activation_events",
1012
+ "company_profile_heads",
1013
+ "company_profile_snapshots",
1014
+ "document_authority_reclassifications",
1015
+ "knowledge_lifecycle_events",
1016
+ "knowledge_memory_lifecycle_events",
1017
+ "knowledge_memory_relationships",
1018
+ "nested_agent_depth_configuration",
1019
+ "preference_registry_events",
1020
+ "preference_registry_snapshots",
1021
+ "session_tenancy_activations",
1022
+ "slack_installation_bindings",
1023
+ "slack_task_policy_activation_events",
1024
+ "slack_task_policy_heads",
1025
+ "slack_task_policy_revisions",
1026
+ "workspace_instruction_policy_deactivation_events",
1027
+ "workspace_instruction_policy_snapshots",
1028
+ "workspace_learning_policy_activation_events",
1029
+ "workspace_learning_policy_heads",
1030
+ "workspace_learning_policy_snapshots"
1031
+ ];
1032
+ var RUNTIME_READ_UPDATE_TABLES = ["workspace_session_activity_revisions"];
1033
+ var RUNTIME_READ_INSERT_TABLES = [
1034
+ "browser_revision_components",
1035
+ "browser_revisions",
1036
+ "company_profile_revisions",
1037
+ "editable_artifact_blob_refs",
1038
+ "editable_artifact_idempotency_receipts",
1039
+ "editable_artifact_live_outbox",
1040
+ "editable_artifact_materialization_jobs",
1041
+ "editable_artifact_materialization_results",
1042
+ "editable_artifact_operations",
1043
+ "editable_artifact_sequence_checkpoints",
1044
+ "editable_artifact_snapshots",
1045
+ "editable_artifact_transactions",
1046
+ "editable_artifact_undo_claims",
1047
+ "editable_artifact_versions",
1048
+ "google_drive_object_acl_evidence",
1049
+ "google_drive_object_acl_principals",
1050
+ "knowledge_change_proposals",
1051
+ "knowledge_claim_evidence",
1052
+ "knowledge_claim_relations",
1053
+ "knowledge_claim_reviews",
1054
+ "knowledge_claims",
1055
+ "knowledge_document_versions",
1056
+ "knowledge_entities",
1057
+ "knowledge_entity_aliases",
1058
+ "knowledge_facts",
1059
+ "knowledge_operation_receipts",
1060
+ "knowledge_providers",
1061
+ "knowledge_source_acl_versions",
1062
+ "knowledge_source_objects",
1063
+ "knowledge_sources",
1064
+ "knowledge_sync_runs",
1065
+ "preference_registry_preferences",
1066
+ "preference_registry_revisions",
1067
+ "session_attempt_tool_catalogs",
1068
+ "session_goal_revisions",
1069
+ "session_spawn_denials",
1070
+ "slack_shared_task_origins",
1071
+ "slack_user_link_access_request_operations",
1072
+ "temporal_schedule_cleanup_outbox",
1073
+ "workspace_artifact_events",
1074
+ "workspace_artifact_versions",
1075
+ "workspace_instruction_policy_activation_events",
1076
+ "workspace_instruction_policy_onboarding_proposals",
1077
+ "workspace_instruction_policy_revisions",
1078
+ "workspace_learning_policy_revisions"
1079
+ ];
1080
+ var RUNTIME_READ_INSERT_UPDATE_TABLES = [
1081
+ "attached_browser_devices",
1082
+ "attached_browser_inventories",
1083
+ "auth_runs",
1084
+ "browser_identities",
1085
+ "browser_sessions",
1086
+ "browser_state_artifacts",
1087
+ "browser_state_uploads",
1088
+ "capability_api_facets",
1089
+ "capability_facets",
1090
+ "capability_integration_facets",
1091
+ "capability_mcp_facets",
1092
+ "capability_plugin_versions",
1093
+ "capability_plugins",
1094
+ "capability_skill_facets",
1095
+ "capability_skill_files",
1096
+ "computer_sessions",
1097
+ "editable_artifact_session_links",
1098
+ "editable_artifacts",
1099
+ "integration_facet_definitions",
1100
+ "integration_spec_revisions",
1101
+ "integration_tools",
1102
+ "interaction_interventions",
1103
+ "interaction_operations",
1104
+ "interaction_resource_operations",
1105
+ "network_routes",
1106
+ "scheduled_task_runs",
1107
+ "scheduled_tasks",
1108
+ "session_attempt_codemode_calls",
1109
+ "session_turn_startup_milestones",
1110
+ "site_auth_connections",
1111
+ "slack_user_link_access_requests",
1112
+ "workspace_interaction_revisions"
1113
+ ];
1114
+ var PROTECTED_NO_DIRECT_DML_TABLES = [
1115
+ "canonical_human_identities",
1116
+ "canonical_human_identity_operations",
1117
+ "canonical_human_identity_subjects",
1118
+ "canonical_human_login_bindings",
1119
+ "company_brain_context_selection_receipts",
1120
+ "company_brain_preference_proposal_receipts",
1121
+ "company_brain_turn_context_snapshots",
1122
+ "company_profile_agent_confirmation_receipts",
1123
+ "company_profile_agent_proposal_receipts",
1124
+ "connection_use_audit_facts",
1125
+ "connection_use_once_consumption_receipts",
1126
+ "document_default_collection_backfill_operations",
1127
+ "document_default_collection_backfill_receipts",
1128
+ "document_default_collection_backfill_runs",
1129
+ "editable_artifact_live_tickets",
1130
+ "editable_artifact_scope_authorization_heads",
1131
+ "governed_learning_activation_receipts",
1132
+ "governed_learning_activation_undo_receipts",
1133
+ "governed_learning_decision_receipts",
1134
+ "host_export_config",
1135
+ "host_export_consumers",
1136
+ "host_export_cursor_state",
1137
+ "host_export_dead_letters",
1138
+ "host_export_outbox",
1139
+ "organization_invitation_binding_events",
1140
+ "organization_membership_invitations",
1141
+ "organization_membership_lifecycle_events",
1142
+ "organization_membership_operation_receipts",
1143
+ "organization_memberships",
1144
+ "organization_private_session_setting_events",
1145
+ "organization_private_session_settings",
1146
+ "organization_profile_events",
1147
+ "organization_shared_workspace_administration_capabilities",
1148
+ "organization_user_resource_authorities",
1149
+ "organization_user_resource_grants",
1150
+ "organization_user_retention_deletion_events",
1151
+ "organization_user_retention_deletions",
1152
+ "organization_user_retention_object_deletion_receipts",
1153
+ "organization_user_retention_object_obligations",
1154
+ "organization_user_retention_policies",
1155
+ "personal_document_once_consumption_receipts",
1156
+ "personal_github_repository_selection_heads",
1157
+ "personal_github_repository_selection_operations",
1158
+ "personal_github_repository_selections",
1159
+ "personal_resource_once_consumption_receipts",
1160
+ "private_session_create_capabilities",
1161
+ "remember_knowledge_confirmation_receipts",
1162
+ "scheduled_task_connection_authority_snapshots",
1163
+ "scheduled_task_personal_resource_authorities",
1164
+ "scheduled_task_personal_resource_snapshots",
1165
+ "scheduled_task_reusable_connection_materializations",
1166
+ "scheduled_task_revision_authorities",
1167
+ "scheduled_task_run_connection_authority_snapshots",
1168
+ "scheduled_task_run_personal_resource_admissions",
1169
+ "scheduled_task_run_personal_resource_once_receipts",
1170
+ "scheduled_task_run_personal_resource_snapshots",
1171
+ "session_attempt_connected_machine_authorizations",
1172
+ "session_attempt_personal_document_admissions",
1173
+ "session_attempt_personal_document_snapshots",
1174
+ "session_attempt_personal_resource_admissions",
1175
+ "session_attempt_personal_resource_snapshots",
1176
+ "session_visibility_write_capabilities",
1177
+ "task_note_events",
1178
+ "task_note_knowledge_promotion_capabilities",
1179
+ "task_note_replacement_receipts",
1180
+ "task_note_write_capabilities",
1181
+ "task_notes",
1182
+ "tenancy_backfill_receipts",
1183
+ "tenancy_backfill_unresolved_rows",
1184
+ "turn_connection_authority_snapshots",
1185
+ "turn_personal_resource_attachment_receipts",
1186
+ "turn_personal_resource_once_receipts",
1187
+ "turn_personal_resource_snapshots",
1188
+ "workspace_variable_set_variables",
1189
+ "workspace_variable_sets"
1190
+ ];
1191
+ var FULL_DML_PRIVILEGES = ["SELECT", "INSERT", "UPDATE", "DELETE"];
1192
+ var RUNTIME_TABLE_PRIVILEGES = Object.freeze({
1193
+ ...Object.fromEntries(RUNTIME_FULL_DML_TABLES.map((table) => [table, FULL_DML_PRIVILEGES])),
1194
+ ...Object.fromEntries(RUNTIME_READ_ONLY_TABLES.map((table) => [table, ["SELECT"]])),
1195
+ ...Object.fromEntries(
1196
+ RUNTIME_READ_UPDATE_TABLES.map((table) => [table, ["SELECT", "UPDATE"]])
1197
+ ),
1198
+ ...Object.fromEntries(
1199
+ RUNTIME_READ_INSERT_TABLES.map((table) => [table, ["SELECT", "INSERT"]])
1200
+ ),
1201
+ ...Object.fromEntries(
1202
+ RUNTIME_READ_INSERT_UPDATE_TABLES.map((table) => [
1203
+ table,
1204
+ ["SELECT", "INSERT", "UPDATE"]
1205
+ ])
1206
+ )
1207
+ });
1208
+ var RUNTIME_DML_TABLES = Object.freeze(
1209
+ Object.keys(RUNTIME_TABLE_PRIVILEGES).sort((a, b) => a.localeCompare(b))
1210
+ );
1211
+ var RuntimeDatabasePostureError = class extends Error {
1212
+ violations;
1213
+ constructor(violations) {
1214
+ super(`Runtime database posture check failed: ${violations.join("; ")}`);
1215
+ this.name = "RuntimeDatabasePostureError";
1216
+ this.violations = violations;
1217
+ }
1218
+ };
1219
+ function resultRows(result) {
1220
+ if (Array.isArray(result)) {
1221
+ return result;
1222
+ }
1223
+ const rows = result?.rows;
1224
+ if (Array.isArray(rows)) {
1225
+ return rows;
1226
+ }
1227
+ throw new Error("Runtime database posture query returned an unsupported result shape");
1228
+ }
1229
+ function sorted(values) {
1230
+ return [...values].sort((a, b) => a.localeCompare(b));
1231
+ }
1232
+ function difference(left, right) {
1233
+ return sorted([...left].filter((value) => !right.has(value)));
1234
+ }
1235
+ async function inspectRuntimeDatabasePosture(db, options) {
1236
+ const targetSchema = options.targetSchema?.trim() || "public";
1237
+ return await db.transaction(
1238
+ async (tx) => {
1239
+ const identityRows = resultRows(
1240
+ await tx.execute(sql`
1241
+ select
1242
+ current_user::text as current_user,
1243
+ session_user::text as session_user,
1244
+ pg_get_userbyid(d.datdba)::text as database_owner,
1245
+ has_database_privilege(current_user, d.oid, 'CONNECT') as can_connect_database,
1246
+ has_database_privilege(current_user, d.oid, 'CREATE') as can_create_in_database,
1247
+ current_setting('row_security')::text as row_security,
1248
+ r.rolcanlogin,
1249
+ r.rolsuper,
1250
+ r.rolinherit,
1251
+ r.rolcreaterole,
1252
+ r.rolcreatedb,
1253
+ r.rolreplication,
1254
+ r.rolbypassrls
1255
+ from pg_roles r
1256
+ join pg_database d on d.datname = current_database()
1257
+ where r.rolname = current_user
1258
+ `)
1259
+ );
1260
+ const identity = identityRows[0];
1261
+ if (!identity) {
1262
+ throw new Error("Runtime database posture could not resolve the current PostgreSQL role");
1263
+ }
1264
+ const mappedIdentity = {
1265
+ currentUser: identity.current_user,
1266
+ sessionUser: identity.session_user,
1267
+ databaseOwner: identity.database_owner,
1268
+ canConnectDatabase: identity.can_connect_database,
1269
+ canCreateInDatabase: identity.can_create_in_database,
1270
+ rowSecurity: identity.row_security,
1271
+ canLogin: identity.rolcanlogin,
1272
+ superuser: identity.rolsuper,
1273
+ inherit: identity.rolinherit,
1274
+ createRole: identity.rolcreaterole,
1275
+ createDatabase: identity.rolcreatedb,
1276
+ replication: identity.rolreplication,
1277
+ bypassRls: identity.rolbypassrls
1278
+ };
1279
+ const activationRows = resultRows(
1280
+ await tx.execute(sql`select session_tenancy_any_product_activation() as activated`)
1281
+ );
1282
+ const sessionTenancyProductActivationPresent = activationRows[0]?.activated === true;
1283
+ if (options.rlsStrategy === "scoped") {
1284
+ return {
1285
+ identity: mappedIdentity,
1286
+ memberships: [],
1287
+ schemas: [],
1288
+ ownedSchemas: [],
1289
+ ownedRelations: [],
1290
+ tables: [],
1291
+ privateTables: [],
1292
+ targetRoutines: [],
1293
+ privateRoutines: [],
1294
+ sessionTenancyProductActivationPresent
1295
+ };
1296
+ }
1297
+ const relationshipRows = resultRows(
1298
+ await tx.execute(sql.raw(roleRelationshipsCatalogQuery("current_user")))
1299
+ );
1300
+ const memberships = classifyRoleRelationships(relationshipRows).unsafeRelationships;
1301
+ const schemas = resultRows(
1302
+ await tx.execute(sql`
1303
+ select
1304
+ n.nspname::text as name,
1305
+ pg_get_userbyid(n.nspowner)::text as owner,
1306
+ has_schema_privilege(current_user, n.oid, 'USAGE') as usage,
1307
+ has_schema_privilege(current_user, n.oid, 'CREATE') as create
1308
+ from pg_namespace n
1309
+ where n.nspname in (${targetSchema}, 'opengeni_private')
1310
+ order by n.nspname
1311
+ `)
1312
+ );
1313
+ const ownedSchemas = resultRows(
1314
+ await tx.execute(sql`
1315
+ select n.nspname::text as name
1316
+ from pg_namespace n
1317
+ join pg_roles r on r.oid = n.nspowner
1318
+ where r.rolname = current_user
1319
+ and n.nspname <> 'information_schema'
1320
+ and n.nspname !~ '^pg_'
1321
+ order by n.nspname
1322
+ `)
1323
+ ).map((row) => row.name);
1324
+ const ownedRelations = resultRows(
1325
+ await tx.execute(sql`
1326
+ select (n.nspname || '.' || c.relname)::text as name
1327
+ from pg_class c
1328
+ join pg_namespace n on n.oid = c.relnamespace
1329
+ join pg_roles r on r.oid = c.relowner
1330
+ where r.rolname = current_user
1331
+ and c.relkind in ('r', 'p', 'S', 'v', 'm', 'f')
1332
+ and n.nspname <> 'information_schema'
1333
+ and n.nspname !~ '^pg_'
1334
+ order by n.nspname, c.relname
1335
+ `)
1336
+ ).map((row) => row.name);
1337
+ const tables = resultRows(
1338
+ await tx.execute(sql`
1339
+ select
1340
+ c.relname::text as name,
1341
+ pg_get_userbyid(c.relowner)::text as owner,
1342
+ c.relrowsecurity as rls_enabled,
1343
+ c.relforcerowsecurity as rls_forced,
1344
+ row_security_active(c.oid) as rls_active,
1345
+ (select count(*)::int from pg_policy policy where policy.polrelid = c.oid) as policy_count,
1346
+ exists(
1347
+ select 1 from pg_policy policy
1348
+ where policy.polrelid = c.oid
1349
+ and policy.polname = 'editable_artifact_outbox_dispatcher'
1350
+ ) as artifact_outbox_dispatcher_policy,
1351
+ exists(
1352
+ select 1 from pg_policy policy
1353
+ where policy.polrelid = c.oid
1354
+ and policy.polname = 'editable_artifact_materializer_owner'
1355
+ ) as artifact_materializer_policy,
1356
+ has_table_privilege(current_user, c.oid, 'SELECT') as can_select,
1357
+ has_table_privilege(current_user, c.oid, 'INSERT') as can_insert,
1358
+ has_table_privilege(current_user, c.oid, 'UPDATE') as can_update,
1359
+ has_table_privilege(current_user, c.oid, 'DELETE') as can_delete,
1360
+ has_table_privilege(current_user, c.oid, 'TRUNCATE') as can_truncate,
1361
+ has_table_privilege(current_user, c.oid, 'REFERENCES') as can_references,
1362
+ has_table_privilege(current_user, c.oid, 'TRIGGER') as can_trigger
1363
+ from pg_class c
1364
+ join pg_namespace n on n.oid = c.relnamespace
1365
+ where n.nspname = ${targetSchema}
1366
+ and c.relkind in ('r', 'p')
1367
+ order by c.relname
1368
+ `)
1369
+ ).map((row) => ({
1370
+ name: row.name,
1371
+ owner: row.owner,
1372
+ rlsEnabled: row.rls_enabled,
1373
+ rlsForced: row.rls_forced,
1374
+ rlsActive: row.rls_active,
1375
+ policyCount: row.policy_count,
1376
+ artifactOutboxDispatcherPolicy: row.artifact_outbox_dispatcher_policy,
1377
+ artifactMaterializerPolicy: row.artifact_materializer_policy,
1378
+ select: row.can_select,
1379
+ insert: row.can_insert,
1380
+ update: row.can_update,
1381
+ delete: row.can_delete,
1382
+ truncate: row.can_truncate,
1383
+ references: row.can_references,
1384
+ trigger: row.can_trigger
1385
+ }));
1386
+ const privateTables = resultRows(
1387
+ await tx.execute(sql`
1388
+ select
1389
+ c.relname::text as name,
1390
+ pg_get_userbyid(c.relowner)::text as owner,
1391
+ has_table_privilege(current_user, c.oid, 'SELECT') as can_select,
1392
+ has_table_privilege(current_user, c.oid, 'INSERT') as can_insert,
1393
+ has_table_privilege(current_user, c.oid, 'UPDATE') as can_update,
1394
+ has_table_privilege(current_user, c.oid, 'DELETE') as can_delete
1395
+ from pg_class c
1396
+ join pg_namespace n on n.oid = c.relnamespace
1397
+ where n.nspname = 'opengeni_private'
1398
+ and c.relkind in ('r', 'p')
1399
+ and c.relname in (
1400
+ ${PERSONAL_RESOURCE_CAPABILITY_TABLE},
1401
+ ${SCHEDULED_PERSONAL_RESOURCE_CAPABILITY_TABLE},
1402
+ ${VARIABLE_SET_CAPABILITY_TABLE},
1403
+ ${PERSONAL_DOCUMENT_CAPABILITY_TABLE},
1404
+ ${DOCUMENT_MIGRATION_CAPABILITY_TABLE},
1405
+ ${SCOPED_COMPUTE_CAPABILITY_TABLE},
1406
+ ${CONNECTION_TENANCY_BACKFILL_CAPABILITY_TABLE}
1407
+ )
1408
+ `)
1409
+ ).map((row) => ({
1410
+ name: row.name,
1411
+ owner: row.owner,
1412
+ select: row.can_select,
1413
+ insert: row.can_insert,
1414
+ update: row.can_update,
1415
+ delete: row.can_delete
1416
+ }));
1417
+ const targetRoutines = resultRows(
1418
+ await tx.execute(sql`
1419
+ select
1420
+ (p.proname || '(' || pg_catalog.oidvectortypes(p.proargtypes) || ')')::text as name,
1421
+ pg_get_userbyid(p.proowner)::text as owner,
1422
+ has_function_privilege(current_user, p.oid, 'EXECUTE') as can_execute,
1423
+ exists (
1424
+ select 1
1425
+ from aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) acl
1426
+ where acl.grantee = 0 and acl.privilege_type = 'EXECUTE'
1427
+ ) as public_execute,
1428
+ p.prosecdef as security_definer
1429
+ from pg_proc p
1430
+ join pg_namespace n on n.oid = p.pronamespace
1431
+ where n.nspname = ${targetSchema}
1432
+ and p.prokind in ('f', 'p')
1433
+ and (p.proname || '(' || pg_catalog.oidvectortypes(p.proargtypes) || ')') = any(
1434
+ array[
1435
+ ${sql.join(
1436
+ [
1437
+ ...RUNTIME_TARGET_SCHEMA_CAPABILITY_ROUTINES,
1438
+ ...RUNTIME_TARGET_SCHEMA_FORBIDDEN_ROUTINES
1439
+ ].map((name) => sql`${name}`),
1440
+ sql`, `
1441
+ )}
1442
+ ]::text[]
1443
+ )
1444
+ order by p.proname, pg_catalog.oidvectortypes(p.proargtypes)
1445
+ `)
1446
+ ).map((row) => ({
1447
+ name: row.name,
1448
+ owner: row.owner,
1449
+ execute: row.can_execute,
1450
+ publicExecute: row.public_execute,
1451
+ securityDefiner: row.security_definer
1452
+ })).sort((left, right) => left.name.localeCompare(right.name));
1453
+ const privateRoutines = resultRows(
1454
+ await tx.execute(sql`
1455
+ select
1456
+ (p.proname || '(' || pg_catalog.oidvectortypes(p.proargtypes) || ')')::text as name,
1457
+ pg_get_userbyid(p.proowner)::text as owner,
1458
+ has_function_privilege(current_user, p.oid, 'EXECUTE') as can_execute,
1459
+ exists (
1460
+ select 1
1461
+ from aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) acl
1462
+ where acl.grantee = 0 and acl.privilege_type = 'EXECUTE'
1463
+ ) as public_execute,
1464
+ p.prosecdef as security_definer
1465
+ from pg_proc p
1466
+ join pg_namespace n on n.oid = p.pronamespace
1467
+ where n.nspname = 'opengeni_private'
1468
+ and p.prokind in ('f', 'p')
1469
+ order by p.proname, pg_catalog.oidvectortypes(p.proargtypes)
1470
+ `)
1471
+ ).map((row) => ({
1472
+ name: row.name,
1473
+ owner: row.owner,
1474
+ execute: row.can_execute,
1475
+ publicExecute: row.public_execute,
1476
+ securityDefiner: row.security_definer
1477
+ }));
1478
+ return {
1479
+ identity: mappedIdentity,
1480
+ memberships,
1481
+ schemas,
1482
+ ownedSchemas,
1483
+ ownedRelations,
1484
+ tables,
1485
+ privateTables,
1486
+ targetRoutines,
1487
+ privateRoutines,
1488
+ sessionTenancyProductActivationPresent
1489
+ };
1490
+ },
1491
+ { isolationLevel: "repeatable read", accessMode: "read only" }
1492
+ );
1493
+ }
1494
+ function evaluateRuntimeDatabasePosture(posture, options) {
1495
+ const violations = [];
1496
+ const identity = posture.identity;
1497
+ if (posture.sessionTenancyProductActivationPresent && options.organizationTenancyCanonicalActivationEnabled !== true) {
1498
+ violations.push(
1499
+ "session-tenancy product activation is durable but OPENGENI_ORGANIZATION_TENANCY_CANONICAL_ACTIVATION_ENABLED is not true"
1500
+ );
1501
+ }
1502
+ if (!identity.currentUser || !identity.sessionUser) {
1503
+ violations.push("database identity is empty");
1504
+ }
1505
+ if (identity.currentUser !== identity.sessionUser) {
1506
+ violations.push(
1507
+ `current_user ${identity.currentUser} does not match session_user ${identity.sessionUser}`
1508
+ );
1509
+ }
1510
+ if (!identity.canConnectDatabase) {
1511
+ violations.push("runtime role lacks CONNECT on the current database");
1512
+ }
1513
+ if (options.rlsStrategy === "scoped") {
1514
+ return violations;
1515
+ }
1516
+ const expectedRole = options.expectedRole?.trim() || "opengeni_app";
1517
+ const targetSchema = options.targetSchema?.trim() || "public";
1518
+ const protectedTables = new Set(options.protectedTables ?? FORCE_RLS_TABLES);
1519
+ const tablePrivileges = options.tablePrivileges ?? RUNTIME_TABLE_PRIVILEGES;
1520
+ const directRuntimeTables = new Set(Object.keys(tablePrivileges));
1521
+ const protectedNoDirectDmlTables = new Set(
1522
+ options.protectedNoDirectDmlTables ?? (options.protectedTables ? [] : PROTECTED_NO_DIRECT_DML_TABLES)
1523
+ );
1524
+ if (identity.currentUser !== expectedRole || identity.sessionUser !== expectedRole) {
1525
+ violations.push(
1526
+ `runtime identity must be ${expectedRole} (current_user=${identity.currentUser}, session_user=${identity.sessionUser})`
1527
+ );
1528
+ }
1529
+ if (!identity.canLogin) violations.push("runtime role is not LOGIN");
1530
+ if (identity.superuser) violations.push("runtime role is SUPERUSER");
1531
+ if (identity.bypassRls) violations.push("runtime role has BYPASSRLS");
1532
+ if (identity.createRole) violations.push("runtime role has CREATEROLE");
1533
+ if (identity.createDatabase) violations.push("runtime role has CREATEDB");
1534
+ if (identity.replication) violations.push("runtime role has REPLICATION");
1535
+ if (identity.inherit) violations.push("runtime role must be NOINHERIT");
1536
+ if (identity.databaseOwner === expectedRole) violations.push("runtime role owns the database");
1537
+ if (identity.canCreateInDatabase) {
1538
+ violations.push("runtime role has CREATE on the current database");
1539
+ }
1540
+ if (identity.rowSecurity.toLowerCase() !== "on") {
1541
+ violations.push(`row_security is ${identity.rowSecurity}, expected on`);
1542
+ }
1543
+ if (posture.memberships.length > 0) {
1544
+ violations.push(`runtime role has memberships: ${sorted(posture.memberships).join(", ")}`);
1545
+ }
1546
+ if (posture.ownedSchemas.length > 0) {
1547
+ violations.push(`runtime role owns schemas: ${sorted(posture.ownedSchemas).join(", ")}`);
1548
+ }
1549
+ if (posture.ownedRelations.length > 0) {
1550
+ violations.push(`runtime role owns relations: ${sorted(posture.ownedRelations).join(", ")}`);
1551
+ }
1552
+ for (const schemaName of /* @__PURE__ */ new Set([targetSchema, "opengeni_private"])) {
1553
+ const schema = posture.schemas.find((candidate) => candidate.name === schemaName);
1554
+ if (!schema) {
1555
+ violations.push(`required schema ${schemaName} is missing`);
1556
+ continue;
1557
+ }
1558
+ if (schema.owner === expectedRole) {
1559
+ violations.push(`runtime role owns schema ${schemaName}`);
1560
+ }
1561
+ if (!schema.usage) violations.push(`runtime role lacks USAGE on schema ${schemaName}`);
1562
+ if (schema.create) violations.push(`runtime role has CREATE on schema ${schemaName}`);
1563
+ }
1564
+ const tableByName = new Map(posture.tables.map((table) => [table.name, table]));
1565
+ const actualRlsTables = new Set(
1566
+ posture.tables.filter((table) => table.rlsEnabled).map((table) => table.name)
1567
+ );
1568
+ const classifiedProtectedTables = /* @__PURE__ */ new Set([
1569
+ ...directRuntimeTables,
1570
+ ...protectedNoDirectDmlTables
1571
+ ]);
1572
+ const unclassifiedProtectedTables = difference(protectedTables, classifiedProtectedTables);
1573
+ if (unclassifiedProtectedTables.length > 0) {
1574
+ violations.push(
1575
+ `protected tables lack an explicit privilege class: ${unclassifiedProtectedTables.join(", ")}`
1576
+ );
1577
+ }
1578
+ const protectedNoDirectDmlOverlap = difference(
1579
+ protectedNoDirectDmlTables,
1580
+ new Set([...protectedNoDirectDmlTables].filter((table) => !directRuntimeTables.has(table)))
1581
+ );
1582
+ if (protectedNoDirectDmlOverlap.length > 0) {
1583
+ violations.push(
1584
+ `protected no-direct-DML tables also declare runtime privileges: ${protectedNoDirectDmlOverlap.join(", ")}`
1585
+ );
1586
+ }
1587
+ const nonProtectedNoDirectDmlTables = difference(protectedNoDirectDmlTables, protectedTables);
1588
+ if (nonProtectedNoDirectDmlTables.length > 0) {
1589
+ violations.push(
1590
+ `no-direct-DML tables are absent from the protected contract: ${nonProtectedNoDirectDmlTables.join(", ")}`
1591
+ );
1592
+ }
1593
+ const catalogTables = new Set(tableByName.keys());
1594
+ const missingRuntimeTables = difference(directRuntimeTables, catalogTables);
1595
+ if (missingRuntimeTables.length > 0) {
1596
+ violations.push(`runtime privilege tables are missing: ${missingRuntimeTables.join(", ")}`);
1597
+ }
1598
+ const missingTables = difference(protectedTables, catalogTables);
1599
+ if (missingTables.length > 0) {
1600
+ violations.push(`protected tables are missing: ${missingTables.join(", ")}`);
1601
+ }
1602
+ const undeclaredRlsTables = difference(actualRlsTables, protectedTables);
1603
+ if (undeclaredRlsTables.length > 0) {
1604
+ violations.push(
1605
+ `RLS tables are absent from the declared contract: ${undeclaredRlsTables.join(", ")}`
1606
+ );
1607
+ }
1608
+ for (const table of posture.tables) {
1609
+ const privileges = [
1610
+ ["SELECT", table.select],
1611
+ ["INSERT", table.insert],
1612
+ ["UPDATE", table.update],
1613
+ ["DELETE", table.delete],
1614
+ ["TRUNCATE", table.truncate],
1615
+ ["REFERENCES", table.references],
1616
+ ["TRIGGER", table.trigger]
1617
+ ];
1618
+ const expectedPrivileges = new Set(tablePrivileges[table.name] ?? []);
1619
+ if (table.owner === expectedRole) {
1620
+ violations.push(`runtime role owns table ${table.name}`);
1621
+ }
1622
+ const missingPrivileges = privileges.filter(([privilege, granted]) => expectedPrivileges.has(privilege) && !granted).map(([privilege]) => privilege);
1623
+ if (missingPrivileges.length > 0) {
1624
+ violations.push(
1625
+ `table ${table.name} lacks required runtime privileges: ${missingPrivileges.join(", ")}`
1626
+ );
1627
+ }
1628
+ const excessPrivileges = privileges.filter(([privilege, granted]) => !expectedPrivileges.has(privilege) && granted).map(([privilege]) => privilege);
1629
+ if (excessPrivileges.length > 0) {
1630
+ violations.push(
1631
+ `table ${table.name} grants excess runtime privileges: ${excessPrivileges.join(", ")}`
1632
+ );
1633
+ }
1634
+ }
1635
+ for (const tableName of protectedTables) {
1636
+ const table = tableByName.get(tableName);
1637
+ if (!table) continue;
1638
+ if (!table.rlsEnabled) violations.push(`table ${tableName} does not ENABLE RLS`);
1639
+ if (!table.rlsForced) violations.push(`table ${tableName} does not FORCE RLS`);
1640
+ if (!table.rlsActive) violations.push(`table ${tableName} has inactive RLS for runtime role`);
1641
+ if (table.policyCount < 1) violations.push(`table ${tableName} has no RLS policy`);
1642
+ }
1643
+ const targetSchemaOwner = posture.schemas.find((schema) => schema.name === targetSchema)?.owner;
1644
+ for (const forbiddenRoutine of RUNTIME_TARGET_SCHEMA_FORBIDDEN_ROUTINES) {
1645
+ const matches = posture.targetRoutines.filter((routine2) => routine2.name === forbiddenRoutine);
1646
+ if (matches.length !== 1) {
1647
+ violations.push(
1648
+ `owner-internal target-schema helper ${forbiddenRoutine} is missing or ambiguous`
1649
+ );
1650
+ continue;
1651
+ }
1652
+ const routine = matches[0];
1653
+ if (!routine.securityDefiner) {
1654
+ violations.push(
1655
+ `owner-internal target-schema helper ${routine.name} is not SECURITY DEFINER`
1656
+ );
1657
+ }
1658
+ const authorityOwner = tableByName.get("sessions")?.owner ?? targetSchemaOwner;
1659
+ if (authorityOwner && routine.owner !== authorityOwner) {
1660
+ violations.push(
1661
+ `owner-internal target-schema helper ${routine.name} owner ${routine.owner} does not match session authority owner ${authorityOwner}`
1662
+ );
1663
+ }
1664
+ if (routine.execute) {
1665
+ violations.push(`runtime role has forbidden owner-internal helper ${routine.name}`);
1666
+ }
1667
+ if (routine.publicExecute) {
1668
+ violations.push(`PUBLIC has forbidden owner-internal helper ${routine.name}`);
1669
+ }
1670
+ }
1671
+ for (const expectedRoutine of RUNTIME_TARGET_SCHEMA_CAPABILITY_ROUTINES) {
1672
+ const matches = posture.targetRoutines.filter((routine2) => routine2.name === expectedRoutine);
1673
+ if (matches.length !== 1) {
1674
+ violations.push(
1675
+ `target-schema runtime capability ${expectedRoutine} is missing or ambiguous`
1676
+ );
1677
+ continue;
1678
+ }
1679
+ const routine = matches[0];
1680
+ if (RUNTIME_TARGET_SCHEMA_INVOKER_ROUTINE_SET.has(routine.name)) {
1681
+ if (routine.securityDefiner) {
1682
+ violations.push(
1683
+ `target-schema runtime capability ${routine.name} must be SECURITY INVOKER`
1684
+ );
1685
+ }
1686
+ } else if (!routine.securityDefiner) {
1687
+ violations.push(`target-schema runtime capability ${routine.name} is not SECURITY DEFINER`);
1688
+ }
1689
+ if (routine.name === GOOGLE_DRIVE_FILE_AUTHORIZATION_ROUTINE || routine.name === GOOGLE_DRIVE_DOCUMENT_CITATION_ROUTINE) {
1690
+ const missingAuthorityTables = GOOGLE_DRIVE_AUTHORITY_TABLES.filter(
1691
+ (tableName) => !tableByName.has(tableName)
1692
+ );
1693
+ if (missingAuthorityTables.length > 0) {
1694
+ violations.push(
1695
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
1696
+ );
1697
+ } else {
1698
+ const authorityTables = GOOGLE_DRIVE_AUTHORITY_TABLES.map(
1699
+ (tableName) => tableByName.get(tableName)
1700
+ );
1701
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1702
+ if (authorityOwners.size !== 1) {
1703
+ violations.push(
1704
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1705
+ );
1706
+ } else if (routine.owner !== authorityTables[0].owner) {
1707
+ violations.push(
1708
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1709
+ );
1710
+ }
1711
+ }
1712
+ } else if (routine.name === KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_ROUTINE) {
1713
+ const missingAuthorityTables = KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_TABLES.filter(
1714
+ (tableName) => !tableByName.has(tableName)
1715
+ );
1716
+ if (missingAuthorityTables.length > 0) {
1717
+ violations.push(
1718
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
1719
+ );
1720
+ } else {
1721
+ const authorityTables = KNOWLEDGE_SOURCE_SYNC_LOCK_AUTHORITY_TABLES.map(
1722
+ (tableName) => tableByName.get(tableName)
1723
+ );
1724
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1725
+ if (authorityOwners.size !== 1) {
1726
+ violations.push(
1727
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1728
+ );
1729
+ } else if (routine.owner !== authorityTables[0].owner) {
1730
+ violations.push(
1731
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1732
+ );
1733
+ }
1734
+ }
1735
+ } else if (routine.name === MANAGED_HUMAN_PERSONAL_WORKSPACE_ROUTINE) {
1736
+ const authorityTables = MANAGED_HUMAN_PERSONAL_WORKSPACE_AUTHORITY_TABLES.filter(
1737
+ (tableName) => tableByName.has(tableName)
1738
+ ).map((tableName) => tableByName.get(tableName));
1739
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1740
+ if (authorityOwners.size > 1) {
1741
+ violations.push(
1742
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1743
+ );
1744
+ } else if (authorityTables[0] && routine.owner !== authorityTables[0].owner) {
1745
+ violations.push(
1746
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1747
+ );
1748
+ }
1749
+ } else if (routine.name === GOVERNED_LEARNING_EVALUATION_ROUTINE) {
1750
+ if (!tableByName.has("governed_learning_decision_receipts")) {
1751
+ continue;
1752
+ }
1753
+ const missingAuthorityTables = GOVERNED_LEARNING_EVALUATION_AUTHORITY_TABLES.filter(
1754
+ (tableName) => !tableByName.has(tableName)
1755
+ );
1756
+ if (missingAuthorityTables.length > 0) {
1757
+ violations.push(
1758
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
1759
+ );
1760
+ } else {
1761
+ const authorityTables = GOVERNED_LEARNING_EVALUATION_AUTHORITY_TABLES.map(
1762
+ (tableName) => tableByName.get(tableName)
1763
+ );
1764
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1765
+ if (authorityOwners.size !== 1) {
1766
+ violations.push(
1767
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1768
+ );
1769
+ } else if (routine.owner !== authorityTables[0].owner) {
1770
+ violations.push(
1771
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1772
+ );
1773
+ }
1774
+ }
1775
+ } else if (GOVERNED_LEARNING_INSPECTION_ROUTINES.includes(
1776
+ routine.name
1777
+ )) {
1778
+ if (!tableByName.has("governed_learning_decision_receipts")) continue;
1779
+ const missingAuthorityTables = GOVERNED_LEARNING_INSPECTION_AUTHORITY_TABLES.filter(
1780
+ (name) => !tableByName.has(name)
1781
+ );
1782
+ if (missingAuthorityTables.length > 0) {
1783
+ violations.push(
1784
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
1785
+ );
1786
+ } else {
1787
+ const authorityTables = GOVERNED_LEARNING_INSPECTION_AUTHORITY_TABLES.map(
1788
+ (name) => tableByName.get(name)
1789
+ );
1790
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1791
+ if (authorityOwners.size !== 1 || routine.owner !== authorityTables[0].owner) {
1792
+ violations.push(
1793
+ `target-schema runtime capability ${routine.name} owner does not match governed-learning inspection authority`
1794
+ );
1795
+ }
1796
+ }
1797
+ } else if (GOVERNED_LEARNING_ACTIVATION_ROUTINES.includes(
1798
+ routine.name
1799
+ )) {
1800
+ if (!tableByName.has("governed_learning_activation_receipts")) {
1801
+ continue;
1802
+ }
1803
+ const missingAuthorityTables = GOVERNED_LEARNING_ACTIVATION_AUTHORITY_TABLES.filter(
1804
+ (tableName) => !tableByName.has(tableName)
1805
+ );
1806
+ if (missingAuthorityTables.length > 0) {
1807
+ violations.push(
1808
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
1809
+ );
1810
+ } else {
1811
+ const authorityTables = GOVERNED_LEARNING_ACTIVATION_AUTHORITY_TABLES.map(
1812
+ (tableName) => tableByName.get(tableName)
1813
+ );
1814
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1815
+ if (authorityOwners.size !== 1) {
1816
+ violations.push(
1817
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1818
+ );
1819
+ } else if (routine.owner !== authorityTables[0].owner) {
1820
+ violations.push(
1821
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1822
+ );
1823
+ }
1824
+ }
1825
+ } else if (COMPANY_PROFILE_AGENT_ADMIN_ROUTINES.includes(
1826
+ routine.name
1827
+ )) {
1828
+ const missingAuthorityTables = COMPANY_PROFILE_AGENT_ADMIN_AUTHORITY_TABLES.filter(
1829
+ (tableName) => !tableByName.has(tableName)
1830
+ );
1831
+ if (missingAuthorityTables.length > 0) {
1832
+ violations.push(
1833
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
1834
+ );
1835
+ } else {
1836
+ const authorityTables = COMPANY_PROFILE_AGENT_ADMIN_AUTHORITY_TABLES.map(
1837
+ (tableName) => tableByName.get(tableName)
1838
+ );
1839
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1840
+ if (authorityOwners.size !== 1) {
1841
+ violations.push(
1842
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1843
+ );
1844
+ } else if (routine.owner !== authorityTables[0].owner) {
1845
+ violations.push(
1846
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1847
+ );
1848
+ }
1849
+ }
1850
+ } else if (ORGANIZATION_MEMBERSHIP_LIFECYCLE_ROUTINES.includes(routine.name)) {
1851
+ const missingAuthorityTables = ORGANIZATION_MEMBERSHIP_LIFECYCLE_AUTHORITY_TABLES.filter(
1852
+ (tableName) => !tableByName.has(tableName)
1853
+ );
1854
+ if (missingAuthorityTables.length > 0) {
1855
+ violations.push(
1856
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
1857
+ );
1858
+ } else {
1859
+ const authorityTables = ORGANIZATION_MEMBERSHIP_LIFECYCLE_AUTHORITY_TABLES.map(
1860
+ (tableName) => tableByName.get(tableName)
1861
+ );
1862
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1863
+ if (authorityOwners.size !== 1) {
1864
+ violations.push(
1865
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1866
+ );
1867
+ } else if (routine.owner !== authorityTables[0].owner) {
1868
+ violations.push(
1869
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1870
+ );
1871
+ }
1872
+ }
1873
+ } else if (ORGANIZATION_PRIVATE_SESSION_ROUTINES.includes(routine.name)) {
1874
+ if (!tableByName.has("organization_private_session_settings")) {
1875
+ continue;
1876
+ }
1877
+ const authorityTableNames = ORGANIZATION_PRIVATE_SESSION_ROUTINE_AUTHORITY_TABLES[routine.name];
1878
+ const missingAuthorityTables = authorityTableNames.filter(
1879
+ (tableName) => !tableByName.has(tableName)
1880
+ );
1881
+ if (missingAuthorityTables.length > 0) {
1882
+ violations.push(
1883
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
1884
+ );
1885
+ } else {
1886
+ const authorityTables = authorityTableNames.map((tableName) => tableByName.get(tableName));
1887
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1888
+ if (authorityOwners.size !== 1) {
1889
+ violations.push(
1890
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1891
+ );
1892
+ } else if (routine.owner !== authorityTables[0].owner) {
1893
+ violations.push(
1894
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1895
+ );
1896
+ }
1897
+ }
1898
+ } else if (routine.name === PREFERENCE_KNOWLEDGE_PROPOSAL_ROUTINE) {
1899
+ if (!tableByName.has("company_brain_preference_proposal_receipts")) {
1900
+ continue;
1901
+ }
1902
+ const missingAuthorityTables = PREFERENCE_KNOWLEDGE_PROPOSAL_AUTHORITY_TABLES.filter(
1903
+ (tableName) => !tableByName.has(tableName)
1904
+ );
1905
+ if (missingAuthorityTables.length > 0) {
1906
+ violations.push(
1907
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
1908
+ );
1909
+ } else {
1910
+ const authorityTables = PREFERENCE_KNOWLEDGE_PROPOSAL_AUTHORITY_TABLES.map(
1911
+ (tableName) => tableByName.get(tableName)
1912
+ );
1913
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1914
+ if (authorityOwners.size !== 1) {
1915
+ violations.push(
1916
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1917
+ );
1918
+ } else if (routine.owner !== authorityTables[0].owner) {
1919
+ violations.push(
1920
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1921
+ );
1922
+ }
1923
+ }
1924
+ } else if (CANONICAL_HUMAN_IDENTITY_ROUTINES.includes(routine.name)) {
1925
+ const authorityTables = CANONICAL_HUMAN_IDENTITY_AUTHORITY_TABLES.filter(
1926
+ (tableName) => tableByName.has(tableName)
1927
+ ).map((tableName) => tableByName.get(tableName));
1928
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1929
+ if (authorityTables.length !== CANONICAL_HUMAN_IDENTITY_AUTHORITY_TABLES.length) {
1930
+ violations.push(
1931
+ `target-schema runtime capability ${routine.name} canonical identity authority tables are missing`
1932
+ );
1933
+ } else if (authorityOwners.size !== 1) {
1934
+ violations.push(
1935
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
1936
+ );
1937
+ } else if (routine.owner !== authorityTables[0].owner) {
1938
+ violations.push(
1939
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
1940
+ );
1941
+ }
1942
+ } else if (PERSONAL_GITHUB_REPOSITORY_AUTHORITY_ROUTINES.includes(routine.name)) {
1943
+ const authorityTables = PERSONAL_GITHUB_REPOSITORY_AUTHORITY_TABLES.map(
1944
+ (tableName) => tableByName.get(tableName)
1945
+ ).filter((table) => table !== void 0);
1946
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1947
+ if (authorityOwners.size > 1) {
1948
+ violations.push(
1949
+ `target-schema runtime capability ${routine.name} personal GitHub repository authority table owners do not match`
1950
+ );
1951
+ } else {
1952
+ const authorityOwner = authorityTables[0]?.owner ?? targetSchemaOwner;
1953
+ if (authorityOwner && routine.owner !== authorityOwner) {
1954
+ violations.push(
1955
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match personal GitHub repository authority owner ${authorityOwner}`
1956
+ );
1957
+ }
1958
+ }
1959
+ } else if (PERSONAL_DOCUMENT_AUTHORITY_ROUTINES.includes(routine.name) || DOCUMENT_MIGRATION_AUTHORITY_ROUTINES.includes(routine.name)) {
1960
+ const authorityOwner = tableByName.get("documents")?.owner ?? targetSchemaOwner;
1961
+ if (authorityOwner && routine.owner !== authorityOwner) {
1962
+ violations.push(
1963
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match document authority owner ${authorityOwner}`
1964
+ );
1965
+ }
1966
+ } else if (VARIABLE_SET_AUTHORITY_ROUTINES.includes(routine.name)) {
1967
+ const authorityTables = ["workspace_variable_sets", "workspace_variable_set_variables"].map((tableName) => tableByName.get(tableName)).filter((table) => table !== void 0);
1968
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1969
+ if (authorityOwners.size > 1) {
1970
+ violations.push(
1971
+ `target-schema runtime capability ${routine.name} variable-set table owners do not match`
1972
+ );
1973
+ } else {
1974
+ const authorityOwner = authorityTables[0]?.owner ?? targetSchemaOwner;
1975
+ if (authorityOwner && routine.owner !== authorityOwner) {
1976
+ violations.push(
1977
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match variable-set authority owner ${authorityOwner}`
1978
+ );
1979
+ }
1980
+ }
1981
+ } else if (SCOPED_COMPUTE_AUTHORITY_ROUTINES.includes(routine.name)) {
1982
+ const authorityTables = ["rigs", "rig_versions", "enrollments", "sandboxes"].map((tableName) => tableByName.get(tableName)).filter((table) => table !== void 0);
1983
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
1984
+ if (authorityOwners.size > 1) {
1985
+ violations.push(
1986
+ `target-schema runtime capability ${routine.name} scoped-compute table owners do not match`
1987
+ );
1988
+ } else {
1989
+ const authorityOwner = authorityTables[0]?.owner ?? targetSchemaOwner;
1990
+ if (authorityOwner && routine.owner !== authorityOwner) {
1991
+ violations.push(
1992
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match scoped-compute authority owner ${authorityOwner}`
1993
+ );
1994
+ }
1995
+ }
1996
+ } else if (SESSION_AUTHORITY_ROUTINES.has(routine.name)) {
1997
+ const authorityOwner = tableByName.get("sessions")?.owner ?? targetSchemaOwner;
1998
+ if (authorityOwner && routine.owner !== authorityOwner) {
1999
+ violations.push(
2000
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match session authority owner ${authorityOwner}`
2001
+ );
2002
+ }
2003
+ } else if (routine.name === XAI_SNAPSHOT_VALIDATOR_ROUTINE) {
2004
+ } else if (routine.name === XAI_CREATE_CREDENTIAL_ROUTINE || routine.name === XAI_DISCONNECT_CREDENTIAL_ROUTINE || routine.name === XAI_AUTHORITY_LIVE_ROUTINE || routine.name === XAI_POOL_VISIBLE_ROUTINE || routine.name === XAI_RESOLVE_POOL_ROUTINE || routine.name === XAI_REVALIDATE_CREDENTIAL_ROUTINE) {
2005
+ if (!tableByName.has("xai_subscription_credentials")) {
2006
+ continue;
2007
+ }
2008
+ const missingAuthorityTables = XAI_AUTHORITY_TABLES.filter(
2009
+ (tableName) => !tableByName.has(tableName)
2010
+ );
2011
+ if (missingAuthorityTables.length > 0) {
2012
+ violations.push(
2013
+ `target-schema runtime capability ${routine.name} authority tables are missing: ${missingAuthorityTables.join(", ")}`
2014
+ );
2015
+ } else {
2016
+ const authorityTables = XAI_AUTHORITY_TABLES.map(
2017
+ (tableName) => tableByName.get(tableName)
2018
+ );
2019
+ const authorityOwners = new Set(authorityTables.map((table) => table.owner));
2020
+ if (authorityOwners.size !== 1) {
2021
+ violations.push(
2022
+ `target-schema runtime capability ${routine.name} authority table owners do not match: ${authorityTables.map((table) => `${table.name}=${table.owner}`).join(", ")}`
2023
+ );
2024
+ } else if (routine.owner !== authorityTables[0].owner) {
2025
+ violations.push(
2026
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match authority table owner ${authorityTables[0].owner}`
2027
+ );
2028
+ }
2029
+ }
2030
+ } else if (targetSchemaOwner && routine.owner !== targetSchemaOwner) {
2031
+ violations.push(
2032
+ `target-schema runtime capability ${routine.name} owner ${routine.owner} does not match schema owner ${targetSchemaOwner}`
2033
+ );
2034
+ }
2035
+ if (!routine.execute) {
2036
+ violations.push(`runtime role lacks target-schema capability ${routine.name}`);
2037
+ }
2038
+ if (routine.publicExecute) {
2039
+ violations.push(`PUBLIC has forbidden target-schema capability ${routine.name}`);
2040
+ }
2041
+ }
2042
+ const artifactOutbox = tableByName.get("editable_artifact_live_outbox");
2043
+ if (artifactOutbox) {
2044
+ if (!artifactOutbox.artifactOutboxDispatcherPolicy) {
2045
+ violations.push("table editable_artifact_live_outbox lacks its owner dispatcher RLS policy");
2046
+ }
2047
+ for (const expectedRoutine of ARTIFACT_OUTBOX_CAPABILITY_ROUTINES) {
2048
+ const matches = posture.privateRoutines.filter((routine2) => routine2.name === expectedRoutine);
2049
+ if (matches.length !== 1) {
2050
+ violations.push(`artifact outbox capability ${expectedRoutine} is missing or ambiguous`);
2051
+ continue;
2052
+ }
2053
+ const routine = matches[0];
2054
+ if (!routine.securityDefiner) {
2055
+ violations.push(`artifact outbox capability ${routine.name} is not SECURITY DEFINER`);
2056
+ }
2057
+ if (routine.owner !== artifactOutbox.owner) {
2058
+ violations.push(
2059
+ `artifact outbox capability ${routine.name} owner ${routine.owner} does not match table owner ${artifactOutbox.owner}`
2060
+ );
2061
+ }
2062
+ if (routine.execute) {
2063
+ violations.push(
2064
+ `generic runtime role has forbidden global artifact outbox capability ${routine.name}`
2065
+ );
2066
+ }
2067
+ }
2068
+ }
2069
+ const artifactMaterializationJobs = tableByName.get("editable_artifact_materialization_jobs");
2070
+ if (artifactMaterializationJobs) {
2071
+ for (const tableName of [
2072
+ "editable_artifact_materialization_jobs",
2073
+ "editable_artifact_materialization_results",
2074
+ "editable_artifact_blob_refs",
2075
+ "editable_artifact_sequence_checkpoints",
2076
+ "editable_artifact_versions",
2077
+ "editable_artifact_idempotency_receipts"
2078
+ ]) {
2079
+ const table = tableByName.get(tableName);
2080
+ if (table && !table.artifactMaterializerPolicy) {
2081
+ violations.push(`table ${tableName} lacks its owner materializer RLS policy`);
2082
+ }
2083
+ }
2084
+ for (const expectedRoutine of ARTIFACT_MATERIALIZER_CAPABILITY_ROUTINES) {
2085
+ const matches = posture.privateRoutines.filter((routine2) => routine2.name === expectedRoutine);
2086
+ if (matches.length !== 1) {
2087
+ violations.push(
2088
+ `artifact materializer capability ${expectedRoutine} is missing or ambiguous`
2089
+ );
2090
+ continue;
2091
+ }
2092
+ const routine = matches[0];
2093
+ if (!routine.securityDefiner) {
2094
+ violations.push(`artifact materializer capability ${routine.name} is not SECURITY DEFINER`);
2095
+ }
2096
+ if (routine.owner !== artifactMaterializationJobs.owner) {
2097
+ violations.push(
2098
+ `artifact materializer capability ${routine.name} owner ${routine.owner} does not match table owner ${artifactMaterializationJobs.owner}`
2099
+ );
2100
+ }
2101
+ if (routine.execute) {
2102
+ violations.push(
2103
+ `generic runtime role has forbidden global artifact materializer capability ${routine.name}`
2104
+ );
2105
+ }
2106
+ }
2107
+ }
2108
+ const artifactAuthority = tableByName.get("editable_artifacts");
2109
+ if (artifactAuthority) {
2110
+ const matches = posture.privateRoutines.filter(
2111
+ (routine) => routine.name.startsWith("advance_editable_artifact_authorization_revision(")
2112
+ );
2113
+ if (matches.length !== 1) {
2114
+ violations.push(
2115
+ "editable artifact authorization revision capability is missing or ambiguous"
2116
+ );
2117
+ } else {
2118
+ const routine = matches[0];
2119
+ if (!routine.securityDefiner) {
2120
+ violations.push(
2121
+ `editable artifact authorization revision capability ${routine.name} is not SECURITY DEFINER`
2122
+ );
2123
+ }
2124
+ if (routine.owner !== artifactAuthority.owner) {
2125
+ violations.push(
2126
+ `editable artifact authorization revision capability ${routine.name} owner ${routine.owner} does not match table owner ${artifactAuthority.owner}`
2127
+ );
2128
+ }
2129
+ }
2130
+ for (const expectedRoutine of ARTIFACT_AUTHORIZATION_CAPABILITY_ROUTINES) {
2131
+ const capabilityMatches = posture.privateRoutines.filter(
2132
+ (routine2) => routine2.name === expectedRoutine
2133
+ );
2134
+ if (capabilityMatches.length !== 1) {
2135
+ violations.push(
2136
+ `editable artifact authorization capability ${expectedRoutine} is missing or ambiguous`
2137
+ );
2138
+ continue;
2139
+ }
2140
+ const routine = capabilityMatches[0];
2141
+ if (!routine.securityDefiner) {
2142
+ violations.push(
2143
+ `editable artifact authorization capability ${routine.name} is not SECURITY DEFINER`
2144
+ );
2145
+ }
2146
+ if (routine.owner !== artifactAuthority.owner) {
2147
+ violations.push(
2148
+ `editable artifact authorization capability ${routine.name} owner ${routine.owner} does not match table owner ${artifactAuthority.owner}`
2149
+ );
2150
+ }
2151
+ if (!routine.execute) {
2152
+ violations.push(
2153
+ `runtime role lacks editable artifact authorization capability ${routine.name}`
2154
+ );
2155
+ }
2156
+ }
2157
+ }
2158
+ const artifactLiveTickets = tableByName.get("editable_artifact_live_tickets");
2159
+ if (artifactLiveTickets) {
2160
+ for (const expectedRoutine of ARTIFACT_LIVE_TICKET_CAPABILITY_ROUTINES) {
2161
+ const matches = posture.privateRoutines.filter((routine2) => routine2.name === expectedRoutine);
2162
+ if (matches.length !== 1) {
2163
+ violations.push(
2164
+ `artifact live ticket capability ${expectedRoutine} is missing or ambiguous`
2165
+ );
2166
+ continue;
2167
+ }
2168
+ const routine = matches[0];
2169
+ if (!routine.securityDefiner) {
2170
+ violations.push(`artifact live ticket capability ${routine.name} is not SECURITY DEFINER`);
2171
+ }
2172
+ if (routine.owner !== artifactLiveTickets.owner) {
2173
+ violations.push(
2174
+ `artifact live ticket capability ${routine.name} owner ${routine.owner} does not match table owner ${artifactLiveTickets.owner}`
2175
+ );
2176
+ }
2177
+ if (!routine.execute) {
2178
+ violations.push(`runtime role lacks artifact live ticket capability ${routine.name}`);
2179
+ }
2180
+ }
2181
+ for (const internalRoutine of ARTIFACT_LIVE_TICKET_INTERNAL_ROUTINES) {
2182
+ const matches = posture.privateRoutines.filter((routine2) => routine2.name === internalRoutine);
2183
+ if (matches.length !== 1) {
2184
+ violations.push(
2185
+ `artifact live ticket internal routine ${internalRoutine} is missing or ambiguous`
2186
+ );
2187
+ continue;
2188
+ }
2189
+ const routine = matches[0];
2190
+ if (!routine.securityDefiner) {
2191
+ violations.push(
2192
+ `artifact live ticket internal routine ${routine.name} is not SECURITY DEFINER`
2193
+ );
2194
+ }
2195
+ if (routine.owner !== artifactLiveTickets.owner) {
2196
+ violations.push(
2197
+ `artifact live ticket internal routine ${routine.name} owner ${routine.owner} does not match table owner ${artifactLiveTickets.owner}`
2198
+ );
2199
+ }
2200
+ if (routine.execute) {
2201
+ violations.push(`runtime role has forbidden ticket schema resolver ${routine.name}`);
2202
+ }
2203
+ }
2204
+ }
2205
+ const personalResourceCapabilityTables = posture.privateTables.filter(
2206
+ (table) => table.name === PERSONAL_RESOURCE_CAPABILITY_TABLE
2207
+ );
2208
+ const personalResourceCapabilityRoutines = posture.privateRoutines.filter(
2209
+ (routine) => routine.name === PERSONAL_RESOURCE_CAPABILITY_PREDICATE_ROUTINE
2210
+ );
2211
+ if (personalResourceCapabilityTables.length !== 1) {
2212
+ violations.push(
2213
+ `personal-resource capability table ${PERSONAL_RESOURCE_CAPABILITY_TABLE} is missing or ambiguous`
2214
+ );
2215
+ }
2216
+ if (personalResourceCapabilityRoutines.length !== 1) {
2217
+ violations.push(
2218
+ `personal-resource capability predicate ${PERSONAL_RESOURCE_CAPABILITY_PREDICATE_ROUTINE} is missing or ambiguous`
2219
+ );
2220
+ }
2221
+ if (personalResourceCapabilityTables.length === 1 && personalResourceCapabilityRoutines.length === 1) {
2222
+ const table = personalResourceCapabilityTables[0];
2223
+ const routine = personalResourceCapabilityRoutines[0];
2224
+ if (routine.owner !== table.owner) {
2225
+ violations.push(
2226
+ `personal-resource capability predicate ${routine.name} owner ${routine.owner} does not match table owner ${table.owner}`
2227
+ );
2228
+ }
2229
+ if (!routine.securityDefiner) {
2230
+ violations.push(
2231
+ `personal-resource capability predicate ${routine.name} is not SECURITY DEFINER`
2232
+ );
2233
+ }
2234
+ if (!routine.execute) {
2235
+ violations.push(`runtime role lacks personal-resource capability predicate ${routine.name}`);
2236
+ }
2237
+ if (routine.publicExecute) {
2238
+ violations.push(
2239
+ `PUBLIC has forbidden personal-resource capability predicate ${routine.name}`
2240
+ );
2241
+ }
2242
+ const directPrivileges = [
2243
+ ["SELECT", table.select],
2244
+ ["INSERT", table.insert],
2245
+ ["UPDATE", table.update],
2246
+ ["DELETE", table.delete]
2247
+ ].filter(([, granted]) => granted);
2248
+ if (directPrivileges.length > 0) {
2249
+ violations.push(
2250
+ `runtime role has forbidden direct privileges on private table ${table.name}: ${directPrivileges.map(([privilege]) => privilege).join(", ")}`
2251
+ );
2252
+ }
2253
+ }
2254
+ const personalDocumentCapabilityTables = posture.privateTables.filter(
2255
+ (table) => table.name === PERSONAL_DOCUMENT_CAPABILITY_TABLE
2256
+ );
2257
+ const personalDocumentCapabilityRoutines = posture.privateRoutines.filter(
2258
+ (routine) => routine.name === PERSONAL_DOCUMENT_CAPABILITY_PREDICATE_ROUTINE
2259
+ );
2260
+ if (personalDocumentCapabilityTables.length !== 1) {
2261
+ violations.push(
2262
+ `personal-document capability table ${PERSONAL_DOCUMENT_CAPABILITY_TABLE} is missing or ambiguous`
2263
+ );
2264
+ }
2265
+ if (personalDocumentCapabilityRoutines.length !== 1) {
2266
+ violations.push(
2267
+ `personal-document capability predicate ${PERSONAL_DOCUMENT_CAPABILITY_PREDICATE_ROUTINE} is missing or ambiguous`
2268
+ );
2269
+ }
2270
+ if (personalDocumentCapabilityTables.length === 1 && personalDocumentCapabilityRoutines.length === 1) {
2271
+ const table = personalDocumentCapabilityTables[0];
2272
+ const routine = personalDocumentCapabilityRoutines[0];
2273
+ if (routine.owner !== table.owner) {
2274
+ violations.push(
2275
+ `personal-document capability predicate ${routine.name} owner ${routine.owner} does not match table owner ${table.owner}`
2276
+ );
2277
+ }
2278
+ if (!routine.securityDefiner) {
2279
+ violations.push(
2280
+ `personal-document capability predicate ${routine.name} is not SECURITY DEFINER`
2281
+ );
2282
+ }
2283
+ if (!routine.execute) {
2284
+ violations.push(`runtime role lacks personal-document capability predicate ${routine.name}`);
2285
+ }
2286
+ if (routine.publicExecute) {
2287
+ violations.push(
2288
+ `PUBLIC has forbidden personal-document capability predicate ${routine.name}`
2289
+ );
2290
+ }
2291
+ const directPrivileges = [
2292
+ ["SELECT", table.select],
2293
+ ["INSERT", table.insert],
2294
+ ["UPDATE", table.update],
2295
+ ["DELETE", table.delete]
2296
+ ].filter(([, granted]) => granted);
2297
+ if (directPrivileges.length > 0) {
2298
+ violations.push(
2299
+ `runtime role has forbidden direct privileges on private table ${table.name}: ${directPrivileges.map(([privilege]) => privilege).join(", ")}`
2300
+ );
2301
+ }
2302
+ }
2303
+ const documentMigrationCapabilityTables = posture.privateTables.filter(
2304
+ (table) => table.name === DOCUMENT_MIGRATION_CAPABILITY_TABLE
2305
+ );
2306
+ const documentMigrationCapabilityRoutines = posture.privateRoutines.filter(
2307
+ (routine) => routine.name === DOCUMENT_MIGRATION_CAPABILITY_PREDICATE_ROUTINE
2308
+ );
2309
+ if (documentMigrationCapabilityTables.length !== 1) {
2310
+ violations.push(
2311
+ `document-migration capability table ${DOCUMENT_MIGRATION_CAPABILITY_TABLE} is missing or ambiguous`
2312
+ );
2313
+ }
2314
+ if (documentMigrationCapabilityRoutines.length !== 1) {
2315
+ violations.push(
2316
+ `document-migration capability predicate ${DOCUMENT_MIGRATION_CAPABILITY_PREDICATE_ROUTINE} is missing or ambiguous`
2317
+ );
2318
+ }
2319
+ if (documentMigrationCapabilityTables.length === 1 && documentMigrationCapabilityRoutines.length === 1) {
2320
+ const table = documentMigrationCapabilityTables[0];
2321
+ const routine = documentMigrationCapabilityRoutines[0];
2322
+ if (routine.owner !== table.owner) {
2323
+ violations.push(
2324
+ `document-migration capability predicate ${routine.name} owner ${routine.owner} does not match table owner ${table.owner}`
2325
+ );
2326
+ }
2327
+ if (!routine.securityDefiner) {
2328
+ violations.push(
2329
+ `document-migration capability predicate ${routine.name} is not SECURITY DEFINER`
2330
+ );
2331
+ }
2332
+ if (!routine.execute) {
2333
+ violations.push(`runtime role lacks document-migration capability predicate ${routine.name}`);
2334
+ }
2335
+ if (routine.publicExecute) {
2336
+ violations.push(
2337
+ `PUBLIC has forbidden document-migration capability predicate ${routine.name}`
2338
+ );
2339
+ }
2340
+ const directPrivileges = [
2341
+ ["SELECT", table.select],
2342
+ ["INSERT", table.insert],
2343
+ ["UPDATE", table.update],
2344
+ ["DELETE", table.delete]
2345
+ ].filter(([, granted]) => granted);
2346
+ if (directPrivileges.length > 0) {
2347
+ violations.push(
2348
+ `runtime role has forbidden direct privileges on private table ${table.name}: ${directPrivileges.map(([privilege]) => privilege).join(", ")}`
2349
+ );
2350
+ }
2351
+ }
2352
+ const scheduledCapabilityTables = posture.privateTables.filter(
2353
+ (table) => table.name === SCHEDULED_PERSONAL_RESOURCE_CAPABILITY_TABLE
2354
+ );
2355
+ const scheduledCapabilityRoutines = posture.privateRoutines.filter(
2356
+ (routine) => routine.name === SCHEDULED_PERSONAL_RESOURCE_CAPABILITY_PREDICATE_ROUTINE
2357
+ );
2358
+ if (scheduledCapabilityTables.length !== 1) {
2359
+ violations.push(
2360
+ `scheduled personal-resource capability table ${SCHEDULED_PERSONAL_RESOURCE_CAPABILITY_TABLE} is missing or ambiguous`
2361
+ );
2362
+ }
2363
+ if (scheduledCapabilityRoutines.length !== 1) {
2364
+ violations.push(
2365
+ `scheduled personal-resource capability predicate ${SCHEDULED_PERSONAL_RESOURCE_CAPABILITY_PREDICATE_ROUTINE} is missing or ambiguous`
2366
+ );
2367
+ }
2368
+ if (scheduledCapabilityTables.length === 1 && scheduledCapabilityRoutines.length === 1) {
2369
+ const table = scheduledCapabilityTables[0];
2370
+ const routine = scheduledCapabilityRoutines[0];
2371
+ if (routine.owner !== table.owner) {
2372
+ violations.push(
2373
+ `scheduled personal-resource capability predicate ${routine.name} owner ${routine.owner} does not match table owner ${table.owner}`
2374
+ );
2375
+ }
2376
+ if (!routine.securityDefiner) {
2377
+ violations.push(
2378
+ `scheduled personal-resource capability predicate ${routine.name} is not SECURITY DEFINER`
2379
+ );
2380
+ }
2381
+ if (!routine.execute) {
2382
+ violations.push(
2383
+ `runtime role lacks scheduled personal-resource capability predicate ${routine.name}`
2384
+ );
2385
+ }
2386
+ if (routine.publicExecute) {
2387
+ violations.push(
2388
+ `PUBLIC has forbidden scheduled personal-resource capability predicate ${routine.name}`
2389
+ );
2390
+ }
2391
+ const directPrivileges = [
2392
+ ["SELECT", table.select],
2393
+ ["INSERT", table.insert],
2394
+ ["UPDATE", table.update],
2395
+ ["DELETE", table.delete]
2396
+ ].filter(([, granted]) => granted);
2397
+ if (directPrivileges.length > 0) {
2398
+ violations.push(
2399
+ `runtime role has forbidden direct privileges on private table ${table.name}: ${directPrivileges.map(([privilege]) => privilege).join(", ")}`
2400
+ );
2401
+ }
2402
+ }
2403
+ if (options.protectedTables === void 0) {
2404
+ const variableSetCapabilityTables = posture.privateTables.filter(
2405
+ (table) => table.name === VARIABLE_SET_CAPABILITY_TABLE
2406
+ );
2407
+ const variableSetCapabilityRoutines = posture.privateRoutines.filter(
2408
+ (routine) => routine.name === VARIABLE_SET_CAPABILITY_PREDICATE_ROUTINE
2409
+ );
2410
+ if (variableSetCapabilityTables.length !== 1) {
2411
+ violations.push(
2412
+ `variable-set capability table ${VARIABLE_SET_CAPABILITY_TABLE} is missing or ambiguous`
2413
+ );
2414
+ }
2415
+ if (variableSetCapabilityRoutines.length !== 1) {
2416
+ violations.push(
2417
+ `variable-set capability predicate ${VARIABLE_SET_CAPABILITY_PREDICATE_ROUTINE} is missing or ambiguous`
2418
+ );
2419
+ }
2420
+ if (variableSetCapabilityTables.length === 1 && variableSetCapabilityRoutines.length === 1) {
2421
+ const table = variableSetCapabilityTables[0];
2422
+ const routine = variableSetCapabilityRoutines[0];
2423
+ if (routine.owner !== table.owner) {
2424
+ violations.push(
2425
+ `variable-set capability predicate ${routine.name} owner ${routine.owner} does not match table owner ${table.owner}`
2426
+ );
2427
+ }
2428
+ if (!routine.securityDefiner) {
2429
+ violations.push(
2430
+ `variable-set capability predicate ${routine.name} is not SECURITY DEFINER`
2431
+ );
2432
+ }
2433
+ if (!routine.execute) {
2434
+ violations.push(`runtime role lacks variable-set capability predicate ${routine.name}`);
2435
+ }
2436
+ if (routine.publicExecute) {
2437
+ violations.push(`PUBLIC has forbidden variable-set capability predicate ${routine.name}`);
2438
+ }
2439
+ const directPrivileges = [
2440
+ ["SELECT", table.select],
2441
+ ["INSERT", table.insert],
2442
+ ["UPDATE", table.update],
2443
+ ["DELETE", table.delete]
2444
+ ].filter(([, granted]) => granted);
2445
+ if (directPrivileges.length > 0) {
2446
+ violations.push(
2447
+ `runtime role has forbidden direct privileges on private table ${table.name}: ${directPrivileges.map(([privilege]) => privilege).join(", ")}`
2448
+ );
2449
+ }
2450
+ }
2451
+ const scopedComputeCapabilityTables = posture.privateTables.filter(
2452
+ (table) => table.name === SCOPED_COMPUTE_CAPABILITY_TABLE
2453
+ );
2454
+ const scopedComputeCapabilityRoutines = posture.privateRoutines.filter(
2455
+ (routine) => routine.name === SCOPED_COMPUTE_CAPABILITY_PREDICATE_ROUTINE
2456
+ );
2457
+ if (scopedComputeCapabilityTables.length !== 1) {
2458
+ violations.push(
2459
+ `scoped-compute capability table ${SCOPED_COMPUTE_CAPABILITY_TABLE} is missing or ambiguous`
2460
+ );
2461
+ }
2462
+ if (scopedComputeCapabilityRoutines.length !== 1) {
2463
+ violations.push(
2464
+ `scoped-compute capability predicate ${SCOPED_COMPUTE_CAPABILITY_PREDICATE_ROUTINE} is missing or ambiguous`
2465
+ );
2466
+ }
2467
+ if (scopedComputeCapabilityTables.length === 1 && scopedComputeCapabilityRoutines.length === 1) {
2468
+ const table = scopedComputeCapabilityTables[0];
2469
+ const routine = scopedComputeCapabilityRoutines[0];
2470
+ if (routine.owner !== table.owner) {
2471
+ violations.push(
2472
+ `scoped-compute capability predicate ${routine.name} owner ${routine.owner} does not match table owner ${table.owner}`
2473
+ );
2474
+ }
2475
+ if (!routine.securityDefiner) {
2476
+ violations.push(
2477
+ `scoped-compute capability predicate ${routine.name} is not SECURITY DEFINER`
2478
+ );
2479
+ }
2480
+ if (!routine.execute) {
2481
+ violations.push(`runtime role lacks scoped-compute capability predicate ${routine.name}`);
2482
+ }
2483
+ if (routine.publicExecute) {
2484
+ violations.push(`PUBLIC has forbidden scoped-compute capability predicate ${routine.name}`);
2485
+ }
2486
+ const directPrivileges = [
2487
+ ["SELECT", table.select],
2488
+ ["INSERT", table.insert],
2489
+ ["UPDATE", table.update],
2490
+ ["DELETE", table.delete]
2491
+ ].filter(([, granted]) => granted);
2492
+ if (directPrivileges.length > 0) {
2493
+ violations.push(
2494
+ `runtime role has forbidden direct privileges on private table ${table.name}: ${directPrivileges.map(([privilege]) => privilege).join(", ")}`
2495
+ );
2496
+ }
2497
+ }
2498
+ }
2499
+ if (posture.privateRoutines.length === 0) {
2500
+ violations.push("opengeni_private has no helper routines");
2501
+ }
2502
+ const connectionBackfillCapabilityTables = posture.privateTables.filter(
2503
+ (table) => table.name === CONNECTION_TENANCY_BACKFILL_CAPABILITY_TABLE
2504
+ );
2505
+ const connectionBackfillCapabilityRoutines = posture.privateRoutines.filter(
2506
+ (routine) => routine.name === CONNECTION_TENANCY_BACKFILL_CAPABILITY_PREDICATE_ROUTINE
2507
+ );
2508
+ if (connectionBackfillCapabilityTables.length !== 1) {
2509
+ violations.push(
2510
+ `connection-tenancy backfill capability table ${CONNECTION_TENANCY_BACKFILL_CAPABILITY_TABLE} is missing or ambiguous`
2511
+ );
2512
+ }
2513
+ if (connectionBackfillCapabilityRoutines.length !== 1) {
2514
+ violations.push(
2515
+ `connection-tenancy backfill capability predicate ${CONNECTION_TENANCY_BACKFILL_CAPABILITY_PREDICATE_ROUTINE} is missing or ambiguous`
2516
+ );
2517
+ }
2518
+ if (connectionBackfillCapabilityTables.length === 1 && connectionBackfillCapabilityRoutines.length === 1) {
2519
+ const table = connectionBackfillCapabilityTables[0];
2520
+ const routine = connectionBackfillCapabilityRoutines[0];
2521
+ if (routine.owner !== table.owner) {
2522
+ violations.push(
2523
+ `connection-tenancy backfill capability predicate ${routine.name} owner ${routine.owner} does not match table owner ${table.owner}`
2524
+ );
2525
+ }
2526
+ if (!routine.securityDefiner) {
2527
+ violations.push(
2528
+ `connection-tenancy backfill capability predicate ${routine.name} is not SECURITY DEFINER`
2529
+ );
2530
+ }
2531
+ if (!routine.execute) {
2532
+ violations.push(
2533
+ `runtime role lacks connection-tenancy backfill capability predicate ${routine.name}`
2534
+ );
2535
+ }
2536
+ if (routine.publicExecute) {
2537
+ violations.push(
2538
+ `PUBLIC has forbidden connection-tenancy backfill capability predicate ${routine.name}`
2539
+ );
2540
+ }
2541
+ const directPrivileges = [
2542
+ ["SELECT", table.select],
2543
+ ["INSERT", table.insert],
2544
+ ["UPDATE", table.update],
2545
+ ["DELETE", table.delete]
2546
+ ].filter(([, granted]) => granted);
2547
+ if (directPrivileges.length > 0) {
2548
+ violations.push(
2549
+ `runtime role has forbidden direct privileges on private table ${table.name}: ${directPrivileges.map(([privilege]) => privilege).join(", ")}`
2550
+ );
2551
+ }
2552
+ }
2553
+ for (const routine of posture.privateRoutines) {
2554
+ if (routine.owner === expectedRole) {
2555
+ violations.push(`runtime role owns private routine ${routine.name}`);
2556
+ }
2557
+ const dedicatedArtifactCapability = DEDICATED_ARTIFACT_CAPABILITY_ROUTINES.has(routine.name);
2558
+ if (!routine.execute && !dedicatedArtifactCapability) {
2559
+ violations.push(`runtime role lacks EXECUTE on private routine ${routine.name}`);
2560
+ }
2561
+ }
2562
+ return violations;
2563
+ }
2564
+ async function assertRuntimeDatabasePosture(db, options) {
2565
+ const posture = await inspectRuntimeDatabasePosture(db, options);
2566
+ const violations = evaluateRuntimeDatabasePosture(posture, options);
2567
+ if (violations.length > 0) {
2568
+ throw new RuntimeDatabasePostureError(violations);
2569
+ }
2570
+ return posture;
2571
+ }
2572
+ function runtimeDatabaseReadyCheck(db, options) {
2573
+ return async () => {
2574
+ await assertRuntimeDatabasePosture(db, options);
2575
+ };
2576
+ }
2577
+
2578
+ // src/provision-roles.ts
2579
+ async function provisionRoles(adminConnection, options = {}) {
2580
+ const schema = validateIdentifier("targetSchema", options.targetSchema ?? "public");
2581
+ const rlsStrategy = options.rlsStrategy ?? "force";
2582
+ const appRole = validateIdentifier(
2583
+ "appRole",
2584
+ options.appRole ?? (process.env.OPENGENI_APP_DATABASE_USER?.trim() || "opengeni_app")
2585
+ );
2586
+ const appPassword = options.appPassword ?? process.env.OPENGENI_APP_DATABASE_PASSWORD;
2587
+ const artifactOutboxDispatcherRole = validateIdentifier(
2588
+ "artifactOutboxDispatcherRole",
2589
+ options.artifactOutboxDispatcherRole ?? (process.env.OPENGENI_ARTIFACT_OUTBOX_DATABASE_USER?.trim() || "opengeni_artifact_outbox_dispatcher")
2590
+ );
2591
+ const artifactOutboxDispatcherPassword = options.artifactOutboxDispatcherPassword ?? process.env.OPENGENI_ARTIFACT_OUTBOX_DATABASE_PASSWORD;
2592
+ const artifactMaterializerRole = validateIdentifier(
2593
+ "artifactMaterializerRole",
2594
+ options.artifactMaterializerRole ?? (process.env.OPENGENI_ARTIFACT_MATERIALIZER_DATABASE_USER?.trim() || "opengeni_artifact_materializer")
2595
+ );
2596
+ const artifactMaterializerPassword = options.artifactMaterializerPassword ?? process.env.OPENGENI_ARTIFACT_MATERIALIZER_DATABASE_PASSWORD;
2597
+ const hostExportRole = validateIdentifier(
2598
+ "hostExportRole",
2599
+ options.hostExportRole ?? (process.env.OPENGENI_HOST_EXPORT_DATABASE_USER?.trim() || "opengeni_host_exporter")
2600
+ );
2601
+ const hostExportPassword = options.hostExportPassword ?? process.env.OPENGENI_HOST_EXPORT_DATABASE_PASSWORD;
2602
+ const temporalRole = validateIdentifier(
2603
+ "temporalRole",
2604
+ options.temporalRole ?? (process.env.OPENGENI_TEMPORAL_DATABASE_USER?.trim() || "opengeni_temporal")
2605
+ );
2606
+ const temporalPassword = options.temporalPassword ?? process.env.OPENGENI_TEMPORAL_DATABASE_PASSWORD;
2607
+ const temporalDatabases = (options.temporalDatabases ?? commaSeparated(process.env.OPENGENI_TEMPORAL_DATABASES ?? "temporal,temporal_visibility")).map((name) => validateIdentifier("temporalDatabases", name));
2608
+ const sql2 = postgres(adminConnection, { max: 1 });
2609
+ try {
2610
+ let provisionedAppRole = null;
2611
+ if (rlsStrategy === "force") {
2612
+ if (!appPassword) {
2613
+ throw new Error(
2614
+ "OPENGENI_APP_DATABASE_PASSWORD (or appPassword) is required for rlsStrategy 'force'"
2615
+ );
2616
+ }
2617
+ await assertAppRoleSafeToNormalize(sql2, appRole);
2618
+ await ensureRestrictedAppLoginRole(sql2, appRole, appPassword);
2619
+ provisionedAppRole = appRole;
2620
+ }
2621
+ let provisionedArtifactOutboxDispatcherRole = null;
2622
+ if (artifactOutboxDispatcherPassword) {
2623
+ await assertAppRoleSafeToNormalize(sql2, artifactOutboxDispatcherRole);
2624
+ await ensureRestrictedAppLoginRole(
2625
+ sql2,
2626
+ artifactOutboxDispatcherRole,
2627
+ artifactOutboxDispatcherPassword
2628
+ );
2629
+ await grantArtifactCapabilityRoleIfSchemaExists(
2630
+ sql2,
2631
+ artifactOutboxDispatcherRole,
2632
+ schema,
2633
+ "outbox"
2634
+ );
2635
+ provisionedArtifactOutboxDispatcherRole = artifactOutboxDispatcherRole;
2636
+ }
2637
+ let provisionedArtifactMaterializerRole = null;
2638
+ if (artifactMaterializerPassword) {
2639
+ await assertAppRoleSafeToNormalize(sql2, artifactMaterializerRole);
2640
+ await ensureRestrictedAppLoginRole(
2641
+ sql2,
2642
+ artifactMaterializerRole,
2643
+ artifactMaterializerPassword
2644
+ );
2645
+ await grantArtifactCapabilityRoleIfSchemaExists(
2646
+ sql2,
2647
+ artifactMaterializerRole,
2648
+ schema,
2649
+ "materializer"
2650
+ );
2651
+ provisionedArtifactMaterializerRole = artifactMaterializerRole;
2652
+ }
2653
+ if (temporalPassword) {
2654
+ await ensureLoginRole(sql2, temporalRole, temporalPassword);
2655
+ for (const database of temporalDatabases) {
2656
+ await ensureDatabase(sql2, database, temporalRole);
2657
+ await grantTemporalRoleInDatabase(adminConnection, database, temporalRole);
2658
+ }
2659
+ }
2660
+ if (hostExportPassword) {
2661
+ await ensureLoginRole(sql2, hostExportRole, hostExportPassword);
2662
+ await grantHostExportRoleIfSchemaExists(sql2, hostExportRole);
2663
+ }
2664
+ if (rlsStrategy === "force") {
2665
+ await grantAppRoleIfSchemaExists(sql2, appRole, schema);
2666
+ }
2667
+ return {
2668
+ appRole: provisionedAppRole,
2669
+ artifactOutboxDispatcherRole: provisionedArtifactOutboxDispatcherRole,
2670
+ artifactMaterializerRole: provisionedArtifactMaterializerRole,
2671
+ hostExportRole: hostExportPassword ? hostExportRole : null,
2672
+ temporalRole: temporalPassword ? temporalRole : null,
2673
+ temporalDatabases: temporalPassword ? temporalDatabases : [],
2674
+ schema,
2675
+ rlsStrategy
2676
+ };
2677
+ } finally {
2678
+ await sql2.end();
2679
+ }
2680
+ }
2681
+ async function grantHostExportRoleIfSchemaExists(sql2, role) {
2682
+ await sql2.unsafe(`
2683
+ DO $$
2684
+ BEGIN
2685
+ IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_host_export') THEN
2686
+ EXECUTE format('GRANT USAGE ON SCHEMA opengeni_host_export TO %I', ${literal(role)});
2687
+ EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA opengeni_host_export TO %I', ${literal(role)});
2688
+ EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA opengeni_host_export GRANT EXECUTE ON FUNCTIONS TO %I', ${literal(role)});
2689
+ END IF;
2690
+ END $$;
2691
+ `);
2692
+ }
2693
+ async function grantArtifactCapabilityRoleIfSchemaExists(sql2, role, dataSchema, capability) {
2694
+ const routines = capability === "outbox" ? [
2695
+ "claim_editable_artifact_live_outbox(text,integer,integer,name)",
2696
+ "mark_editable_artifact_live_outbox_published(text,text,integer,name)",
2697
+ "renew_editable_artifact_live_outbox(text,text,integer,integer,name)",
2698
+ "retry_editable_artifact_live_outbox(text,text,integer,integer,text,name)",
2699
+ "dead_letter_editable_artifact_live_outbox(text,text,integer,text,name)",
2700
+ "release_editable_artifact_live_outbox(text,text,integer,name)"
2701
+ ] : [
2702
+ "claim_editable_artifact_materializations(text,integer,integer,name)",
2703
+ "renew_editable_artifact_materialization(uuid,uuid,text,text,text,integer,integer,name)",
2704
+ "succeed_editable_artifact_materialization(uuid,uuid,text,text,text,integer,text,text,text,bigint,text,text,timestamp with time zone,name)",
2705
+ "fail_editable_artifact_materialization(uuid,uuid,text,text,text,integer,text,name)"
2706
+ ];
2707
+ const routineArray = `ARRAY[${routines.map(literal).join(", ")}]`;
2708
+ await sql2.unsafe(`
2709
+ DO $$
2710
+ DECLARE routine_signature text;
2711
+ BEGIN
2712
+ IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = ${literal(dataSchema)})
2713
+ AND EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_private')
2714
+ THEN
2715
+ EXECUTE format('GRANT CONNECT ON DATABASE %I TO %I', current_database(), ${literal(role)});
2716
+ EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', ${literal(dataSchema)}, ${literal(role)});
2717
+ EXECUTE format('GRANT USAGE ON SCHEMA opengeni_private TO %I', ${literal(role)});
2718
+ EXECUTE format(
2719
+ 'REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA %I FROM %I',
2720
+ ${literal(dataSchema)}, ${literal(role)}
2721
+ );
2722
+ EXECUTE format(
2723
+ 'REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA %I FROM %I',
2724
+ ${literal(dataSchema)}, ${literal(role)}
2725
+ );
2726
+ EXECUTE format(
2727
+ 'REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA opengeni_private FROM %I',
2728
+ ${literal(role)}
2729
+ );
2730
+ FOREACH routine_signature IN ARRAY ${routineArray} LOOP
2731
+ IF to_regprocedure('opengeni_private.' || routine_signature) IS NOT NULL THEN
2732
+ EXECUTE format(
2733
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.%s TO %I',
2734
+ routine_signature, ${literal(role)}
2735
+ );
2736
+ END IF;
2737
+ END LOOP;
2738
+ END IF;
2739
+ END $$;
2740
+ `);
2741
+ }
2742
+ async function ensureLoginRole(sql2, role, password) {
2743
+ await sql2.unsafe(`
2744
+ DO $$
2745
+ BEGIN
2746
+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(role)}) THEN
2747
+ EXECUTE format('CREATE ROLE %I LOGIN PASSWORD %L', ${literal(role)}, ${literal(password)});
2748
+ ELSE
2749
+ EXECUTE format('ALTER ROLE %I LOGIN PASSWORD %L', ${literal(role)}, ${literal(password)});
2750
+ END IF;
2751
+ END $$;
2752
+ `);
2753
+ }
2754
+ async function ensureRestrictedAppLoginRole(sql2, role, password) {
2755
+ await sql2.unsafe(`
2756
+ DO $$
2757
+ BEGIN
2758
+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(role)}) THEN
2759
+ EXECUTE format(
2760
+ 'CREATE ROLE %I WITH LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB NOREPLICATION NOINHERIT PASSWORD %L',
2761
+ ${literal(role)},
2762
+ ${literal(password)}
2763
+ );
2764
+ ELSIF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = current_user AND rolsuper) THEN
2765
+ EXECUTE format(
2766
+ 'ALTER ROLE %I WITH LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB NOREPLICATION NOINHERIT PASSWORD %L',
2767
+ ${literal(role)},
2768
+ ${literal(password)}
2769
+ );
2770
+ ELSE
2771
+ -- PostgreSQL requires elevated attributes merely to name SUPERUSER,
2772
+ -- BYPASSRLS, REPLICATION, or CREATEDB in ALTER ROLE, even when setting them
2773
+ -- false. The preflight has already proved those protected attributes are
2774
+ -- false, so a managed CREATEROLE administrator converges only the
2775
+ -- attributes it may change.
2776
+ EXECUTE format(
2777
+ 'ALTER ROLE %I WITH LOGIN NOCREATEROLE NOINHERIT PASSWORD %L',
2778
+ ${literal(role)},
2779
+ ${literal(password)}
2780
+ );
2781
+ END IF;
2782
+ END $$;
2783
+ `);
2784
+ }
2785
+ async function assertAppRoleSafeToNormalize(sql2, role) {
2786
+ const exists = await sql2`
2787
+ select exists(select 1 from pg_roles where rolname = ${role}) as exists
2788
+ `;
2789
+ if (!exists[0]?.exists) {
2790
+ return;
2791
+ }
2792
+ const [roleAttributes] = await sql2`
2793
+ select
2794
+ administrator.rolsuper as administrator_superuser,
2795
+ app.rolsuper as app_superuser,
2796
+ app.rolbypassrls as app_bypass_rls,
2797
+ app.rolcreatedb as app_create_database,
2798
+ app.rolreplication as app_replication
2799
+ from pg_roles app
2800
+ join pg_roles administrator on administrator.rolname = current_user
2801
+ where app.rolname = ${role}
2802
+ `;
2803
+ if (roleAttributes && !roleAttributes.administrator_superuser) {
2804
+ const protectedAttributes = [
2805
+ roleAttributes.app_superuser ? "SUPERUSER" : null,
2806
+ roleAttributes.app_bypass_rls ? "BYPASSRLS" : null,
2807
+ roleAttributes.app_create_database ? "CREATEDB" : null,
2808
+ roleAttributes.app_replication ? "REPLICATION" : null
2809
+ ].filter((attribute) => attribute !== null);
2810
+ if (protectedAttributes.length > 0) {
2811
+ throw new Error(
2812
+ `Refusing to normalize app role ${role}: a non-superuser administrator cannot clear protected attributes (${protectedAttributes.join(", ")})`
2813
+ );
2814
+ }
2815
+ }
2816
+ const relationshipRows = await sql2.unsafe(
2817
+ roleRelationshipsCatalogQuery("$1"),
2818
+ [role]
2819
+ );
2820
+ const { unsafeRelationships } = classifyRoleRelationships(relationshipRows);
2821
+ if (unsafeRelationships.length > 0) {
2822
+ throw new Error(
2823
+ `Refusing to normalize app role ${role}: remove privilege-bearing role relationships first (${unsafeRelationships.join(", ")})`
2824
+ );
2825
+ }
2826
+ const ownedObjects = await sql2`
2827
+ select ('database:' || d.datname)::text as object_name
2828
+ from pg_database d
2829
+ join pg_roles owner on owner.oid = d.datdba
2830
+ where owner.rolname = ${role}
2831
+ union all
2832
+ select ('schema:' || n.nspname)::text as object_name
2833
+ from pg_namespace n
2834
+ join pg_roles owner on owner.oid = n.nspowner
2835
+ where owner.rolname = ${role}
2836
+ and n.nspname <> 'information_schema'
2837
+ and n.nspname !~ '^pg_'
2838
+ union all
2839
+ select ('relation:' || n.nspname || '.' || c.relname)::text as object_name
2840
+ from pg_class c
2841
+ join pg_namespace n on n.oid = c.relnamespace
2842
+ join pg_roles owner on owner.oid = c.relowner
2843
+ where owner.rolname = ${role}
2844
+ and n.nspname <> 'information_schema'
2845
+ and n.nspname !~ '^pg_'
2846
+ union all
2847
+ select (
2848
+ 'routine:' || n.nspname || '.' || p.proname || '(' ||
2849
+ pg_get_function_identity_arguments(p.oid) || ')'
2850
+ )::text as object_name
2851
+ from pg_proc p
2852
+ join pg_namespace n on n.oid = p.pronamespace
2853
+ join pg_roles owner on owner.oid = p.proowner
2854
+ where owner.rolname = ${role}
2855
+ and n.nspname <> 'information_schema'
2856
+ and n.nspname !~ '^pg_'
2857
+ order by object_name
2858
+ `;
2859
+ if (ownedObjects.length > 0) {
2860
+ throw new Error(
2861
+ `Refusing to normalize app role ${role}: transfer owned objects first (${ownedObjects.map((row) => row.object_name).join(", ")})`
2862
+ );
2863
+ }
2864
+ }
2865
+ async function ensureDatabase(sql2, database, owner) {
2866
+ const existing = await sql2`
2867
+ select exists(select 1 from pg_database where datname = ${database}) as exists
2868
+ `;
2869
+ if (!existing[0]?.exists) {
2870
+ await sql2.unsafe(`CREATE DATABASE ${identifier(database)} OWNER ${identifier(owner)}`);
2871
+ }
2872
+ await sql2.unsafe(
2873
+ `GRANT ALL PRIVILEGES ON DATABASE ${identifier(database)} TO ${identifier(owner)}`
2874
+ );
2875
+ }
2876
+ async function grantTemporalRoleInDatabase(adminConnection, database, role) {
2877
+ const databaseUrl = databaseUrlFor(adminConnection, database);
2878
+ const databaseSql = postgres(databaseUrl, { max: 1 });
2879
+ try {
2880
+ await databaseSql.unsafe(`GRANT USAGE, CREATE ON SCHEMA public TO ${identifier(role)}`);
2881
+ } finally {
2882
+ await databaseSql.end();
2883
+ }
2884
+ }
2885
+ async function grantAppRoleIfSchemaExists(sql2, role, schema) {
2886
+ const runtimeFullDmlTables = `ARRAY[${RUNTIME_FULL_DML_TABLES.map(literal).join(", ")}]`;
2887
+ const runtimeReadOnlyTables = `ARRAY[${RUNTIME_READ_ONLY_TABLES.map(literal).join(", ")}]`;
2888
+ const runtimeReadUpdateTables = `ARRAY[${RUNTIME_READ_UPDATE_TABLES.map(literal).join(", ")}]`;
2889
+ const runtimeReadInsertTables = `ARRAY[${RUNTIME_READ_INSERT_TABLES.map(literal).join(", ")}]`;
2890
+ const runtimeReadInsertUpdateTables = `ARRAY[${RUNTIME_READ_INSERT_UPDATE_TABLES.map(literal).join(", ")}]`;
2891
+ const organizationMembershipLifecycleRoutines = `ARRAY[${[
2892
+ "list_self_organization_memberships(text)",
2893
+ "list_self_organization_invitations(text)",
2894
+ "list_self_organization_invitations(text,uuid,integer)",
2895
+ "get_self_organization_invitation(text,uuid)",
2896
+ "list_organization_members(uuid,text)",
2897
+ "list_organization_invitations(uuid,text,uuid,integer)",
2898
+ "get_organization_administration_overview(uuid,text)",
2899
+ "create_managed_organization(text,text,text,uuid)",
2900
+ "assert_organization_shared_workspace_administrator(uuid,uuid,text)",
2901
+ "open_organization_shared_workspace_administration_capability(uuid,uuid,text)",
2902
+ "close_organization_shared_workspace_administration_capability(uuid)",
2903
+ "create_organization_shared_workspace(uuid,text,text,text,text,uuid)",
2904
+ "upsert_organization_shared_workspace_member(uuid,uuid,text,uuid,text,text,jsonb,boolean)",
2905
+ "update_organization_name(uuid,text,text,timestamptz,uuid)",
2906
+ "create_organization_invitation_v2(jsonb)",
2907
+ "bind_pending_organization_invitations_for_verified_email(text,text)",
2908
+ "has_pending_organization_invitation_for_subject(text)",
2909
+ "accept_organization_invitation_v2(jsonb)",
2910
+ "organization_membership_command(jsonb)",
2911
+ "prepare_organization_membership_protocol_settlements(jsonb)",
2912
+ "assert_active_managed_human_organization_membership(uuid,text)",
2913
+ "resolve_workspace_writer_grant_identity(uuid,text)",
2914
+ "prepare_workspace_membership_removal_settlements(jsonb)",
2915
+ "workspace_membership_removal_command(jsonb)",
2916
+ "get_organization_retention_policy(uuid,text)",
2917
+ "preview_organization_retention_deletions(uuid,integer)",
2918
+ "claim_organization_retention_deletion(uuid,uuid,uuid[])",
2919
+ "list_organization_retention_deletion_objects(uuid,uuid,uuid,text,integer)",
2920
+ "record_organization_retention_object_deleted(uuid,uuid,uuid,text,text,text,text)",
2921
+ "fail_organization_retention_deletion(uuid,uuid,uuid,text)",
2922
+ "finalize_organization_retention_deletion(uuid,uuid,uuid,text)",
2923
+ "complete_organization_retention_deletion(uuid,uuid,uuid,text)"
2924
+ ].map(literal).join(", ")}]`;
2925
+ await sql2.unsafe(`
2926
+ DO $$
2927
+ DECLARE
2928
+ owner_role text := current_user;
2929
+ runtime_table text;
2930
+ routine_signature text;
2931
+ BEGIN
2932
+ EXECUTE format('REVOKE CREATE ON DATABASE %I FROM %I', current_database(), ${literal(role)});
2933
+ IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = ${literal(schema)}) THEN
2934
+ EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', ${literal(schema)}, ${literal(role)});
2935
+ EXECUTE format('REVOKE CREATE ON SCHEMA %I FROM %I', ${literal(schema)}, ${literal(role)});
2936
+ EXECUTE format('REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA %I FROM %I', ${literal(schema)}, ${literal(role)});
2937
+ FOREACH runtime_table IN ARRAY ${runtimeFullDmlTables} LOOP
2938
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
2939
+ EXECUTE format(
2940
+ 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE %I.%I TO %I',
2941
+ ${literal(schema)},
2942
+ runtime_table,
2943
+ ${literal(role)}
2944
+ );
2945
+ END IF;
2946
+ END LOOP;
2947
+ FOREACH runtime_table IN ARRAY ${runtimeReadOnlyTables} LOOP
2948
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
2949
+ EXECUTE format(
2950
+ 'GRANT SELECT ON TABLE %I.%I TO %I',
2951
+ ${literal(schema)},
2952
+ runtime_table,
2953
+ ${literal(role)}
2954
+ );
2955
+ END IF;
2956
+ END LOOP;
2957
+ FOREACH runtime_table IN ARRAY ${runtimeReadUpdateTables} LOOP
2958
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
2959
+ EXECUTE format(
2960
+ 'GRANT SELECT, UPDATE ON TABLE %I.%I TO %I',
2961
+ ${literal(schema)},
2962
+ runtime_table,
2963
+ ${literal(role)}
2964
+ );
2965
+ END IF;
2966
+ END LOOP;
2967
+ FOREACH runtime_table IN ARRAY ${runtimeReadInsertTables} LOOP
2968
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
2969
+ EXECUTE format(
2970
+ 'GRANT SELECT, INSERT ON TABLE %I.%I TO %I',
2971
+ ${literal(schema)},
2972
+ runtime_table,
2973
+ ${literal(role)}
2974
+ );
2975
+ END IF;
2976
+ END LOOP;
2977
+ FOREACH runtime_table IN ARRAY ${runtimeReadInsertUpdateTables} LOOP
2978
+ IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN
2979
+ EXECUTE format(
2980
+ 'GRANT SELECT, INSERT, UPDATE ON TABLE %I.%I TO %I',
2981
+ ${literal(schema)},
2982
+ runtime_table,
2983
+ ${literal(role)}
2984
+ );
2985
+ END IF;
2986
+ END LOOP;
2987
+ -- Migration 0301 creates this target-schema capability before
2988
+ -- opengeni_app exists on a fresh migrate-then-provision installation. Its
2989
+ -- policy is evaluated for ordinary session-list snapshot writes, so the
2990
+ -- runtime role must be able to execute the predicate even when no
2991
+ -- visibility-transition capability is active. Re-converge the exact ACL
2992
+ -- here and keep PUBLIC revoked.
2993
+ IF to_regprocedure(
2994
+ format('%I.session_visibility_lifecycle_capability_held()', ${literal(schema)})
2995
+ ) IS NOT NULL THEN
2996
+ EXECUTE format(
2997
+ 'REVOKE ALL ON FUNCTION %I.session_visibility_lifecycle_capability_held() FROM PUBLIC',
2998
+ ${literal(schema)}
2999
+ );
3000
+ EXECUTE format(
3001
+ 'GRANT EXECUTE ON FUNCTION %I.session_visibility_lifecycle_capability_held() TO %I',
3002
+ ${literal(schema)},
3003
+ ${literal(role)}
3004
+ );
3005
+ END IF;
3006
+ -- Migration 0300's tenancy backfill ledger seam has the same shape: its
3007
+ -- own conditional GRANT block is skipped whenever opengeni_app does not
3008
+ -- yet exist, and these three live in the data schema rather than
3009
+ -- opengeni_private, so the blanket sweep above never reaches them.
3010
+ -- Re-converge them here so migrate-then-provision matches the reverse
3011
+ -- order; without this the "only write path" seam is unreachable on a
3012
+ -- green-field database.
3013
+ FOR routine_signature IN
3014
+ SELECT unnest(ARRAY[
3015
+ 'open_tenancy_backfill_receipt(uuid, text, text)',
3016
+ 'record_tenancy_backfill_unresolved(uuid, uuid, text)',
3017
+ 'complete_tenancy_backfill_receipt(uuid, bigint, bigint, text)'
3018
+ ])
3019
+ LOOP
3020
+ IF to_regprocedure(format('%I.%s', ${literal(schema)}, routine_signature))
3021
+ IS NOT NULL
3022
+ THEN
3023
+ EXECUTE format(
3024
+ 'GRANT EXECUTE ON FUNCTION %I.%s TO %I',
3025
+ ${literal(schema)},
3026
+ routine_signature,
3027
+ ${literal(role)}
3028
+ );
3029
+ END IF;
3030
+ END LOOP;
3031
+ -- Migration 0291's classification assertion seam has the same shape: its
3032
+ -- own conditional GRANT block is skipped whenever opengeni_app does not yet
3033
+ -- exist, and it lives in the data schema rather than opengeni_private, so
3034
+ -- the blanket sweep above never reaches it. (Its inner capability predicate
3035
+ -- IS in opengeni_private and is covered by that sweep.)
3036
+ IF to_regprocedure(
3037
+ format(
3038
+ '%I.verify_organization_resource_classification(uuid,text)',
3039
+ ${literal(schema)}
3040
+ )
3041
+ ) IS NOT NULL THEN
3042
+ EXECUTE format(
3043
+ 'GRANT EXECUTE ON FUNCTION %I.verify_organization_resource_classification(uuid, text) TO %I',
3044
+ ${literal(schema)},
3045
+ ${literal(role)}
3046
+ );
3047
+ END IF;
3048
+ -- Migration 0297's session ownership seams have the same shape: their own
3049
+ -- conditional GRANT block is skipped whenever opengeni_app does not yet
3050
+ -- exist, and they live in the data schema rather than opengeni_private, so
3051
+ -- the blanket sweep above never reaches them. (Their inner capability
3052
+ -- predicate IS in opengeni_private and is covered by that sweep.)
3053
+ IF to_regprocedure(
3054
+ format(
3055
+ '%I.classify_organization_session_ownership(uuid,text)',
3056
+ ${literal(schema)}
3057
+ )
3058
+ ) IS NOT NULL THEN
3059
+ EXECUTE format(
3060
+ 'GRANT EXECUTE ON FUNCTION %I.classify_organization_session_ownership(uuid, text) TO %I',
3061
+ ${literal(schema)},
3062
+ ${literal(role)}
3063
+ );
3064
+ END IF;
3065
+ IF to_regprocedure(
3066
+ format(
3067
+ '%I.backfill_organization_session_ownership(uuid,integer,boolean,text)',
3068
+ ${literal(schema)}
3069
+ )
3070
+ ) IS NOT NULL THEN
3071
+ EXECUTE format(
3072
+ 'GRANT EXECUTE ON FUNCTION %I.backfill_organization_session_ownership(uuid, integer, boolean, text) TO %I',
3073
+ ${literal(schema)},
3074
+ ${literal(role)}
3075
+ );
3076
+ END IF;
3077
+ -- Migration 0340's bounded connection convergence and repaired parity
3078
+ -- seams also live in the data schema. Converge their exact grants for the
3079
+ -- supported migrate-then-provision order.
3080
+ FOREACH routine_signature IN ARRAY ARRAY[
3081
+ 'classify_organization_connection_authority(uuid,text)',
3082
+ 'backfill_organization_connection_authority(uuid,integer,boolean)',
3083
+ 'check_organization_tenancy_parity(uuid,integer,integer)'
3084
+ ] LOOP
3085
+ IF to_regprocedure(format('%I.%s', ${literal(schema)}, routine_signature))
3086
+ IS NOT NULL
3087
+ THEN
3088
+ EXECUTE format(
3089
+ 'GRANT EXECUTE ON FUNCTION %I.%s TO %I',
3090
+ ${literal(schema)},
3091
+ routine_signature,
3092
+ ${literal(role)}
3093
+ );
3094
+ END IF;
3095
+ END LOOP;
3096
+ -- Migration 0110 creates this target-schema-local SECURITY DEFINER
3097
+ -- capability before opengeni_app may exist. Re-converge its exact EXECUTE
3098
+ -- grant here so the supported migrate-then-provision order is equivalent to
3099
+ -- provisioning the role before that migration.
3100
+ IF to_regprocedure(
3101
+ format('%I.lock_nested_agent_depth_configuration()', ${literal(schema)})
3102
+ ) IS NOT NULL THEN
3103
+ EXECUTE format(
3104
+ 'GRANT EXECUTE ON FUNCTION %I.lock_nested_agent_depth_configuration() TO %I',
3105
+ ${literal(schema)},
3106
+ ${literal(role)}
3107
+ );
3108
+ END IF;
3109
+ IF to_regprocedure(
3110
+ format(
3111
+ '%I.preference_registry_apply_lifecycle(text,uuid,integer,uuid,uuid,text,uuid,text,text)',
3112
+ ${literal(schema)}
3113
+ )
3114
+ ) IS NOT NULL THEN
3115
+ EXECUTE format(
3116
+ 'GRANT EXECUTE ON FUNCTION %I.preference_registry_apply_lifecycle(text, uuid, integer, uuid, uuid, text, uuid, text, text) TO %I',
3117
+ ${literal(schema)},
3118
+ ${literal(role)}
3119
+ );
3120
+ END IF;
3121
+ IF to_regprocedure(
3122
+ format('%I.preference_registry_lock_heads(uuid[])', ${literal(schema)})
3123
+ ) IS NOT NULL THEN
3124
+ EXECUTE format(
3125
+ 'GRANT EXECUTE ON FUNCTION %I.preference_registry_lock_heads(uuid[]) TO %I',
3126
+ ${literal(schema)},
3127
+ ${literal(role)}
3128
+ );
3129
+ END IF;
3130
+ IF to_regprocedure(
3131
+ format(
3132
+ '%I.knowledge_memory_apply_operation(jsonb,text,text,text,uuid,uuid,uuid,integer)',
3133
+ ${literal(schema)}
3134
+ )
3135
+ ) IS NOT NULL THEN
3136
+ EXECUTE format(
3137
+ 'GRANT EXECUTE ON FUNCTION %I.knowledge_memory_apply_operation(jsonb, text, text, text, uuid, uuid, uuid, integer) TO %I',
3138
+ ${literal(schema)},
3139
+ ${literal(role)}
3140
+ );
3141
+ END IF;
3142
+ IF to_regprocedure(
3143
+ format(
3144
+ '%I.knowledge_memory_revert_operation(uuid,uuid,text,text,text,uuid,uuid,uuid,integer)',
3145
+ ${literal(schema)}
3146
+ )
3147
+ ) IS NOT NULL THEN
3148
+ EXECUTE format(
3149
+ 'GRANT EXECUTE ON FUNCTION %I.knowledge_memory_revert_operation(uuid, uuid, text, text, text, uuid, uuid, uuid, integer) TO %I',
3150
+ ${literal(schema)},
3151
+ ${literal(role)}
3152
+ );
3153
+ END IF;
3154
+ IF to_regprocedure(
3155
+ format(
3156
+ '%I.preference_registry_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',
3157
+ ${literal(schema)}
3158
+ )
3159
+ ) IS NOT NULL THEN
3160
+ EXECUTE format(
3161
+ 'GRANT EXECUTE ON FUNCTION %I.preference_registry_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',
3162
+ ${literal(schema)},
3163
+ ${literal(role)}
3164
+ );
3165
+ END IF;
3166
+ -- Migration 0289 creates this definer accessor before opengeni_app may
3167
+ -- exist, so its migration-time GRANT is skipped on the supported
3168
+ -- migrate-then-provision order. Re-converge it here.
3169
+ IF to_regprocedure(
3170
+ format(
3171
+ '%I.preference_registry_activation_authority(uuid,uuid[])',
3172
+ ${literal(schema)}
3173
+ )
3174
+ ) IS NOT NULL THEN
3175
+ EXECUTE format(
3176
+ 'GRANT EXECUTE ON FUNCTION %I.preference_registry_activation_authority(uuid, uuid[]) TO %I',
3177
+ ${literal(schema)},
3178
+ ${literal(role)}
3179
+ );
3180
+ END IF;
3181
+ IF to_regprocedure(
3182
+ format(
3183
+ '%I.preference_registry_create_knowledge_proposal_for_attempt(uuid,uuid,uuid,uuid,uuid,integer,uuid,text,uuid,text,text,text,text,integer,text,jsonb,timestamptz,text)',
3184
+ ${literal(schema)}
3185
+ )
3186
+ ) IS NOT NULL THEN
3187
+ EXECUTE format(
3188
+ 'GRANT EXECUTE ON FUNCTION %I.preference_registry_create_knowledge_proposal_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, text, uuid, text, text, text, text, integer, text, jsonb, timestamptz, text) TO %I',
3189
+ ${literal(schema)},
3190
+ ${literal(role)}
3191
+ );
3192
+ END IF;
3193
+ IF to_regprocedure(
3194
+ format(
3195
+ '%I.create_task_note_for_attempt(uuid,uuid,uuid,uuid,uuid,integer,uuid,text,text,integer)',
3196
+ ${literal(schema)}
3197
+ )
3198
+ ) IS NOT NULL THEN
3199
+ EXECUTE format(
3200
+ 'GRANT EXECUTE ON FUNCTION %I.create_task_note_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, text, text, integer) TO %I',
3201
+ ${literal(schema)},
3202
+ ${literal(role)}
3203
+ );
3204
+ EXECUTE format(
3205
+ 'GRANT EXECUTE ON FUNCTION %I.archive_task_note_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, uuid, integer, text) TO %I',
3206
+ ${literal(schema)},
3207
+ ${literal(role)}
3208
+ );
3209
+ EXECUTE format(
3210
+ 'GRANT EXECUTE ON FUNCTION %I.list_task_notes_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, boolean, integer) TO %I',
3211
+ ${literal(schema)},
3212
+ ${literal(role)}
3213
+ );
3214
+ END IF;
3215
+ IF to_regprocedure(
3216
+ format(
3217
+ '%I.company_brain_context_get_or_create_selection(uuid,uuid,uuid,uuid,uuid,integer)',
3218
+ ${literal(schema)}
3219
+ )
3220
+ ) IS NOT NULL THEN
3221
+ EXECUTE format(
3222
+ 'GRANT EXECUTE ON FUNCTION %I.company_brain_context_get_or_create_selection(uuid, uuid, uuid, uuid, uuid, integer) TO %I',
3223
+ ${literal(schema)},
3224
+ ${literal(role)}
3225
+ );
3226
+ END IF;
3227
+ IF to_regprocedure(
3228
+ format(
3229
+ '%I.company_brain_inspect_context_receipts(uuid,uuid,text,uuid,timestamptz,uuid,integer)',
3230
+ ${literal(schema)}
3231
+ )
3232
+ ) IS NOT NULL THEN
3233
+ EXECUTE format(
3234
+ 'GRANT EXECUTE ON FUNCTION %I.company_brain_inspect_context_receipts(uuid, uuid, text, uuid, timestamptz, uuid, integer) TO %I',
3235
+ ${literal(schema)},
3236
+ ${literal(role)}
3237
+ );
3238
+ END IF;
3239
+ IF to_regprocedure(
3240
+ format(
3241
+ '%I.evaluate_governed_learning_proposal(uuid,uuid,uuid,uuid,uuid,integer,uuid,uuid,uuid,uuid,uuid)',
3242
+ ${literal(schema)}
3243
+ )
3244
+ ) IS NOT NULL THEN
3245
+ EXECUTE format(
3246
+ 'GRANT EXECUTE ON FUNCTION %I.evaluate_governed_learning_proposal(uuid, uuid, uuid, uuid, uuid, integer, uuid, uuid, uuid, uuid, uuid) TO %I',
3247
+ ${literal(schema)},
3248
+ ${literal(role)}
3249
+ );
3250
+ END IF;
3251
+ IF to_regprocedure(
3252
+ format('%I.activate_governed_learning_decision(uuid,uuid,uuid,uuid)', ${literal(schema)})
3253
+ ) IS NOT NULL THEN
3254
+ EXECUTE format(
3255
+ 'GRANT EXECUTE ON FUNCTION %I.activate_governed_learning_decision(uuid, uuid, uuid, uuid) TO %I',
3256
+ ${literal(schema)},
3257
+ ${literal(role)}
3258
+ );
3259
+ END IF;
3260
+ IF to_regprocedure(
3261
+ format('%I.activate_human_confirmed_learning_decision(uuid,uuid,uuid,uuid,uuid)', ${literal(schema)})
3262
+ ) IS NOT NULL THEN
3263
+ EXECUTE format(
3264
+ 'GRANT EXECUTE ON FUNCTION %I.activate_human_confirmed_learning_decision(uuid, uuid, uuid, uuid, uuid) TO %I',
3265
+ ${literal(schema)},
3266
+ ${literal(role)}
3267
+ );
3268
+ END IF;
3269
+ IF to_regprocedure(
3270
+ format('%I.confirm_remember_knowledge_claim(uuid,uuid,uuid,uuid,integer,uuid,uuid,uuid)', ${literal(schema)})
3271
+ ) IS NOT NULL THEN
3272
+ EXECUTE format(
3273
+ 'GRANT EXECUTE ON FUNCTION %I.confirm_remember_knowledge_claim(uuid, uuid, uuid, uuid, integer, uuid, uuid, uuid) TO %I',
3274
+ ${literal(schema)},
3275
+ ${literal(role)}
3276
+ );
3277
+ END IF;
3278
+ IF to_regprocedure(
3279
+ format('%I.undo_governed_learning_activation(uuid,uuid,uuid,uuid)', ${literal(schema)})
3280
+ ) IS NOT NULL THEN
3281
+ EXECUTE format(
3282
+ 'GRANT EXECUTE ON FUNCTION %I.undo_governed_learning_activation(uuid, uuid, uuid, uuid) TO %I',
3283
+ ${literal(schema)},
3284
+ ${literal(role)}
3285
+ );
3286
+ END IF;
3287
+ IF to_regprocedure(
3288
+ format('%I.inspect_governed_learning_decisions(uuid,uuid,text,integer)', ${literal(schema)})
3289
+ ) IS NOT NULL THEN
3290
+ EXECUTE format(
3291
+ 'GRANT EXECUTE ON FUNCTION %I.inspect_governed_learning_decisions(uuid, uuid, text, integer) TO %I',
3292
+ ${literal(schema)},
3293
+ ${literal(role)}
3294
+ );
3295
+ END IF;
3296
+ IF to_regprocedure(
3297
+ format('%I.inspect_governed_learning_activations(uuid,uuid,text,integer)', ${literal(schema)})
3298
+ ) IS NOT NULL THEN
3299
+ EXECUTE format(
3300
+ 'GRANT EXECUTE ON FUNCTION %I.inspect_governed_learning_activations(uuid, uuid, text, integer) TO %I',
3301
+ ${literal(schema)},
3302
+ ${literal(role)}
3303
+ );
3304
+ END IF;
3305
+ IF to_regprocedure(
3306
+ format('%I.inspect_governed_learning_activation_undos(uuid,uuid,text,integer)', ${literal(schema)})
3307
+ ) IS NOT NULL THEN
3308
+ EXECUTE format(
3309
+ 'GRANT EXECUTE ON FUNCTION %I.inspect_governed_learning_activation_undos(uuid, uuid, text, integer) TO %I',
3310
+ ${literal(schema)},
3311
+ ${literal(role)}
3312
+ );
3313
+ END IF;
3314
+ IF to_regprocedure(
3315
+ format(
3316
+ '%I.replace_task_note_for_attempt(uuid,uuid,uuid,uuid,uuid,integer,uuid,uuid,uuid,uuid,integer,text,text,integer,text)',
3317
+ ${literal(schema)}
3318
+ )
3319
+ ) IS NOT NULL THEN
3320
+ EXECUTE format(
3321
+ 'GRANT EXECUTE ON FUNCTION %I.replace_task_note_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, uuid, uuid, uuid, integer, text, text, integer, text) TO %I',
3322
+ ${literal(schema)},
3323
+ ${literal(role)}
3324
+ );
3325
+ END IF;
3326
+ IF to_regprocedure(
3327
+ format(
3328
+ '%I.resolve_task_note_knowledge_promotion_source(uuid,uuid,uuid,uuid,uuid,integer,uuid,integer,text,text,text)',
3329
+ ${literal(schema)}
3330
+ )
3331
+ ) IS NOT NULL THEN
3332
+ EXECUTE format(
3333
+ 'GRANT EXECUTE ON FUNCTION %I.resolve_task_note_knowledge_promotion_source(uuid, uuid, uuid, uuid, uuid, integer, uuid, integer, text, text, text) TO %I',
3334
+ ${literal(schema)},
3335
+ ${literal(role)}
3336
+ );
3337
+ END IF;
3338
+ IF to_regprocedure(
3339
+ format(
3340
+ '%I.workspace_instruction_policy_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',
3341
+ ${literal(schema)}
3342
+ )
3343
+ ) IS NOT NULL THEN
3344
+ EXECUTE format(
3345
+ 'GRANT EXECUTE ON FUNCTION %I.workspace_instruction_policy_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',
3346
+ ${literal(schema)},
3347
+ ${literal(role)}
3348
+ );
3349
+ END IF;
3350
+ IF to_regprocedure(
3351
+ format(
3352
+ '%I.company_profile_apply_activation(uuid,text,uuid,uuid,uuid,uuid,bigint,text,text,text,text)',
3353
+ ${literal(schema)}
3354
+ )
3355
+ ) IS NOT NULL THEN
3356
+ EXECUTE format(
3357
+ 'GRANT EXECUTE ON FUNCTION %I.company_profile_apply_activation(uuid, text, uuid, uuid, uuid, uuid, bigint, text, text, text, text) TO %I',
3358
+ ${literal(schema)},
3359
+ ${literal(role)}
3360
+ );
3361
+ END IF;
3362
+ IF to_regprocedure(
3363
+ format(
3364
+ '%I.company_profile_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',
3365
+ ${literal(schema)}
3366
+ )
3367
+ ) IS NOT NULL THEN
3368
+ EXECUTE format(
3369
+ 'GRANT EXECUTE ON FUNCTION %I.company_profile_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',
3370
+ ${literal(schema)},
3371
+ ${literal(role)}
3372
+ );
3373
+ END IF;
3374
+ IF to_regprocedure(
3375
+ format(
3376
+ '%I.propose_company_profile_for_attempt(uuid,uuid,uuid,uuid,uuid,integer,uuid,text,text,text)',
3377
+ ${literal(schema)}
3378
+ )
3379
+ ) IS NOT NULL THEN
3380
+ EXECUTE format(
3381
+ 'GRANT EXECUTE ON FUNCTION %I.propose_company_profile_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, text, text, text) TO %I',
3382
+ ${literal(schema)},
3383
+ ${literal(role)}
3384
+ );
3385
+ END IF;
3386
+ IF to_regprocedure(
3387
+ format(
3388
+ '%I.confirm_company_profile_for_attempt(uuid,uuid,uuid,uuid,uuid,integer,uuid,uuid,uuid)',
3389
+ ${literal(schema)}
3390
+ )
3391
+ ) IS NOT NULL THEN
3392
+ EXECUTE format(
3393
+ 'GRANT EXECUTE ON FUNCTION %I.confirm_company_profile_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid, uuid, uuid) TO %I',
3394
+ ${literal(schema)},
3395
+ ${literal(role)}
3396
+ );
3397
+ END IF;
3398
+ IF to_regprocedure(
3399
+ format(
3400
+ '%I.workspace_learning_policy_apply_activation(uuid,text,uuid,uuid,uuid,uuid,bigint,text,text,text)',
3401
+ ${literal(schema)}
3402
+ )
3403
+ ) IS NOT NULL THEN
3404
+ EXECUTE format(
3405
+ 'GRANT EXECUTE ON FUNCTION %I.workspace_learning_policy_apply_activation(uuid, text, uuid, uuid, uuid, uuid, bigint, text, text, text) TO %I',
3406
+ ${literal(schema)},
3407
+ ${literal(role)}
3408
+ );
3409
+ END IF;
3410
+ IF to_regprocedure(
3411
+ format('%I.workspace_learning_policy_source_overrides_valid(jsonb)', ${literal(schema)})
3412
+ ) IS NOT NULL THEN
3413
+ EXECUTE format(
3414
+ 'GRANT EXECUTE ON FUNCTION %I.workspace_learning_policy_source_overrides_valid(jsonb) TO %I',
3415
+ ${literal(schema)},
3416
+ ${literal(role)}
3417
+ );
3418
+ END IF;
3419
+ IF to_regprocedure(
3420
+ format('%I.workspace_learning_policy_hash(text,jsonb)', ${literal(schema)})
3421
+ ) IS NOT NULL THEN
3422
+ EXECUTE format(
3423
+ 'GRANT EXECUTE ON FUNCTION %I.workspace_learning_policy_hash(text, jsonb) TO %I',
3424
+ ${literal(schema)},
3425
+ ${literal(role)}
3426
+ );
3427
+ END IF;
3428
+ IF to_regprocedure(
3429
+ format(
3430
+ '%I.workspace_learning_policy_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',
3431
+ ${literal(schema)}
3432
+ )
3433
+ ) IS NOT NULL THEN
3434
+ EXECUTE format(
3435
+ 'GRANT EXECUTE ON FUNCTION %I.workspace_learning_policy_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',
3436
+ ${literal(schema)},
3437
+ ${literal(role)}
3438
+ );
3439
+ END IF;
3440
+ IF to_regprocedure(
3441
+ format(
3442
+ '%I.slack_task_policy_update(uuid,text,uuid,uuid,jsonb,uuid,bigint,text,text)',
3443
+ ${literal(schema)}
3444
+ )
3445
+ ) IS NOT NULL THEN
3446
+ EXECUTE format(
3447
+ 'GRANT EXECUTE ON FUNCTION %I.slack_task_policy_update(uuid, text, uuid, uuid, jsonb, uuid, bigint, text, text) TO %I',
3448
+ ${literal(schema)},
3449
+ ${literal(role)}
3450
+ );
3451
+ END IF;
3452
+ IF to_regprocedure(
3453
+ format(
3454
+ '%I.scoped_knowledge_apply_lifecycle(uuid,text,uuid,text,bigint,text,text,text,text,text,text)',
3455
+ ${literal(schema)}
3456
+ )
3457
+ ) IS NOT NULL THEN
3458
+ EXECUTE format(
3459
+ 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_apply_lifecycle(uuid, text, uuid, text, bigint, text, text, text, text, text, text) TO %I',
3460
+ ${literal(schema)},
3461
+ ${literal(role)}
3462
+ );
3463
+ END IF;
3464
+ -- Migration 0197 creates this target-schema-local SECURITY DEFINER lock
3465
+ -- before opengeni_app may exist. Re-converge only its exact EXECUTE grant
3466
+ -- for the supported migrate-then-provision install order; keep PUBLIC
3467
+ -- revoked and do not widen table privileges.
3468
+ IF to_regprocedure(
3469
+ format(
3470
+ '%I.knowledge_source_sync_lock_authority(uuid,uuid,uuid)',
3471
+ ${literal(schema)}
3472
+ )
3473
+ ) IS NOT NULL THEN
3474
+ EXECUTE format(
3475
+ 'REVOKE ALL ON FUNCTION %I.knowledge_source_sync_lock_authority(uuid, uuid, uuid) FROM PUBLIC',
3476
+ ${literal(schema)}
3477
+ );
3478
+ EXECUTE format(
3479
+ 'GRANT EXECUTE ON FUNCTION %I.knowledge_source_sync_lock_authority(uuid, uuid, uuid) TO %I',
3480
+ ${literal(schema)},
3481
+ ${literal(role)}
3482
+ );
3483
+ END IF;
3484
+ -- Migration 0243 adds the exact Google Drive object authorization and
3485
+ -- safe-citation projections. Re-converge both capabilities for the same
3486
+ -- supported migrate-then-provision order without granting direct mutation
3487
+ -- of their append-only ACL evidence tables.
3488
+ IF to_regprocedure(
3489
+ format(
3490
+ '%I.google_drive_file_authorized(uuid,uuid,text,uuid)',
3491
+ ${literal(schema)}
3492
+ )
3493
+ ) IS NOT NULL THEN
3494
+ EXECUTE format(
3495
+ 'REVOKE ALL ON FUNCTION %I.google_drive_file_authorized(uuid, uuid, text, uuid) FROM PUBLIC',
3496
+ ${literal(schema)}
3497
+ );
3498
+ EXECUTE format(
3499
+ 'GRANT EXECUTE ON FUNCTION %I.google_drive_file_authorized(uuid, uuid, text, uuid) TO %I',
3500
+ ${literal(schema)},
3501
+ ${literal(role)}
3502
+ );
3503
+ END IF;
3504
+ IF to_regprocedure(
3505
+ format(
3506
+ '%I.google_drive_document_citation(uuid,uuid,text,uuid,uuid)',
3507
+ ${literal(schema)}
3508
+ )
3509
+ ) IS NOT NULL THEN
3510
+ EXECUTE format(
3511
+ 'REVOKE ALL ON FUNCTION %I.google_drive_document_citation(uuid, uuid, text, uuid, uuid) FROM PUBLIC',
3512
+ ${literal(schema)}
3513
+ );
3514
+ EXECUTE format(
3515
+ 'GRANT EXECUTE ON FUNCTION %I.google_drive_document_citation(uuid, uuid, text, uuid, uuid) TO %I',
3516
+ ${literal(schema)},
3517
+ ${literal(role)}
3518
+ );
3519
+ END IF;
3520
+ IF to_regprocedure(
3521
+ format(
3522
+ '%I.ensure_managed_human_personal_workspace(uuid,text,uuid)',
3523
+ ${literal(schema)}
3524
+ )
3525
+ ) IS NOT NULL THEN
3526
+ EXECUTE format(
3527
+ 'REVOKE ALL ON FUNCTION %I.ensure_managed_human_personal_workspace(uuid, text, uuid) FROM PUBLIC',
3528
+ ${literal(schema)}
3529
+ );
3530
+ EXECUTE format(
3531
+ 'GRANT EXECUTE ON FUNCTION %I.ensure_managed_human_personal_workspace(uuid, text, uuid) TO %I',
3532
+ ${literal(schema)},
3533
+ ${literal(role)}
3534
+ );
3535
+ END IF;
3536
+ FOREACH routine_signature IN ARRAY ${organizationMembershipLifecycleRoutines} LOOP
3537
+ IF to_regprocedure(format('%I.%s', ${literal(schema)}, routine_signature)) IS NOT NULL THEN
3538
+ EXECUTE format(
3539
+ 'REVOKE ALL ON FUNCTION %I.%s FROM PUBLIC',
3540
+ ${literal(schema)}, routine_signature
3541
+ );
3542
+ EXECUTE format(
3543
+ 'GRANT EXECUTE ON FUNCTION %I.%s TO %I',
3544
+ ${literal(schema)}, routine_signature, ${literal(role)}
3545
+ );
3546
+ END IF;
3547
+ END LOOP;
3548
+ IF to_regprocedure(format('%I.ensure_canonical_human_identity(text,text)', ${literal(schema)})) IS NOT NULL THEN
3549
+ EXECUTE format(
3550
+ 'REVOKE ALL ON FUNCTION %I.ensure_canonical_human_identity(text, text) FROM PUBLIC',
3551
+ ${literal(schema)}
3552
+ );
3553
+ EXECUTE format(
3554
+ 'GRANT EXECUTE ON FUNCTION %I.ensure_canonical_human_identity(text, text) TO %I',
3555
+ ${literal(schema)},
3556
+ ${literal(role)}
3557
+ );
3558
+ END IF;
3559
+ IF to_regprocedure(format('%I.validate_canonical_human_session(text,text,boolean)', ${literal(schema)})) IS NOT NULL THEN
3560
+ EXECUTE format(
3561
+ 'REVOKE ALL ON FUNCTION %I.validate_canonical_human_session(text, text, boolean) FROM PUBLIC',
3562
+ ${literal(schema)}
3563
+ );
3564
+ EXECUTE format(
3565
+ 'GRANT EXECUTE ON FUNCTION %I.validate_canonical_human_session(text, text, boolean) TO %I',
3566
+ ${literal(schema)},
3567
+ ${literal(role)}
3568
+ );
3569
+ END IF;
3570
+ IF to_regprocedure(format('%I.get_canonical_human_identity_projection(text)', ${literal(schema)})) IS NOT NULL THEN
3571
+ EXECUTE format(
3572
+ 'REVOKE ALL ON FUNCTION %I.get_canonical_human_identity_projection(text) FROM PUBLIC',
3573
+ ${literal(schema)}
3574
+ );
3575
+ EXECUTE format(
3576
+ 'GRANT EXECUTE ON FUNCTION %I.get_canonical_human_identity_projection(text) TO %I',
3577
+ ${literal(schema)},
3578
+ ${literal(role)}
3579
+ );
3580
+ END IF;
3581
+ IF to_regprocedure(format('%I.apply_canonical_human_identity_operation(uuid,text,bigint,text,uuid,text,text,text)', ${literal(schema)})) IS NOT NULL THEN
3582
+ EXECUTE format(
3583
+ 'REVOKE ALL ON FUNCTION %I.apply_canonical_human_identity_operation(uuid, text, bigint, text, uuid, text, text, text) FROM PUBLIC',
3584
+ ${literal(schema)}
3585
+ );
3586
+ EXECUTE format(
3587
+ 'GRANT EXECUTE ON FUNCTION %I.apply_canonical_human_identity_operation(uuid, text, bigint, text, uuid, text, text, text) TO %I',
3588
+ ${literal(schema)},
3589
+ ${literal(role)}
3590
+ );
3591
+ END IF;
3592
+ -- Migration 0225 creates these target-schema-local session visibility
3593
+ -- capabilities before opengeni_app may exist. Re-converge their exact
3594
+ -- EXECUTE grants for migrate-then-provision installs without granting
3595
+ -- blanket execution on target-schema routines.
3596
+ IF to_regprocedure(
3597
+ format(
3598
+ '%I.session_private_actor_visible(uuid,uuid,uuid,text)',
3599
+ ${literal(schema)}
3600
+ )
3601
+ ) IS NOT NULL THEN
3602
+ EXECUTE format(
3603
+ 'REVOKE ALL ON FUNCTION %I.session_private_actor_visible(uuid, uuid, uuid, text) FROM PUBLIC',
3604
+ ${literal(schema)}
3605
+ );
3606
+ EXECUTE format(
3607
+ 'GRANT EXECUTE ON FUNCTION %I.session_private_actor_visible(uuid, uuid, uuid, text) TO %I',
3608
+ ${literal(schema)},
3609
+ ${literal(role)}
3610
+ );
3611
+ END IF;
3612
+ IF to_regprocedure(
3613
+ format(
3614
+ '%I.session_reference_visible(uuid,uuid,uuid)',
3615
+ ${literal(schema)}
3616
+ )
3617
+ ) IS NOT NULL THEN
3618
+ EXECUTE format(
3619
+ 'REVOKE ALL ON FUNCTION %I.session_reference_visible(uuid, uuid, uuid) FROM PUBLIC',
3620
+ ${literal(schema)}
3621
+ );
3622
+ EXECUTE format(
3623
+ 'GRANT EXECUTE ON FUNCTION %I.session_reference_visible(uuid, uuid, uuid) TO %I',
3624
+ ${literal(schema)},
3625
+ ${literal(role)}
3626
+ );
3627
+ END IF;
3628
+ IF to_regprocedure(
3629
+ format(
3630
+ '%I.transition_session_visibility(uuid,uuid,uuid,text,text,integer,text,text,integer)',
3631
+ ${literal(schema)}
3632
+ )
3633
+ ) IS NOT NULL THEN
3634
+ EXECUTE format(
3635
+ 'REVOKE ALL ON FUNCTION %I.transition_session_visibility(uuid, uuid, uuid, text, text, integer, text, text, integer) FROM PUBLIC',
3636
+ ${literal(schema)}
3637
+ );
3638
+ EXECUTE format(
3639
+ 'GRANT EXECUTE ON FUNCTION %I.transition_session_visibility(uuid, uuid, uuid, text, text, integer, text, text, integer) TO %I',
3640
+ ${literal(schema)},
3641
+ ${literal(role)}
3642
+ );
3643
+ END IF;
3644
+ IF to_regprocedure(
3645
+ format(
3646
+ '%I.fork_session_content(uuid,uuid,uuid,text,uuid,text,text,text,integer)',
3647
+ ${literal(schema)}
3648
+ )
3649
+ ) IS NOT NULL THEN
3650
+ EXECUTE format(
3651
+ 'REVOKE ALL ON FUNCTION %I.fork_session_content(uuid, uuid, uuid, text, uuid, text, text, text, integer) FROM PUBLIC',
3652
+ ${literal(schema)}
3653
+ );
3654
+ EXECUTE format(
3655
+ 'GRANT EXECUTE ON FUNCTION %I.fork_session_content(uuid, uuid, uuid, text, uuid, text, text, text, integer) TO %I',
3656
+ ${literal(schema)},
3657
+ ${literal(role)}
3658
+ );
3659
+ END IF;
3660
+ IF to_regprocedure(
3661
+ format(
3662
+ '%I.fork_session_content(uuid,uuid,uuid,text,uuid,text,boolean,text,text,integer)',
3663
+ ${literal(schema)}
3664
+ )
3665
+ ) IS NOT NULL THEN
3666
+ EXECUTE format(
3667
+ 'REVOKE ALL ON FUNCTION %I.fork_session_content(uuid, uuid, uuid, text, uuid, text, boolean, text, text, integer) FROM PUBLIC',
3668
+ ${literal(schema)}
3669
+ );
3670
+ EXECUTE format(
3671
+ 'GRANT EXECUTE ON FUNCTION %I.fork_session_content(uuid, uuid, uuid, text, uuid, text, boolean, text, text, integer) TO %I',
3672
+ ${literal(schema)},
3673
+ ${literal(role)}
3674
+ );
3675
+ END IF;
3676
+ IF to_regprocedure(
3677
+ format(
3678
+ '%I.replay_applied_session_fork(uuid,uuid,uuid,text,uuid,text,boolean,text,text,integer)',
3679
+ ${literal(schema)}
3680
+ )
3681
+ ) IS NOT NULL THEN
3682
+ EXECUTE format(
3683
+ 'REVOKE ALL ON FUNCTION %I.replay_applied_session_fork(uuid, uuid, uuid, text, uuid, text, boolean, text, text, integer) FROM PUBLIC',
3684
+ ${literal(schema)}
3685
+ );
3686
+ EXECUTE format(
3687
+ 'GRANT EXECUTE ON FUNCTION %I.replay_applied_session_fork(uuid, uuid, uuid, text, uuid, text, boolean, text, text, integer) TO %I',
3688
+ ${literal(schema)},
3689
+ ${literal(role)}
3690
+ );
3691
+ END IF;
3692
+ IF to_regprocedure(
3693
+ format('%I.session_tenancy_product_activated(uuid,integer)', ${literal(schema)})
3694
+ ) IS NOT NULL THEN
3695
+ EXECUTE format(
3696
+ 'REVOKE ALL ON FUNCTION %I.session_tenancy_product_activated(uuid, integer) FROM PUBLIC',
3697
+ ${literal(schema)}
3698
+ );
3699
+ EXECUTE format(
3700
+ 'GRANT EXECUTE ON FUNCTION %I.session_tenancy_product_activated(uuid, integer) TO %I',
3701
+ ${literal(schema)},
3702
+ ${literal(role)}
3703
+ );
3704
+ EXECUTE format(
3705
+ 'REVOKE ALL ON FUNCTION %I.session_tenancy_any_product_activation() FROM PUBLIC',
3706
+ ${literal(schema)}
3707
+ );
3708
+ EXECUTE format(
3709
+ 'GRANT EXECUTE ON FUNCTION %I.session_tenancy_any_product_activation() TO %I',
3710
+ ${literal(schema)},
3711
+ ${literal(role)}
3712
+ );
3713
+ EXECUTE format(
3714
+ 'REVOKE ALL ON FUNCTION %I.assert_session_tenancy_quiescent(uuid, uuid, uuid, boolean) FROM PUBLIC',
3715
+ ${literal(schema)}
3716
+ );
3717
+ EXECUTE format(
3718
+ 'REVOKE ALL ON FUNCTION %I.assert_session_tenancy_quiescent(uuid, uuid, uuid, boolean) FROM %I',
3719
+ ${literal(schema)},
3720
+ ${literal(role)}
3721
+ );
3722
+ END IF;
3723
+ IF to_regprocedure(
3724
+ format('%I.get_private_session_create_policy(uuid,uuid,text)', ${literal(schema)})
3725
+ ) IS NOT NULL THEN
3726
+ EXECUTE format(
3727
+ 'REVOKE ALL ON FUNCTION %I.get_private_session_create_policy(uuid, uuid, text) FROM PUBLIC',
3728
+ ${literal(schema)}
3729
+ );
3730
+ EXECUTE format(
3731
+ 'GRANT EXECUTE ON FUNCTION %I.get_private_session_create_policy(uuid, uuid, text) TO %I',
3732
+ ${literal(schema)}, ${literal(role)}
3733
+ );
3734
+ END IF;
3735
+ IF to_regprocedure(
3736
+ format('%I.get_organization_private_session_settings(uuid,text)', ${literal(schema)})
3737
+ ) IS NOT NULL THEN
3738
+ EXECUTE format(
3739
+ 'REVOKE ALL ON FUNCTION %I.get_organization_private_session_settings(uuid, text) FROM PUBLIC',
3740
+ ${literal(schema)}
3741
+ );
3742
+ EXECUTE format(
3743
+ 'GRANT EXECUTE ON FUNCTION %I.get_organization_private_session_settings(uuid, text) TO %I',
3744
+ ${literal(schema)}, ${literal(role)}
3745
+ );
3746
+ END IF;
3747
+ IF to_regprocedure(
3748
+ format(
3749
+ '%I.update_organization_private_session_settings(uuid,text,boolean,bigint,uuid)',
3750
+ ${literal(schema)}
3751
+ )
3752
+ ) IS NOT NULL THEN
3753
+ EXECUTE format(
3754
+ 'REVOKE ALL ON FUNCTION %I.update_organization_private_session_settings(uuid, text, boolean, bigint, uuid) FROM PUBLIC',
3755
+ ${literal(schema)}
3756
+ );
3757
+ EXECUTE format(
3758
+ 'GRANT EXECUTE ON FUNCTION %I.update_organization_private_session_settings(uuid, text, boolean, bigint, uuid) TO %I',
3759
+ ${literal(schema)}, ${literal(role)}
3760
+ );
3761
+ END IF;
3762
+ IF to_regprocedure(
3763
+ format('%I.organization_private_sessions_enabled(uuid)', ${literal(schema)})
3764
+ ) IS NOT NULL THEN
3765
+ EXECUTE format(
3766
+ 'REVOKE ALL ON FUNCTION %I.organization_private_sessions_enabled(uuid) FROM PUBLIC',
3767
+ ${literal(schema)}
3768
+ );
3769
+ EXECUTE format(
3770
+ 'REVOKE ALL ON FUNCTION %I.organization_private_sessions_enabled(uuid) FROM %I',
3771
+ ${literal(schema)}, ${literal(role)}
3772
+ );
3773
+ END IF;
3774
+ IF to_regprocedure(
3775
+ format('%I.open_private_session_create_capability(uuid,uuid,uuid,text)', ${literal(schema)})
3776
+ ) IS NOT NULL THEN
3777
+ EXECUTE format(
3778
+ 'REVOKE ALL ON FUNCTION %I.open_private_session_create_capability(uuid, uuid, uuid, text) FROM PUBLIC',
3779
+ ${literal(schema)}
3780
+ );
3781
+ EXECUTE format(
3782
+ 'GRANT EXECUTE ON FUNCTION %I.open_private_session_create_capability(uuid, uuid, uuid, text) TO %I',
3783
+ ${literal(schema)}, ${literal(role)}
3784
+ );
3785
+ EXECUTE format(
3786
+ 'REVOKE ALL ON FUNCTION %I.close_private_session_create_capability(uuid) FROM PUBLIC',
3787
+ ${literal(schema)}
3788
+ );
3789
+ EXECUTE format(
3790
+ 'GRANT EXECUTE ON FUNCTION %I.close_private_session_create_capability(uuid) TO %I',
3791
+ ${literal(schema)}, ${literal(role)}
3792
+ );
3793
+ END IF;
3794
+ IF to_regprocedure(
3795
+ format(
3796
+ '%I.open_private_child_session_create_capability(uuid,uuid,uuid,uuid,uuid,uuid,integer)',
3797
+ ${literal(schema)}
3798
+ )
3799
+ ) IS NOT NULL THEN
3800
+ EXECUTE format(
3801
+ 'REVOKE ALL ON FUNCTION %I.open_private_child_session_create_capability(uuid,uuid,uuid,uuid,uuid,uuid,integer) FROM PUBLIC',
3802
+ ${literal(schema)}
3803
+ );
3804
+ EXECUTE format(
3805
+ 'GRANT EXECUTE ON FUNCTION %I.open_private_child_session_create_capability(uuid,uuid,uuid,uuid,uuid,uuid,integer) TO %I',
3806
+ ${literal(schema)}, ${literal(role)}
3807
+ );
3808
+ END IF;
3809
+ IF to_regprocedure(
3810
+ format(
3811
+ '%I.create_xai_subscription_credential(uuid,uuid,text,text,text,text,text,text,text,timestamptz)',
3812
+ ${literal(schema)}
3813
+ )
3814
+ ) IS NOT NULL THEN
3815
+ EXECUTE format(
3816
+ 'REVOKE ALL ON FUNCTION %I.create_xai_subscription_credential(uuid, uuid, text, text, text, text, text, text, text, timestamptz) FROM PUBLIC',
3817
+ ${literal(schema)}
3818
+ );
3819
+ EXECUTE format(
3820
+ 'GRANT EXECUTE ON FUNCTION %I.create_xai_subscription_credential(uuid, uuid, text, text, text, text, text, text, text, timestamptz) TO %I',
3821
+ ${literal(schema)},
3822
+ ${literal(role)}
3823
+ );
3824
+ EXECUTE format(
3825
+ 'REVOKE ALL ON FUNCTION %I.disconnect_xai_subscription_credential(uuid, uuid, text, uuid, jsonb) FROM PUBLIC',
3826
+ ${literal(schema)}
3827
+ );
3828
+ EXECUTE format(
3829
+ 'GRANT EXECUTE ON FUNCTION %I.disconnect_xai_subscription_credential(uuid, uuid, text, uuid, jsonb) TO %I',
3830
+ ${literal(schema)},
3831
+ ${literal(role)}
3832
+ );
3833
+ EXECUTE format(
3834
+ 'REVOKE ALL ON FUNCTION %I.resolve_xai_authority_pool(uuid, uuid, text, jsonb) FROM PUBLIC',
3835
+ ${literal(schema)}
3836
+ );
3837
+ EXECUTE format(
3838
+ 'GRANT EXECUTE ON FUNCTION %I.resolve_xai_authority_pool(uuid, uuid, text, jsonb) TO %I',
3839
+ ${literal(schema)},
3840
+ ${literal(role)}
3841
+ );
3842
+ EXECUTE format(
3843
+ 'REVOKE ALL ON FUNCTION %I.revalidate_xai_subscription_authority(uuid, text, uuid, jsonb) FROM PUBLIC',
3844
+ ${literal(schema)}
3845
+ );
3846
+ EXECUTE format(
3847
+ 'GRANT EXECUTE ON FUNCTION %I.revalidate_xai_subscription_authority(uuid, text, uuid, jsonb) TO %I',
3848
+ ${literal(schema)},
3849
+ ${literal(role)}
3850
+ );
3851
+ EXECUTE format(
3852
+ 'REVOKE ALL ON FUNCTION %I.xai_provider_account_authority_snapshot_v1_valid(jsonb) FROM PUBLIC',
3853
+ ${literal(schema)}
3854
+ );
3855
+ EXECUTE format(
3856
+ 'GRANT EXECUTE ON FUNCTION %I.xai_provider_account_authority_snapshot_v1_valid(jsonb) TO %I',
3857
+ ${literal(schema)},
3858
+ ${literal(role)}
3859
+ );
3860
+ EXECUTE format(
3861
+ 'REVOKE ALL ON FUNCTION %I.xai_subscription_authority_live(uuid, uuid, text, uuid, text, uuid, uuid, bigint) FROM PUBLIC',
3862
+ ${literal(schema)}
3863
+ );
3864
+ EXECUTE format(
3865
+ 'GRANT EXECUTE ON FUNCTION %I.xai_subscription_authority_live(uuid, uuid, text, uuid, text, uuid, uuid, bigint) TO %I',
3866
+ ${literal(schema)},
3867
+ ${literal(role)}
3868
+ );
3869
+ EXECUTE format(
3870
+ 'REVOKE ALL ON FUNCTION %I.xai_subscription_pool_visible(uuid, uuid, text, text, uuid) FROM PUBLIC',
3871
+ ${literal(schema)}
3872
+ );
3873
+ EXECUTE format(
3874
+ 'GRANT EXECUTE ON FUNCTION %I.xai_subscription_pool_visible(uuid, uuid, text, text, uuid) TO %I',
3875
+ ${literal(schema)},
3876
+ ${literal(role)}
3877
+ );
3878
+ END IF;
3879
+ IF to_regprocedure(
3880
+ format(
3881
+ '%I.resolve_session_attempt_personal_resources(uuid,uuid,uuid)',
3882
+ ${literal(schema)}
3883
+ )
3884
+ ) IS NOT NULL THEN
3885
+ EXECUTE format(
3886
+ 'REVOKE ALL ON FUNCTION %I.resolve_session_attempt_personal_resources(uuid, uuid, uuid) FROM PUBLIC',
3887
+ ${literal(schema)}
3888
+ );
3889
+ EXECUTE format(
3890
+ 'GRANT EXECUTE ON FUNCTION %I.resolve_session_attempt_personal_resources(uuid, uuid, uuid) TO %I',
3891
+ ${literal(schema)},
3892
+ ${literal(role)}
3893
+ );
3894
+ END IF;
3895
+ IF to_regprocedure(
3896
+ format(
3897
+ '%I.accept_turn_personal_resource_attachment(uuid,uuid,uuid,uuid,text,integer,boolean,integer)',
3898
+ ${literal(schema)}
3899
+ )
3900
+ ) IS NOT NULL THEN
3901
+ EXECUTE format(
3902
+ 'REVOKE ALL ON FUNCTION %I.accept_turn_personal_resource_attachment(uuid, uuid, uuid, uuid, text, integer, boolean, integer) FROM PUBLIC',
3903
+ ${literal(schema)}
3904
+ );
3905
+ EXECUTE format(
3906
+ 'GRANT EXECUTE ON FUNCTION %I.accept_turn_personal_resource_attachment(uuid, uuid, uuid, uuid, text, integer, boolean, integer) TO %I',
3907
+ ${literal(schema)},
3908
+ ${literal(role)}
3909
+ );
3910
+ END IF;
3911
+ IF to_regprocedure(format('%I.list_self_user_resource_authorities(uuid,uuid,text,uuid,integer)', ${literal(schema)}))
3912
+ IS NOT NULL THEN
3913
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.list_self_user_resource_authorities(uuid) FROM PUBLIC', ${literal(schema)});
3914
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.list_self_user_resource_authorities(uuid) FROM %I', ${literal(schema)}, ${literal(role)});
3915
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.issue_self_user_resource_grant(uuid, uuid, uuid, text, text, text, uuid, boolean) FROM PUBLIC', ${literal(schema)});
3916
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.issue_self_user_resource_grant(uuid, uuid, uuid, text, text, text, uuid, boolean) FROM %I', ${literal(schema)}, ${literal(role)});
3917
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.revoke_self_user_resource_grant(uuid, uuid) FROM PUBLIC', ${literal(schema)});
3918
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.revoke_self_user_resource_grant(uuid, uuid) FROM %I', ${literal(schema)}, ${literal(role)});
3919
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.list_self_user_resource_authorities(uuid, uuid, text, uuid, integer) FROM PUBLIC', ${literal(schema)});
3920
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.list_self_user_resource_authorities(uuid, uuid, text, uuid, integer) TO %I', ${literal(schema)}, ${literal(role)});
3921
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.issue_self_user_resource_grant(uuid, uuid, uuid, text, text, text, uuid, integer, boolean) FROM PUBLIC', ${literal(schema)});
3922
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.issue_self_user_resource_grant(uuid, uuid, uuid, text, text, text, uuid, integer, boolean) TO %I', ${literal(schema)}, ${literal(role)});
3923
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.revoke_self_user_resource_grant(uuid, uuid, uuid) FROM PUBLIC', ${literal(schema)});
3924
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.revoke_self_user_resource_grant(uuid, uuid, uuid) TO %I', ${literal(schema)}, ${literal(role)});
3925
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.authorize_session_attempt_personal_resource_reads(uuid, uuid, uuid) FROM PUBLIC', ${literal(schema)});
3926
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.authorize_session_attempt_personal_resource_reads(uuid, uuid, uuid) TO %I', ${literal(schema)}, ${literal(role)});
3927
+ END IF;
3928
+ IF to_regprocedure(format('%I.resolve_connection_use_authority(uuid,uuid,uuid,jsonb)', ${literal(schema)}))
3929
+ IS NOT NULL THEN
3930
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.list_self_connection_authorities(uuid) FROM PUBLIC', ${literal(schema)});
3931
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.list_self_connection_authorities(uuid) FROM %I', ${literal(schema)}, ${literal(role)});
3932
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.issue_self_connection_use_grant(uuid, uuid, uuid, text, text, uuid, boolean) FROM PUBLIC', ${literal(schema)});
3933
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.issue_self_connection_use_grant(uuid, uuid, uuid, text, text, uuid, boolean) FROM %I', ${literal(schema)}, ${literal(role)});
3934
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.revoke_self_connection_use_grant(uuid, uuid) FROM PUBLIC', ${literal(schema)});
3935
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.revoke_self_connection_use_grant(uuid, uuid) FROM %I', ${literal(schema)}, ${literal(role)});
3936
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.resolve_connection_use_authority(uuid, uuid, uuid, jsonb) FROM PUBLIC', ${literal(schema)});
3937
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.resolve_connection_use_authority(uuid, uuid, uuid, jsonb) TO %I', ${literal(schema)}, ${literal(role)});
3938
+ IF to_regprocedure(format('%I.resolve_personal_connection_authority_selection(uuid,uuid,text,uuid,jsonb)', ${literal(schema)})) IS NOT NULL THEN
3939
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.resolve_personal_connection_authority_selection(uuid, uuid, text, uuid, jsonb) FROM PUBLIC', ${literal(schema)});
3940
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.resolve_personal_connection_authority_selection(uuid, uuid, text, uuid, jsonb) TO %I', ${literal(schema)}, ${literal(role)});
3941
+ END IF;
3942
+ IF to_regprocedure(format('%I.resolve_accepted_connection_use(uuid,uuid,uuid,uuid,uuid,integer,uuid,text,text,uuid,text,text,text,text)', ${literal(schema)})) IS NOT NULL THEN
3943
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.resolve_accepted_connection_use(uuid, uuid, uuid, uuid, uuid, integer, uuid, text, text, uuid, text, text, text, text) FROM PUBLIC', ${literal(schema)});
3944
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.resolve_accepted_connection_use(uuid, uuid, uuid, uuid, uuid, integer, uuid, text, text, uuid, text, text, text, text) TO %I', ${literal(schema)}, ${literal(role)});
3945
+ END IF;
3946
+ END IF;
3947
+ IF to_regprocedure(
3948
+ format('%I.get_self_personal_github_repository_selection(uuid,uuid,text,uuid)', ${literal(schema)})
3949
+ ) IS NOT NULL THEN
3950
+ EXECUTE format(
3951
+ 'REVOKE ALL ON FUNCTION %I.get_self_personal_github_repository_selection(uuid,uuid,text,uuid) FROM PUBLIC',
3952
+ ${literal(schema)}
3953
+ );
3954
+ EXECUTE format(
3955
+ 'GRANT EXECUTE ON FUNCTION %I.get_self_personal_github_repository_selection(uuid,uuid,text,uuid) TO %I',
3956
+ ${literal(schema)}, ${literal(role)}
3957
+ );
3958
+ EXECUTE format(
3959
+ 'REVOKE ALL ON FUNCTION %I.mutate_self_personal_github_repository_selection(uuid,uuid,text,uuid,bigint,bigint,text,jsonb,boolean) FROM PUBLIC',
3960
+ ${literal(schema)}
3961
+ );
3962
+ EXECUTE format(
3963
+ 'GRANT EXECUTE ON FUNCTION %I.mutate_self_personal_github_repository_selection(uuid,uuid,text,uuid,bigint,bigint,text,jsonb,boolean) TO %I',
3964
+ ${literal(schema)}, ${literal(role)}
3965
+ );
3966
+ EXECUTE format(
3967
+ 'REVOKE ALL PRIVILEGES ON TABLE %I.personal_github_repository_selection_heads, %I.personal_github_repository_selections, %I.personal_github_repository_selection_operations FROM %I',
3968
+ ${literal(schema)}, ${literal(schema)}, ${literal(schema)}, ${literal(role)}
3969
+ );
3970
+ END IF;
3971
+ IF to_regprocedure(
3972
+ format('%I.create_personal_document_authority(uuid,uuid,uuid)', ${literal(schema)})
3973
+ ) IS NOT NULL THEN
3974
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.create_personal_document_authority(uuid, uuid, uuid) FROM PUBLIC', ${literal(schema)});
3975
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.create_personal_document_authority(uuid, uuid, uuid) TO %I', ${literal(schema)}, ${literal(role)});
3976
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.resolve_document_original_file(uuid, uuid, text, uuid) FROM PUBLIC', ${literal(schema)});
3977
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.resolve_document_original_file(uuid, uuid, text, uuid) TO %I', ${literal(schema)}, ${literal(role)});
3978
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.prepare_session_attempt_personal_document_reads(uuid, uuid, uuid, uuid) FROM PUBLIC', ${literal(schema)});
3979
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.prepare_session_attempt_personal_document_reads(uuid, uuid, uuid, uuid) FROM %I', ${literal(schema)}, ${literal(role)});
3980
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.resolve_session_attempt_personal_document_reads(uuid, uuid, uuid, uuid) FROM PUBLIC', ${literal(schema)});
3981
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.resolve_session_attempt_personal_document_reads(uuid, uuid, uuid, uuid) TO %I', ${literal(schema)}, ${literal(role)});
3982
+ EXECUTE format('REVOKE ALL ON FUNCTION opengeni_private.personal_document_authority_capability_active(text) FROM PUBLIC');
3983
+ EXECUTE format('GRANT EXECUTE ON FUNCTION opengeni_private.personal_document_authority_capability_active(text) TO %I', ${literal(role)});
3984
+ EXECUTE format('REVOKE ALL PRIVILEGES ON TABLE opengeni_private.personal_document_authority_capabilities FROM %I', ${literal(role)});
3985
+ EXECUTE format('REVOKE ALL PRIVILEGES ON TABLE %I.session_attempt_personal_document_admissions FROM %I', ${literal(schema)}, ${literal(role)});
3986
+ EXECUTE format('REVOKE ALL PRIVILEGES ON TABLE %I.session_attempt_personal_document_snapshots FROM %I', ${literal(schema)}, ${literal(role)});
3987
+ EXECUTE format('REVOKE ALL PRIVILEGES ON TABLE %I.personal_document_once_consumption_receipts FROM %I', ${literal(schema)}, ${literal(role)});
3988
+ END IF;
3989
+ IF to_regprocedure(
3990
+ format('%I.reclassify_document_authority(jsonb)', ${literal(schema)})
3991
+ ) IS NOT NULL THEN
3992
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.reclassify_document_authority(jsonb) FROM PUBLIC', ${literal(schema)});
3993
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.reclassify_document_authority(jsonb) TO %I', ${literal(schema)}, ${literal(role)});
3994
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.list_document_authority_reclassifications(uuid, uuid, text, uuid, integer, timestamptz, uuid) FROM PUBLIC', ${literal(schema)});
3995
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.list_document_authority_reclassifications(uuid, uuid, text, uuid, integer, timestamptz, uuid) TO %I', ${literal(schema)}, ${literal(role)});
3996
+ EXECUTE format('REVOKE ALL ON FUNCTION %I.run_document_default_collection_backfill(jsonb) FROM PUBLIC', ${literal(schema)});
3997
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.run_document_default_collection_backfill(jsonb) TO %I', ${literal(schema)}, ${literal(role)});
3998
+ EXECUTE format('REVOKE ALL ON FUNCTION opengeni_private.document_migration_capability_active(text) FROM PUBLIC');
3999
+ EXECUTE format('GRANT EXECUTE ON FUNCTION opengeni_private.document_migration_capability_active(text) TO %I', ${literal(role)});
4000
+ EXECUTE format('REVOKE ALL PRIVILEGES ON TABLE opengeni_private.document_migration_capabilities FROM %I', ${literal(role)});
4001
+ EXECUTE format('GRANT SELECT ON TABLE %I.document_authority_reclassifications TO %I', ${literal(schema)}, ${literal(role)});
4002
+ EXECUTE format('REVOKE INSERT, UPDATE, DELETE ON TABLE %I.document_authority_reclassifications FROM %I', ${literal(schema)}, ${literal(role)});
4003
+ EXECUTE format('REVOKE ALL PRIVILEGES ON TABLE %I.document_default_collection_backfill_runs, %I.document_default_collection_backfill_operations, %I.document_default_collection_backfill_receipts FROM %I', ${literal(schema)}, ${literal(schema)}, ${literal(schema)}, ${literal(role)});
4004
+ END IF;
4005
+ IF to_regprocedure(
4006
+ format('%I.create_scoped_variable_set(uuid,uuid,text,text,text,jsonb,boolean)', ${literal(schema)})
4007
+ ) IS NOT NULL THEN
4008
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.create_scoped_variable_set(uuid, uuid, text, text, text, jsonb, boolean) TO %I', ${literal(schema)}, ${literal(role)});
4009
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.list_scoped_variable_sets(uuid, uuid, uuid, text, text) TO %I', ${literal(schema)}, ${literal(role)});
4010
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.count_scoped_variable_sets(uuid, uuid, text) TO %I', ${literal(schema)}, ${literal(role)});
4011
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.mutate_scoped_variable_set(uuid, uuid, uuid, text, text, boolean, text, boolean, text, text, boolean) TO %I', ${literal(schema)}, ${literal(role)});
4012
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.read_scoped_variable_set_secret(uuid, uuid, uuid, text, text, text, uuid, uuid, uuid, integer) TO %I', ${literal(schema)}, ${literal(role)});
4013
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.materialize_scoped_variable_set_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid) TO %I', ${literal(schema)}, ${literal(role)});
4014
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.materialize_scoped_variable_set_for_session(uuid, uuid, uuid, uuid) TO %I', ${literal(schema)}, ${literal(role)});
4015
+ EXECUTE format('REVOKE ALL PRIVILEGES ON TABLE %I.workspace_variable_sets FROM %I', ${literal(schema)}, ${literal(role)});
4016
+ EXECUTE format('REVOKE ALL PRIVILEGES ON TABLE %I.workspace_variable_set_variables FROM %I', ${literal(schema)}, ${literal(role)});
4017
+ END IF;
4018
+ IF to_regprocedure(
4019
+ format('%I.create_scoped_rig(uuid,uuid,text,text,text,text,jsonb,boolean)', ${literal(schema)})
4020
+ ) IS NOT NULL THEN
4021
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.create_scoped_rig(uuid, uuid, text, text, text, text, jsonb, boolean) TO %I', ${literal(schema)}, ${literal(role)});
4022
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.list_scoped_rigs(uuid, uuid, uuid, text, text) TO %I', ${literal(schema)}, ${literal(role)});
4023
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.count_scoped_rigs(uuid, uuid, text) TO %I', ${literal(schema)}, ${literal(role)});
4024
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.mutate_scoped_rig(uuid, uuid, uuid, text, text, boolean, text, boolean, boolean) TO %I', ${literal(schema)}, ${literal(role)});
4025
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.finalize_scoped_enrollment(uuid, uuid, text, text, boolean, boolean, text, text, text, boolean) TO %I', ${literal(schema)}, ${literal(role)});
4026
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.list_scoped_enrollments(uuid, uuid, uuid, text) TO %I', ${literal(schema)}, ${literal(role)});
4027
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.get_scoped_sandbox(uuid, uuid, uuid) TO %I', ${literal(schema)}, ${literal(role)});
4028
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.authorize_scoped_sandbox_attach(uuid, uuid, uuid) TO %I', ${literal(schema)}, ${literal(role)});
4029
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.materialize_scoped_rig_version_for_attempt(uuid, uuid, uuid, uuid, uuid, integer) TO %I', ${literal(schema)}, ${literal(role)});
4030
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.authorize_session_attempt_personal_machine(uuid, uuid, uuid, uuid, uuid, integer, uuid) TO %I', ${literal(schema)}, ${literal(role)});
4031
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.assert_session_attempt_personal_machine(uuid, uuid, uuid, uuid, uuid, integer, uuid, boolean) TO %I', ${literal(schema)}, ${literal(role)});
4032
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.list_scoped_machine_dependent_sessions(uuid, uuid, uuid) TO %I', ${literal(schema)}, ${literal(role)});
4033
+ EXECUTE format('GRANT EXECUTE ON FUNCTION %I.detach_scoped_machine_dependent_sessions(uuid, uuid, uuid) TO %I', ${literal(schema)}, ${literal(role)});
4034
+ EXECUTE format('REVOKE ALL PRIVILEGES ON TABLE %I.session_attempt_connected_machine_authorizations FROM %I', ${literal(schema)}, ${literal(role)});
4035
+ END IF;
4036
+ IF to_regprocedure(
4037
+ format(
4038
+ '%I.freeze_scheduled_task_personal_resources(uuid,uuid,uuid,bigint)',
4039
+ ${literal(schema)}
4040
+ )
4041
+ ) IS NOT NULL THEN
4042
+ EXECUTE format(
4043
+ 'REVOKE ALL ON FUNCTION %I.freeze_scheduled_task_personal_resources(uuid, uuid, uuid, bigint) FROM PUBLIC',
4044
+ ${literal(schema)}
4045
+ );
4046
+ EXECUTE format(
4047
+ 'GRANT EXECUTE ON FUNCTION %I.freeze_scheduled_task_personal_resources(uuid, uuid, uuid, bigint) TO %I',
4048
+ ${literal(schema)},
4049
+ ${literal(role)}
4050
+ );
4051
+ EXECUTE format(
4052
+ 'REVOKE ALL ON FUNCTION %I.clone_scheduled_task_personal_resource_authority(uuid, uuid, uuid, bigint, bigint) FROM PUBLIC',
4053
+ ${literal(schema)}
4054
+ );
4055
+ EXECUTE format(
4056
+ 'GRANT EXECUTE ON FUNCTION %I.clone_scheduled_task_personal_resource_authority(uuid, uuid, uuid, bigint, bigint) TO %I',
4057
+ ${literal(schema)},
4058
+ ${literal(role)}
4059
+ );
4060
+ IF to_regprocedure(
4061
+ format(
4062
+ '%I.refresh_scheduled_task_personal_resources_clone_connections(uuid,uuid,uuid,bigint,bigint)',
4063
+ ${literal(schema)}
4064
+ )
4065
+ ) IS NOT NULL THEN
4066
+ EXECUTE format(
4067
+ 'REVOKE ALL ON FUNCTION %I.refresh_scheduled_task_personal_resources_clone_connections(uuid, uuid, uuid, bigint, bigint) FROM PUBLIC',
4068
+ ${literal(schema)}
4069
+ );
4070
+ EXECUTE format(
4071
+ 'GRANT EXECUTE ON FUNCTION %I.refresh_scheduled_task_personal_resources_clone_connections(uuid, uuid, uuid, bigint, bigint) TO %I',
4072
+ ${literal(schema)}, ${literal(role)}
4073
+ );
4074
+ EXECUTE format(
4075
+ 'REVOKE ALL ON FUNCTION %I.create_scheduled_agent_run_with_admission(uuid, uuid, uuid, uuid, bigint, text, text, text, timestamp with time zone, timestamp with time zone, jsonb) FROM PUBLIC',
4076
+ ${literal(schema)}
4077
+ );
4078
+ EXECUTE format(
4079
+ 'GRANT EXECUTE ON FUNCTION %I.create_scheduled_agent_run_with_admission(uuid, uuid, uuid, uuid, bigint, text, text, text, timestamp with time zone, timestamp with time zone, jsonb) TO %I',
4080
+ ${literal(schema)}, ${literal(role)}
4081
+ );
4082
+ EXECUTE format(
4083
+ 'REVOKE ALL ON FUNCTION %I.scheduled_task_run_connection_authority_subject(uuid, uuid, uuid) FROM PUBLIC',
4084
+ ${literal(schema)}
4085
+ );
4086
+ EXECUTE format(
4087
+ 'GRANT EXECUTE ON FUNCTION %I.scheduled_task_run_connection_authority_subject(uuid, uuid, uuid) TO %I',
4088
+ ${literal(schema)}, ${literal(role)}
4089
+ );
4090
+ EXECUTE format(
4091
+ 'REVOKE ALL ON FUNCTION %I.scheduled_task_personal_resource_authority_subject(uuid, uuid, uuid, bigint) FROM PUBLIC',
4092
+ ${literal(schema)}
4093
+ );
4094
+ EXECUTE format(
4095
+ 'GRANT EXECUTE ON FUNCTION %I.scheduled_task_personal_resource_authority_subject(uuid, uuid, uuid, bigint) TO %I',
4096
+ ${literal(schema)}, ${literal(role)}
4097
+ );
4098
+ EXECUTE format(
4099
+ 'REVOKE ALL ON FUNCTION %I.record_scheduled_task_revision_authority(uuid, uuid, uuid, bigint) FROM PUBLIC',
4100
+ ${literal(schema)}
4101
+ );
4102
+ EXECUTE format(
4103
+ 'GRANT EXECUTE ON FUNCTION %I.record_scheduled_task_revision_authority(uuid, uuid, uuid, bigint) TO %I',
4104
+ ${literal(schema)}, ${literal(role)}
4105
+ );
4106
+ EXECUTE format(
4107
+ 'REVOKE ALL ON FUNCTION %I.clone_scheduled_task_revision_authority(uuid, uuid, uuid, bigint, bigint) FROM PUBLIC',
4108
+ ${literal(schema)}
4109
+ );
4110
+ EXECUTE format(
4111
+ 'GRANT EXECUTE ON FUNCTION %I.clone_scheduled_task_revision_authority(uuid, uuid, uuid, bigint, bigint) TO %I',
4112
+ ${literal(schema)}, ${literal(role)}
4113
+ );
4114
+ EXECUTE format(
4115
+ 'REVOKE ALL ON FUNCTION %I.scheduled_task_revision_authority_subject(uuid, uuid, uuid, bigint) FROM PUBLIC',
4116
+ ${literal(schema)}
4117
+ );
4118
+ EXECUTE format(
4119
+ 'GRANT EXECUTE ON FUNCTION %I.scheduled_task_revision_authority_subject(uuid, uuid, uuid, bigint) TO %I',
4120
+ ${literal(schema)}, ${literal(role)}
4121
+ );
4122
+ EXECUTE format(
4123
+ 'REVOKE ALL ON FUNCTION %I.scheduled_task_revision_authority_snapshot(uuid, uuid, uuid, bigint) FROM PUBLIC',
4124
+ ${literal(schema)}
4125
+ );
4126
+ EXECUTE format(
4127
+ 'GRANT EXECUTE ON FUNCTION %I.scheduled_task_revision_authority_snapshot(uuid, uuid, uuid, bigint) TO %I',
4128
+ ${literal(schema)}, ${literal(role)}
4129
+ );
4130
+ EXECUTE format(
4131
+ 'REVOKE ALL ON FUNCTION %I.validate_scheduled_agent_run_live_authority(uuid, uuid, uuid) FROM PUBLIC',
4132
+ ${literal(schema)}
4133
+ );
4134
+ EXECUTE format(
4135
+ 'GRANT EXECUTE ON FUNCTION %I.validate_scheduled_agent_run_live_authority(uuid, uuid, uuid) TO %I',
4136
+ ${literal(schema)}, ${literal(role)}
4137
+ );
4138
+ EXECUTE format(
4139
+ 'REVOKE ALL ON FUNCTION %I.scheduled_scoped_rig_version_metadata(uuid, uuid, text, uuid, uuid) FROM PUBLIC',
4140
+ ${literal(schema)}
4141
+ );
4142
+ EXECUTE format(
4143
+ 'GRANT EXECUTE ON FUNCTION %I.scheduled_scoped_rig_version_metadata(uuid, uuid, text, uuid, uuid) TO %I',
4144
+ ${literal(schema)}, ${literal(role)}
4145
+ );
4146
+ EXECUTE format(
4147
+ 'REVOKE ALL ON FUNCTION %I.scheduled_variable_set_expected_generation_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid) FROM PUBLIC',
4148
+ ${literal(schema)}
4149
+ );
4150
+ EXECUTE format(
4151
+ 'GRANT EXECUTE ON FUNCTION %I.scheduled_variable_set_expected_generation_for_attempt(uuid, uuid, uuid, uuid, uuid, integer, uuid) TO %I',
4152
+ ${literal(schema)}, ${literal(role)}
4153
+ );
4154
+ EXECUTE format(
4155
+ 'REVOKE ALL ON FUNCTION %I.bind_scheduled_task_run_session(uuid, uuid, uuid, uuid) FROM PUBLIC',
4156
+ ${literal(schema)}
4157
+ );
4158
+ EXECUTE format(
4159
+ 'GRANT EXECUTE ON FUNCTION %I.bind_scheduled_task_run_session(uuid, uuid, uuid, uuid) TO %I',
4160
+ ${literal(schema)}, ${literal(role)}
4161
+ );
4162
+ EXECUTE format(
4163
+ 'REVOKE ALL ON FUNCTION %I.transition_scheduled_agent_run(uuid, uuid, uuid, uuid, uuid, text, text) FROM PUBLIC',
4164
+ ${literal(schema)}
4165
+ );
4166
+ EXECUTE format(
4167
+ 'GRANT EXECUTE ON FUNCTION %I.transition_scheduled_agent_run(uuid, uuid, uuid, uuid, uuid, text, text) TO %I',
4168
+ ${literal(schema)}, ${literal(role)}
4169
+ );
4170
+ EXECUTE format(
4171
+ 'REVOKE DELETE ON TABLE %I.scheduled_tasks, %I.scheduled_task_runs FROM %I',
4172
+ ${literal(schema)}, ${literal(schema)}, ${literal(role)}
4173
+ );
4174
+ EXECUTE format(
4175
+ 'REVOKE ALL PRIVILEGES ON TABLE %I.scheduled_task_connection_authority_snapshots FROM %I',
4176
+ ${literal(schema)}, ${literal(role)}
4177
+ );
4178
+ EXECUTE format(
4179
+ 'REVOKE ALL PRIVILEGES ON TABLE %I.scheduled_task_run_connection_authority_snapshots FROM %I',
4180
+ ${literal(schema)}, ${literal(role)}
4181
+ );
4182
+ EXECUTE format(
4183
+ 'REVOKE ALL PRIVILEGES ON TABLE %I.scheduled_task_reusable_connection_materializations FROM %I',
4184
+ ${literal(schema)}, ${literal(role)}
4185
+ );
4186
+ EXECUTE format(
4187
+ 'REVOKE ALL PRIVILEGES ON TABLE %I.scheduled_task_revision_authorities FROM %I',
4188
+ ${literal(schema)}, ${literal(role)}
4189
+ );
4190
+ END IF;
4191
+ EXECUTE format(
4192
+ 'REVOKE ALL ON FUNCTION %I.materialize_scheduled_task_reusable_session_from_run(uuid, uuid, uuid, uuid, uuid, bigint, text) FROM PUBLIC',
4193
+ ${literal(schema)}
4194
+ );
4195
+ EXECUTE format(
4196
+ 'GRANT EXECUTE ON FUNCTION %I.materialize_scheduled_task_reusable_session_from_run(uuid, uuid, uuid, uuid, uuid, bigint, text) TO %I',
4197
+ ${literal(schema)},
4198
+ ${literal(role)}
4199
+ );
4200
+ EXECUTE format(
4201
+ 'REVOKE ALL ON FUNCTION %I.scheduled_task_run_personal_resource_authority(uuid, uuid, uuid) FROM PUBLIC',
4202
+ ${literal(schema)}
4203
+ );
4204
+ EXECUTE format(
4205
+ 'GRANT EXECUTE ON FUNCTION %I.scheduled_task_run_personal_resource_authority(uuid, uuid, uuid) TO %I',
4206
+ ${literal(schema)},
4207
+ ${literal(role)}
4208
+ );
4209
+ END IF;
4210
+ IF to_regprocedure(
4211
+ format(
4212
+ '%I.scoped_knowledge_advance_source_acl(uuid,uuid,bigint,bigint,uuid,text,text,text,text,text,text)',
4213
+ ${literal(schema)}
4214
+ )
4215
+ ) IS NOT NULL THEN
4216
+ EXECUTE format(
4217
+ 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_advance_source_acl(uuid, uuid, bigint, bigint, uuid, text, text, text, text, text, text) TO %I',
4218
+ ${literal(schema)},
4219
+ ${literal(role)}
4220
+ );
4221
+ END IF;
4222
+ IF to_regprocedure(
4223
+ format(
4224
+ '%I.scoped_knowledge_complete_sync(uuid,uuid,text,text,timestamptz,jsonb,text,text,text)',
4225
+ ${literal(schema)}
4226
+ )
4227
+ ) IS NOT NULL THEN
4228
+ EXECUTE format(
4229
+ 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_complete_sync(uuid, uuid, text, text, timestamptz, jsonb, text, text, text) TO %I',
4230
+ ${literal(schema)},
4231
+ ${literal(role)}
4232
+ );
4233
+ END IF;
4234
+ IF to_regprocedure(
4235
+ format(
4236
+ '%I.scoped_knowledge_advance_object_version(uuid,uuid,bigint,bigint,uuid,text,text,text,text,text,text)',
4237
+ ${literal(schema)}
4238
+ )
4239
+ ) IS NOT NULL THEN
4240
+ EXECUTE format(
4241
+ 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_advance_object_version(uuid, uuid, bigint, bigint, uuid, text, text, text, text, text, text) TO %I',
4242
+ ${literal(schema)},
4243
+ ${literal(role)}
4244
+ );
4245
+ END IF;
4246
+ EXECUTE format('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA %I TO %I', ${literal(schema)}, ${literal(role)});
4247
+ EXECUTE format(
4248
+ 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA %I REVOKE ALL PRIVILEGES ON TABLES FROM %I',
4249
+ owner_role,
4250
+ ${literal(schema)},
4251
+ ${literal(role)}
4252
+ );
4253
+ EXECUTE format(
4254
+ 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA %I GRANT USAGE, SELECT ON SEQUENCES TO %I',
4255
+ owner_role,
4256
+ ${literal(schema)},
4257
+ ${literal(role)}
4258
+ );
4259
+ END IF;
4260
+ IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_private') THEN
4261
+ EXECUTE format('GRANT USAGE ON SCHEMA opengeni_private TO %I', ${literal(role)});
4262
+ EXECUTE format('REVOKE CREATE ON SCHEMA opengeni_private FROM %I', ${literal(role)});
4263
+ EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA opengeni_private TO %I', ${literal(role)});
4264
+ EXECUTE format(
4265
+ 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA opengeni_private REVOKE EXECUTE ON FUNCTIONS FROM %I',
4266
+ owner_role,
4267
+ ${literal(role)}
4268
+ );
4269
+ IF to_regprocedure('opengeni_private.personal_resource_delegation_capability_active(text)') IS NOT NULL THEN
4270
+ REVOKE ALL ON FUNCTION
4271
+ opengeni_private.personal_resource_delegation_capability_active(text)
4272
+ FROM PUBLIC;
4273
+ EXECUTE format(
4274
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.personal_resource_delegation_capability_active(text) TO %I',
4275
+ ${literal(role)}
4276
+ );
4277
+ END IF;
4278
+ IF to_regprocedure('opengeni_private.scheduled_personal_resource_capability_active(text)') IS NOT NULL THEN
4279
+ REVOKE ALL ON FUNCTION
4280
+ opengeni_private.scheduled_personal_resource_capability_active(text)
4281
+ FROM PUBLIC;
4282
+ EXECUTE format(
4283
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.scheduled_personal_resource_capability_active(text) TO %I',
4284
+ ${literal(role)}
4285
+ );
4286
+ END IF;
4287
+ IF to_regprocedure('opengeni_private.variable_set_authority_capability_active(text)') IS NOT NULL THEN
4288
+ REVOKE ALL ON FUNCTION
4289
+ opengeni_private.variable_set_authority_capability_active(text)
4290
+ FROM PUBLIC;
4291
+ EXECUTE format(
4292
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.variable_set_authority_capability_active(text) TO %I',
4293
+ ${literal(role)}
4294
+ );
4295
+ EXECUTE format(
4296
+ 'REVOKE ALL PRIVILEGES ON TABLE opengeni_private.variable_set_authority_capabilities FROM %I',
4297
+ ${literal(role)}
4298
+ );
4299
+ END IF;
4300
+ IF to_regprocedure('opengeni_private.scoped_compute_capability_active(text)') IS NOT NULL THEN
4301
+ REVOKE ALL ON FUNCTION opengeni_private.scoped_compute_capability_active(text) FROM PUBLIC;
4302
+ EXECUTE format(
4303
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.scoped_compute_capability_active(text) TO %I',
4304
+ ${literal(role)}
4305
+ );
4306
+ EXECUTE format(
4307
+ 'REVOKE ALL PRIVILEGES ON TABLE opengeni_private.scoped_compute_capabilities FROM %I',
4308
+ ${literal(role)}
4309
+ );
4310
+ END IF;
4311
+ -- Global cross-workspace artifact workers are separate capabilities. Never
4312
+ -- let the generic tenant-scoped app role inherit them from the historical
4313
+ -- blanket grant of already-installed helpers.
4314
+ IF to_regprocedure('opengeni_private.claim_editable_artifact_live_outbox(text,integer,integer,name)') IS NOT NULL THEN
4315
+ EXECUTE format(
4316
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.claim_editable_artifact_live_outbox(text, integer, integer, name) FROM %I',
4317
+ ${literal(role)}
4318
+ );
4319
+ EXECUTE format(
4320
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.mark_editable_artifact_live_outbox_published(text, text, integer, name) FROM %I',
4321
+ ${literal(role)}
4322
+ );
4323
+ EXECUTE format(
4324
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.renew_editable_artifact_live_outbox(text, text, integer, integer, name) FROM %I',
4325
+ ${literal(role)}
4326
+ );
4327
+ EXECUTE format(
4328
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.retry_editable_artifact_live_outbox(text, text, integer, integer, text, name) FROM %I',
4329
+ ${literal(role)}
4330
+ );
4331
+ EXECUTE format(
4332
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.dead_letter_editable_artifact_live_outbox(text, text, integer, text, name) FROM %I',
4333
+ ${literal(role)}
4334
+ );
4335
+ EXECUTE format(
4336
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.release_editable_artifact_live_outbox(text, text, integer, name) FROM %I',
4337
+ ${literal(role)}
4338
+ );
4339
+ END IF;
4340
+ IF to_regprocedure('opengeni_private.claim_editable_artifact_materializations(text,integer,integer,name)') IS NOT NULL THEN
4341
+ EXECUTE format(
4342
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.claim_editable_artifact_materializations(text, integer, integer, name) FROM %I',
4343
+ ${literal(role)}
4344
+ );
4345
+ EXECUTE format(
4346
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.renew_editable_artifact_materialization(uuid, uuid, text, text, text, integer, integer, name) FROM %I',
4347
+ ${literal(role)}
4348
+ );
4349
+ EXECUTE format(
4350
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.succeed_editable_artifact_materialization(uuid, uuid, text, text, text, integer, text, text, text, bigint, text, text, timestamptz, name) FROM %I',
4351
+ ${literal(role)}
4352
+ );
4353
+ EXECUTE format(
4354
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.fail_editable_artifact_materialization(uuid, uuid, text, text, text, integer, text, name) FROM %I',
4355
+ ${literal(role)}
4356
+ );
4357
+ END IF;
4358
+ IF to_regprocedure('opengeni_private.consume_editable_artifact_live_ticket(text,name)') IS NOT NULL THEN
4359
+ EXECUTE format(
4360
+ 'REVOKE EXECUTE ON FUNCTION opengeni_private.resolve_editable_artifact_ticket_data_schema(name) FROM %I',
4361
+ ${literal(role)}
4362
+ );
4363
+ EXECUTE format(
4364
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.put_editable_artifact_live_ticket(text, uuid, uuid, text, text, text, text, text, text, text, text, integer, text, boolean, integer, timestamptz, timestamptz, name) TO %I',
4365
+ ${literal(role)}
4366
+ );
4367
+ EXECUTE format(
4368
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.consume_editable_artifact_live_ticket(text, name) TO %I',
4369
+ ${literal(role)}
4370
+ );
4371
+ EXECUTE format(
4372
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.cleanup_expired_editable_artifact_live_tickets(integer, name) TO %I',
4373
+ ${literal(role)}
4374
+ );
4375
+ END IF;
4376
+ IF to_regprocedure('opengeni_private.authorize_editable_artifact_actor(uuid,uuid,text,text,text,text,text,text,integer,text,text,name)') IS NOT NULL THEN
4377
+ EXECUTE format(
4378
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.authorize_editable_artifact_actor(uuid, uuid, text, text, text, text, text, text, integer, text, text, name) TO %I',
4379
+ ${literal(role)}
4380
+ );
4381
+ END IF;
4382
+ FOREACH routine_signature IN ARRAY ARRAY[
4383
+ 'complete_temporal_schedule_connector_cleanup(uuid,uuid)',
4384
+ 'upgrade_temporal_schedule_connector_cleanup(uuid,uuid,text,uuid,text,jsonb,uuid)',
4385
+ 'complete_workspace_temporal_connector_cleanups(uuid,uuid)'
4386
+ ] LOOP
4387
+ IF to_regprocedure('opengeni_private.' || routine_signature) IS NOT NULL THEN
4388
+ EXECUTE format(
4389
+ 'REVOKE ALL ON FUNCTION opengeni_private.%s FROM PUBLIC',
4390
+ routine_signature
4391
+ );
4392
+ EXECUTE format(
4393
+ 'GRANT EXECUTE ON FUNCTION opengeni_private.%s TO %I',
4394
+ routine_signature,
4395
+ ${literal(role)}
4396
+ );
4397
+ END IF;
4398
+ END LOOP;
4399
+ END IF;
4400
+ END $$;
4401
+ `);
4402
+ }
4403
+ function commaSeparated(value) {
4404
+ return value.split(",").map((item) => item.trim()).filter(Boolean);
4405
+ }
4406
+ function validateIdentifier(name, value) {
4407
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
4408
+ throw new Error(`${name} contains an invalid Postgres identifier: ${value}`);
4409
+ }
4410
+ return value;
4411
+ }
4412
+ function identifier(value) {
4413
+ return `"${value.replace(/"/g, '""')}"`;
4414
+ }
4415
+ function literal(value) {
4416
+ return `'${value.replace(/'/g, "''")}'`;
4417
+ }
4418
+ function databaseUrlFor(value, database) {
4419
+ const url = new URL(value);
4420
+ url.pathname = `/${database}`;
4421
+ return url.toString();
4422
+ }
4423
+ if (import.meta.main) {
4424
+ const adminUrl = process.env.OPENGENI_MIGRATIONS_DATABASE_URL ?? process.env.OPENGENI_DATABASE_ADMIN_URL ?? process.env.OPENGENI_DATABASE_URL;
4425
+ if (!adminUrl) {
4426
+ throw new Error(
4427
+ "OPENGENI_MIGRATIONS_DATABASE_URL, OPENGENI_DATABASE_ADMIN_URL, or OPENGENI_DATABASE_URL is required"
4428
+ );
4429
+ }
4430
+ const result = await provisionRoles(adminUrl, {
4431
+ ...process.env.OPENGENI_DB_SCHEMA?.trim() ? { targetSchema: process.env.OPENGENI_DB_SCHEMA.trim() } : {}
4432
+ });
4433
+ console.log(JSON.stringify(result, null, 2));
4434
+ }
4435
+
4436
+ export {
4437
+ RUNTIME_TARGET_SCHEMA_CAPABILITY_ROUTINES,
4438
+ RUNTIME_TARGET_SCHEMA_FORBIDDEN_ROUTINES,
4439
+ RUNTIME_TARGET_SCHEMA_INVOKER_ROUTINES,
4440
+ FORCE_RLS_TABLES,
4441
+ NON_RLS_RUNTIME_TABLES,
4442
+ RUNTIME_FULL_DML_TABLES,
4443
+ RUNTIME_READ_ONLY_TABLES,
4444
+ RUNTIME_READ_UPDATE_TABLES,
4445
+ RUNTIME_READ_INSERT_TABLES,
4446
+ RUNTIME_READ_INSERT_UPDATE_TABLES,
4447
+ PROTECTED_NO_DIRECT_DML_TABLES,
4448
+ RUNTIME_TABLE_PRIVILEGES,
4449
+ RUNTIME_DML_TABLES,
4450
+ RuntimeDatabasePostureError,
4451
+ inspectRuntimeDatabasePosture,
4452
+ evaluateRuntimeDatabasePosture,
4453
+ assertRuntimeDatabasePosture,
4454
+ runtimeDatabaseReadyCheck,
4455
+ provisionRoles
4456
+ };
4457
+ //# sourceMappingURL=chunk-OF5OBB76.js.map