@consiliency/agent-board-schema 1.81.0 → 1.84.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 (264) hide show
  1. package/README.md +11 -0
  2. package/fixtures/already-applied.json +12 -0
  3. package/migrations/20261202000100_agent_board_archive_board.sql +1238 -0
  4. package/migrations/20261203000100_agent_board_archive_board_reads.sql +391 -0
  5. package/migrations/20261203000200_agent_board_signed_seat_gates.sql +695 -0
  6. package/package.json +1 -1
  7. package/schema-manifest.json +30 -3
  8. package/src/tooling.test.mjs +8 -2
  9. package/tests/agent_board_667_history_class.test.sql +20 -3
  10. package/tests/agent_board_954_signed_seat_gates.test.sql +472 -0
  11. package/tests/agent_board_archive_board.test.sql +956 -0
  12. package/tests/agent_board_archive_board_reads.test.sql +785 -0
  13. package/tests/agent_board_archive_board_reads_plan.test.sql +56 -0
  14. package/tests/agent_board_atomic_fleet_onboarding.test.sql +2 -0
  15. package/tests/agent_board_board_claim_policy.test.sql +5 -3
  16. package/tests/agent_board_claimpolicy_race.test.sql +8 -6
  17. package/tests/agent_board_fk_lock_edges.test.sql +27 -3
  18. package/tests/agent_board_gatenull_membstate.test.sql +3 -1
  19. package/tests/agent_board_invite_no_downgrade.test.sql +2 -2
  20. package/tests/agent_board_ledger_authority.test.sql +3 -1
  21. package/tests/agent_board_role_guard.test.sql +4 -1
  22. package/tests/agent_board_rolereset.test.sql +5 -4
  23. package/tests/agent_board_room_roster.test.sql +2 -2
  24. package/tests/agent_board_step_up.test.sql +12 -7
  25. package/tests/agent_board_step_up_helper.test.sql +20 -17
  26. package/tests/agent_board_write_enforcement_class.test.sql +2 -1
  27. package/tests/catalog/function_execute_privileges.json +72 -0
  28. package/tests/catalog/p_metadata_parameters.json +32 -0
  29. package/tests/catalog/step_up_gated_closure.json +2 -0
  30. package/tests/isolation/expected/archive_vs_content.out +800 -0
  31. package/tests/isolation/specs/archive_vs_content.spec +128 -0
  32. package/tests/mutations/918/M01_any_role.sql +13 -0
  33. package/tests/mutations/918/M02_departed_owner.sql +13 -0
  34. package/tests/mutations/918/M03_no_fleet_recheck.sql +13 -0
  35. package/tests/mutations/918/M04_no_step_up.sql +13 -0
  36. package/tests/mutations/918/M04b_step_up_archive_only.sql +14 -0
  37. package/tests/mutations/918/M04c_step_up_change_only.sql +17 -0
  38. package/tests/mutations/918/M05_null_flag.sql +12 -0
  39. package/tests/mutations/918/M05b_null_board.sql +12 -0
  40. package/tests/mutations/918/M06_not_idempotent.sql +12 -0
  41. package/tests/mutations/918/M06b_wrong_flag_returned.sql +12 -0
  42. package/tests/mutations/918/M07_create_board_unarchives.sql +15 -0
  43. package/tests/mutations/918/M08_no_moderation.sql +12 -0
  44. package/tests/mutations/918/M08b_any_change.sql +12 -0
  45. package/tests/mutations/918/M09_bootstrap_archived.sql +12 -0
  46. package/tests/mutations/918/M10_drop_artifacts.sql +2 -0
  47. package/tests/mutations/918/M10_drop_board_authority_ceilings.sql +2 -0
  48. package/tests/mutations/918/M10_drop_board_invite_blocks.sql +2 -0
  49. package/tests/mutations/918/M10_drop_board_invite_tokens.sql +3 -0
  50. package/tests/mutations/918/M10_drop_board_memberships.sql +3 -0
  51. package/tests/mutations/918/M10_drop_boards.sql +2 -0
  52. package/tests/mutations/918/M10_drop_callback_subscriptions.sql +3 -0
  53. package/tests/mutations/918/M10_drop_claims.sql +3 -0
  54. package/tests/mutations/918/M10_drop_conflicts.sql +2 -0
  55. package/tests/mutations/918/M10_drop_delegations.sql +2 -0
  56. package/tests/mutations/918/M10_drop_delivery_recipients.sql +2 -0
  57. package/tests/mutations/918/M10_drop_escalations.sql +2 -0
  58. package/tests/mutations/918/M10_drop_fleet_receive_policies.sql +2 -0
  59. package/tests/mutations/918/M10_drop_messages.sql +2 -0
  60. package/tests/mutations/918/M10_drop_task_events.sql +2 -0
  61. package/tests/mutations/918/M10_drop_tasks.sql +2 -0
  62. package/tests/mutations/918/M10_drop_thread_memberships.sql +3 -0
  63. package/tests/mutations/918/M10_drop_threads.sql +2 -0
  64. package/tests/mutations/918/M10i_drop_insert_board_invite_tokens.sql +2 -0
  65. package/tests/mutations/918/M10i_drop_insert_board_memberships.sql +2 -0
  66. package/tests/mutations/918/M10i_drop_insert_callback_subscriptions.sql +2 -0
  67. package/tests/mutations/918/M10i_drop_insert_claims.sql +2 -0
  68. package/tests/mutations/918/M10i_drop_insert_thread_memberships.sql +2 -0
  69. package/tests/mutations/918/M10u_drop_update_board_invite_tokens.sql +2 -0
  70. package/tests/mutations/918/M10u_drop_update_board_memberships.sql +2 -0
  71. package/tests/mutations/918/M10u_drop_update_callback_subscriptions.sql +2 -0
  72. package/tests/mutations/918/M10u_drop_update_claims.sql +2 -0
  73. package/tests/mutations/918/M10u_drop_update_thread_memberships.sql +2 -0
  74. package/tests/mutations/918/M11_artifacts_no_message.sql +10 -0
  75. package/tests/mutations/918/M11_artifacts_no_task.sql +10 -0
  76. package/tests/mutations/918/M11_artifacts_no_task_event.sql +10 -0
  77. package/tests/mutations/918/M11_claims_no_resource_key.sql +10 -0
  78. package/tests/mutations/918/M11_claims_no_thread.sql +10 -0
  79. package/tests/mutations/918/M11_delivery_no_source_message.sql +10 -0
  80. package/tests/mutations/918/M11_delivery_no_source_task.sql +10 -0
  81. package/tests/mutations/918/M12_claims_all.sql +9 -0
  82. package/tests/mutations/918/M13_memberships_all.sql +9 -0
  83. package/tests/mutations/918/M14_tokens_all.sql +9 -0
  84. package/tests/mutations/918/M15_subscriptions_all.sql +9 -0
  85. package/tests/mutations/918/M15b_thread_memberships_all.sql +9 -0
  86. package/tests/mutations/918/M16_messages_update.sql +10 -0
  87. package/tests/mutations/918/M16b_task_events_update.sql +10 -0
  88. package/tests/mutations/918/M17_boards_old_only.sql +10 -0
  89. package/tests/mutations/918/M18_threads_insert_only.sql +10 -0
  90. package/tests/mutations/918/M18b_guard_disabled.sql +2 -0
  91. package/tests/mutations/918/M20_no_clamp_exemption.sql +14 -0
  92. package/tests/mutations/918/M20b_clamp_any_session.sql +14 -0
  93. package/tests/mutations/918/M20c_clamp_raise.sql +13 -0
  94. package/tests/mutations/918/M20d_clamp_other_columns.sql +13 -0
  95. package/tests/mutations/918/M20e_clamp_any_principal.sql +15 -0
  96. package/tests/mutations/918/M20f_clamp_any_identity_row.sql +13 -0
  97. package/tests/mutations/918/M21_ignore_old_row.sql +14 -0
  98. package/tests/mutations/918/M22_never_refuses.sql +12 -0
  99. package/tests/mutations/918/M22b_wrong_sqlstate.sql +12 -0
  100. package/tests/mutations/918/M23_delegate_execute.sql +2 -0
  101. package/tests/mutations/918/M23b_status_oracle.sql +2 -0
  102. package/tests/mutations/918/M24_new_writer.sql +2 -0
  103. package/tests/mutations/918/M24b_new_dynamic_writer.sql +2 -0
  104. package/tests/mutations/918/M24c_second_status_writer.sql +2 -0
  105. package/tests/mutations/918/M24d_new_relation.sql +2 -0
  106. package/tests/mutations/918/M24e_direct_grant.sql +2 -0
  107. package/tests/mutations/918/M25_memberships_dropped_on_archive.sql +10 -0
  108. package/tests/mutations/918/M27_departure_result_only.sql +10 -0
  109. package/tests/mutations/918/M27b_departure_any_role.sql +10 -0
  110. package/tests/mutations/918/M27c_claim_result_only.sql +10 -0
  111. package/tests/mutations/918/M27d_claim_any_thread.sql +10 -0
  112. package/tests/mutations/918/M27e_subscription_result_only.sql +10 -0
  113. package/tests/mutations/918/M28_token_update_not_expiry.sql +8 -0
  114. package/tests/mutations/918/M28_token_update_not_reanchor.sql +8 -0
  115. package/tests/mutations/918/M28_token_update_not_role.sql +8 -0
  116. package/tests/mutations/918/M28_token_update_not_uses.sql +8 -0
  117. package/tests/mutations/918/M28b_revocation_any_edit.sql +10 -0
  118. package/tests/mutations/918/M28c_unrevoke.sql +10 -0
  119. package/tests/mutations/918/M28d_thread_access_agent.sql +10 -0
  120. package/tests/mutations/918/M28e_thread_access_thread.sql +10 -0
  121. package/tests/mutations/918/M28f_thread_access_expiry.sql +10 -0
  122. package/tests/mutations/918/M28g_thread_access_unrevoke.sql +10 -0
  123. package/tests/mutations/918/M29_grant_no_refusal.sql +13 -0
  124. package/tests/mutations/918/M29b_grant_refuses_first.sql +18 -0
  125. package/tests/mutations/918/M30_redeem_no_status.sql +12 -0
  126. package/tests/mutations/918/M30b_redeem_distinct_text.sql +16 -0
  127. package/tests/mutations/918/M31_display_any_status.sql +7 -0
  128. package/tests/mutations/918/M31b_display_not_service.sql +2 -0
  129. package/tests/mutations/918/M32_status_before_authority.sql +15 -0
  130. package/tests/mutations/918/M33_retention_refused.sql +14 -0
  131. package/tests/mutations/918/M33b_retention_any_metadata.sql +14 -0
  132. package/tests/mutations/918/M34_guard_rewrites_board_id.sql +13 -0
  133. package/tests/mutations/918/M34_guard_rewrites_claim_policy.sql +13 -0
  134. package/tests/mutations/918/M34_guard_rewrites_status.sql +13 -0
  135. package/tests/mutations/918/M34d_guard_returns_null.sql +16 -0
  136. package/tests/mutations/918/M34e_guard_rewrites_uppercase.sql +13 -0
  137. package/tests/mutations/918/M34f_guard_select_into_uppercase.sql +13 -0
  138. package/tests/mutations/918/M35_new_resource_kind.sql +3 -0
  139. package/tests/mutations/918/M35b_new_fk_anchor.sql +2 -0
  140. package/tests/mutations/918/M35c_exempt_gains_writer.sql +2 -0
  141. package/tests/mutations/918/M35d_service_role_gains_update.sql +2 -0
  142. package/tests/mutations/918/M36_token_created_at.sql +10 -0
  143. package/tests/mutations/918/M36b_thread_access_created_at.sql +10 -0
  144. package/tests/mutations/918/M37_non_object_refused.sql +14 -0
  145. package/tests/mutations/918/M37b_non_object_any_edit.sql +13 -0
  146. package/tests/mutations/918/M37c_non_object_any_key.sql +13 -0
  147. package/tests/mutations/918/M37d_non_object_partial_mark.sql +13 -0
  148. package/tests/mutations/918/M37e_non_object_result_any_type.sql +13 -0
  149. package/tests/mutations/918/M37f_non_object_any_last_element.sql +13 -0
  150. package/tests/mutations/918/M38_claim_key_free.sql +10 -0
  151. package/tests/mutations/918/M38b_claim_key_verbatim.sql +10 -0
  152. package/tests/mutations/918/M38c_claim_key_canonical_only.sql +10 -0
  153. package/tests/mutations/918/equivalents/M37ef_grid.sql +42 -0
  154. package/tests/mutations/918/isolation/I1_guard_no_lock.sql +13 -0
  155. package/tests/mutations/918/isolation/I2_archive_no_key_update.sql +12 -0
  156. package/tests/mutations/918/isolation/I3_guard_for_update.sql +12 -0
  157. package/tests/mutations/918/isolation/I4_archive_any_isolation.sql +12 -0
  158. package/tests/mutations/918/isolation/I5_redeem_unlocked.sql +12 -0
  159. package/tests/mutations/918/isolation/I6_thread_membership_unlocked.sql +12 -0
  160. package/tests/mutations/918/isolation/I7_thread_membership_for_share.sql +12 -0
  161. package/tests/mutations/918/pr2/R01_inbox_no_filter.sql +9 -0
  162. package/tests/mutations/918/pr2/R01b_inbox_hides_boardless.sql +9 -0
  163. package/tests/mutations/918/pr2/R01d_inbox_requires_readable.sql +9 -0
  164. package/tests/mutations/918/pr2/R01e_inbox_active_too.sql +9 -0
  165. package/tests/mutations/918/pr2/R02_counts_no_filter.sql +9 -0
  166. package/tests/mutations/918/pr2/R02b_counts_hide_boardless.sql +9 -0
  167. package/tests/mutations/918/pr2/R03_dashboard_no_filter.sql +9 -0
  168. package/tests/mutations/918/pr2/R03b_dashboard_hides_boardless.sql +9 -0
  169. package/tests/mutations/918/pr2/R03c_dashboard_tasks.sql +9 -0
  170. package/tests/mutations/918/pr2/R03d_dashboard_calls_helper.sql +9 -0
  171. package/tests/mutations/918/pr2/R04_open_esc_no_filter.sql +9 -0
  172. package/tests/mutations/918/pr2/R04b_open_esc_no_task.sql +9 -0
  173. package/tests/mutations/918/pr2/R04c_open_esc_no_thread.sql +9 -0
  174. package/tests/mutations/918/pr2/R05_ops_esc_no_filter.sql +9 -0
  175. package/tests/mutations/918/pr2/R05b_ops_esc_no_task.sql +9 -0
  176. package/tests/mutations/918/pr2/R05c_ops_esc_no_thread.sql +9 -0
  177. package/tests/mutations/918/pr2/R06_stale_no_filter.sql +9 -0
  178. package/tests/mutations/918/pr2/R06b_stale_no_task.sql +9 -0
  179. package/tests/mutations/918/pr2/R06c_stale_no_thread.sql +9 -0
  180. package/tests/mutations/918/pr2/R06d_stale_no_key.sql +9 -0
  181. package/tests/mutations/918/pr2/R06e_stale_unguarded_cast.sql +9 -0
  182. package/tests/mutations/918/pr2/R07_memberships_filtered.sql +9 -0
  183. package/tests/mutations/918/pr2/R07b_memberships_constant.sql +9 -0
  184. package/tests/mutations/918/pr2/R08a_v_active_claims_filtered.sql +9 -0
  185. package/tests/mutations/918/pr2/R08b_v_board_feed_filtered.sql +9 -0
  186. package/tests/mutations/918/pr2/R08c_task_tree_filtered.sql +5 -0
  187. package/tests/mutations/918/pr2/R08d_thread_feed_filtered.sql +5 -0
  188. package/tests/mutations/918/pr2/R08e_callback_subs_filtered.sql +5 -0
  189. package/tests/mutations/918/pr2/R09_inbox_definer_view.sql +9 -0
  190. package/tests/mutations/918/pr2/R09b_view_grant.sql +2 -0
  191. package/tests/mutations/918/pr2/R09c_view_revoke.sql +2 -0
  192. package/tests/mutations/918/pr2/R09d_column_renamed.sql +2 -0
  193. package/tests/mutations/918/pr2/R10_new_view.sql +2 -0
  194. package/tests/mutations/918/pr2/R10b_new_routine.sql +2 -0
  195. package/tests/mutations/918/pr2/R10c_new_indirect_routine.sql +2 -0
  196. package/tests/mutations/918/pr2/R10d_predicate_returns_rows.sql +2 -0
  197. package/tests/mutations/918/pr2/R10e_overload.sql +3 -0
  198. package/tests/mutations/918/pr2/R10f_execute_root.sql +2 -0
  199. package/tests/mutations/918/pr2/R10g_predicate_array.sql +2 -0
  200. package/tests/mutations/918/pr2/R10h_predicate_domain.sql +2 -0
  201. package/tests/mutations/918/pr2/R10i_polymorphic.sql +2 -0
  202. package/tests/mutations/918/pr2/R10j_predicate_json.sql +2 -0
  203. package/tests/mutations/918/pr2/R10k_foreign_view.sql +2 -0
  204. package/tests/mutations/918/pr2/R10l_foreign_view_transitive.sql +2 -0
  205. package/tests/mutations/918/pr2/R10m_foreign_view_function.sql +2 -0
  206. package/tests/mutations/918/pr2/R10n_foreign_matview.sql +2 -0
  207. package/tests/mutations/918/pr2/R10o_ambiguous_overload.sql +6 -0
  208. package/tests/mutations/918/pr2/R10p_resolved_overload.sql +6 -0
  209. package/tests/mutations/918/pr2/R11_requests_no_filter.sql +9 -0
  210. package/tests/mutations/918/pr2/R11b_requests_hide_all.sql +9 -0
  211. package/tests/mutations/918/pr2/R11c_requests_no_creator.sql +11 -0
  212. package/tests/mutations/918/pr2/R11d_requests_no_pending.sql +9 -0
  213. package/tests/mutations/918/pr2/R11e_requests_any_state.sql +9 -0
  214. package/tests/mutations/918/pr2/R11f_requests_active_too.sql +9 -0
  215. package/tests/mutations/918/pr2/R12_helper_definer.sql +2 -0
  216. package/tests/mutations/918/pr2/R12b_helper_no_thread.sql +11 -0
  217. package/tests/mutations/918/pr2/R12c_helper_no_task.sql +11 -0
  218. package/tests/mutations/918/pr2/R12d_helper_any_board.sql +10 -0
  219. package/tests/mutations/918/pr2/R12e_helper_task_any_board.sql +10 -0
  220. package/tests/mutations/918/pr2/R12f_helper_null.sql +11 -0
  221. package/tests/mutations/918/pr2/R12g_helper_delegate.sql +2 -0
  222. package/tests/mutations/918/pr2/R12h_helper_public.sql +2 -0
  223. package/tests/mutations/918/pr2/R12i_no_generic_plan.sql +2 -0
  224. package/tests/mutations/918/pr2/R13_archive_columns.sql +2 -0
  225. package/tests/mutations/918/pr2/R13b_second_agents_fk.sql +2 -0
  226. package/tests/mutations/918/pr2/R13c_archive_column.sql +2 -0
  227. package/tests/mutations/918/pr2/R15_rls_narrowed.sql +2 -0
  228. package/tests/mutations/918/pr2/R15b_rls_widened.sql +2 -0
  229. package/tests/mutations/918/pr2/R15c_threads_rls_narrowed.sql +2 -0
  230. package/tests/mutations/918/pr2/R16_archive_deletes.sql +10 -0
  231. package/tests/mutations/918/pr2/R16b_archive_marks_read.sql +10 -0
  232. package/tests/mutations/918/pr2/R17_wake_bypasses_inbox.sql +8 -0
  233. package/tests/mutations/918/pr2/R18_directory_archived.sql +7 -0
  234. package/tests/mutations/918/pr2/R19_delegate_ids_active_only.sql +7 -0
  235. package/tests/mutations/918/run.sh +95 -0
  236. package/tests/mutations/954/MA1_resolver_ignores_signer.sql +15 -0
  237. package/tests/mutations/954/MA2_null_actor_resolves_to_signer.sql +22 -0
  238. package/tests/mutations/954/MB1_no_bind.sql +14 -0
  239. package/tests/mutations/954/MC1_context_any_role.sql +15 -0
  240. package/tests/mutations/954/MG1_has_board_access_service_bypass.sql +18 -0
  241. package/tests/mutations/954/MG2_can_send_to_board_service_bypass.sql +18 -0
  242. package/tests/mutations/954/MG3_can_access_thread_service_bypass.sql +18 -0
  243. package/tests/mutations/954/MG4_can_post_to_thread_service_bypass.sql +13 -0
  244. package/tests/mutations/954/MG5_can_access_task_service_bypass.sql +18 -0
  245. package/tests/mutations/954/MG6_can_mutate_task_service_bypass.sql +18 -0
  246. package/tests/mutations/954/MR1_post_board_message_no_release.sql +14 -0
  247. package/tests/mutations/954/MR2_send_direct_message_no_release.sql +14 -0
  248. package/tests/mutations/954/MR3_send_multicast_message_no_release.sql +14 -0
  249. package/tests/mutations/954/MR4_create_tasking_delivery_no_release.sql +14 -0
  250. package/tests/mutations/954/MR5_append_task_event_no_release.sql +14 -0
  251. package/tests/mutations/954/MR6_grant_board_role_no_release.sql +14 -0
  252. package/tests/mutations/954/MR7_set_board_authority_ceiling_no_release.sql +14 -0
  253. package/tests/mutations/954/MW1_post_board_message_unbound.sql +25 -0
  254. package/tests/mutations/954/MW2_send_direct_message_unbound.sql +25 -0
  255. package/tests/mutations/954/MW3_send_multicast_message_unbound.sql +25 -0
  256. package/tests/mutations/954/MW4_create_tasking_delivery_unbound.sql +25 -0
  257. package/tests/mutations/954/MW5_append_task_event_unbound.sql +25 -0
  258. package/tests/mutations/954/MW6_grant_board_role_unbound.sql +25 -0
  259. package/tests/mutations/954/MW7_set_board_authority_ceiling_unbound.sql +25 -0
  260. package/tests/mutations/954/MX1_bind_session_level.sql +13 -0
  261. package/tests/mutations/954/MX2_release_session_level.sql +13 -0
  262. package/tests/mutations/954/run.sh +93 -0
  263. package/tests/seeds/20261202000100_agent_board_archive_board.sql.pre.sql +24 -0
  264. package/tests/seeds/20261203000100_agent_board_archive_board_reads.sql.pre.sql +38 -0
@@ -0,0 +1,1238 @@
1
+ -- #918 ARCHIVEBOARD PR-1: a sole writer for boards.status, and no new content on an archived board.
2
+ --
3
+ -- Owner decisions (2026-11-30): members keep READ access to an archived board's history (no RLS
4
+ -- change here); only an active board OWNER may archive or un-archive, with step-up BOTH ways.
5
+ -- Reads/views (inbox, lists) are PR-2.
6
+ --
7
+ -- WHAT THIS ADDS
8
+ -- * set_board_archived(p_board_id, p_archived): the only API writer of boards.status.
9
+ -- * MBA01 'board is archived': one SQLSTATE for every refused write on an archived board.
10
+ -- Distinct from 42501 (which clients read as "denied") and from MBS01 (step-up).
11
+ -- * _archived_board_guard(): ONE refusal, attached as trg_archived_board_guard to every relation
12
+ -- that holds board content or board settings. The tables are the narrowest shared point: an
13
+ -- unsigned RPC, a signed_* gateway, a hosted-delegate route and a service_role statement all
14
+ -- reach the same row write (no anon/authenticated/delegate role writes these tables directly;
15
+ -- service_role writes five of them, AB-C4). It is the shape #675 used for the last-owner rule.
16
+ -- It fires at the write, so a route's own authorization refusals come first: MBA01 means "you
17
+ -- were otherwise allowed; the board is archived".
18
+ -- BOUND: it sees INSERT and UPDATE of those 18 relations by any route, DELETE of none. The class
19
+ -- tests that keep the set current see agent_board routines that write a board-scoped relation
20
+ -- with a static statement or run EXECUTE. They do not see a writable view, a rewrite rule, a
21
+ -- routine in another schema, or a trigger that assigns NEW.
22
+ -- * create_board's slug-collision branch no longer sets status = 'active' (it un-archived a
23
+ -- board as a side effect, with no step-up).
24
+ -- * update_board_membership lets an owner/admin remove another member of an archived board.
25
+ -- * bootstrap_board_owner_memberships skips archived boards (it seats owners).
26
+ -- * grant_board_role refuses an archived board itself, after its authority checks, so the guard's
27
+ -- one role-reduction exemption (below) is not reachable through a grant.
28
+ -- * An invite for a non-active board answers the uniform 42501 'invite is not usable', decided
29
+ -- under the board's lock, and invite_board_for_display does not resolve it: holding a code is
30
+ -- not membership, so it must not reveal that the board is archived.
31
+ -- * update_board_membership checks the caller's owner/admin standing BEFORE the board's status, so
32
+ -- an outsider gets one answer for an active, an archived and an unknown board.
33
+ --
34
+ -- STAYS ALLOWED ON AN ARCHIVED BOARD: reading; a DEPARTURE (a membership UPDATE from a pending or
35
+ -- active state to left/removed, same board, agent and role: self-leave, principal withdrawal,
36
+ -- owner/admin removal, the D12 cascade, link_session_alias' removal); revoking an invite link;
37
+ -- releasing or expiring a live claim, and reclaim_fleet_machine's release; disabling a callback
38
+ -- subscription and finishing an in-flight callback delivery; inbox item state and read receipts;
39
+ -- presence heartbeats; unblocking an inviter; audit, telemetry, signature-evidence and
40
+ -- membership-event rows; and the retention sweep, which on a departed membership may write only its
41
+ -- three ops_retained/ops_retention metadata keys. Editing a row that had already departed
42
+ -- (including left -> removed), and inserting a departed row, are refused.
43
+ --
44
+ -- ISOLATION. Two guarantees, stated separately.
45
+ -- CONTENT. set_board_archived locks the board row FOR UPDATE before it flips the status. The guard
46
+ -- reads the status FOR KEY SHARE, the lock every FK to boards already takes; KEY SHARE conflicts
47
+ -- with FOR UPDATE and with nothing weaker, so the guard adds no conflict against the other boards
48
+ -- writers (NO KEY UPDATE). A guarded write either commits before the archive, or waits and is
49
+ -- refused: MBA01 under READ COMMITTED (the status is re-read after the wait), 40001 under
50
+ -- REPEATABLE READ and above.
51
+ -- AUTHORITY. set_board_archived decides on the caller's owner standing read AFTER it takes the
52
+ -- board authority lock, which serialises it with grants, departures and evictions. That reading is
53
+ -- current only under READ COMMITTED, so any other isolation level is refused (25001), as the
54
+ -- last-owner guard refuses it.
55
+ -- Not covered: a raw table-owner `update boards set status` (NO KEY UPDATE) is not serialised
56
+ -- against an in-flight post.
57
+ --
58
+ -- LOCK ORDER: advisory board lock -> boards FOR UPDATE -> agents FOR SHARE, the canonical
59
+ -- boards -> agents order (#194) onboard_federated_fleet_agent uses, under the same advisory lock.
60
+ --
61
+ -- DEPLOY. CREATE TRIGGER takes SHARE ROW EXCLUSIVE on each guarded table; all are taken up front in
62
+ -- one statement and held to commit. Catalog-only: no scan, no rewrite. lock_timeout is set to a
63
+ -- transaction-local 5 s when the applier left it unset (the #655 rule); 55P03 or 40P01 aborts the
64
+ -- whole transaction with nothing applied. Existing archived boards are not modified.
65
+ --
66
+ -- ACL AND COMMENT: restated for every function created or replaced (AGENTS.md "Schema-change
67
+ -- mechanics that bite"). Each re-created body is pg_get_functiondef of the 1.81.0 tree plus only
68
+ -- the #918-marked edits. agent_board.schema_version stays 8 (additive).
69
+
70
+ -- =============================================================================
71
+ -- 0. Locks
72
+ -- =============================================================================
73
+ do $s0$
74
+ begin
75
+ if current_setting('lock_timeout') in ('0', '0ms', '0s') then
76
+ perform set_config('lock_timeout', '5s', true);
77
+ end if;
78
+ end
79
+ $s0$;
80
+
81
+ lock table
82
+ agent_board.boards,
83
+ agent_board.board_memberships,
84
+ agent_board.board_invite_tokens,
85
+ agent_board.board_invite_blocks,
86
+ agent_board.board_authority_ceilings,
87
+ agent_board.fleet_receive_policies,
88
+ agent_board.callback_subscriptions,
89
+ agent_board.threads,
90
+ agent_board.thread_memberships,
91
+ agent_board.messages,
92
+ agent_board.delivery_recipients,
93
+ agent_board.tasks,
94
+ agent_board.task_events,
95
+ agent_board.delegations,
96
+ agent_board.claims,
97
+ agent_board.artifacts,
98
+ agent_board.conflicts,
99
+ agent_board.escalations
100
+ in share row exclusive mode;
101
+
102
+ -- =============================================================================
103
+ -- 1. The assertion: MBA01 when any named board is archived
104
+ -- =============================================================================
105
+ create function agent_board._assert_boards_not_archived(p_board_ids uuid[])
106
+ returns void
107
+ language plpgsql
108
+ security definer
109
+ set search_path = ''
110
+ as $fn$
111
+ declare
112
+ v_status text;
113
+ begin
114
+ -- FOR KEY SHARE, in id order. After a wait on set_board_archived's FOR UPDATE, READ COMMITTED
115
+ -- returns the committed status, so the decision is never made on the pre-archive row.
116
+ for v_status in
117
+ select b.status
118
+ from agent_board.boards b
119
+ where b.id = any(p_board_ids)
120
+ order by b.id
121
+ for key share of b
122
+ loop
123
+ if v_status = 'archived' then
124
+ raise exception 'board is archived'
125
+ using errcode = 'MBA01',
126
+ hint = 'the board is read-only; a board owner can un-archive it with set_board_archived';
127
+ end if;
128
+ end loop;
129
+ end;
130
+ $fn$;
131
+
132
+ revoke all on function agent_board._assert_boards_not_archived(uuid[])
133
+ from public, anon, authenticated, service_role, agent_board_delegate;
134
+ comment on function agent_board._assert_boards_not_archived(uuid[]) is
135
+ 'Consiliency/message-board#918: raises MBA01 ''board is archived'' when any of the named boards has status ''archived''. Reads each board FOR KEY SHARE in id order, which set_board_archived''s FOR UPDATE excludes, so a content write and an archive serialise. Its only raise is MBA01. A NULL or unknown id is ignored (no board, nothing to protect). No API-role EXECUTE: it would be a status oracle.';
136
+
137
+ -- =============================================================================
138
+ -- 2. The guard
139
+ -- =============================================================================
140
+ -- The trigger's arguments NAME the row's anchor columns, so what the guard resolves is readable
141
+ -- from pg_trigger and the class test derives it against pg_constraint. Every named column of the
142
+ -- new row, and of the old row on UPDATE, is resolved to its board; if ANY is archived the write is
143
+ -- refused. Which transitions are exempt is in each trigger's WHEN clause, not in this body, with
144
+ -- two exceptions on board_memberships (the session-identity role clamp and the retention marks).
145
+ -- A thread is read unlocked: a routine that writes on a board-less thread already holds the thread
146
+ -- row NO KEY UPDATE against a concurrent association (#667), and a thread on a board never changes
147
+ -- board. thread_memberships has no routine writer, so nothing holds that lock for it: the guard takes
148
+ -- the thread FOR NO KEY UPDATE there, and _associate_empty_thread then waits and sees the committed
149
+ -- row. Not FOR SHARE: two transactions that each grant access and then post on one thread would both
150
+ -- hold SHARE and both wait for the post's NO KEY UPDATE (40P01).
151
+ create function agent_board._archived_board_guard()
152
+ returns trigger
153
+ language plpgsql
154
+ security definer
155
+ set search_path = ''
156
+ as $fn$
157
+ declare
158
+ v_row jsonb;
159
+ v_rows jsonb[];
160
+ v_anchor text;
161
+ v_id uuid;
162
+ v_thread uuid;
163
+ v_board uuid;
164
+ v_boards uuid[] := '{}';
165
+ begin
166
+ if tg_table_name = 'board_memberships' and tg_op = 'UPDATE' then
167
+ -- link_session_alias (service_role only) clamps a SESSION identity's role DOWN to its parent's.
168
+ -- Refusing it would break session continuity for every identity seated on an archived board, and
169
+ -- it only reduces authority. identity_kind = 'session' is the condition that matters: every agent
170
+ -- gets a `legacy` session_identities row at commit (trg_session_identity_agent_lineage is
171
+ -- deferred). grant_board_role refuses an archived board itself, so no grant reaches this.
172
+ if agent_board._is_service_role()
173
+ and agent_board._role_rank(new.role) < agent_board._role_rank(old.role)
174
+ and (to_jsonb(new) - 'role' - 'updated_at') = (to_jsonb(old) - 'role' - 'updated_at')
175
+ and exists (
176
+ select 1 from agent_board.session_identities si
177
+ where si.agent_id = new.agent_id
178
+ and si.identity_kind = 'session') then
179
+ return new;
180
+ end if;
181
+ -- mark_retention_metadata marks departed memberships. Refusing it would abort the whole sweep
182
+ -- for one archived board. Only its three metadata keys (and updated_at) may differ. Its mark is
183
+ -- `metadata || {three keys}`: on an object it merges them, on an array or scalar it APPENDS that one
184
+ -- object, so the second form is exactly that append and nothing else.
185
+ if old.membership_state in ('left', 'removed')
186
+ and (to_jsonb(new) - 'metadata' - 'updated_at') = (to_jsonb(old) - 'metadata' - 'updated_at')
187
+ and (case
188
+ when jsonb_typeof(old.metadata) = 'object' then
189
+ jsonb_typeof(new.metadata) = 'object'
190
+ and (new.metadata - array['ops_retained_at', 'ops_retention_run_id', 'ops_retention_reason'])
191
+ = (old.metadata - array['ops_retained_at', 'ops_retention_run_id', 'ops_retention_reason'])
192
+ else
193
+ jsonb_typeof(new.metadata) = 'array'
194
+ and jsonb_typeof(new.metadata -> -1) = 'object'
195
+ and (new.metadata -> -1) ?& array['ops_retained_at', 'ops_retention_run_id', 'ops_retention_reason']
196
+ and ((new.metadata -> -1) - array['ops_retained_at', 'ops_retention_run_id', 'ops_retention_reason']) = '{}'::jsonb
197
+ and old.metadata || (new.metadata -> -1) = new.metadata
198
+ end) then
199
+ return new;
200
+ end if;
201
+ end if;
202
+
203
+ v_rows := array[to_jsonb(new)];
204
+ if tg_op = 'UPDATE' then
205
+ v_rows := v_rows || to_jsonb(old);
206
+ end if;
207
+
208
+ foreach v_row in array v_rows loop
209
+ foreach v_anchor in array tg_argv loop
210
+ if v_anchor = 'resource_key' then
211
+ -- A claim on a TASK names it in resource_key, not in an FK column.
212
+ if v_row ->> 'resource_kind' is distinct from 'task'
213
+ or v_row ->> 'resource_key' !~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$' then
214
+ continue;
215
+ end if;
216
+ elsif v_row ->> v_anchor is null then
217
+ continue;
218
+ end if;
219
+ v_id := (v_row ->> v_anchor)::uuid;
220
+ v_board := null;
221
+ v_thread := null;
222
+ case
223
+ when v_anchor = 'id' and tg_table_name = 'boards' then
224
+ v_board := v_id;
225
+ when v_anchor = 'board_id' then
226
+ v_board := v_id;
227
+ when v_anchor = 'thread_id' then
228
+ v_thread := v_id;
229
+ when v_anchor in ('task_id', 'source_task_id', 'parent_task_id', 'child_task_id', 'resource_key') then
230
+ select t.thread_id into v_thread from agent_board.tasks t where t.id = v_id;
231
+ when v_anchor in ('message_id', 'source_message_id') then
232
+ select m.thread_id into v_thread from agent_board.messages m where m.id = v_id;
233
+ when v_anchor = 'task_event_id' then
234
+ select te.thread_id into v_thread from agent_board.task_events te where te.id = v_id;
235
+ when v_anchor = 'source_delegation_id' then
236
+ select t.thread_id into v_thread
237
+ from agent_board.delegations d
238
+ join agent_board.tasks t on t.id = d.child_task_id
239
+ where d.id = v_id;
240
+ else
241
+ -- Fail closed: an anchor this body cannot resolve protects nothing.
242
+ raise exception 'archived-board guard: unknown anchor % on %', v_anchor, tg_table_name
243
+ using errcode = 'XX000';
244
+ end case;
245
+ if v_thread is not null then
246
+ if tg_table_name = 'thread_memberships' then
247
+ select th.board_id into v_board from agent_board.threads th where th.id = v_thread for no key update;
248
+ else
249
+ select th.board_id into v_board from agent_board.threads th where th.id = v_thread;
250
+ end if;
251
+ end if;
252
+ if v_board is not null then
253
+ v_boards := v_boards || v_board;
254
+ end if;
255
+ end loop;
256
+ end loop;
257
+
258
+ if cardinality(v_boards) > 0 then
259
+ perform agent_board._assert_boards_not_archived(v_boards);
260
+ end if;
261
+ return new;
262
+ end;
263
+ $fn$;
264
+
265
+ revoke all on function agent_board._archived_board_guard()
266
+ from public, anon, authenticated, service_role, agent_board_delegate;
267
+ comment on function agent_board._archived_board_guard() is
268
+ 'Consiliency/message-board#918: trigger function of trg_archived_board_guard. Refuses (MBA01, through _assert_boards_not_archived) a row write whose anchor columns, named by the trigger''s arguments, resolve to an ARCHIVED board, directly or through a thread, task, message, task event or delegation; on UPDATE the old row''s anchors count too. Refusal-only: NEW is never rewritten. An anchor it cannot resolve raises XX000. Exempt transitions are in each trigger''s WHEN clause, except two on board_memberships: a service_role role REDUCTION, and nothing else, on the membership of an identity of kind ''session'' (link_session_alias'' clamp), and the retention sweep''s three metadata keys on a departed row. For thread_memberships it takes the thread FOR NO KEY UPDATE, which excludes a concurrent board association. No role has EXECUTE.';
269
+
270
+ -- =============================================================================
271
+ -- 3. The guard, per relation
272
+ -- =============================================================================
273
+ -- Board settings. An archived board that stays archived takes no edit; archiving and un-archiving
274
+ -- (status changes) pass.
275
+ create trigger trg_archived_board_guard
276
+ before update on agent_board.boards
277
+ for each row when (old.status = 'archived' and new.status = 'archived')
278
+ execute function agent_board._archived_board_guard('id');
279
+ create trigger trg_archived_board_guard
280
+ before insert or update on agent_board.board_authority_ceilings
281
+ for each row execute function agent_board._archived_board_guard('board_id');
282
+ create trigger trg_archived_board_guard
283
+ before insert or update on agent_board.fleet_receive_policies
284
+ for each row execute function agent_board._archived_board_guard('board_id');
285
+ -- Membership. Every INSERT is guarded. An UPDATE passes only as a DEPARTURE: from a pending or active
286
+ -- state to left/removed, with board, agent and role unchanged.
287
+ create trigger trg_archived_board_guard
288
+ before insert on agent_board.board_memberships
289
+ for each row execute function agent_board._archived_board_guard('board_id');
290
+ create trigger trg_archived_board_guard_update
291
+ before update on agent_board.board_memberships
292
+ for each row when (not (
293
+ old.membership_state not in ('left', 'removed')
294
+ and new.membership_state in ('left', 'removed')
295
+ and (old.board_id, old.agent_id, old.role) is not distinct from (new.board_id, new.agent_id, new.role)))
296
+ execute function agent_board._archived_board_guard('board_id');
297
+ -- Invites. Minting, consuming and every edit are guarded; an UPDATE passes only as a REVOCATION:
298
+ -- the whole row compared but for the revocation columns, so a later column cannot ride along.
299
+ create trigger trg_archived_board_guard
300
+ before insert on agent_board.board_invite_tokens
301
+ for each row execute function agent_board._archived_board_guard('board_id');
302
+ create trigger trg_archived_board_guard_update
303
+ before update on agent_board.board_invite_tokens
304
+ for each row when (not (
305
+ old.revoked_at is null
306
+ and new.revoked_at is not null
307
+ and (to_jsonb(old) - 'revoked_at' - 'revoked_by_agent_id') = (to_jsonb(new) - 'revoked_at' - 'revoked_by_agent_id')))
308
+ execute function agent_board._archived_board_guard('board_id');
309
+ create trigger trg_archived_board_guard
310
+ before insert on agent_board.board_invite_blocks
311
+ for each row execute function agent_board._archived_board_guard('board_id');
312
+ -- Callback subscriptions. An UPDATE passes only as a disable.
313
+ create trigger trg_archived_board_guard
314
+ before insert on agent_board.callback_subscriptions
315
+ for each row execute function agent_board._archived_board_guard('board_id');
316
+ create trigger trg_archived_board_guard_update
317
+ before update on agent_board.callback_subscriptions
318
+ for each row when (not (
319
+ old.subscription_status = 'active'
320
+ and new.subscription_status = 'disabled'
321
+ and old.board_id is not distinct from new.board_id))
322
+ execute function agent_board._archived_board_guard('board_id');
323
+ -- Threads and what is posted in them. Retention metadata updates (messages, task_events,
324
+ -- delivery_recipients) are UPDATEs and pass; _next_thread_message_sequence does not write board_id.
325
+ create trigger trg_archived_board_guard
326
+ before insert or update of board_id on agent_board.threads
327
+ for each row execute function agent_board._archived_board_guard('board_id');
328
+ -- Thread access. No routine writes it; service_role can. An UPDATE passes only as a revocation (the whole
329
+ -- row compared but for revoked_at).
330
+ create trigger trg_archived_board_guard
331
+ before insert on agent_board.thread_memberships
332
+ for each row execute function agent_board._archived_board_guard('thread_id');
333
+ create trigger trg_archived_board_guard_update
334
+ before update on agent_board.thread_memberships
335
+ for each row when (not (
336
+ old.revoked_at is null
337
+ and new.revoked_at is not null
338
+ and (to_jsonb(old) - 'revoked_at') = (to_jsonb(new) - 'revoked_at')))
339
+ execute function agent_board._archived_board_guard('thread_id');
340
+ create trigger trg_archived_board_guard
341
+ before insert on agent_board.messages
342
+ for each row execute function agent_board._archived_board_guard('thread_id');
343
+ create trigger trg_archived_board_guard
344
+ before insert on agent_board.delivery_recipients
345
+ for each row execute function agent_board._archived_board_guard(
346
+ 'board_id', 'source_message_id', 'source_task_id', 'source_delegation_id');
347
+ create trigger trg_archived_board_guard
348
+ before insert or update on agent_board.tasks
349
+ for each row execute function agent_board._archived_board_guard('thread_id');
350
+ create trigger trg_archived_board_guard
351
+ before insert on agent_board.task_events
352
+ for each row execute function agent_board._archived_board_guard('thread_id');
353
+ create trigger trg_archived_board_guard
354
+ before insert or update on agent_board.delegations
355
+ for each row execute function agent_board._archived_board_guard('parent_task_id', 'child_task_id');
356
+ create trigger trg_archived_board_guard
357
+ before insert or update on agent_board.artifacts
358
+ for each row execute function agent_board._archived_board_guard(
359
+ 'thread_id', 'task_id', 'message_id', 'task_event_id');
360
+ create trigger trg_archived_board_guard
361
+ before insert or update on agent_board.conflicts
362
+ for each row execute function agent_board._archived_board_guard('thread_id');
363
+ create trigger trg_archived_board_guard
364
+ before insert or update on agent_board.escalations
365
+ for each row execute function agent_board._archived_board_guard('thread_id');
366
+ -- Claims. Every INSERT is guarded. An UPDATE passes only as a live claim ending (released or expired)
367
+ -- in place; acquire and renew do not. The key is kept, or becomes its own canonical form (release_claim
368
+ -- canonicalises a fleet-backed alias; a task key is canonical verbatim, so it cannot move).
369
+ create trigger trg_archived_board_guard
370
+ before insert on agent_board.claims
371
+ for each row execute function agent_board._archived_board_guard('thread_id', 'task_id', 'resource_key');
372
+ create trigger trg_archived_board_guard_update
373
+ before update on agent_board.claims
374
+ for each row when (not (
375
+ old.status = 'active'
376
+ and new.status in ('released', 'expired')
377
+ and (old.thread_id, old.task_id, old.agent_id, old.resource_kind) is not distinct from (new.thread_id, new.task_id, new.agent_id, new.resource_kind)
378
+ and (new.resource_key = old.resource_key
379
+ or new.resource_key = agent_board._canonical_claim_key(old.resource_kind, old.resource_key))))
380
+ execute function agent_board._archived_board_guard('thread_id', 'task_id', 'resource_key');
381
+
382
+ do $c$
383
+ declare r record;
384
+ begin
385
+ for r in select t.tgrelid::regclass as rel, t.tgname from pg_trigger t
386
+ where t.tgfoid = 'agent_board._archived_board_guard()'::regprocedure and not t.tgisinternal loop
387
+ execute format('comment on trigger %I on %s is %L', r.tgname, r.rel,
388
+ 'Consiliency/message-board#918: refuses (MBA01 board is archived) a write that adds or changes content or settings on an archived board; every INSERT and UPDATE of the relation is covered whatever route writes it, DELETE is not. Refusal-only: NEW is never rewritten. The arguments name the anchor columns resolved to a board; the WHEN clause names the transitions that stay allowed.');
389
+ end loop;
390
+ end
391
+ $c$;
392
+
393
+ -- =============================================================================
394
+ -- 4. set_board_archived
395
+ -- =============================================================================
396
+ create function agent_board.set_board_archived(p_board_id uuid, p_archived boolean)
397
+ returns table(board_id uuid, archived boolean, updated_at timestamp with time zone)
398
+ language plpgsql
399
+ security definer
400
+ set search_path to 'agent_board', 'public'
401
+ as $function$
402
+ declare
403
+ v_actor uuid := agent_board.current_agent_id();
404
+ v_target text := case when p_archived then 'archived' else 'active' end;
405
+ v_row agent_board.boards%rowtype;
406
+ begin
407
+ if p_board_id is null or p_archived is null then
408
+ raise exception 'p_board_id and p_archived must not be null' using errcode = '22023';
409
+ end if;
410
+ -- The owner standing below is read after the board authority lock. Under a transaction snapshot
411
+ -- that read is as old as the snapshot, so a former owner could still act: refuse, as the
412
+ -- last-owner guard does.
413
+ if current_setting('transaction_isolation') <> 'read committed' then
414
+ raise exception 'set_board_archived requires read committed' using errcode = '25001';
415
+ end if;
416
+
417
+ -- The board authority lock first, before any row lock: the owner standing read below then
418
+ -- serialises against grants, departures and evictions, and this function's agents row lock
419
+ -- (in _assert_actor_not_fleet_revoked) against onboard_federated_fleet_agent.
420
+ perform agent_board._lock_board_authority_ceiling(p_board_id);
421
+
422
+ -- Owner gate: only an active owner-role member. service_role (current_agent_id() = null) is not
423
+ -- an owner and is rejected here. It holds no UPDATE on boards either: the operator route is the
424
+ -- table owner's own SQL.
425
+ if v_actor is null
426
+ or not exists (
427
+ select 1
428
+ from agent_board.board_memberships bm
429
+ where bm.board_id = p_board_id
430
+ and bm.agent_id = v_actor
431
+ and bm.role = 'owner'
432
+ and bm.membership_state in ('joined', 'subscribed')
433
+ ) then
434
+ raise exception 'only a board owner may archive or un-archive a board' using errcode = '42501';
435
+ end if;
436
+
437
+ -- FOR UPDATE, not the NO KEY UPDATE an UPDATE takes: it is what excludes the guard's and the
438
+ -- FKs' KEY SHARE, so every content write on this board is wholly before or wholly after this.
439
+ select * into v_row
440
+ from agent_board.boards b
441
+ where b.id = p_board_id
442
+ for update;
443
+ if v_row.id is null then
444
+ raise exception 'board not found' using errcode = 'P0002';
445
+ end if;
446
+
447
+ -- Idempotent: asking for the state the board already has writes nothing (updated_at included).
448
+ if v_row.status is distinct from v_target then
449
+ update agent_board.boards b
450
+ set status = v_target,
451
+ updated_at = now()
452
+ where b.id = p_board_id
453
+ returning * into v_row;
454
+ end if;
455
+
456
+ -- #276 shape: after the boards write (boards -> agents, #194). The raise rolls it back.
457
+ perform agent_board._assert_actor_not_fleet_revoked(v_actor, 'set_board_archived');
458
+
459
+ -- #669 D1 shape: the LAST statement before return, on EVERY call, both directions (owner
460
+ -- decision 2), so every other refusal comes first and MBS01 means "otherwise allowed".
461
+ perform agent_board._require_human_step_up('set_board_archived');
462
+
463
+ return query
464
+ select v_row.id, v_row.status = 'archived', v_row.updated_at;
465
+ end;
466
+ $function$;
467
+
468
+ revoke all on function agent_board.set_board_archived(uuid, boolean)
469
+ from public, anon, authenticated, service_role, agent_board_delegate;
470
+ grant execute on function agent_board.set_board_archived(uuid, boolean) to authenticated, service_role;
471
+ comment on function agent_board.set_board_archived(uuid, boolean) is
472
+ 'Consiliency/message-board#918: archives (true) or un-archives (false) a board; the only API writer of boards.status. Null argument -> 22023. Any isolation level but READ COMMITTED -> 25001 (the owner standing is read after the board authority lock, which is current only there). Only current_agent_id() holding an ACTIVE owner membership (else 42501); service_role is not an owner here. Takes the board authority advisory lock first, then the board row FOR UPDATE, which excludes the KEY SHARE trg_archived_board_guard and every FK to boards take, so a concurrent guarded write is wholly before the archive or refused after it (MBA01, or 40001 under a transaction snapshot). Idempotent: the state the board already has writes nothing. Then _assert_actor_not_fleet_revoked (42501 ''fleet_revoked:''; after the write, boards -> agents), and _require_human_step_up(''set_board_archived'') as the last statement before return on every call in both directions (MBS01, the write rolled back; agent/system principals exempt). An archived board keeps its memberships, history and RLS; it only refuses new content and settings.';
473
+
474
+ -- =============================================================================
475
+ -- 5. Re-created bodies (each is the 1.81.0 definition plus only its #918 edit)
476
+ -- =============================================================================
477
+
478
+ -- =============================================================================
479
+ -- 6. create_board: repeating a slug never un-archives
480
+ -- =============================================================================
481
+ CREATE OR REPLACE FUNCTION agent_board.create_board(p_created_by_agent_id uuid, p_slug text, p_name text, p_description text DEFAULT NULL::text, p_metadata jsonb DEFAULT '{}'::jsonb, p_visibility text DEFAULT 'private'::text)
482
+ RETURNS TABLE(board_id uuid, slug text, name text, status text, visibility text, created_at timestamp with time zone, updated_at timestamp with time zone)
483
+ LANGUAGE plpgsql
484
+ SECURITY DEFINER
485
+ SET search_path TO 'agent_board', 'public'
486
+ AS $function$
487
+ #variable_conflict use_column
488
+ declare
489
+ v_seed_state text;
490
+ v_actor uuid;
491
+ v_existing agent_board.boards%rowtype;
492
+ v_board agent_board.boards%rowtype;
493
+ begin
494
+ if nullif(trim(p_slug), '') is null or nullif(trim(p_name), '') is null then
495
+ raise exception 'board slug and name are required' using errcode = '22023';
496
+ end if;
497
+ if coalesce(p_visibility, 'private') not in ('private', 'invite_only', 'open', 'directory_hidden') then
498
+ raise exception 'invalid board visibility' using errcode = '22023';
499
+ end if;
500
+
501
+ -- Effective actor: service_role -> supplied arg (create-on-behalf-of);
502
+ -- authenticated -> current_agent_id() and rejects arg <> current (42501).
503
+ v_actor := agent_board._resolved_actor_agent_id(p_created_by_agent_id, 'p_created_by_agent_id');
504
+
505
+ -- HOSTED (placement class): create_board seeds its creator's own owner seat directly. A
506
+ -- hosted delegate is never seated except by add_delegate_to_board.
507
+ perform agent_board._refuse_delegate_membership_target(v_actor, 'create_board');
508
+
509
+ if not exists (select 1 from agent_board.agents where id = v_actor) then
510
+ raise exception 'agent not found' using errcode = 'P0002';
511
+ end if;
512
+
513
+ select * into v_existing
514
+ from agent_board.boards b
515
+ where b.slug = trim(p_slug);
516
+
517
+ if found then
518
+ -- Slug-collision path is OWNER-ONLY, keyed on CURRENT authority: the actor must
519
+ -- hold an ACTIVE owner-role membership on the existing board — NOT merely be its
520
+ -- original `created_by_agent_id`. A demoted or departed original creator no longer
521
+ -- owns the board and must NOT be able to re-open/rename/flip-visibility it.
522
+ if not exists (
523
+ select 1 from agent_board.board_memberships m
524
+ where m.board_id = v_existing.id
525
+ and m.agent_id = v_actor
526
+ and m.role = 'owner'
527
+ and m.membership_state in ('joined', 'subscribed')
528
+ ) then
529
+ raise exception 'board slug already in use' using errcode = '42501';
530
+ end if;
531
+
532
+ update agent_board.boards as b
533
+ set name = trim(p_name),
534
+ description = nullif(trim(p_description), ''),
535
+ -- #918: status is NOT written here. The collision branch used to reopen an archived
536
+ -- board as a side effect of repeating its slug. This UPDATE of an archived board is
537
+ -- now refused (MBA01) by trg_archived_board_guard on boards, under this row's lock;
538
+ -- set_board_archived is the only API writer of boards.status.
539
+ visibility = coalesce(p_visibility, 'private'),
540
+ metadata = coalesce(b.metadata, '{}'::jsonb) || coalesce(p_metadata, '{}'::jsonb),
541
+ updated_at = now()
542
+ where b.id = v_existing.id
543
+ returning * into v_board;
544
+ -- No owner re-seed: the owner was seeded at this board's original creation, and
545
+ -- re-promoting on every create_board would resurrect a deliberately demoted owner.
546
+ else
547
+ insert into agent_board.boards as b(slug, name, description, created_by_agent_id, visibility, metadata)
548
+ values (
549
+ trim(p_slug),
550
+ trim(p_name),
551
+ nullif(trim(p_description), ''),
552
+ v_actor,
553
+ coalesce(p_visibility, 'private'),
554
+ coalesce(p_metadata, '{}'::jsonb)
555
+ )
556
+ returning * into v_board;
557
+
558
+ -- Seed the creator's owner membership, bound to the board's ACTUAL
559
+ -- created_by_agent_id (never the raw param). Idempotent against the active
560
+ -- partial-unique index so at most one active owner row exists.
561
+ insert into agent_board.board_memberships as bm(board_id, agent_id, membership_state, role, created_by_agent_id)
562
+ values (v_board.id, v_board.created_by_agent_id, 'joined', 'owner', v_board.created_by_agent_id)
563
+ on conflict (board_id, agent_id) where (membership_state in ('joined', 'subscribed'))
564
+ do update set role = 'owner', updated_at = now()
565
+ returning bm.membership_state into v_seed_state;
566
+ -- The creator seeds their OWN owner seat, so the session is the subject and this emits
567
+ -- target-authored. Under service_role it emits operator-designated instead -- correct
568
+ -- either way, because the helper reads the session rather than being told.
569
+ --
570
+ -- v_seed_state, NOT a literal 'joined'. The ON CONFLICT above lifts only the ROLE, so a
571
+ -- board whose creator already holds a `subscribed` row stays subscribed while a literal
572
+ -- would record `joined` -- a ledger contradicting the table. Same defect the redemption
573
+ -- path had; fixing one instance without sweeping the class is how it survived here.
574
+ perform agent_board._emit_membership_event(v_board.id, v_board.created_by_agent_id, v_seed_state, 'owner_seed');
575
+ end if;
576
+
577
+ -- #280. Revoked means revoked: a fleet-revoked agent creates nothing. #276 gated the three
578
+ -- authority chokepoints and both invite halves and left this function open on a stated
579
+ -- argument (a fresh board confers nothing on anyone else); the owner overturned that in favour
580
+ -- of the simpler rule, and this line is the whole of the change.
581
+ --
582
+ -- SITED HERE, at the convergence of both branches and AFTER every write, for the lock order.
583
+ -- Fresh branch: boards(insert) -> board_memberships(insert, FK KEY SHARE on agents) ->
584
+ -- agents(SHARE). Collision branch: boards(FOR UPDATE) -> agents(SHARE). Both are
585
+ -- boards-before-agents, the canonical order. HOISTED above the slug read it would become
586
+ -- agents(SHARE) -> boards(FOR UPDATE) on the collision branch, which is #269 F4's exact ABBA
587
+ -- against onboard_federated_fleet_agent's boards -> agents. One transaction, so this raise
588
+ -- rolls back the board, the owner seat and the owner_seed event alike -- position costs
589
+ -- nothing in correctness and everything in deadlock safety.
590
+ --
591
+ -- On the fresh branch the FK on the seat insert has ALREADY taken KEY SHARE on this row, so
592
+ -- the FOR SHARE is a free upgrade and is NOT what serializes that path (see the header). On
593
+ -- the collision branch it is the only agents lock there is, and it is the serialization point.
594
+ perform agent_board._assert_actor_not_fleet_revoked(v_actor, 'create_board');
595
+
596
+ return query
597
+ select v_board.id, v_board.slug, v_board.name, v_board.status, v_board.visibility, v_board.created_at, v_board.updated_at;
598
+ end;
599
+ $function$;
600
+
601
+ revoke all on function agent_board.create_board(uuid, text, text, text, jsonb, text)
602
+ from public, anon, authenticated, service_role, agent_board_delegate;
603
+ grant execute on function agent_board.create_board(uuid, text, text, text, jsonb, text) to authenticated, service_role;
604
+ comment on function agent_board.create_board(uuid, text, text, text, jsonb, text) is
605
+ 'Creates a board and seeds the resolved actor''s owner membership; on a slug COLLISION it instead renames/re-visibilities the existing board, but only for an actor holding an ACTIVE owner-role membership on it (else 42501 ''board slug already in use''), and it never re-seeds an owner. Actor is _resolved_actor_agent_id: service_role uses the supplied arg (create-on-behalf-of), authenticated uses current_agent_id() and fails closed on mismatch. #280: the resolved actor is then checked against the fleet revocation ledger by _assert_actor_not_fleet_revoked -- an agent carrying an agent-subject fleet_revocation_events row cannot create a board at all (42501, ''fleet_revoked:''), the same answer evaluate_fleet_sender_policy already gives it on the send path and #276 gave it on the five authority routes. This CLOSES the residual #276 named and left open. The gate covers BOTH branches by design, so a revoked owner also cannot rename or re-visibility an existing board. It is placed AFTER the writes so the lock order stays boards -> agents (fresh branch: boards -> board_memberships -> agents); hoisting it would give agents -> boards on the collision branch and invert against onboard_federated_fleet_agent, the ABBA #269 reproduced. The function is one transaction, so the raise rolls back the board, the owner seat and the owner_seed event. A principal with no fleet binding has no ledger row and is unaffected. Consiliency/message-board#918: the collision branch no longer sets status, so it never un-archives; on an ARCHIVED board its owner gets MBA01 ''board is archived'' (a non-owner still gets 42501 first). set_board_archived is the only API writer of boards.status.';
606
+
607
+ -- =============================================================================
608
+ -- 7. update_board_membership: removal of another member works on an archived board
609
+ -- =============================================================================
610
+ CREATE OR REPLACE FUNCTION agent_board.update_board_membership(p_board_id uuid, p_agent_id uuid, p_membership_state text, p_metadata jsonb DEFAULT '{}'::jsonb)
611
+ RETURNS TABLE(membership_id uuid, board_id uuid, agent_id uuid, membership_state text, left_at timestamp with time zone, updated_at timestamp with time zone)
612
+ LANGUAGE plpgsql
613
+ SECURITY DEFINER
614
+ SET search_path TO 'agent_board', 'public'
615
+ AS $function$
616
+ declare
617
+ v_membership agent_board.board_memberships%rowtype;
618
+ v_board agent_board.boards%rowtype;
619
+ v_actor uuid := agent_board.current_agent_id();
620
+ v_is_service boolean := agent_board._is_service_role();
621
+ v_existing_state text;
622
+ v_target_role text;
623
+ v_actor_role text;
624
+ -- HOSTED (D7): the caller is the target hosted delegate's principal asking for `left`.
625
+ v_principal_withdraw boolean;
626
+ begin
627
+ if v_actor is null and not v_is_service then
628
+ raise exception 'current agent principal not resolved' using errcode = '42501';
629
+ end if;
630
+
631
+ -- Board authority lock first, before the target row and the sink's FK locks.
632
+ perform agent_board._lock_board_authority_ceiling(p_board_id);
633
+
634
+ v_principal_withdraw := not v_is_service
635
+ and v_actor <> p_agent_id
636
+ and p_membership_state = 'left'
637
+ and v_actor = agent_board._delegate_principal_agent_id(p_agent_id);
638
+
639
+ if not v_is_service and v_actor <> p_agent_id and not v_principal_withdraw then
640
+ select bm.role
641
+ into v_actor_role
642
+ from agent_board.board_memberships bm
643
+ where bm.board_id = p_board_id
644
+ and bm.agent_id = v_actor
645
+ and bm.membership_state in ('joined', 'subscribed')
646
+ limit 1;
647
+ if v_actor_role is null or v_actor_role not in ('owner', 'admin') then
648
+ raise exception 'board membership change requires owner or admin role'
649
+ using errcode = '42501';
650
+ end if;
651
+ -- #918: authority BEFORE status, so a caller without it gets one answer for an active, an
652
+ -- archived and an unknown board. On an ARCHIVED board an owner or admin may still REMOVE another
653
+ -- member (moderation stays possible while the board is read-only); every other change to another
654
+ -- member keeps the not-found answer it had. set_board_archived takes the same board authority
655
+ -- lock, so this read cannot race an archive.
656
+ select * into v_board from agent_board.boards
657
+ where id = p_board_id
658
+ and (status = 'active' or (status = 'archived' and p_membership_state = 'removed'));
659
+ if v_board.id is null then
660
+ raise exception 'board not found' using errcode = 'P0002';
661
+ end if;
662
+ end if;
663
+
664
+ -- HOSTED: LOCKED, so every transition rule below is decided on the state the sink will
665
+ -- overwrite. Unlocked, an admin's uncommitted `removed` committed after this read, and the D7
666
+ -- withdrawal (and an ordinary self-leave, the same branch shape) then wrote `left` over it in
667
+ -- the sink, erasing the eviction R-LINK-7 reads (hosted_delegate_withdraw_evict_race). The
668
+ -- sink's own first lock is this same row in the same order, so the lock set is unchanged;
669
+ -- it is only taken earlier, before reads that lock nothing.
670
+ select bm.membership_state, bm.role
671
+ into v_existing_state, v_target_role
672
+ from agent_board.board_memberships bm
673
+ where bm.board_id = p_board_id
674
+ and bm.agent_id = p_agent_id
675
+ order by
676
+ case when bm.membership_state in ('joined', 'subscribed') then 0 else 1 end,
677
+ bm.created_at desc,
678
+ bm.id desc
679
+ limit 1
680
+ for update;
681
+ if v_existing_state is null then
682
+ raise exception 'board membership not found' using errcode = 'P0002';
683
+ end if;
684
+
685
+ if v_principal_withdraw then
686
+ -- HOSTED (D7): the owner withdraws its own delegate whatever its board role, but ONLY from
687
+ -- the states a self-leave may leave. Never from `removed`: turning an eviction into `left`
688
+ -- would erase the standing R-LINK-7 reads and let the owner re-add the evicted delegate.
689
+ if v_existing_state not in ('joined', 'subscribed', 'invited', 'requested') then
690
+ raise exception 'a principal may withdraw its delegate only from an active or pending membership'
691
+ using errcode = '42501';
692
+ end if;
693
+ elsif not v_is_service then
694
+ if v_actor = p_agent_id then
695
+ if not (
696
+ (p_membership_state = 'left'
697
+ and v_existing_state in ('joined', 'subscribed', 'invited', 'requested'))
698
+ or (p_membership_state in ('joined', 'subscribed')
699
+ and v_existing_state in ('joined', 'subscribed'))
700
+ or (p_membership_state = v_existing_state
701
+ and p_membership_state in ('left', 'removed'))
702
+ ) then
703
+ raise exception 'self membership change not permitted; use the join/approval path'
704
+ using errcode = '42501';
705
+ end if;
706
+ else
707
+ if agent_board._role_rank(v_actor_role)
708
+ <= agent_board._role_rank(
709
+ case
710
+ when p_membership_state in ('joined', 'subscribed')
711
+ and coalesce(v_existing_state, '') not in ('joined', 'subscribed')
712
+ then 'member'
713
+ else coalesce(v_target_role, '')
714
+ end) then
715
+ raise exception 'board membership change requires a higher board role than the target'
716
+ using errcode = '42501';
717
+ end if;
718
+
719
+ -- #906 REMOVALSTATE: another actor may not remove a PENDING target. Without this, a
720
+ -- client acting on a stale roster evicted a target that had meanwhile left and been
721
+ -- re-invited, or is `requested`, overriding that newer decision. Pending rows are
722
+ -- cancelled/declined through resolve_board_request (it lands `left`, REJECTSEM #89).
723
+ -- NOT refused: `left` (the documented bar on a departed agent, and R-LINK-7's
724
+ -- order-independent eviction, isolation hosted_delegate_withdraw_evict_race P2) and
725
+ -- `removed` (the LEAVEIDEM no-op below). Spelled as the complement of the permitted prior
726
+ -- states, so a state added later is refused until someone decides otherwise. After the
727
+ -- rank check (a caller that does not outrank the target learns nothing about its state)
728
+ -- and before the sink, so the #669 step-up gate below remains the last statement.
729
+ if p_membership_state = 'removed'
730
+ and v_existing_state not in ('joined', 'subscribed', 'left', 'removed') then
731
+ raise exception 'board membership removal requires an active target membership'
732
+ using errcode = '42501',
733
+ detail = format('current membership state: %s', v_existing_state),
734
+ hint = 'cancel a pending invitation or request with resolve_board_request';
735
+ end if;
736
+
737
+ if p_membership_state in ('joined', 'subscribed')
738
+ and coalesce(v_existing_state, '') not in ('joined', 'subscribed')
739
+ and not agent_board._membership_consent_present(p_board_id, p_agent_id) then
740
+ raise exception 'admitting % requires an act by that agent', p_agent_id
741
+ using errcode = '42501';
742
+ end if;
743
+
744
+ -- INVITEPOLICY (#90): seating an inbound-disclosure membership ('invited'/'requested')
745
+ -- for a target that has blocked THIS actor is refused, mirroring invite_board_member.
746
+ -- Without this, an owner/admin re-seats the exact row the block refuses. Active-admission
747
+ -- states are already consent-gated above; service_role/self never reach this branch.
748
+ if p_membership_state in ('invited', 'requested')
749
+ and not agent_board._invite_permitted(p_board_id, p_agent_id, v_actor) then
750
+ raise exception 'target has blocked invitations from this inviter on this board'
751
+ using errcode = '42501';
752
+ end if;
753
+ end if;
754
+ end if;
755
+
756
+ if not v_is_service
757
+ and p_membership_state = v_existing_state
758
+ and p_membership_state in ('left', 'removed') then
759
+ return query
760
+ select bm.id, bm.board_id, bm.agent_id, bm.membership_state, bm.left_at, bm.updated_at
761
+ from agent_board.board_memberships bm
762
+ where bm.board_id = p_board_id
763
+ and bm.agent_id = p_agent_id
764
+ order by
765
+ case when bm.membership_state in ('joined', 'subscribed') then 0 else 1 end,
766
+ bm.created_at desc,
767
+ bm.id desc
768
+ limit 1;
769
+ return;
770
+ end if;
771
+
772
+ select * into v_membership
773
+ from agent_board._upsert_board_membership_state(
774
+ p_board_id,
775
+ p_agent_id,
776
+ p_membership_state,
777
+ null,
778
+ p_metadata
779
+ );
780
+
781
+ -- #669 STEPUP PR-B (D1, plan §6.2): the step-up check is the LAST statement before the
782
+ -- function returns, after every refusal, the write and the fleet-revocation assert, so every
783
+ -- authorization refusal (22023, P0002, 42501 incl. fleet_revoked: and last-owner) comes first
784
+ -- by construction and MBS01 means "otherwise allowed; confirm it is you". The raise rolls the
785
+ -- whole transaction back. The helper takes no actor: it judges the SESSION (D2).
786
+ -- Q1 as amended by E-5: another actor takes an owner/admin target out of active standing.
787
+ -- Keyed on the target's role and prior state read FOR UPDATE above, and on the state the SINK
788
+ -- RESULTED in, never on the requested state: the #317 sink suppresses an offer (`invited`/
789
+ -- `requested`) over an active row, so a re-invite of an active admin keeps it joined and is
790
+ -- ungated (A-11d), while `removed` or `left` set by another member is gated (R-17/R-17b).
791
+ -- IS DISTINCT FROM: a NULL actor (the operator key) reaches the helper, which exempts it.
792
+ -- coalesce: a NULL resulting state must gate, never pass by three-valued logic.
793
+ if v_actor is distinct from p_agent_id
794
+ and v_target_role in ('owner', 'admin')
795
+ and v_existing_state in ('joined', 'subscribed')
796
+ and coalesce(v_membership.membership_state, '') not in ('joined', 'subscribed') then
797
+ perform agent_board._require_human_step_up('update_board_membership');
798
+ end if;
799
+
800
+ return query
801
+ select v_membership.id, v_membership.board_id, v_membership.agent_id, v_membership.membership_state, v_membership.left_at, v_membership.updated_at;
802
+ end;
803
+ $function$;
804
+
805
+ revoke all on function agent_board.update_board_membership(uuid, uuid, text, jsonb)
806
+ from public, anon, authenticated, service_role, agent_board_delegate;
807
+ grant execute on function agent_board.update_board_membership(uuid, uuid, text, jsonb) to authenticated, service_role;
808
+ comment on function agent_board.update_board_membership(uuid, uuid, text, jsonb) is
809
+ 'Authorized membership state transitions with existing self, principal-withdrawal, rank, consent and idempotency rules. Consiliency/message-board#675: board advisory lock before target membership/FK locks; the table refuses any transition removing the last active owner. Consiliency/message-board#906: another (non-service) actor may not set `removed` over a PENDING target: from invited/requested it raises 42501 ''board membership removal requires an active target membership'' (DETAIL the current state, HINT resolve_board_request), after the owner/admin and rank checks and before the write. Cancel or decline a pending row with resolve_board_request (lands left). left -> removed by an outranking owner/admin is unchanged (the bar on a departed agent; R-LINK-7 order-independent eviction), and removed -> removed stays the idempotent no-op. #669 STEPUP PR-B (Q1, E-5): after the membership sink and before the final return, when the actor is not the target, the target''s role (read FOR UPDATE before the write) is owner or admin, its prior state was joined/subscribed and the sink''s RESULTING state is not joined/subscribed, it calls _require_human_step_up(''update_board_membership''), so a human removing an owner/admin, or setting one to left, needs a fresh step-up proof (else MBS01 step_up_required, the transition rolled back). Ordinary members, self transitions, idempotent no-ops and a re-invite the sink suppresses are ungated. Consiliency/message-board#918: on an ARCHIVED board an owner or admin may still set another member ''removed'' (same owner/admin, rank, #906 pending-target and step-up rules); every other change to another member is still P0002 ''board not found''. left -> removed is REFUSED there (MBA01): it edits a row that has already departed; the sentence above about it describes an active board. The owner/admin check now precedes the board-status check, so a caller without that standing gets the same 42501 for an active, an archived and an unknown board. A self change other than a departure is refused MBA01 by trg_archived_board_guard.';
810
+
811
+ -- =============================================================================
812
+ -- 8. bootstrap_board_owner_memberships: skips archived boards
813
+ -- =============================================================================
814
+ CREATE OR REPLACE FUNCTION agent_board.bootstrap_board_owner_memberships()
815
+ RETURNS TABLE(board_id uuid, owner_agent_id uuid, membership_id uuid)
816
+ LANGUAGE plpgsql
817
+ SECURITY DEFINER
818
+ SET search_path TO 'agent_board', 'public'
819
+ AS $function$
820
+ #variable_conflict use_column
821
+ declare
822
+ v_seed_state text;
823
+ v_row record;
824
+ v_membership_id uuid;
825
+ begin
826
+ -- service_role-only: current_agent_id() is null for service_role, non-null for any
827
+ -- authenticated principal (guarded here in addition to the EXECUTE revoke below).
828
+ if not agent_board._is_service_role() then
829
+ raise exception 'bootstrap_board_owner_memberships is service_role-only' using errcode = '42501';
830
+ end if;
831
+
832
+ -- R-LINK-7 guard shape (structural proof requires no-active AND no-removed
833
+ -- contiguously): re-seed only when the creator has no active membership AND is
834
+ -- not currently removed. NEVER suppress on 'left' alone — that is the
835
+ -- sole-owner-lockout recovery trigger (agent_board_rolereset.test.sql assertion
836
+ -- 23). requested/invited-only creators still re-seed; a removed+left pair is
837
+ -- suppressed.
838
+ for v_row in
839
+ select b.id as board_id, b.created_by_agent_id as owner_agent_id
840
+ from agent_board.boards b
841
+ where b.status = 'active' -- #918: an archived board takes no new seat; un-archive it first
842
+ and not exists (
843
+ select 1
844
+ from agent_board.board_memberships bm
845
+ where bm.board_id = b.id
846
+ and bm.agent_id = b.created_by_agent_id
847
+ and bm.membership_state in ('joined', 'subscribed')
848
+ )
849
+ and not exists (
850
+ select 1
851
+ from agent_board.board_memberships bm
852
+ where bm.board_id = b.id
853
+ and bm.agent_id = b.created_by_agent_id
854
+ and bm.membership_state = 'removed'
855
+ )
856
+ loop
857
+ -- HOSTED (placement class): bootstrap seats a board creator directly; never a delegate.
858
+ perform agent_board._refuse_delegate_membership_target(v_row.owner_agent_id, 'bootstrap_board_owner_memberships');
859
+ insert into agent_board.board_memberships as bm(board_id, agent_id, membership_state, role, created_by_agent_id)
860
+ values (v_row.board_id, v_row.owner_agent_id, 'joined', 'owner', v_row.owner_agent_id)
861
+ on conflict (board_id, agent_id) where (membership_state in ('joined', 'subscribed'))
862
+ do update set role = 'owner', updated_at = now()
863
+ returning bm.id, bm.membership_state into v_membership_id, v_seed_state;
864
+
865
+ -- Operator repair path: always operator-designated, never the owner's own act.
866
+ -- v_seed_state, NOT a literal: the ON CONFLICT lifts only the ROLE, so a concurrently
867
+ -- created `subscribed` membership stays subscribed while a literal would record `joined`.
868
+ perform agent_board._emit_membership_event(v_row.board_id, v_row.owner_agent_id, v_seed_state, 'operator_repair');
869
+
870
+ board_id := v_row.board_id;
871
+ owner_agent_id := v_row.owner_agent_id;
872
+ membership_id := v_membership_id;
873
+ return next;
874
+ end loop;
875
+ end;
876
+ $function$;
877
+
878
+ revoke all on function agent_board.bootstrap_board_owner_memberships()
879
+ from public, anon, authenticated, service_role, agent_board_delegate;
880
+ grant execute on function agent_board.bootstrap_board_owner_memberships() to service_role;
881
+ comment on function agent_board.bootstrap_board_owner_memberships() is
882
+ 'service_role-only repair sweep: seeds a joined owner membership for boards whose creator has no active membership AND is not currently removed (R-LINK-7). Voluntary left remains the sole-owner-lockout recovery trigger. Takes no caller/role param. Consiliency/message-board#918: only ACTIVE boards are repaired. Seating an owner on an archived board would be refused MBA01 by trg_archived_board_guard and abort the whole sweep; the operator un-archives such a board first.';
883
+
884
+ -- =============================================================================
885
+ -- 9. grant_board_role: refuses an archived board
886
+ -- =============================================================================
887
+ CREATE OR REPLACE FUNCTION agent_board.grant_board_role(p_board_id uuid, p_agent_id uuid, p_grantee_role text, p_grantor_agent_id uuid DEFAULT NULL::uuid)
888
+ RETURNS TABLE(board_id uuid, agent_id uuid, role text, updated_at timestamp with time zone)
889
+ LANGUAGE plpgsql
890
+ SECURITY DEFINER
891
+ SET search_path TO 'agent_board', 'public'
892
+ AS $function$
893
+ declare
894
+ v_grantor uuid;
895
+ v_updated agent_board.board_memberships%rowtype;
896
+ -- #674: the target's and the grantor's CURRENT active roles, read in one statement (step 6).
897
+ v_target_role text;
898
+ v_grantor_role text;
899
+ begin
900
+ if p_grantee_role not in ('owner', 'admin', 'member', 'observer') then
901
+ raise exception 'invalid grantee role' using errcode = '22023';
902
+ end if;
903
+
904
+ -- #276, FORCED BY AN EXISTING CLASS ASSERTION, not chosen. Adding the ledger gate makes this
905
+ -- function row-lock `agents` (transitively, through _assert_actor_not_fleet_revoked) as well
906
+ -- as board_memberships, which puts it in the class agent_board_signer_lifecycle.test.sql
907
+ -- section 9 pins from the call-graph closure: every function locking BOTH relations must take
908
+ -- the board advisory lock that serialises them against onboard_federated_fleet_agent. That
909
+ -- assertion FAILED and named this function when the gate was added without this line.
910
+ --
911
+ -- The tempting reply is that this function's order is agents -> board_memberships, the SAME
912
+ -- direction as onboarding, so it cannot close the F4 cycle. That is true today and is exactly
913
+ -- the ordering argument #269 refused: mutual exclusion survives a lock being added downstream,
914
+ -- a re-derived ordering does not. So the lock is taken rather than the assertion relaxed.
915
+ --
916
+ -- It also closes a gap 20260901000110 left open and explicitly declined to determine: this
917
+ -- function reads the ceiling for authorization (via _grant_within_ceiling below) and was one
918
+ -- of the three readers that did NOT take the lock serialising the ceiling row's ABSENCE, so a
919
+ -- concurrent first-ceiling insert could be missed and the read pass as default-owner. It is
920
+ -- now serialised, and agent_board_atomic_fleet_onboarding.test.sql's ceiling-reader registry
921
+ -- records it as such.
922
+ --
923
+ -- FIRST, before any row lock, so both routes are advisory -> agents -> board_memberships.
924
+ -- Re-taking it inside signed_grant_board_role (which already holds it) is a no-op: advisory
925
+ -- transaction locks are re-entrant within a session.
926
+ -- HOSTED (role-writer class): a hosted delegate is a member, never higher.
927
+ perform agent_board._refuse_delegate_membership_target(p_agent_id, 'grant_board_role');
928
+
929
+ perform agent_board._lock_board_authority_ceiling(p_board_id);
930
+
931
+ -- Grantor is the RESOLVED actor. service_role -> supplied arg; authenticated ->
932
+ -- current_agent_id() and raises 42501 if null (suspended/unmapped) or if the
933
+ -- supplied arg <> current_agent_id(). This closes the single-principal escalation.
934
+ v_grantor := agent_board._resolved_actor_agent_id(p_grantor_agent_id, 'p_grantor_agent_id');
935
+
936
+ -- #276. Fleet revocation removes board authority, not only send. Sited HERE — inside the
937
+ -- chokepoint, not in the signed wrapper — because signed_grant_board_role is the only other
938
+ -- referrer of this function in the whole database, so the signed route inherits this check
939
+ -- by construction and the unsigned `authenticated` route (the wider door) is closed by the
940
+ -- same line. Before the membership pre-check so the lock order is agents -> board_memberships,
941
+ -- matching onboard_federated_fleet_agent; below the write it would be the inversion #269
942
+ -- reproduced as `deadlock detected`, and this route has no advisory lock to be rescued by.
943
+ perform agent_board._assert_actor_not_fleet_revoked(v_grantor, 'grant_board_role');
944
+
945
+ -- #674 step 6. ONE statement replaces the bare EXISTS pre-check: the target's active row,
946
+ -- row-locked in NO KEY UPDATE mode, on t only (the mode the UPDATE below takes, only earlier),
947
+ -- LEFT JOINed to the grantor's active row, which is NOT locked. Its snapshot is taken after
948
+ -- the board advisory-lock wait above. After a row-lock wait, READ COMMITTED re-fetches only
949
+ -- the locked row t; the joined grantor row g keeps the statement snapshot's version. That is
950
+ -- benign (plan D5): every grant on this board and link_session_alias are excluded by the
951
+ -- advisory lock, and the one unserialized writer that can change an active grantor's role
952
+ -- (invite-link redeem's rank-max) only RAISES it, so a stale grantor rank is conservative.
953
+ -- A later change (#675's hook) must not rely on g being fresh after this statement.
954
+ -- Both reads are single-row by the partial unique index on active memberships.
955
+ select t.role, g.role
956
+ into v_target_role, v_grantor_role
957
+ from agent_board.board_memberships t
958
+ left join agent_board.board_memberships g
959
+ on g.board_id = t.board_id
960
+ and g.agent_id = v_grantor
961
+ and g.membership_state in ('joined', 'subscribed')
962
+ where t.board_id = p_board_id
963
+ and t.agent_id = p_agent_id
964
+ and t.membership_state in ('joined', 'subscribed')
965
+ for no key update of t;
966
+ if not found then
967
+ raise exception 'grantee has no membership on this board' using errcode = 'P0002';
968
+ end if;
969
+
970
+ -- Ceiling consumption: grantee-bounded against min(grantor role, board ceiling).
971
+ if not agent_board._grant_within_ceiling(v_grantor, p_board_id, p_grantee_role) then
972
+ raise exception 'grant exceeds grantor role or board authority ceiling' using errcode = '42501';
973
+ end if;
974
+
975
+ -- #674 step 8. Two checks for a grantor that is NOT the target (self = the same agent id,
976
+ -- not the same human). C-A (owner decision 3): only an owner or admin may change anyone
977
+ -- else's role. C-B (#674): the grantor must STRICTLY outrank the target's current role, so
978
+ -- equal rank is refused for every rank (owner -> owner, admin -> admin). Both read the roles
979
+ -- step 6 observed. A null role ranks 0, so a missing grantor row fails closed. C-A runs
980
+ -- before C-B; the ceiling above runs before both. Self-grants are exempt from both, and the
981
+ -- ceiling still bounds a self-grant to keep-or-lower.
982
+ if v_grantor is distinct from p_agent_id then
983
+ if agent_board._role_rank(v_grantor_role) < agent_board._role_rank('admin') then
984
+ raise exception 'grant on another member requires owner or admin role' using errcode = '42501';
985
+ end if;
986
+ if agent_board._role_rank(v_grantor_role) <= agent_board._role_rank(v_target_role) then
987
+ raise exception 'grant requires a higher board role than the target' using errcode = '42501';
988
+ end if;
989
+ end if;
990
+
991
+ -- #918: no role change on an archived board, in either direction, on any route. After every
992
+ -- authority check of THIS function, so a caller without standing never sees MBA01 here. The signed
993
+ -- route (service_role only) verifies its signer AFTER this returns, so there MBA01 can come before
994
+ -- that refusal;
995
+ -- explicit rather than left to
996
+ -- trg_archived_board_guard, whose link_session_alias exemption a service_role grant would otherwise
997
+ -- match.
998
+ perform agent_board._assert_boards_not_archived(array[p_board_id]);
999
+
1000
+ update agent_board.board_memberships bm
1001
+ set role = p_grantee_role,
1002
+ updated_at = now()
1003
+ where bm.board_id = p_board_id
1004
+ and bm.agent_id = p_agent_id
1005
+ and bm.membership_state in ('joined', 'subscribed')
1006
+ returning * into v_updated;
1007
+
1008
+ -- CR finding: the state predicate above closes the unauthorized WRITE, but on its own it
1009
+ -- CREATES a false-success path. If an eviction commits between the pre-check and this
1010
+ -- UPDATE (the TOCTOU window the mirrored predicate exists for), the UPDATE matches zero
1011
+ -- rows, v_updated stays NULL, and the RETURN QUERY below would emit ONE ALL-NULL ROW with
1012
+ -- no error -- a caller that checks "did I get a row back?" reads that as a completed grant.
1013
+ -- Fail closed with the same P0002 the pre-check raises, so the serial and racing cases are
1014
+ -- indistinguishable to the caller.
1015
+ if not found then
1016
+ raise exception 'grantee has no membership on this board' using errcode = 'P0002';
1017
+ end if;
1018
+
1019
+ -- #669 STEPUP PR-B (D1, plan §6.2): the step-up check is the LAST statement before the
1020
+ -- function returns, after every refusal, the write and the fleet-revocation assert, so every
1021
+ -- authorization refusal (22023, P0002, 42501 incl. fleet_revoked: and last-owner) comes first
1022
+ -- by construction and MBS01 means "otherwise allowed; confirm it is you". The raise rolls the
1023
+ -- whole transaction back. The helper takes no actor: it judges the SESSION (D2).
1024
+ perform agent_board._require_human_step_up('grant_board_role');
1025
+
1026
+ return query
1027
+ select v_updated.board_id, v_updated.agent_id, v_updated.role, v_updated.updated_at;
1028
+ end;
1029
+ $function$;
1030
+
1031
+ revoke all on function agent_board.grant_board_role(uuid, uuid, text, uuid)
1032
+ from public, anon, authenticated, service_role, agent_board_delegate;
1033
+ grant execute on function agent_board.grant_board_role(uuid, uuid, text, uuid) to authenticated, service_role;
1034
+ comment on function agent_board.grant_board_role(uuid, uuid, text, uuid) is
1035
+ 'Live board-role grant chokepoint. Grantor is the resolved actor (_resolved_actor_agent_id: service_role uses the supplied arg, authenticated uses current_agent_id() and fails closed on null/mismatch). #276: the resolved grantor is then checked against the fleet revocation ledger by _assert_actor_not_fleet_revoked -- an agent carrying an agent-subject fleet_revocation_events row cannot complete a grant (42501, ''fleet_revoked:''), which is the same answer evaluate_fleet_sender_policy already gives that principal on the send path. The check sits in THIS function rather than in signed_grant_board_role because signed_grant_board_role is the only other referrer of it in the database, so the signed route inherits the gate and the wider unsigned authenticated route is closed by the same line; it is placed before the membership pre-check so the lock order is agents(FOR SHARE) -> board_memberships, matching onboard_federated_fleet_agent. A principal with no fleet binding has no such row and is unaffected. Then requires an ACTIVE grantee membership (joined|subscribed; P0002 otherwise) -- predicate on both the pre-check and the UPDATE (TOCTOU). Then enforces _grant_within_ceiling(grantor, board, grantee_role) before setting board_memberships.role. ROLERESET (#79): non-active rows cannot be re-armed with an elevated role. #674: the membership pre-check is ONE statement that locks the target''s active row FOR NO KEY UPDATE OF t (the mode the UPDATE takes, only earlier; lock order unchanged: advisory -> agents(SHARE) -> board_memberships) and LEFT JOINs the grantor''s active row, unlocked. After the unchanged ceiling check, a grantor that is not the target (self = the same agent id, not the same human) must be an owner or admin (C-A, 42501 ''grant on another member requires owner or admin role'') and must strictly outrank the target''s CURRENT role (C-B, 42501 ''grant requires a higher board role than the target''), so equal rank is refused for every rank. A self-grant is exempt from both and stays bounded to keep-or-lower by the ceiling. For service_role the checks run relative to the grantor the caller SUPPLIES -- the existing operator-trust boundary, which #674 does not change (passing p_grantor_agent_id = p_agent_id takes the self-exemption). #669 STEPUP PR-B: after the UPDATE and its not-found check, and before return, it calls _require_human_step_up(''grant_board_role'') on every call (D1: the last statement, so every existing refusal comes first; the raise rolls the grant back). A human principal, or a service_role relay token whose sub names a human, needs a fresh step-up proof of its class or gets MBS01 step_up_required; the operator key (no principal, no sub) and agent/system principals are exempt (D3). The helper judges the session, never the supplied grantor or the target (D2). Consiliency/message-board#918: after the ceiling, C-A and C-B checks and before the write, an archived board is refused MBA01 (_assert_boards_not_archived), on the unsigned and the signed route.';
1036
+
1037
+ -- =============================================================================
1038
+ -- 10. _redeem_unbounded_invite_for_agent: an invite for a non-active board is not usable
1039
+ -- =============================================================================
1040
+ CREATE OR REPLACE FUNCTION agent_board._redeem_unbounded_invite_for_agent(p_code text, p_agent_id uuid)
1041
+ RETURNS TABLE(board_id uuid, agent_id uuid, role text, membership_state text, updated_at timestamp with time zone)
1042
+ LANGUAGE plpgsql
1043
+ SECURITY DEFINER
1044
+ SET search_path TO 'agent_board', 'public'
1045
+ AS $function$
1046
+ -- OUT params board_id/agent_id/role/membership_state/updated_at share names with the
1047
+ -- membership columns referenced in the on-conflict target + update set below; prefer
1048
+ -- the column in any collision (mirrors ROOMOWN create_board).
1049
+ #variable_conflict use_column
1050
+ declare
1051
+ v_inv agent_board.board_invite_tokens%rowtype;
1052
+ v_led agent_board.board_invite_redemptions%rowtype;
1053
+ v_m agent_board.board_memberships%rowtype;
1054
+ begin
1055
+ -- HOSTED (placement class): a hosted delegate redeems no invite; this helper seats directly.
1056
+ perform agent_board._refuse_delegate_membership_target(p_agent_id, 'invite redemption');
1057
+ -- Lock the token row FIRST (concurrency invariant: the exhaustion check and the
1058
+ -- same-txn uses_count increment happen under this lock, and concurrent redeemers
1059
+ -- of the same token serialize here).
1060
+ select * into v_inv
1061
+ from agent_board.board_invite_tokens t
1062
+ where t.code = p_code
1063
+ for update;
1064
+ if not found then
1065
+ raise exception 'invite is not usable' using errcode = '42501';
1066
+ end if;
1067
+
1068
+ -- M1 idempotency ordering: an existing (invite, agent) ledger row means this is a
1069
+ -- replay -> return the existing membership and SKIP every exhaustion/ceiling check
1070
+ -- (a maxed link re-redeemed by the same agent is a no-op, NOT 42501).
1071
+ select * into v_led
1072
+ from agent_board.board_invite_redemptions r
1073
+ where r.invite_id = v_inv.id
1074
+ and r.agent_id = p_agent_id;
1075
+ if found then
1076
+ select * into v_m
1077
+ from agent_board.board_memberships bm
1078
+ where bm.id = v_led.membership_id;
1079
+ return query
1080
+ select v_m.board_id, v_m.agent_id, v_m.role, v_m.membership_state, v_m.updated_at;
1081
+ return;
1082
+ end if;
1083
+
1084
+ -- Genuinely new redemption: uniform 42501 for revoked / expired / exhausted
1085
+ -- (no P0002-vs-42501 existence oracle).
1086
+ if v_inv.revoked_at is not null then
1087
+ raise exception 'invite is not usable' using errcode = '42501';
1088
+ end if;
1089
+ if v_inv.expires_at <= now() then
1090
+ raise exception 'invite is not usable' using errcode = '42501';
1091
+ end if;
1092
+ if v_inv.max_uses is not null and v_inv.uses_count >= v_inv.max_uses then
1093
+ raise exception 'invite is not usable' using errcode = '42501';
1094
+ end if;
1095
+
1096
+ -- R-LINK-2 suspension containment: the creator must still be an ACTIVE agent
1097
+ -- (revoke_agent suspends but does not drop memberships, so an outstanding link
1098
+ -- from a compromised-then-suspended owner must stop minting).
1099
+ if not exists (
1100
+ select 1 from agent_board.agents a
1101
+ where a.id = v_inv.created_by_agent_id and a.status = 'active'
1102
+ ) then
1103
+ -- Uniform message (see other 42501s) so a code-bearer cannot distinguish
1104
+ -- "creator suspended" from a dead/expired/exhausted link (no lifecycle oracle).
1105
+ raise exception 'invite is not usable' using errcode = '42501';
1106
+ end if;
1107
+
1108
+ -- #276 fleet containment, the sibling of R-LINK-2 one column over. Fleet revocation
1109
+ -- deliberately leaves agents.status = 'active', so the check above passes for a
1110
+ -- ledger-revoked creator and an outstanding admin link kept conferring admin -- the same
1111
+ -- principal the send path already refuses. Keyed on the CREATOR because the creator is who
1112
+ -- confers here; the redeemer is receiving, and its own standing is handled by
1113
+ -- current_agent_id() and by the R-LINK-7 clause below.
1114
+ --
1115
+ -- UNLOCKED (_actor_fleet_revoked, not the share-locking assert) and with the SAME uniform
1116
+ -- message as every other arm. Both choices are load-bearing, not stylistic: see the header.
1117
+ if agent_board._actor_fleet_revoked(v_inv.created_by_agent_id) then
1118
+ raise exception 'invite is not usable' using errcode = '42501';
1119
+ end if;
1120
+
1121
+ -- Re-bind: the creator's CURRENT authority must still cover the preset role
1122
+ -- (stale admin-link auto-degrades if the creator was demoted).
1123
+ if not agent_board._grant_within_ceiling(v_inv.created_by_agent_id, v_inv.board_id, v_inv.preset_role) then
1124
+ raise exception 'invite is not usable' using errcode = '42501';
1125
+ end if;
1126
+
1127
+ -- R-LINK-7 kicked-agent re-entry: refuse when the agent's CURRENT standing on the
1128
+ -- board is 'removed' — i.e. a 'removed' row exists AND there is no active
1129
+ -- (joined/subscribed) membership. The active partial-unique index does NOT cover
1130
+ -- 'removed' rows, so a fresh 'joined' insert would otherwise bypass revocation +
1131
+ -- join-approval. Scoping to "removed and not currently active" avoids a false
1132
+ -- negative for an agent who was removed and then legitimately re-added (an active
1133
+ -- row present ⇒ the rank-max upsert handles them correctly). Voluntary 'left' is
1134
+ -- intentionally NOT blocked (self-departure).
1135
+ if exists (
1136
+ select 1 from agent_board.board_memberships bm
1137
+ where bm.board_id = v_inv.board_id
1138
+ and bm.agent_id = p_agent_id
1139
+ and bm.membership_state = 'removed'
1140
+ ) and not exists (
1141
+ select 1 from agent_board.board_memberships bm
1142
+ where bm.board_id = v_inv.board_id
1143
+ and bm.agent_id = p_agent_id
1144
+ and bm.membership_state in ('joined', 'subscribed')
1145
+ ) then
1146
+ raise exception 'invite is not usable' using errcode = '42501';
1147
+ end if;
1148
+
1149
+ -- #918: the board must be active, decided under the KEY SHARE lock the inserts below take anyway
1150
+ -- (set_board_archived's FOR UPDATE excludes it), so a racing archive gives the same answer. Same
1151
+ -- uniform message: holding a code must not reveal that the board is archived.
1152
+ perform 1 from agent_board.boards b where b.id = v_inv.board_id and b.status = 'active' for key share;
1153
+ if not found then
1154
+ raise exception 'invite is not usable' using errcode = '42501';
1155
+ end if;
1156
+
1157
+ -- Record the ledger row (idempotent under concurrent same-agent redemption).
1158
+ insert into agent_board.board_invite_redemptions as r(invite_id, agent_id)
1159
+ values (v_inv.id, p_agent_id)
1160
+ on conflict (invite_id, agent_id) do nothing;
1161
+
1162
+ -- B1 atomic rank-max membership upsert: never downgrade a higher existing role,
1163
+ -- race-safe across concurrent tokens. On conflict targets the active partial-unique
1164
+ -- index; the CASE lifts ONLY when the preset outranks the current role.
1165
+ insert into agent_board.board_memberships (
1166
+ board_id, agent_id, membership_state, role, created_by_agent_id
1167
+ )
1168
+ values (
1169
+ v_inv.board_id, p_agent_id, v_inv.preset_membership_state, v_inv.preset_role,
1170
+ v_inv.created_by_agent_id
1171
+ )
1172
+ on conflict (board_id, agent_id) where (membership_state in ('joined', 'subscribed'))
1173
+ do update set
1174
+ role = case
1175
+ when agent_board._role_rank(excluded.role) > agent_board._role_rank(agent_board.board_memberships.role)
1176
+ then excluded.role
1177
+ else agent_board.board_memberships.role
1178
+ end,
1179
+ updated_at = now()
1180
+ returning * into v_m;
1181
+
1182
+ -- The redeemer places THEMSELVES -- the public wrapper passes current_agent_id() and takes no
1183
+ -- target parameter -- so this emits target-authored: redeeming a link IS the consenting act.
1184
+ --
1185
+ -- v_m.membership_state, NOT v_inv.preset_membership_state. The ON CONFLICT above lifts only
1186
+ -- the ROLE and leaves an existing membership_state untouched, so an already-`subscribed`
1187
+ -- member redeeming a `joined` link stays subscribed. Emitting the token's preset would
1188
+ -- record a resulting state the row does not have -- a ledger that contradicts the table it
1189
+ -- describes. Recording the redemption as a fresh consent act is right; recording the wrong
1190
+ -- outcome is not.
1191
+ perform agent_board._emit_membership_event(
1192
+ v_inv.board_id, p_agent_id, v_m.membership_state, 'consent_link_redeem');
1193
+
1194
+ -- Consume one use and bind the ledger row to the resulting membership.
1195
+ update agent_board.board_invite_tokens t
1196
+ set uses_count = t.uses_count + 1
1197
+ where t.id = v_inv.id;
1198
+
1199
+ update agent_board.board_invite_redemptions r
1200
+ set membership_id = v_m.id
1201
+ where r.invite_id = v_inv.id
1202
+ and r.agent_id = p_agent_id;
1203
+
1204
+ return query
1205
+ select v_m.board_id, v_m.agent_id, v_m.role, v_m.membership_state, v_m.updated_at;
1206
+ end;
1207
+ $function$;
1208
+
1209
+ revoke all on function agent_board._redeem_unbounded_invite_for_agent(text, uuid)
1210
+ from public, anon, authenticated, service_role, agent_board_delegate;
1211
+ grant execute on function agent_board._redeem_unbounded_invite_for_agent(text, uuid) to service_role;
1212
+ comment on function agent_board._redeem_unbounded_invite_for_agent(text, uuid) is
1213
+ 'Internal ROOMLINK redemption core (service_role-only). Locks the token FOR UPDATE, no-ops idempotently on a replayed (invite, agent), then gates revoked/expired/exhausted (uniform 42501), creator-active (R-LINK-2), creator NOT fleet-revoked (#276), creator ceiling re-bind, and kicked-agent refusal (R-LINK-7) before an atomic rank-max membership upsert + uses_count increment. Shared by redeem_invite_link and the /enroll hook. #276 keys on the CREATOR, the principal who confers here, and is the sibling of R-LINK-2 one column over: fleet revocation leaves agents.status = ''active'', so an outstanding admin link from a ledger-revoked creator kept conferring admin. It calls _actor_fleet_revoked (UNLOCKED) rather than the share-locking assert the other five gates use, because this function is reached from enroll_federated_identity while a boards row lock is already held, and every placement of a creator row lock here closes a cycle against onboard_federated_fleet_agent; the adjacent R-LINK-2 check has likewise always been unlocked. It raises the same uniform ''invite is not usable'' message as every other arm so a code-bearer cannot distinguish a revoked creator from a dead link. Consiliency/message-board#918: a board that is not active gives the same uniform 42501 ''invite is not usable'', decided under the board row''s KEY SHARE lock (after the replay return, which writes nothing).';
1214
+
1215
+ -- =============================================================================
1216
+ -- 11. invite_board_for_display: a non-active board does not resolve
1217
+ -- =============================================================================
1218
+ CREATE OR REPLACE FUNCTION agent_board.invite_board_for_display(p_code_sha256 text)
1219
+ RETURNS TABLE(board_id uuid, board_name text, board_slug text, preset_role text)
1220
+ LANGUAGE sql
1221
+ STABLE SECURITY DEFINER
1222
+ SET search_path TO 'agent_board', 'public'
1223
+ AS $function$
1224
+ select b.id, b.name, b.slug, t.preset_role
1225
+ from agent_board.board_invite_tokens t
1226
+ join agent_board.boards b on b.id = t.board_id
1227
+ where encode(extensions.digest(t.code, 'sha256'), 'hex') = lower(p_code_sha256)
1228
+ and t.revoked_at is null
1229
+ and t.expires_at > now()
1230
+ and (t.max_uses is null or t.uses_count < t.max_uses)
1231
+ and b.status = 'active'; -- #918: the redeem core refuses a non-active board
1232
+ $function$;
1233
+
1234
+ revoke all on function agent_board.invite_board_for_display(text)
1235
+ from public, anon, authenticated, service_role, agent_board_delegate;
1236
+ grant execute on function agent_board.invite_board_for_display(text) to service_role;
1237
+ comment on function agent_board.invite_board_for_display(text) is
1238
+ 'IF-0-ONBOARD-11: resolves an invite code''s digest (lowercase hex sha256 of the code, compared case-insensitively) to (board_id, board_name, board_slug, preset_role) for display on the Portal consent page. Only a usable code resolves -- not revoked, expires_at > now(), and max_uses null or uses_count < max_uses (a subset of the redeem core''s checks, so a displayed board can still fail to redeem); revoked, expired, exhausted and unknown codes return no row. Read-only. EXECUTE is service_role only: the Portal calls it server-side. Consiliency/message-board#918: the board must be active, as the redeem core requires; an archived board''s code returns no row.';