@consiliency/agent-board-schema 1.79.0 → 1.81.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 (113) hide show
  1. package/fixtures/already-applied.json +8 -0
  2. package/migrations/20261126000100_agent_board_membership_removal_requires_active.sql +243 -0
  3. package/migrations/20261201000100_agent_board_reply_to_message.sql +1241 -0
  4. package/package.json +1 -1
  5. package/schema-manifest.json +21 -3
  6. package/src/tooling.test.mjs +6 -2
  7. package/tests/agent_board_661_reply_delivery.test.sql +12 -12
  8. package/tests/agent_board_667_history_class.test.sql +31 -13
  9. package/tests/agent_board_717_message_replay_scope.test.sql +29 -16
  10. package/tests/agent_board_717_tasking_replay_scope.test.sql +3 -3
  11. package/tests/agent_board_bundle_endpoint_compat.test.sql +2 -2
  12. package/tests/agent_board_canary_signed_fleet_enforcement.test.sql +3 -3
  13. package/tests/agent_board_claim_subject_gate.test.sql +3 -1
  14. package/tests/agent_board_delegate_role_class.test.sql +1 -1
  15. package/tests/agent_board_delivery_writer_execute.test.sql +7 -7
  16. package/tests/agent_board_hosted_delegates.test.sql +3 -3
  17. package/tests/agent_board_inbox_rpcs.test.sql +6 -6
  18. package/tests/agent_board_membership_removal_state.test.sql +228 -0
  19. package/tests/agent_board_refusal_atomicity.test.sql +958 -0
  20. package/tests/agent_board_reply_to.test.sql +874 -0
  21. package/tests/agent_board_scoped_send_regrant.test.sql +8 -8
  22. package/tests/agent_board_send_outcome.test.sql +10 -10
  23. package/tests/agent_board_send_role_gate.test.sql +2 -2
  24. package/tests/agent_board_write_enforcement_class.test.sql +7 -7
  25. package/tests/catalog/function_execute_privileges.json +23 -14
  26. package/tests/catalog/p_metadata_parameters.json +12 -8
  27. package/tests/isolation/expected/reply_parent_vs_thread_delete.out +55 -0
  28. package/tests/isolation/expected/reply_vs_parent_author_delete.out +56 -0
  29. package/tests/isolation/specs/reply_parent_vs_thread_delete.spec +42 -0
  30. package/tests/isolation/specs/reply_vs_parent_author_delete.spec +46 -0
  31. package/tests/mutations/655/M01_no_writer_check.sql +22 -0
  32. package/tests/mutations/655/M02_drop_fk.sql +2 -0
  33. package/tests/mutations/655/M03_existence_only.sql +13 -0
  34. package/tests/mutations/655/M04_distinct_cross_thread_error.sql +17 -0
  35. package/tests/mutations/655/M05_view_no_thread_conjunct.sql +46 -0
  36. package/tests/mutations/655/M06_thread_feed_not_invoker.sql +46 -0
  37. package/tests/mutations/655/M06b_board_feed_not_invoker.sql +49 -0
  38. package/tests/mutations/655/M07_excerpt_via_definer.sql +49 -0
  39. package/tests/mutations/655/M08_excerpt_200.sql +46 -0
  40. package/tests/mutations/655/M09_fk_restrict.sql +4 -0
  41. package/tests/mutations/655/M10_post_message_drops_arg.sql +13 -0
  42. package/tests/mutations/655/M10b_post_message_passes_null.sql +12 -0
  43. package/tests/mutations/655/M11_slug_drops_arg.sql +15 -0
  44. package/tests/mutations/655/M11b_dm_descriptor_positional.sql +31 -0
  45. package/tests/mutations/655/M12_signed_pbm_nine_args.sql +19 -0
  46. package/tests/mutations/655/M12b_signed_mc_one_branch.sql +15 -0
  47. package/tests/mutations/655/M13_undriven_entrypoint.sql +8 -0
  48. package/tests/mutations/655/M14_second_writer.sql +6 -0
  49. package/tests/mutations/655/M15_insert_primitive_public.sql +2 -0
  50. package/tests/mutations/655/M16_comment_missing.sql +2 -0
  51. package/tests/mutations/655/M17_old_allow_set_rows.sql +5 -0
  52. package/tests/mutations/655/M18_board_excerpt_139.sql +49 -0
  53. package/tests/mutations/655/M19_column_in_middle.sql +47 -0
  54. package/tests/mutations/655/M20_projects_parent_id.sql +46 -0
  55. package/tests/mutations/655/M21_replay_applies_new_parent.sql +22 -0
  56. package/tests/mutations/655/M22_fk_not_valid.sql +4 -0
  57. package/tests/mutations/655/MB4a_no_readability.sql +13 -0
  58. package/tests/mutations/655/MB4b_own_readability_message.sql +20 -0
  59. package/tests/mutations/655/MB4c_service_role_reads_all.sql +12 -0
  60. package/tests/mutations/655/MB4d_delegate_uses_authenticated_arm.sql +12 -0
  61. package/tests/mutations/655/MB4f_no_board_member_branch.sql +14 -0
  62. package/tests/mutations/655/MB4g_helper_granted_authenticated.sql +2 -0
  63. package/tests/mutations/655/MB4j_writer_uses_current_agent.sql +12 -0
  64. package/tests/mutations/655/MB4k_delegate_policy_loses_initplan.sql +5 -0
  65. package/tests/mutations/655/MB4l_board_memberships_policy_narrowed.sql +3 -0
  66. package/tests/mutations/655/W1_auth_no_membership_state.sql +13 -0
  67. package/tests/mutations/655/W2_auth_no_agent_binding.sql +13 -0
  68. package/tests/mutations/655/W3_delivery_no_recipient_binding.sql +12 -0
  69. package/tests/mutations/655/W4_delegate_no_board_conjunct.sql +18 -0
  70. package/tests/mutations/655/W5_boardset_no_membership_state.sql +13 -0
  71. package/tests/mutations/655/W6_boardset_no_agent_binding.sql +14 -0
  72. package/tests/mutations/655/run.sh +93 -0
  73. package/tests/mutations/670/M10_lock_removed.sql +2 -2
  74. package/tests/mutations/670/M14_post_message_mints_from_metadata.sql +2 -2
  75. package/tests/mutations/670/M3-DM_helper_on_replay_branch.sql +2 -2
  76. package/tests/mutations/670/M3-MC_helper_on_replay_branch.sql +2 -2
  77. package/tests/mutations/670/M3_helper_on_replay_branch.sql +2 -2
  78. package/tests/mutations/670/M8_delivery_swallows_errors.sql +2 -2
  79. package/tests/mutations/670/M9_lock_key_includes_board.sql +2 -2
  80. package/tests/mutations/670/run.sh +1 -1
  81. package/tests/mutations/717-f1/M10_wrapper_stops_delegating.sql +1 -1
  82. package/tests/mutations/717-f1/M9_public_route_revoked_from_service_role.sql +1 -1
  83. package/tests/mutations/717-f2b/L1_dm_lock_split_by_recipient.sql +2 -2
  84. package/tests/mutations/717-f2b/L2_dm_lock_removed.sql +2 -2
  85. package/tests/mutations/717-f2b/L3_mc_lock_split_by_recipients.sql +2 -2
  86. package/tests/mutations/717-f2b/L4_mc_lock_removed.sql +2 -2
  87. package/tests/mutations/717-f2b/M0_prefix_definitions.sql +1 -1
  88. package/tests/mutations/717-f2b/M10_mc_lookup_any_author.sql +2 -2
  89. package/tests/mutations/717-f2b/M11_dm_swallow_refusal.sql +2 -2
  90. package/tests/mutations/717-f2b/M12_mc_swallow_refusal.sql +2 -2
  91. package/tests/mutations/717-f2b/M15_mc_any_source.sql +1 -1
  92. package/tests/mutations/717-f2b/M1_dm_drop_recipient_proof.sql +2 -2
  93. package/tests/mutations/717-f2b/M2_mc_drop_recipient_proof.sql +2 -2
  94. package/tests/mutations/717-f2b/M3_dm_metadata_as_proof.sql +2 -2
  95. package/tests/mutations/717-f2b/M4_mc_metadata_as_proof.sql +2 -2
  96. package/tests/mutations/717-f2b/M5_dm_any_mode.sql +2 -2
  97. package/tests/mutations/717-f2b/M6_dm_board_delivery_counts.sql +2 -2
  98. package/tests/mutations/717-f2b/M7_mc_any_mode.sql +2 -2
  99. package/tests/mutations/717-f2b/M8_dm_thread_stamp_as_proof.sql +2 -2
  100. package/tests/mutations/717-f2b/M9_dm_lookup_any_author.sql +2 -2
  101. package/tests/mutations/717-f2b/run.sh +2 -2
  102. package/tests/mutations/919/M10_quoted_net_http_post_scratch.sql +5 -0
  103. package/tests/mutations/919/M11_pbm_calls_public.sql +11 -0
  104. package/tests/mutations/919/M1_pbm_refusal_swallowed_after_write.sql +14 -0
  105. package/tests/mutations/919/M2_cof_refusal_swallowed_after_write.sql +13 -0
  106. package/tests/mutations/919/M3_pbm_receipt_fault_swallowed.sql +10 -0
  107. package/tests/mutations/919/M4_pg_notify_scratch.sql +5 -0
  108. package/tests/mutations/919/M5_dynamic_notify_scratch.sql +5 -0
  109. package/tests/mutations/919/M6_trigger_outside_schema.sql +3 -0
  110. package/tests/mutations/919/M7_pbm_step_up_gate.sql +10 -0
  111. package/tests/mutations/919/M8_pbm_positive_writes_nothing.sql +10 -0
  112. package/tests/mutations/919/M9_cof_positive_writes_nothing.sql +10 -0
  113. package/tests/mutations/919/run.sh +81 -0
@@ -0,0 +1,1241 @@
1
+ -- #655 REPLYTO: reply to a specific message (chat-bubbles P2; message-board-ui CONV-08 / PR-18).
2
+ -- Plan: plans/REPLYTO-655-plan.md (revision R3, president ruling R3). Section numbers below are
3
+ -- the plan's.
4
+ --
5
+ -- WHAT THIS ADDS
6
+ -- * agent_board.messages.reply_to_message_id: the message this one replies to, or NULL.
7
+ -- * Same-thread is a TABLE invariant (D1): unique (thread_id, id) plus the composite FK
8
+ -- (thread_id, reply_to_message_id) -> messages (thread_id, id), MATCH SIMPLE, NO ACTION.
9
+ -- * Every API message entrypoint takes p_reply_to_message_id (D4): post_message, both
10
+ -- post_board_message overloads, both send_direct_message overloads and both
11
+ -- send_multicast_message overloads take it as a trailing `uuid default null` parameter; the
12
+ -- three signed_* wrappers read it from their payload. Each forwards it to the one insert
13
+ -- primitive, _insert_thread_message, by name.
14
+ -- * The primitive refuses an unusable parent with ONE error (D2): 22023 'reply_to_message_id not
15
+ -- found in thread', for a parent that is missing, in another thread, or not readable by the
16
+ -- session-derived actor (D3, fail closed). Readability is evaluated by the writer's copy of the
17
+ -- two messages SELECT policies, _actor_can_read_message (§6.2), which no API role can execute.
18
+ -- * v_thread_feed and v_board_feed append seven reply_to_* columns from an RLS-filtered LEFT JOIN
19
+ -- to the parent (D5-D7). Nothing about the parent is stored on the reply.
20
+ --
21
+ -- WHAT THIS DOES NOT CHANGE
22
+ -- * Both messages SELECT policies are byte-identical (R3 item 1): there is no DROP or CREATE
23
+ -- POLICY here. RT-B4-1 freezes their polqual so a later policy edit forces a re-review of the
24
+ -- writer copy below.
25
+ -- * An idempotent replay ignores the reply argument exactly as it ignores p_body (D8): the
26
+ -- argument reaches the primitive only on the insert branch.
27
+ -- * agent_board.schema_version stays 8 (D9): the change is additive.
28
+ --
29
+ -- LOCK ORDER (§2.1, binding). Every lock is held to commit, because the deploy applies one
30
+ -- transaction. S1 (SHARE, the only large scan of the write-blocking window) runs BEFORE S2 takes
31
+ -- ACCESS EXCLUSIVE, so the read-blocking window holds only the S4 and S6 scans and the DDL after
32
+ -- them. lock_timeout is mandatory (§2.3): S0 sets a transaction-local 5 s when the applier left it
33
+ -- unset (0), and never loosens an applier's own value. A lock that cannot be acquired raises 55P03
34
+ -- and the whole transaction rolls back with nothing applied. The clock_timestamp() notices after
35
+ -- S1, S2, S4, S6 and at the end are the §9.4 dry-run's per-step timings.
36
+ --
37
+ -- ACL AND COMMENT (AGENTS.md "Schema-change mechanics that bite"): DROP FUNCTION discards both,
38
+ -- and a recreated definer grants EXECUTE to PUBLIC. Every function created or replaced here is
39
+ -- followed by `revoke all ... from public, anon, authenticated, service_role, agent_board_delegate`,
40
+ -- exactly the grants the function EXECUTE-privilege snapshot recorded for the old signature, and
41
+ -- `comment on function`, in this file.
42
+
43
+ -- =============================================================================
44
+ -- S0. Preconditions
45
+ -- =============================================================================
46
+ do $s0$
47
+ declare
48
+ v_def text;
49
+ v_valid boolean;
50
+ begin
51
+ if current_setting('lock_timeout') in ('0', '0ms', '0s') then
52
+ perform set_config('lock_timeout', '5s', true);
53
+ end if;
54
+ -- O1 (§2.3) pre-builds the unique index CONCURRENTLY out of band. A failed CONCURRENTLY build
55
+ -- leaves an INVALID index behind, and `create unique index if not exists` would then skip it.
56
+ select i.indisvalid, pg_get_indexdef(i.indexrelid)
57
+ into v_valid, v_def
58
+ from pg_index i
59
+ where i.indexrelid = to_regclass('agent_board.messages_thread_id_id_key');
60
+ if found then
61
+ if not v_valid then
62
+ raise exception '#655 S0: index agent_board.messages_thread_id_id_key exists but is INVALID; drop it (drop index concurrently) and rebuild it before applying';
63
+ end if;
64
+ if v_def <> 'CREATE UNIQUE INDEX messages_thread_id_id_key ON agent_board.messages USING btree (thread_id, id)' then
65
+ raise exception '#655 S0: index agent_board.messages_thread_id_id_key has an unexpected definition: %', v_def;
66
+ end if;
67
+ end if;
68
+ raise notice '#655 S0 % lock_timeout=%', clock_timestamp(), current_setting('lock_timeout');
69
+ end
70
+ $s0$;
71
+
72
+ -- =============================================================================
73
+ -- S1-S7. The column, the invariant, the indexes
74
+ -- =============================================================================
75
+ -- S1: SHARE (blocks writes, allows reads). A no-op when O1 pre-built it.
76
+ create unique index if not exists messages_thread_id_id_key on agent_board.messages (thread_id, id);
77
+ do $n1$ begin raise notice '#655 S1 %', clock_timestamp(); end $n1$;
78
+
79
+ -- S2: ACCESS EXCLUSIVE, catalog-only (a NULL-default column rewrites nothing).
80
+ alter table agent_board.messages add column reply_to_message_id uuid;
81
+ do $n2$ begin raise notice '#655 S2 %', clock_timestamp(); end $n2$;
82
+
83
+ -- S3: the unique constraint the composite FK references, over the S1 index.
84
+ alter table agent_board.messages
85
+ add constraint messages_thread_id_id_key unique using index messages_thread_id_id_key;
86
+
87
+ -- S4: the reply lookup index (the view join and the FK's referencing side).
88
+ create index messages_reply_to_idx on agent_board.messages (thread_id, reply_to_message_id)
89
+ where reply_to_message_id is not null;
90
+ do $n4$ begin raise notice '#655 S4 %', clock_timestamp(); end $n4$;
91
+
92
+ -- S5: the same-thread invariant, NOT VALID first.
93
+ alter table agent_board.messages
94
+ add constraint messages_reply_to_same_thread_fkey
95
+ foreign key (thread_id, reply_to_message_id) references agent_board.messages (thread_id, id)
96
+ match simple on delete no action on update no action not valid;
97
+
98
+ -- S6: validated in-bundle. Every existing row has a NULL reference, so validation cannot fail; it
99
+ -- runs because the #667 XB class requires convalidated (§8.5.2).
100
+ alter table agent_board.messages validate constraint messages_reply_to_same_thread_fkey;
101
+ do $n6$ begin raise notice '#655 S6 %', clock_timestamp(); end $n6$;
102
+
103
+ -- S7
104
+ comment on column agent_board.messages.reply_to_message_id is
105
+ '#655: the message this one replies to, or NULL (not a reply). Always a message of the SAME thread (messages_reply_to_same_thread_fkey). Written only by _insert_thread_message, which refuses a parent its actor cannot read. The parent''s sequence, author and excerpt are derived at read time by v_thread_feed / v_board_feed under the reader''s RLS; nothing about the parent is stored here.';
106
+ comment on constraint messages_reply_to_same_thread_fkey on agent_board.messages is
107
+ '#655: same-thread reply invariant. (thread_id, reply_to_message_id) references (thread_id, id), MATCH SIMPLE, so a NULL reply id is unconstrained and a non-NULL one names a message of the same thread. NO ACTION: a thread cascade deletes parent and reply in one statement; a single-message delete of a replied-to parent is refused (23503).';
108
+ comment on constraint messages_thread_id_id_key on agent_board.messages is
109
+ '#655: the referenced key of messages_reply_to_same_thread_fkey. id is already the primary key; (thread_id, id) exists so the reply FK can require the parent''s thread to equal the reply''s own.';
110
+
111
+ -- =============================================================================
112
+ -- §6.2 The writer's copy of the readability predicate
113
+ -- =============================================================================
114
+ -- ONE copy of the two messages SELECT policies, evaluated for a NAMED actor. The policies
115
+ -- themselves are untouched; this function exists because the writer must ask "can THIS actor read
116
+ -- that parent" as the owner, where RLS does not apply.
117
+ -- * Delegate actor (agents.is_delegate): the delegate policy (20261008000100:3035-3038), with
118
+ -- _delegate_visible_board_ids() replaced by its body (20261008000100:493-504) bound to the
119
+ -- actor instead of current_agent_id().
120
+ -- * Any other actor: the authenticated policy (20260514000000:34-58), with current_agent_id()
121
+ -- replaced by the actor and messages.id by p_message_id.
122
+ -- The sub-reads run as the owner, so delivery_recipients and board_memberships are read
123
+ -- unfiltered. That gives the same answer as the policies' RLS-filtered reads, because each
124
+ -- predicate only ever looks for rows the reader's own sub-table policy admits (plan §1.3), and
125
+ -- RT-B4-EQ pins the equality on every fixture pair.
126
+ -- A missing message, or a missing actor, yields NULL. The writer's `is true` test refuses NULL.
127
+ -- EXECUTE is granted to no role: as an API route it would be a cross-agent readability oracle.
128
+ create function agent_board._actor_can_read_message(p_actor_agent_id uuid, p_message_id uuid)
129
+ returns boolean
130
+ language sql
131
+ stable
132
+ security definer
133
+ set search_path = ''
134
+ as $fn$
135
+ select case
136
+ when m.id is null or a.id is null then null
137
+ when a.is_delegate then
138
+ exists (
139
+ select 1
140
+ from agent_board.delivery_recipients dr
141
+ where dr.source_message_id = m.id
142
+ and dr.board_id = any (coalesce((
143
+ select coalesce(array_agg(bm.board_id order by bm.board_id), '{}'::uuid[])
144
+ from agent_board.board_memberships bm
145
+ where bm.agent_id = p_actor_agent_id
146
+ and bm.membership_state in ('joined', 'subscribed')), '{}'::uuid[])))
147
+ else
148
+ m.author_agent_id = p_actor_agent_id
149
+ or exists (
150
+ select 1
151
+ from agent_board.delivery_recipients dr
152
+ where dr.source_message_id = m.id
153
+ and (dr.recipient_agent_id = p_actor_agent_id
154
+ or (dr.board_id is not null
155
+ and exists (
156
+ select 1
157
+ from agent_board.board_memberships bm
158
+ where bm.board_id = dr.board_id
159
+ and bm.agent_id = p_actor_agent_id
160
+ and bm.membership_state in ('joined', 'subscribed')))))
161
+ end
162
+ from (select p_message_id as id) k
163
+ left join agent_board.messages m on m.id = k.id
164
+ left join agent_board.agents a on a.id = p_actor_agent_id
165
+ $fn$;
166
+
167
+ revoke all on function agent_board._actor_can_read_message(uuid, uuid)
168
+ from public, anon, authenticated, service_role, agent_board_delegate;
169
+ comment on function agent_board._actor_can_read_message(uuid, uuid) is
170
+ '#655 (§6.2): the writer''s ONE copy of the two messages SELECT policies, for a named actor: the delegate policy when the actor is a hosted delegate, the authenticated policy otherwise. NULL for a missing message or actor. Called only by _insert_thread_message with the session-derived actor, which refuses unless the result is true. EXECUTE to no API role (it would be a cross-agent readability oracle). RT-B4-1 freezes the policies it copies; RT-B4-EQ pins that it agrees with them.';
171
+
172
+ -- =============================================================================
173
+ -- §3.1 / §3.3 The sole insert primitive
174
+ -- =============================================================================
175
+ -- The catalog body (20261104065658) unchanged, plus the parameter, the #655 check and the column.
176
+ drop function agent_board._insert_thread_message(uuid, uuid, text, text, uuid, jsonb);
177
+
178
+ create function agent_board._insert_thread_message(p_thread_id uuid, p_author_agent_id uuid, p_body text, p_message_type text DEFAULT 'comment'::text, p_task_id uuid DEFAULT NULL::uuid, p_metadata jsonb DEFAULT '{}'::jsonb, p_reply_to_message_id uuid DEFAULT NULL::uuid)
179
+ RETURNS TABLE(message_id uuid, thread_id uuid, task_id uuid, message_sequence bigint, created_at timestamp with time zone)
180
+ LANGUAGE plpgsql
181
+ SECURITY DEFINER
182
+ SET search_path TO 'agent_board', 'public'
183
+ AS $function$
184
+ declare
185
+ v_sequence bigint;
186
+ v_actor_agent_id uuid;
187
+ v_metadata jsonb;
188
+ v_instance agent_board.delegate_instances%rowtype;
189
+ v_reply_parent_id uuid;
190
+ begin
191
+ v_actor_agent_id := agent_board._resolved_actor_agent_id(p_author_agent_id, 'p_author_agent_id');
192
+
193
+ if nullif(trim(p_body), '') is null then
194
+ raise exception 'message body is required' using errcode = '22023';
195
+ end if;
196
+ if not exists (select 1 from agent_board.threads where id = p_thread_id) then
197
+ raise exception 'thread not found' using errcode = 'P0002';
198
+ end if;
199
+ if not agent_board._current_agent_can_access_thread(p_thread_id) then
200
+ raise exception 'thread not accessible to current agent' using errcode = '42501';
201
+ end if;
202
+ -- OBSGATE (#78): a board-linked thread under 'inherit' requires a non-observer board role.
203
+ -- All message entrypoints use this authorized insertion primitive; the gate cannot be bypassed
204
+ -- by any send path. Board-less threads and service_role fall through (access check above).
205
+ if not agent_board._current_agent_can_post_to_thread(p_thread_id) then
206
+ raise exception 'thread posting requires a non-observer board role' using errcode = '42501';
207
+ end if;
208
+ if p_task_id is not null and not exists (select 1 from agent_board.tasks where id = p_task_id and tasks.thread_id = p_thread_id) then
209
+ raise exception 'task not found in thread' using errcode = '22023';
210
+ end if;
211
+ -- #655 (D2, D3): the reply parent must exist, be in THIS thread, and be readable by the
212
+ -- session-derived actor. One code and one message for all three, so the refusal is no oracle.
213
+ -- A service_role caller acts for v_actor_agent_id and gets that actor's readability, never an
214
+ -- RLS bypass. No lock: the parent is immutable, and the composite FK's KEY SHARE on the parent
215
+ -- row closes the window between this check and the insert.
216
+ if p_reply_to_message_id is not null then
217
+ select pm.id into v_reply_parent_id
218
+ from agent_board.messages pm
219
+ where pm.id = p_reply_to_message_id
220
+ and pm.thread_id = p_thread_id;
221
+ if v_reply_parent_id is null
222
+ or agent_board._actor_can_read_message(v_actor_agent_id, v_reply_parent_id) is not true then
223
+ raise exception 'reply_to_message_id not found in thread' using errcode = '22023';
224
+ end if;
225
+ end if;
226
+
227
+ -- HOSTED attribution: the `delegate` key is written by the server, never by a caller. A
228
+ -- hosted delegate's post carries it (overwriting anything supplied); every other author's
229
+ -- caller-supplied `delegate` key is removed, so no keyed agent can forge the mark.
230
+ -- client_verified is always false: under dynamic client registration anyone can name a client.
231
+ v_metadata := coalesce(p_metadata, '{}'::jsonb);
232
+ if jsonb_typeof(v_metadata) = 'object' then
233
+ v_metadata := v_metadata - 'delegate';
234
+ end if;
235
+ select di.* into v_instance
236
+ from agent_board.agents a
237
+ join agent_board.delegate_instances di on di.agent_id = a.id
238
+ where a.id = v_actor_agent_id
239
+ and a.is_delegate;
240
+ if found then
241
+ if jsonb_typeof(v_metadata) <> 'object' then
242
+ raise exception 'a hosted delegate''s message metadata must be a JSON object' using errcode = '22023';
243
+ end if;
244
+ v_metadata := v_metadata || jsonb_build_object('delegate', jsonb_build_object(
245
+ 'delegate', true,
246
+ 'instance_id', v_instance.instance_id,
247
+ 'owner_agent_id', agent_board._delegate_principal_agent_id(v_actor_agent_id),
248
+ 'client_id', v_instance.client_id,
249
+ 'client_verified', false));
250
+ end if;
251
+
252
+ v_sequence := agent_board._next_thread_message_sequence(p_thread_id);
253
+ -- The sequence update may have waited for an association; re-read after that wait.
254
+ if not agent_board._current_agent_can_access_thread(p_thread_id) then
255
+ raise exception 'thread not accessible to current agent' using errcode = '42501';
256
+ end if;
257
+ if not agent_board._current_agent_can_post_to_thread(p_thread_id) then
258
+ raise exception 'thread posting requires a non-observer board role' using errcode = '42501';
259
+ end if;
260
+
261
+ return query
262
+ insert into agent_board.messages(thread_id, author_agent_id, task_id, message_sequence, message_type, body, metadata, reply_to_message_id)
263
+ values (p_thread_id, v_actor_agent_id, p_task_id, v_sequence, coalesce(p_message_type, 'comment'), p_body, v_metadata, p_reply_to_message_id)
264
+ returning id, messages.thread_id, messages.task_id, messages.message_sequence, messages.created_at;
265
+ end;
266
+ $function$;
267
+
268
+ revoke all on function agent_board._insert_thread_message(uuid, uuid, text, text, uuid, jsonb, uuid)
269
+ from public, anon, authenticated, service_role, agent_board_delegate;
270
+ comment on function agent_board._insert_thread_message(uuid, uuid, text, text, uuid, jsonb, uuid) is
271
+ 'Internal authorized message insertion; preserves sequence locking, session author and hosted attribution. Delivery is the caller responsibility. #655: p_reply_to_message_id must name a message of the same thread that the session-derived actor can read (_actor_can_read_message is true); otherwise 22023 reply_to_message_id not found in thread.';
272
+
273
+ -- =============================================================================
274
+ -- §3.2 Pass-through: the uuid cores (DROP and CREATE, the new parameter LAST)
275
+ -- =============================================================================
276
+ -- post_message (20260914000100's body, unchanged but for the argument).
277
+ drop function agent_board.post_message(uuid, uuid, text, text, uuid, jsonb);
278
+
279
+ create function agent_board.post_message(p_thread_id uuid, p_author_agent_id uuid, p_body text, p_message_type text DEFAULT 'comment'::text, p_task_id uuid DEFAULT NULL::uuid, p_metadata jsonb DEFAULT '{}'::jsonb, p_reply_to_message_id uuid DEFAULT NULL::uuid)
280
+ RETURNS TABLE(message_id uuid, thread_id uuid, task_id uuid, message_sequence bigint, created_at timestamp with time zone)
281
+ LANGUAGE plpgsql
282
+ SECURITY DEFINER
283
+ SET search_path TO 'agent_board', 'public'
284
+ AS $function$
285
+ declare
286
+ v_message record;
287
+ v_board_id uuid;
288
+ v_subject text;
289
+ v_access_mode text;
290
+ begin
291
+ select * into v_message from agent_board._insert_thread_message(
292
+ p_thread_id,p_author_agent_id,p_body,p_message_type,p_task_id,p_metadata,
293
+ p_reply_to_message_id => p_reply_to_message_id);
294
+ -- Insertion holds the sequence/thread lock. Read the association after that
295
+ -- lock, so an initially unstamped thread cannot race past board delivery.
296
+ select t.board_id,coalesce(nullif(trim(t.subject),''),'Thread reply'),t.access_mode
297
+ into v_board_id,v_subject,v_access_mode from agent_board.threads t where t.id=p_thread_id;
298
+ -- Restricted threads keep their explicit audience; board association alone
299
+ -- does not authorize broadcasting an ordinary reply to all board members.
300
+ if v_board_id is not null and v_access_mode = 'inherit' then
301
+ if not agent_board._current_agent_has_board_access(v_board_id) then
302
+ raise exception 'board not accessible to current agent' using errcode='42501';
303
+ end if;
304
+ if not agent_board._current_agent_can_send_to_board(v_board_id) then
305
+ raise exception 'board send requires a non-observer board role' using errcode='42501';
306
+ end if;
307
+ perform * from agent_board._deliver_board_message(v_message.message_id,v_subject,p_body,'medium');
308
+ end if;
309
+ return query select v_message.message_id,v_message.thread_id,v_message.task_id,
310
+ v_message.message_sequence,v_message.created_at;
311
+ end;
312
+ $function$;
313
+
314
+ revoke all on function agent_board.post_message(uuid, uuid, text, text, uuid, jsonb, uuid)
315
+ from public, anon, authenticated, service_role, agent_board_delegate;
316
+ grant execute on function agent_board.post_message(uuid, uuid, text, text, uuid, jsonb, uuid)
317
+ to authenticated, service_role, agent_board_delegate;
318
+ comment on function agent_board.post_message(uuid, uuid, text, text, uuid, jsonb, uuid) is
319
+ 'Posts a thread reply; inherited board threads use canonical board delivery; non-board and restricted threads retain insertion-only behavior. Session-derived author and return shape are unchanged. #655: p_reply_to_message_id (optional) names the message this one replies to; it must be in the same thread and readable by the author, else 22023 reply_to_message_id not found in thread.';
320
+
321
+ -- post_board_message, the board-id core (20261108000100's body, unchanged but for the argument,
322
+ -- which reaches the primitive only on the insert branch: a same-key replay ignores it, D8).
323
+ drop function agent_board.post_board_message(uuid, uuid, uuid, text, text, text, text, text, jsonb);
324
+
325
+ create function agent_board.post_board_message(p_thread_id uuid, p_author_agent_id uuid, p_board_id uuid, p_subject text, p_body text, p_message_type text DEFAULT 'comment'::text, p_priority text DEFAULT 'medium'::text, p_idempotency_key text DEFAULT NULL::text, p_metadata jsonb DEFAULT '{}'::jsonb, p_reply_to_message_id uuid DEFAULT NULL::uuid)
326
+ RETURNS TABLE(message_id uuid, board_id uuid, delivered_recipient_count integer, callback_outbox_count integer, created_at timestamp with time zone)
327
+ LANGUAGE plpgsql
328
+ SECURITY DEFINER
329
+ SET search_path TO 'agent_board', 'public'
330
+ AS $function$
331
+ declare
332
+ v_message agent_board.messages%rowtype;
333
+ v_created_message record;
334
+ v_membership record;
335
+ v_recipient agent_board.delivery_recipients%rowtype;
336
+ v_inbox agent_board.inbox_items%rowtype;
337
+ v_delivered_count integer := 0;
338
+ v_callback_count integer := 0;
339
+ v_metadata jsonb;
340
+ v_preview text;
341
+ v_fetch_descriptor jsonb;
342
+ v_idempotency_key text := nullif(trim(p_idempotency_key), '');
343
+ v_actor_agent_id uuid;
344
+ v_inserted boolean := false;
345
+ v_is_author boolean;
346
+ begin
347
+ v_actor_agent_id := agent_board._resolved_actor_agent_id(p_author_agent_id, 'p_author_agent_id');
348
+
349
+ if nullif(trim(p_subject), '') is null or nullif(trim(p_body), '') is null then
350
+ raise exception 'subject and body are required' using errcode = '22023';
351
+ end if;
352
+ if p_priority not in ('low', 'medium', 'high', 'urgent') then
353
+ raise exception 'invalid priority' using errcode = '22023';
354
+ end if;
355
+ if not exists (select 1 from agent_board.threads where id = p_thread_id) then
356
+ raise exception 'thread not found' using errcode = 'P0002';
357
+ end if;
358
+ if not exists (select 1 from agent_board.boards where id = p_board_id) then
359
+ raise exception 'board not found' using errcode = 'P0002';
360
+ end if;
361
+ if not agent_board._current_agent_can_access_thread(p_thread_id) then
362
+ raise exception 'thread not accessible to current agent' using errcode = '42501';
363
+ end if;
364
+ if not agent_board._current_agent_has_board_access(p_board_id) then
365
+ raise exception 'board not accessible to current agent' using errcode = '42501';
366
+ end if;
367
+ if not agent_board._current_agent_can_send_to_board(p_board_id) then
368
+ raise exception 'board send requires a non-observer board role' using errcode = '42501';
369
+ end if;
370
+
371
+ if agent_board._is_service_role() then
372
+ perform agent_board._record_send_authz_telemetry(
373
+ 'service_role_bypass',
374
+ coalesce(nullif(p_metadata -> 'signed_write' ->> 'origin', ''), 'unknown'),
375
+ v_actor_agent_id,
376
+ p_board_id,
377
+ 'post_board_message',
378
+ agent_board._resolve_send_fleet_scope(v_actor_agent_id),
379
+ null,
380
+ jsonb_build_object('redacted', true)
381
+ );
382
+ end if;
383
+
384
+ perform agent_board._lock_idempotency_key(
385
+ 'post_board_message:' || p_thread_id::text || ':' || v_actor_agent_id::text,
386
+ v_idempotency_key
387
+ );
388
+
389
+ if p_board_id is not null then
390
+ perform agent_board._associate_empty_thread(p_thread_id, p_board_id);
391
+ -- Both checks are new statements after the thread-lock wait.
392
+ if not agent_board._current_agent_can_access_thread(p_thread_id) then
393
+ raise exception 'thread not accessible to current agent' using errcode = '42501';
394
+ end if;
395
+ if not agent_board._current_agent_has_board_access(p_board_id) then
396
+ raise exception 'board not accessible to current agent' using errcode = '42501';
397
+ end if;
398
+ if not agent_board._current_agent_can_send_to_board(p_board_id) then
399
+ raise exception 'board send requires a non-observer board role' using errcode = '42501';
400
+ end if;
401
+ end if;
402
+
403
+ if v_idempotency_key is not null then
404
+ select *
405
+ into v_message
406
+ from agent_board.messages
407
+ where thread_id = p_thread_id
408
+ and author_agent_id = v_actor_agent_id
409
+ and metadata ->> 'rpcName' = 'post_board_message'
410
+ and metadata ->> 'idempotencyKey' = v_idempotency_key
411
+ order by created_at desc, id desc
412
+ limit 1;
413
+ end if;
414
+
415
+ if v_message.id is null then
416
+ v_metadata := coalesce(p_metadata, '{}'::jsonb)
417
+ || jsonb_build_object(
418
+ 'rpcName', 'post_board_message',
419
+ 'subject', trim(p_subject),
420
+ 'priority', p_priority,
421
+ 'boardId', p_board_id::text
422
+ );
423
+ if v_idempotency_key is not null then
424
+ v_metadata := v_metadata || jsonb_build_object('idempotencyKey', v_idempotency_key);
425
+ end if;
426
+
427
+ select *
428
+ into v_created_message
429
+ from agent_board._insert_thread_message(
430
+ p_thread_id,
431
+ v_actor_agent_id,
432
+ p_body,
433
+ p_message_type,
434
+ null,
435
+ v_metadata,
436
+ p_reply_to_message_id => p_reply_to_message_id
437
+ );
438
+
439
+ select *
440
+ into v_message
441
+ from agent_board.messages
442
+ where id = v_created_message.message_id;
443
+ v_inserted := true;
444
+ end if;
445
+
446
+ select d.delivered_recipient_count, d.callback_outbox_count
447
+ into v_delivered_count, v_callback_count
448
+ from agent_board._deliver_board_message(v_message.id, trim(p_subject), p_body, p_priority) d;
449
+
450
+ -- #670: the author-scoped send receipt. Only a message inserted by THIS call, under a key, after
451
+ -- delivery and immediately before returning; replays never record. The helper derives the author
452
+ -- from the session and records nothing for service_role.
453
+ if v_inserted and v_idempotency_key is not null then
454
+ perform agent_board._record_send_outcome('post_board_message', v_message.id, v_idempotency_key, p_board_id);
455
+ end if;
456
+
457
+ return query
458
+ select v_message.id, p_board_id, v_delivered_count, v_callback_count, v_message.created_at;
459
+ end;
460
+ $function$;
461
+
462
+ revoke all on function agent_board.post_board_message(uuid, uuid, uuid, text, text, text, text, text, jsonb, uuid)
463
+ from public, anon, authenticated, service_role, agent_board_delegate;
464
+ grant execute on function agent_board.post_board_message(uuid, uuid, uuid, text, text, text, text, text, jsonb, uuid)
465
+ to authenticated, service_role, agent_board_delegate;
466
+ comment on function agent_board.post_board_message(uuid, uuid, uuid, text, text, text, text, text, jsonb, uuid) is
467
+ 'Creates or reuses a canonical board post after validating the session actor, board authority and locked thread association; delivery fan-out and downstream effects are transactional. Same-key calls serialize on (thread, actor, key), whatever the board. A keyed session send that inserts records the author-scoped receipt get_send_outcome reads (#670). #655: p_reply_to_message_id (optional) names a same-thread parent the author can read, else 22023 reply_to_message_id not found in thread; a same-key replay ignores it, as it ignores p_body.';
468
+
469
+ -- post_board_message, the by-slug overload (20260517000000's body; forwards BY NAME).
470
+ drop function agent_board.post_board_message(uuid, uuid, text, text, text, text, text, text, text, jsonb);
471
+
472
+ create function agent_board.post_board_message(p_thread_id uuid, p_author_agent_id uuid, p_board_slug text, p_addressing_mode text, p_subject text, p_body text, p_message_type text, p_priority text, p_idempotency_key text, p_metadata jsonb, p_reply_to_message_id uuid DEFAULT NULL::uuid)
473
+ RETURNS TABLE(message_id uuid, board_id uuid, delivered_recipient_count integer, callback_outbox_count integer, created_at timestamp with time zone)
474
+ LANGUAGE plpgsql
475
+ SECURITY DEFINER
476
+ SET search_path TO 'agent_board', 'public'
477
+ AS $function$
478
+ declare
479
+ v_board_id uuid;
480
+ begin
481
+ if p_addressing_mode <> 'addressing_v1' then
482
+ raise exception 'invalid addressing mode' using errcode = '22023';
483
+ end if;
484
+
485
+ select b.id into v_board_id
486
+ from agent_board.boards b
487
+ where b.slug = nullif(trim(p_board_slug), '')
488
+ and b.status = 'active';
489
+ if v_board_id is null then
490
+ raise exception 'board slug not found' using errcode = 'P0002';
491
+ end if;
492
+
493
+ return query
494
+ select *
495
+ from agent_board.post_board_message(
496
+ p_thread_id => p_thread_id,
497
+ p_author_agent_id => p_author_agent_id,
498
+ p_board_id => v_board_id,
499
+ p_subject => p_subject,
500
+ p_body => p_body,
501
+ p_message_type => p_message_type,
502
+ p_priority => p_priority,
503
+ p_idempotency_key => p_idempotency_key,
504
+ p_metadata => p_metadata,
505
+ p_reply_to_message_id => p_reply_to_message_id
506
+ );
507
+ end;
508
+ $function$;
509
+
510
+ revoke all on function agent_board.post_board_message(uuid, uuid, text, text, text, text, text, text, text, jsonb, uuid)
511
+ from public, anon, authenticated, service_role, agent_board_delegate;
512
+ grant execute on function agent_board.post_board_message(uuid, uuid, text, text, text, text, text, text, text, jsonb, uuid)
513
+ to authenticated, service_role, agent_board_delegate;
514
+ comment on function agent_board.post_board_message(uuid, uuid, text, text, text, text, text, text, text, jsonb, uuid) is
515
+ 'By-slug board post (addressing_v1): resolves an active board by slug and forwards every argument by name to the board-id overload, including #655 p_reply_to_message_id.';
516
+
517
+ -- send_direct_message, the uuid core (20261108000100's body; insert branch only, D8).
518
+ drop function agent_board.send_direct_message(uuid, uuid, uuid, text, text, text, text, text, jsonb);
519
+
520
+ create function agent_board.send_direct_message(p_thread_id uuid, p_author_agent_id uuid, p_recipient_agent_id uuid, p_subject text, p_body text, p_message_type text DEFAULT 'comment'::text, p_priority text DEFAULT 'medium'::text, p_idempotency_key text DEFAULT NULL::text, p_metadata jsonb DEFAULT '{}'::jsonb, p_reply_to_message_id uuid DEFAULT NULL::uuid)
521
+ RETURNS TABLE(message_id uuid, delivery_recipient_id uuid, inbox_item_id uuid, callback_outbox_count integer, created_at timestamp with time zone)
522
+ LANGUAGE plpgsql
523
+ SECURITY DEFINER
524
+ SET search_path TO 'agent_board', 'public'
525
+ AS $function$
526
+ declare
527
+ v_message agent_board.messages%rowtype;
528
+ v_created_message record;
529
+ v_recipient agent_board.delivery_recipients%rowtype;
530
+ v_inbox agent_board.inbox_items%rowtype;
531
+ v_callback_count integer := 0;
532
+ v_metadata jsonb;
533
+ v_preview text;
534
+ v_fetch_descriptor jsonb;
535
+ v_idempotency_key text := nullif(trim(p_idempotency_key), '');
536
+ v_actor_agent_id uuid;
537
+ v_inserted boolean := false;
538
+ begin
539
+ v_actor_agent_id := agent_board._resolved_actor_agent_id(p_author_agent_id, 'p_author_agent_id');
540
+
541
+ if nullif(trim(p_subject), '') is null or nullif(trim(p_body), '') is null then
542
+ raise exception 'subject and body are required' using errcode = '22023';
543
+ end if;
544
+ if p_priority not in ('low', 'medium', 'high', 'urgent') then
545
+ raise exception 'invalid priority' using errcode = '22023';
546
+ end if;
547
+ if not exists (select 1 from agent_board.threads where id = p_thread_id) then
548
+ raise exception 'thread not found' using errcode = 'P0002';
549
+ end if;
550
+ if not agent_board._current_agent_can_access_thread(p_thread_id) then
551
+ raise exception 'thread not accessible to current agent' using errcode = '42501';
552
+ end if;
553
+ if not exists (select 1 from agent_board.agents where id = p_recipient_agent_id) then
554
+ raise exception 'recipient agent not found' using errcode = 'P0002';
555
+ end if;
556
+
557
+ if agent_board._is_service_role() then
558
+ perform agent_board._record_send_authz_telemetry(
559
+ 'service_role_bypass',
560
+ coalesce(nullif(p_metadata -> 'signed_write' ->> 'origin', ''), 'unknown'),
561
+ v_actor_agent_id,
562
+ null,
563
+ 'send_direct_message',
564
+ agent_board._resolve_send_fleet_scope(v_actor_agent_id),
565
+ null,
566
+ jsonb_build_object('redacted', true)
567
+ );
568
+ end if;
569
+
570
+ perform agent_board._lock_idempotency_key(
571
+ 'send_direct_message:' || p_thread_id::text || ':' || v_actor_agent_id::text,
572
+ v_idempotency_key
573
+ );
574
+
575
+ if v_idempotency_key is not null then
576
+ select *
577
+ into v_message
578
+ from agent_board.messages
579
+ where thread_id = p_thread_id
580
+ and author_agent_id = v_actor_agent_id
581
+ and metadata ->> 'rpcName' = 'send_direct_message'
582
+ and metadata ->> 'idempotencyKey' = v_idempotency_key
583
+ order by created_at desc
584
+ limit 1;
585
+ end if;
586
+
587
+ -- #717 F2b: a same-key replay may only re-deliver the source message to the recipient it was
588
+ -- already PRIVATELY delivered to. The proof is the persisted delivery row of THIS source
589
+ -- message in THIS function's mode, for THIS recipient, with no board scope. Metadata, the
590
+ -- thread's board stamp and any board-mode delivery are not evidence. Refused before any
591
+ -- replay effect, so the whole call (telemetry, signed evidence) rolls back. A new recipient
592
+ -- needs a new key, which creates a new message without the source's artifacts.
593
+ if v_message.id is not null and not exists (
594
+ select 1
595
+ from agent_board.delivery_recipients dr
596
+ where dr.source_kind = 'message'
597
+ and dr.source_message_id = v_message.id
598
+ and dr.delivery_mode = 'direct'
599
+ and dr.recipient_agent_id = p_recipient_agent_id
600
+ and dr.board_id is null
601
+ ) then
602
+ raise exception 'message replay cannot widen delivery scope' using errcode = '42501';
603
+ end if;
604
+
605
+ if v_message.id is null then
606
+ v_metadata := coalesce(p_metadata, '{}'::jsonb)
607
+ || jsonb_build_object(
608
+ 'rpcName', 'send_direct_message',
609
+ 'subject', trim(p_subject),
610
+ 'priority', p_priority
611
+ );
612
+ if v_idempotency_key is not null then
613
+ v_metadata := v_metadata || jsonb_build_object('idempotencyKey', v_idempotency_key);
614
+ end if;
615
+
616
+ select *
617
+ into v_created_message
618
+ from agent_board._insert_thread_message(
619
+ p_thread_id,
620
+ v_actor_agent_id,
621
+ p_body,
622
+ p_message_type,
623
+ null,
624
+ v_metadata,
625
+ p_reply_to_message_id => p_reply_to_message_id
626
+ );
627
+
628
+ select *
629
+ into v_message
630
+ from agent_board.messages
631
+ where id = v_created_message.message_id;
632
+ v_inserted := true;
633
+ end if;
634
+
635
+ v_preview := agent_board._trim_inbox_text(p_body, 280);
636
+ v_fetch_descriptor := agent_board._build_fetch_descriptor(
637
+ 'thread',
638
+ p_thread_id,
639
+ 'agent_board.v_thread_feed',
640
+ 'direct delivery',
641
+ jsonb_build_object('messageId', v_message.id::text, 'recipientAgentId', p_recipient_agent_id::text)
642
+ );
643
+
644
+ v_recipient := agent_board._upsert_delivery_recipient(
645
+ 'direct',
646
+ p_recipient_agent_id,
647
+ 'message',
648
+ v_message.id,
649
+ null,
650
+ null,
651
+ null,
652
+ null,
653
+ jsonb_build_object('priority', p_priority)
654
+ );
655
+
656
+ v_inbox := agent_board._upsert_inbox_item(
657
+ v_recipient.id,
658
+ p_recipient_agent_id,
659
+ null,
660
+ v_recipient.delivery_mode,
661
+ 'message',
662
+ v_message.id,
663
+ null,
664
+ null,
665
+ trim(p_subject),
666
+ v_preview,
667
+ p_priority,
668
+ true,
669
+ false,
670
+ v_fetch_descriptor,
671
+ jsonb_build_object('threadId', p_thread_id::text)
672
+ );
673
+
674
+ v_callback_count := agent_board._queue_inbox_callbacks(v_inbox.id, 'inbox.item.delivered');
675
+
676
+ -- #670: the author-scoped send receipt. Only a message inserted by THIS call, under a key, after
677
+ -- delivery and immediately before returning; replays never record. The helper derives the author
678
+ -- from the session and records nothing for service_role.
679
+ if v_inserted and v_idempotency_key is not null then
680
+ perform agent_board._record_send_outcome('send_direct_message', v_message.id, v_idempotency_key, null);
681
+ end if;
682
+
683
+ return query
684
+ select v_message.id, v_recipient.id, v_inbox.id, v_callback_count, v_message.created_at;
685
+ end;
686
+ $function$;
687
+
688
+ revoke all on function agent_board.send_direct_message(uuid, uuid, uuid, text, text, text, text, text, jsonb, uuid)
689
+ from public, anon, authenticated, service_role, agent_board_delegate;
690
+ grant execute on function agent_board.send_direct_message(uuid, uuid, uuid, text, text, text, text, text, jsonb, uuid)
691
+ to authenticated, service_role;
692
+ comment on function agent_board.send_direct_message(uuid, uuid, uuid, text, text, text, text, text, jsonb, uuid) is
693
+ 'Sends privately to the explicit recipient, including on board threads; uses the common authorized insertion primitive. A same-key replay cannot widen the message''s audience: it is refused (42501) unless the recipient already holds a private direct delivery of the source message. A keyed session send that inserts records the author-scoped receipt get_send_outcome reads (#670). #655: p_reply_to_message_id (optional) names a same-thread parent the author can read, else 22023 reply_to_message_id not found in thread; a same-key replay ignores it.';
694
+
695
+ -- send_direct_message, the descriptor overload (20260517000000's body; forwards the argument BY
696
+ -- NAME after the positional ones, so the reply cannot be dropped by a call that still resolves).
697
+ drop function agent_board.send_direct_message(uuid, uuid, jsonb, text, text, text, text, text, text, jsonb);
698
+
699
+ create function agent_board.send_direct_message(p_thread_id uuid, p_author_agent_id uuid, p_recipient_descriptor jsonb, p_addressing_mode text, p_subject text, p_body text, p_message_type text, p_priority text, p_idempotency_key text, p_metadata jsonb, p_reply_to_message_id uuid DEFAULT NULL::uuid)
700
+ RETURNS TABLE(message_id uuid, delivery_recipient_id uuid, inbox_item_id uuid, callback_outbox_count integer, created_at timestamp with time zone)
701
+ LANGUAGE plpgsql
702
+ SECURITY DEFINER
703
+ SET search_path TO 'agent_board', 'public'
704
+ AS $function$
705
+ declare
706
+ v_recipients uuid[];
707
+ begin
708
+ if p_addressing_mode <> 'addressing_v1' then
709
+ raise exception 'invalid addressing mode' using errcode = '22023';
710
+ end if;
711
+ v_recipients := agent_board._addressing_agent_ids_or_raise(p_author_agent_id, jsonb_build_array(p_recipient_descriptor));
712
+ if cardinality(v_recipients) <> 1 then
713
+ raise exception 'direct message requires exactly one recipient' using errcode = '22023';
714
+ end if;
715
+
716
+ return query
717
+ select *
718
+ from agent_board.send_direct_message(
719
+ p_thread_id => p_thread_id,
720
+ p_author_agent_id => p_author_agent_id,
721
+ p_recipient_agent_id => v_recipients[1],
722
+ p_subject => p_subject,
723
+ p_body => p_body,
724
+ p_message_type => p_message_type,
725
+ p_priority => p_priority,
726
+ p_idempotency_key => p_idempotency_key,
727
+ p_metadata => p_metadata,
728
+ p_reply_to_message_id => p_reply_to_message_id
729
+ );
730
+ end;
731
+ $function$;
732
+
733
+ revoke all on function agent_board.send_direct_message(uuid, uuid, jsonb, text, text, text, text, text, text, jsonb, uuid)
734
+ from public, anon, authenticated, service_role, agent_board_delegate;
735
+ grant execute on function agent_board.send_direct_message(uuid, uuid, jsonb, text, text, text, text, text, text, jsonb, uuid)
736
+ to authenticated, service_role;
737
+ comment on function agent_board.send_direct_message(uuid, uuid, jsonb, text, text, text, text, text, text, jsonb, uuid) is
738
+ 'Direct message by recipient descriptor (addressing_v1): resolves exactly one recipient and forwards every argument by name to the uuid overload, including #655 p_reply_to_message_id.';
739
+
740
+ -- send_multicast_message, the uuid[] core (20261108000100's body; insert branch only, D8).
741
+ drop function agent_board.send_multicast_message(uuid, uuid, uuid[], text, text, text, text, text, jsonb);
742
+
743
+ create function agent_board.send_multicast_message(p_thread_id uuid, p_author_agent_id uuid, p_recipient_agent_ids uuid[], p_subject text, p_body text, p_message_type text DEFAULT 'comment'::text, p_priority text DEFAULT 'medium'::text, p_idempotency_key text DEFAULT NULL::text, p_metadata jsonb DEFAULT '{}'::jsonb, p_reply_to_message_id uuid DEFAULT NULL::uuid)
744
+ RETURNS TABLE(message_id uuid, delivered_recipient_count integer, inbox_item_count integer, callback_outbox_count integer, created_at timestamp with time zone)
745
+ LANGUAGE plpgsql
746
+ SECURITY DEFINER
747
+ SET search_path TO 'agent_board', 'public'
748
+ AS $function$
749
+ declare
750
+ v_message agent_board.messages%rowtype;
751
+ v_created_message record;
752
+ v_recipient_ids uuid[];
753
+ v_recipient_id uuid;
754
+ v_recipient agent_board.delivery_recipients%rowtype;
755
+ v_inbox agent_board.inbox_items%rowtype;
756
+ v_delivered_count integer := 0;
757
+ v_inbox_count integer := 0;
758
+ v_callback_count integer := 0;
759
+ v_metadata jsonb;
760
+ v_preview text;
761
+ v_fetch_descriptor jsonb;
762
+ v_idempotency_key text := nullif(trim(p_idempotency_key), '');
763
+ v_actor_agent_id uuid;
764
+ v_inserted boolean := false;
765
+ begin
766
+ v_actor_agent_id := agent_board._resolved_actor_agent_id(p_author_agent_id, 'p_author_agent_id');
767
+
768
+ if nullif(trim(p_subject), '') is null or nullif(trim(p_body), '') is null then
769
+ raise exception 'subject and body are required' using errcode = '22023';
770
+ end if;
771
+ if p_priority not in ('low', 'medium', 'high', 'urgent') then
772
+ raise exception 'invalid priority' using errcode = '22023';
773
+ end if;
774
+ if p_recipient_agent_ids is null or cardinality(p_recipient_agent_ids) = 0 then
775
+ raise exception 'recipient_agent_ids must not be empty' using errcode = '22023';
776
+ end if;
777
+ if array_position(p_recipient_agent_ids, null) is not null then
778
+ raise exception 'recipient_agent_ids must not contain nulls' using errcode = '22023';
779
+ end if;
780
+ if not exists (select 1 from agent_board.threads where id = p_thread_id) then
781
+ raise exception 'thread not found' using errcode = 'P0002';
782
+ end if;
783
+ if not agent_board._current_agent_can_access_thread(p_thread_id) then
784
+ raise exception 'thread not accessible to current agent' using errcode = '42501';
785
+ end if;
786
+
787
+ select array_agg(distinct recipient_id)
788
+ into v_recipient_ids
789
+ from unnest(p_recipient_agent_ids) as recipient_id;
790
+
791
+ if (
792
+ select count(*)
793
+ from agent_board.agents
794
+ where id = any(v_recipient_ids)
795
+ ) <> cardinality(v_recipient_ids) then
796
+ raise exception 'recipient agent not found' using errcode = 'P0002';
797
+ end if;
798
+
799
+ if agent_board._is_service_role() then
800
+ perform agent_board._record_send_authz_telemetry(
801
+ 'service_role_bypass',
802
+ coalesce(nullif(p_metadata -> 'signed_write' ->> 'origin', ''), 'unknown'),
803
+ v_actor_agent_id,
804
+ null,
805
+ 'send_multicast_message',
806
+ agent_board._resolve_send_fleet_scope(v_actor_agent_id),
807
+ null,
808
+ jsonb_build_object('redacted', true)
809
+ );
810
+ end if;
811
+
812
+ perform agent_board._lock_idempotency_key(
813
+ 'send_multicast_message:' || p_thread_id::text || ':' || v_actor_agent_id::text,
814
+ v_idempotency_key
815
+ );
816
+
817
+ if v_idempotency_key is not null then
818
+ select *
819
+ into v_message
820
+ from agent_board.messages
821
+ where thread_id = p_thread_id
822
+ and author_agent_id = v_actor_agent_id
823
+ and metadata ->> 'rpcName' = 'send_multicast_message'
824
+ and metadata ->> 'idempotencyKey' = v_idempotency_key
825
+ order by created_at desc
826
+ limit 1;
827
+ end if;
828
+
829
+ -- #717 F2b: a same-key replay may name the same normalized recipient set or a nonempty subset
830
+ -- of it, never a new recipient. Each requested recipient must already hold a persisted
831
+ -- multicast delivery of THIS source message with no board scope; an omitted recipient's
832
+ -- delivery is kept, not revoked. Metadata, the thread's board stamp and board-mode deliveries
833
+ -- are not evidence. Refused before any replay effect, so the whole call rolls back. A new
834
+ -- recipient needs a new key, which creates a new message without the source's artifacts.
835
+ if v_message.id is not null and exists (
836
+ select 1
837
+ from unnest(v_recipient_ids) as requested(recipient_id)
838
+ where not exists (
839
+ select 1
840
+ from agent_board.delivery_recipients dr
841
+ where dr.source_kind = 'message'
842
+ and dr.source_message_id = v_message.id
843
+ and dr.delivery_mode = 'multicast'
844
+ and dr.recipient_agent_id = requested.recipient_id
845
+ and dr.board_id is null
846
+ )
847
+ ) then
848
+ raise exception 'message replay cannot widen delivery scope' using errcode = '42501';
849
+ end if;
850
+
851
+ if v_message.id is null then
852
+ v_metadata := coalesce(p_metadata, '{}'::jsonb)
853
+ || jsonb_build_object(
854
+ 'rpcName', 'send_multicast_message',
855
+ 'subject', trim(p_subject),
856
+ 'priority', p_priority
857
+ );
858
+ if v_idempotency_key is not null then
859
+ v_metadata := v_metadata || jsonb_build_object('idempotencyKey', v_idempotency_key);
860
+ end if;
861
+
862
+ select *
863
+ into v_created_message
864
+ from agent_board._insert_thread_message(
865
+ p_thread_id,
866
+ v_actor_agent_id,
867
+ p_body,
868
+ p_message_type,
869
+ null,
870
+ v_metadata,
871
+ p_reply_to_message_id => p_reply_to_message_id
872
+ );
873
+
874
+ select *
875
+ into v_message
876
+ from agent_board.messages
877
+ where id = v_created_message.message_id;
878
+ v_inserted := true;
879
+ end if;
880
+
881
+ v_preview := agent_board._trim_inbox_text(p_body, 280);
882
+
883
+ foreach v_recipient_id in array v_recipient_ids loop
884
+ v_fetch_descriptor := agent_board._build_fetch_descriptor(
885
+ 'thread',
886
+ p_thread_id,
887
+ 'agent_board.v_thread_feed',
888
+ 'multicast delivery',
889
+ jsonb_build_object('messageId', v_message.id::text, 'recipientAgentId', v_recipient_id::text)
890
+ );
891
+
892
+ v_recipient := agent_board._upsert_delivery_recipient(
893
+ 'multicast',
894
+ v_recipient_id,
895
+ 'message',
896
+ v_message.id,
897
+ null,
898
+ null,
899
+ null,
900
+ null,
901
+ jsonb_build_object('priority', p_priority)
902
+ );
903
+
904
+ v_inbox := agent_board._upsert_inbox_item(
905
+ v_recipient.id,
906
+ v_recipient_id,
907
+ null,
908
+ v_recipient.delivery_mode,
909
+ 'message',
910
+ v_message.id,
911
+ null,
912
+ null,
913
+ trim(p_subject),
914
+ v_preview,
915
+ p_priority,
916
+ true,
917
+ false,
918
+ v_fetch_descriptor,
919
+ jsonb_build_object('threadId', p_thread_id::text)
920
+ );
921
+
922
+ v_delivered_count := v_delivered_count + 1;
923
+ v_inbox_count := v_inbox_count + 1;
924
+ v_callback_count := v_callback_count + agent_board._queue_inbox_callbacks(v_inbox.id, 'inbox.item.delivered');
925
+ end loop;
926
+
927
+ -- #670: the author-scoped send receipt. Only a message inserted by THIS call, under a key, after
928
+ -- delivery and immediately before returning; replays never record. The helper derives the author
929
+ -- from the session and records nothing for service_role.
930
+ if v_inserted and v_idempotency_key is not null then
931
+ perform agent_board._record_send_outcome('send_multicast_message', v_message.id, v_idempotency_key, null);
932
+ end if;
933
+
934
+ return query
935
+ select v_message.id, v_delivered_count, v_inbox_count, v_callback_count, v_message.created_at;
936
+ end;
937
+ $function$;
938
+
939
+ revoke all on function agent_board.send_multicast_message(uuid, uuid, uuid[], text, text, text, text, text, jsonb, uuid)
940
+ from public, anon, authenticated, service_role, agent_board_delegate;
941
+ grant execute on function agent_board.send_multicast_message(uuid, uuid, uuid[], text, text, text, text, text, jsonb, uuid)
942
+ to authenticated, service_role;
943
+ comment on function agent_board.send_multicast_message(uuid, uuid, uuid[], text, text, text, text, text, jsonb, uuid) is
944
+ 'Sends privately to explicit recipients, including on board threads; uses the common authorized insertion primitive. A same-key replay cannot widen the message''s audience: it is refused (42501) unless every requested recipient already holds a private multicast delivery of the source message. A keyed session send that inserts records the author-scoped receipt get_send_outcome reads (#670). #655: p_reply_to_message_id (optional) names a same-thread parent the author can read, else 22023 reply_to_message_id not found in thread; a same-key replay ignores it.';
945
+
946
+ -- send_multicast_message, the descriptor overload (20260517000000's body; by name, as above).
947
+ drop function agent_board.send_multicast_message(uuid, uuid, jsonb, text, text, text, text, text, text, jsonb);
948
+
949
+ create function agent_board.send_multicast_message(p_thread_id uuid, p_author_agent_id uuid, p_recipient_descriptors jsonb, p_addressing_mode text, p_subject text, p_body text, p_message_type text, p_priority text, p_idempotency_key text, p_metadata jsonb, p_reply_to_message_id uuid DEFAULT NULL::uuid)
950
+ RETURNS TABLE(message_id uuid, delivered_recipient_count integer, inbox_item_count integer, callback_outbox_count integer, created_at timestamp with time zone)
951
+ LANGUAGE plpgsql
952
+ SECURITY DEFINER
953
+ SET search_path TO 'agent_board', 'public'
954
+ AS $function$
955
+ begin
956
+ if p_addressing_mode <> 'addressing_v1' then
957
+ raise exception 'invalid addressing mode' using errcode = '22023';
958
+ end if;
959
+
960
+ return query
961
+ select *
962
+ from agent_board.send_multicast_message(
963
+ p_thread_id => p_thread_id,
964
+ p_author_agent_id => p_author_agent_id,
965
+ p_recipient_agent_ids => agent_board._addressing_agent_ids_or_raise(p_author_agent_id, p_recipient_descriptors),
966
+ p_subject => p_subject,
967
+ p_body => p_body,
968
+ p_message_type => p_message_type,
969
+ p_priority => p_priority,
970
+ p_idempotency_key => p_idempotency_key,
971
+ p_metadata => p_metadata,
972
+ p_reply_to_message_id => p_reply_to_message_id
973
+ );
974
+ end;
975
+ $function$;
976
+
977
+ revoke all on function agent_board.send_multicast_message(uuid, uuid, jsonb, text, text, text, text, text, text, jsonb, uuid)
978
+ from public, anon, authenticated, service_role, agent_board_delegate;
979
+ grant execute on function agent_board.send_multicast_message(uuid, uuid, jsonb, text, text, text, text, text, text, jsonb, uuid)
980
+ to authenticated, service_role;
981
+ comment on function agent_board.send_multicast_message(uuid, uuid, jsonb, text, text, text, text, text, text, jsonb, uuid) is
982
+ 'Multicast by recipient descriptors (addressing_v1): resolves the recipients and forwards every argument by name to the uuid[] overload, including #655 p_reply_to_message_id.';
983
+
984
+ -- =============================================================================
985
+ -- §3.2 The signed wrappers (create or replace: same signatures). Each passes the payload's
986
+ -- p_reply_to_message_id BY NAME. Without this, a signed reply would silently become a plain post.
987
+ -- =============================================================================
988
+ CREATE OR REPLACE FUNCTION agent_board.signed_post_board_message(p_payload jsonb, p_gateway_decision jsonb)
989
+ RETURNS TABLE(message_id uuid, board_id uuid, delivered_recipient_count integer, callback_outbox_count integer, signature_evidence_id uuid, verification_status text, created_at timestamp with time zone)
990
+ LANGUAGE plpgsql
991
+ SECURITY DEFINER
992
+ SET search_path TO 'agent_board', 'public'
993
+ AS $function$
994
+ declare
995
+ v_row record;
996
+ v_evidence_id uuid;
997
+ v_actor uuid;
998
+ begin
999
+ v_actor := agent_board._signed_write_actor_id(p_payload, p_gateway_decision, 'p_author_agent_id');
1000
+ select *
1001
+ into v_row
1002
+ from agent_board.post_board_message(
1003
+ (p_payload ->> 'p_thread_id')::uuid,
1004
+ v_actor,
1005
+ (p_payload ->> 'p_board_id')::uuid,
1006
+ p_payload ->> 'p_subject',
1007
+ p_payload ->> 'p_body',
1008
+ coalesce(p_payload ->> 'p_message_type', 'comment'),
1009
+ coalesce(p_payload ->> 'p_priority', 'medium'),
1010
+ nullif(p_payload ->> 'p_idempotency_key', ''),
1011
+ coalesce(p_payload -> 'p_metadata', '{}'::jsonb) || jsonb_build_object('signed_write', jsonb_build_object('verification_status', coalesce(p_gateway_decision ->> 'verification_status', 'unsigned'), 'redacted', true)),
1012
+ p_reply_to_message_id => nullif(p_payload ->> 'p_reply_to_message_id', '')::uuid
1013
+ );
1014
+
1015
+ v_evidence_id := agent_board._record_signed_write_evidence('message', v_row.message_id, 'post_board_message', p_payload, p_gateway_decision);
1016
+
1017
+ return query
1018
+ select v_row.message_id, v_row.board_id, v_row.delivered_recipient_count, v_row.callback_outbox_count, v_evidence_id, coalesce(p_gateway_decision ->> 'verification_status', 'unsigned'), v_row.created_at;
1019
+ end;
1020
+ $function$;
1021
+
1022
+ revoke all on function agent_board.signed_post_board_message(jsonb, jsonb)
1023
+ from public, anon, authenticated, service_role, agent_board_delegate;
1024
+ grant execute on function agent_board.signed_post_board_message(jsonb, jsonb) to service_role;
1025
+ comment on function agent_board.signed_post_board_message(jsonb, jsonb) is
1026
+ 'Signed-write gateway wrapper (service_role only): post_board_message as the gateway-decided actor, recording signature evidence. #655: the payload key p_reply_to_message_id is forwarded by name.';
1027
+
1028
+ CREATE OR REPLACE FUNCTION agent_board.signed_send_direct_message(p_payload jsonb, p_gateway_decision jsonb)
1029
+ RETURNS TABLE(message_id uuid, delivery_recipient_id uuid, inbox_item_id uuid, callback_outbox_count integer, signature_evidence_id uuid, verification_status text, created_at timestamp with time zone)
1030
+ LANGUAGE plpgsql
1031
+ SECURITY DEFINER
1032
+ SET search_path TO 'agent_board', 'public'
1033
+ AS $function$
1034
+ declare
1035
+ v_row record;
1036
+ v_evidence_id uuid;
1037
+ v_actor uuid;
1038
+ begin
1039
+ v_actor := agent_board._signed_write_actor_id(p_payload, p_gateway_decision, 'p_author_agent_id');
1040
+ select *
1041
+ into v_row
1042
+ from agent_board.send_direct_message(
1043
+ (p_payload ->> 'p_thread_id')::uuid,
1044
+ v_actor,
1045
+ (p_payload ->> 'p_recipient_agent_id')::uuid,
1046
+ p_payload ->> 'p_subject',
1047
+ p_payload ->> 'p_body',
1048
+ coalesce(p_payload ->> 'p_message_type', 'comment'),
1049
+ coalesce(p_payload ->> 'p_priority', 'medium'),
1050
+ nullif(p_payload ->> 'p_idempotency_key', ''),
1051
+ coalesce(p_payload -> 'p_metadata', '{}'::jsonb) || jsonb_build_object('signed_write', jsonb_build_object('verification_status', coalesce(p_gateway_decision ->> 'verification_status', 'unsigned'), 'redacted', true)),
1052
+ p_reply_to_message_id => nullif(p_payload ->> 'p_reply_to_message_id', '')::uuid
1053
+ );
1054
+
1055
+ v_evidence_id := agent_board._record_signed_write_evidence('message', v_row.message_id, 'send_direct_message', p_payload, p_gateway_decision);
1056
+
1057
+ return query
1058
+ select v_row.message_id, v_row.delivery_recipient_id, v_row.inbox_item_id, v_row.callback_outbox_count, v_evidence_id, coalesce(p_gateway_decision ->> 'verification_status', 'unsigned'), v_row.created_at;
1059
+ end;
1060
+ $function$;
1061
+
1062
+ revoke all on function agent_board.signed_send_direct_message(jsonb, jsonb)
1063
+ from public, anon, authenticated, service_role, agent_board_delegate;
1064
+ grant execute on function agent_board.signed_send_direct_message(jsonb, jsonb) to service_role;
1065
+ comment on function agent_board.signed_send_direct_message(jsonb, jsonb) is
1066
+ 'Signed-write gateway wrapper (service_role only): send_direct_message as the gateway-decided actor, recording signature evidence. #655: the payload key p_reply_to_message_id is forwarded by name.';
1067
+
1068
+ CREATE OR REPLACE FUNCTION agent_board.signed_send_multicast_message(p_payload jsonb, p_gateway_decision jsonb)
1069
+ RETURNS TABLE(message_id uuid, delivered_recipient_count integer, inbox_item_count integer, callback_outbox_count integer, signature_evidence_id uuid, verification_status text, created_at timestamp with time zone)
1070
+ LANGUAGE plpgsql
1071
+ SECURITY DEFINER
1072
+ SET search_path TO 'agent_board', 'public'
1073
+ AS $function$
1074
+ declare
1075
+ v_row record;
1076
+ v_actor uuid := agent_board._signed_write_actor_id(p_payload, p_gateway_decision, 'p_author_agent_id');
1077
+ v_evidence_id uuid;
1078
+ v_recipient_ids uuid[];
1079
+ begin
1080
+ if p_payload ? 'p_recipient_agent_ids' then
1081
+ select array_agg(value::uuid) into v_recipient_ids from jsonb_array_elements_text(p_payload -> 'p_recipient_agent_ids');
1082
+ select * into v_row from agent_board.send_multicast_message(
1083
+ (p_payload ->> 'p_thread_id')::uuid, v_actor, v_recipient_ids,
1084
+ p_payload ->> 'p_subject', p_payload ->> 'p_body', coalesce(p_payload ->> 'p_message_type', 'comment'),
1085
+ coalesce(p_payload ->> 'p_priority', 'medium'), nullif(p_payload ->> 'p_idempotency_key', ''),
1086
+ coalesce(p_payload -> 'p_metadata', '{}'::jsonb) || jsonb_build_object('signed_write', jsonb_build_object('verification_status', coalesce(p_gateway_decision ->> 'verification_status', 'unsigned'), 'redacted', true)),
1087
+ p_reply_to_message_id => nullif(p_payload ->> 'p_reply_to_message_id', '')::uuid
1088
+ );
1089
+ else
1090
+ select * into v_row from agent_board.send_multicast_message(
1091
+ (p_payload ->> 'p_thread_id')::uuid, v_actor, p_payload -> 'p_recipient_descriptors',
1092
+ coalesce(p_payload ->> 'p_addressing_mode', 'addressing_v1'), p_payload ->> 'p_subject', p_payload ->> 'p_body',
1093
+ coalesce(p_payload ->> 'p_message_type', 'comment'), coalesce(p_payload ->> 'p_priority', 'medium'),
1094
+ nullif(p_payload ->> 'p_idempotency_key', ''), coalesce(p_payload -> 'p_metadata', '{}'::jsonb),
1095
+ p_reply_to_message_id => nullif(p_payload ->> 'p_reply_to_message_id', '')::uuid
1096
+ );
1097
+ end if;
1098
+ v_evidence_id := agent_board._record_signed_write_evidence('message', v_row.message_id, 'send_multicast_message', p_payload, p_gateway_decision);
1099
+ return query select v_row.message_id, v_row.delivered_recipient_count, v_row.inbox_item_count, v_row.callback_outbox_count, v_evidence_id, coalesce(p_gateway_decision ->> 'verification_status', 'unsigned'), v_row.created_at;
1100
+ end;
1101
+ $function$;
1102
+
1103
+ revoke all on function agent_board.signed_send_multicast_message(jsonb, jsonb)
1104
+ from public, anon, authenticated, service_role, agent_board_delegate;
1105
+ grant execute on function agent_board.signed_send_multicast_message(jsonb, jsonb) to service_role;
1106
+ comment on function agent_board.signed_send_multicast_message(jsonb, jsonb) is
1107
+ 'Signed-write gateway wrapper (service_role only): send_multicast_message as the gateway-decided actor, by recipient ids or descriptors, recording signature evidence. #655: the payload key p_reply_to_message_id is forwarded by name on BOTH branches.';
1108
+
1109
+ -- =============================================================================
1110
+ -- §6.1 The delegate allow set: the old post_* signatures out, the new ones in. Its grant loop
1111
+ -- (20261008000100) ran once, so the grants above are explicit.
1112
+ -- =============================================================================
1113
+ delete from agent_board.delegate_allowed_operations
1114
+ where kind = 'rpc'
1115
+ and signature in ('post_board_message(uuid, uuid, uuid, text, text, text, text, text, jsonb)',
1116
+ 'post_board_message(uuid, uuid, text, text, text, text, text, text, text, jsonb)',
1117
+ 'post_message(uuid, uuid, text, text, uuid, jsonb)');
1118
+ insert into agent_board.delegate_allowed_operations(kind, name, signature, reason) values
1119
+ ('rpc', 'post_board_message',
1120
+ 'post_board_message(uuid, uuid, uuid, text, text, text, text, text, jsonb, uuid)',
1121
+ 'post to a board by id (tools post_board_message, post_board)'),
1122
+ ('rpc', 'post_board_message',
1123
+ 'post_board_message(uuid, uuid, text, text, text, text, text, text, text, jsonb, uuid)',
1124
+ 'the by-slug overload; both overloads must agree, or the boundary test refuses the name'),
1125
+ ('rpc', 'post_message',
1126
+ 'post_message(uuid, uuid, text, text, uuid, jsonb, uuid)',
1127
+ 'reply in a thread (tool post_message)');
1128
+
1129
+ -- =============================================================================
1130
+ -- §4.1 Read side: seven columns APPENDED to both feed views (create or replace keeps the grants;
1131
+ -- security_invoker is restated because create or replace view resets reloptions, and without it
1132
+ -- the view would run with the owner's rights and compute every parent snippet unfiltered).
1133
+ -- The parent and its author are LEFT joins evaluated under the READER's RLS, so a reader who
1134
+ -- cannot read the parent sees the reply's own reply_to_message_id (D6) and NULL for the rest. The
1135
+ -- thread conjunct is defence in depth beside the FK. The excerpt is inlined (D7): a helper called
1136
+ -- from an invoker view would need EXECUTE for authenticated.
1137
+ -- The parent lookup is ONE LATERAL subquery fenced with OFFSET 0 (never pulled up into a plain join),
1138
+ -- gated on m.reply_to_message_id IS NOT NULL: for a row that is not a reply the gate is a one-time
1139
+ -- filter and nothing is probed; for a reply it is one primary-key probe of messages and, inside it, one
1140
+ -- of agents (fenced the same way). PERF-1 measured the plain-join form: the planner hashed a full scan
1141
+ -- of agents, filtered row by row through the delegate's agents policy (_delegate_visible_agent, a
1142
+ -- definer), at 1.33x on the delegate's board feed; and an ungated probe per row cost 1.29x on the
1143
+ -- authenticated thread feed. The reader's RLS still applies to both tables inside the subquery, and
1144
+ -- the keys are primary keys, so it yields at most one row.
1145
+ -- =============================================================================
1146
+ create or replace view agent_board.v_thread_feed with (security_invoker = true) as
1147
+ SELECT m.thread_id,
1148
+ m.id AS message_id,
1149
+ m.message_sequence,
1150
+ m.created_at AS message_created_at,
1151
+ m.author_agent_id,
1152
+ a.handle AS author_handle,
1153
+ a.display_name AS author_display_name,
1154
+ m.message_type,
1155
+ m.body,
1156
+ m.task_id,
1157
+ sig.verification_status,
1158
+ sig.key_fingerprint,
1159
+ sig.key_version,
1160
+ sig.algorithm,
1161
+ sig.verified_at,
1162
+ sig.failure_class,
1163
+ m.reply_to_message_id,
1164
+ r.message_sequence AS reply_to_message_sequence,
1165
+ r.author_agent_id AS reply_to_author_agent_id,
1166
+ r.handle AS reply_to_author_handle,
1167
+ r.display_name AS reply_to_author_display_name,
1168
+ left(r.body, 140) AS reply_to_excerpt,
1169
+ char_length(r.body) > 140 AS reply_to_excerpt_truncated
1170
+ FROM agent_board.messages m
1171
+ JOIN agent_board.agents a ON a.id = m.author_agent_id
1172
+ LEFT JOIN LATERAL ( SELECT se.verification_status,
1173
+ ask.fingerprint AS key_fingerprint,
1174
+ se.key_version,
1175
+ se.algorithm,
1176
+ se.verified_at,
1177
+ se.failure_class
1178
+ FROM agent_board.signature_evidence se
1179
+ LEFT JOIN agent_board.agent_signing_keys ask ON ask.id = se.signing_key_id
1180
+ WHERE se.source_kind = 'message'::text AND se.source_message_id = m.id
1181
+ ORDER BY se.created_at DESC
1182
+ LIMIT 1) sig ON true
1183
+ LEFT JOIN LATERAL ( SELECT p.message_sequence, p.author_agent_id, p.body, pa.handle, pa.display_name
1184
+ FROM agent_board.messages p
1185
+ LEFT JOIN LATERAL ( SELECT a2.handle, a2.display_name
1186
+ FROM agent_board.agents a2
1187
+ WHERE a2.id = p.author_agent_id
1188
+ OFFSET 0) pa ON true
1189
+ WHERE m.reply_to_message_id IS NOT NULL AND p.thread_id = m.thread_id AND p.id = m.reply_to_message_id
1190
+ OFFSET 0) r ON true;
1191
+
1192
+ create or replace view agent_board.v_board_feed with (security_invoker = true) as
1193
+ WITH board_posts AS (
1194
+ SELECT DISTINCT ON (dr.board_id, dr.source_message_id) dr.board_id,
1195
+ dr.source_message_id AS message_id,
1196
+ min(ii.created_at) OVER (PARTITION BY dr.board_id, dr.source_message_id) AS first_delivered_at,
1197
+ ii.subject,
1198
+ ii.preview,
1199
+ ii.priority,
1200
+ ii.fetch_descriptor
1201
+ FROM agent_board.delivery_recipients dr
1202
+ JOIN agent_board.inbox_items ii ON ii.delivery_recipient_id = dr.id
1203
+ WHERE dr.board_id IS NOT NULL AND dr.source_kind = 'message'::text AND dr.source_message_id IS NOT NULL AND ii.visible_in_board_feed = true
1204
+ ORDER BY dr.board_id, dr.source_message_id, ii.created_at, ii.id
1205
+ )
1206
+ SELECT bp.board_id,
1207
+ b.slug AS board_slug,
1208
+ b.name AS board_name,
1209
+ bp.message_id,
1210
+ m.thread_id,
1211
+ m.message_sequence,
1212
+ m.created_at AS message_created_at,
1213
+ m.author_agent_id,
1214
+ author.handle AS author_handle,
1215
+ author.display_name AS author_display_name,
1216
+ bp.subject,
1217
+ bp.preview,
1218
+ bp.priority,
1219
+ bp.fetch_descriptor,
1220
+ bp.first_delivered_at,
1221
+ m.reply_to_message_id,
1222
+ r.message_sequence AS reply_to_message_sequence,
1223
+ r.author_agent_id AS reply_to_author_agent_id,
1224
+ r.handle AS reply_to_author_handle,
1225
+ r.display_name AS reply_to_author_display_name,
1226
+ left(r.body, 140) AS reply_to_excerpt,
1227
+ char_length(r.body) > 140 AS reply_to_excerpt_truncated
1228
+ FROM board_posts bp
1229
+ JOIN agent_board.boards b ON b.id = bp.board_id
1230
+ JOIN agent_board.messages m ON m.id = bp.message_id
1231
+ JOIN agent_board.agents author ON author.id = m.author_agent_id
1232
+ LEFT JOIN LATERAL ( SELECT p.message_sequence, p.author_agent_id, p.body, pa.handle, pa.display_name
1233
+ FROM agent_board.messages p
1234
+ LEFT JOIN LATERAL ( SELECT a2.handle, a2.display_name
1235
+ FROM agent_board.agents a2
1236
+ WHERE a2.id = p.author_agent_id
1237
+ OFFSET 0) pa ON true
1238
+ WHERE m.reply_to_message_id IS NOT NULL AND p.thread_id = m.thread_id AND p.id = m.reply_to_message_id
1239
+ OFFSET 0) r ON true;
1240
+
1241
+ do $nend$ begin raise notice '#655 END %', clock_timestamp(); end $nend$;