@consiliency/agent-board-schema 1.83.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 (36) hide show
  1. package/README.md +5 -0
  2. package/fixtures/already-applied.json +4 -0
  3. package/migrations/20261203000200_agent_board_signed_seat_gates.sql +695 -0
  4. package/package.json +1 -1
  5. package/schema-manifest.json +12 -3
  6. package/src/tooling.test.mjs +4 -2
  7. package/tests/agent_board_954_signed_seat_gates.test.sql +472 -0
  8. package/tests/catalog/function_execute_privileges.json +36 -0
  9. package/tests/catalog/p_metadata_parameters.json +16 -0
  10. package/tests/mutations/954/MA1_resolver_ignores_signer.sql +15 -0
  11. package/tests/mutations/954/MA2_null_actor_resolves_to_signer.sql +22 -0
  12. package/tests/mutations/954/MB1_no_bind.sql +14 -0
  13. package/tests/mutations/954/MC1_context_any_role.sql +15 -0
  14. package/tests/mutations/954/MG1_has_board_access_service_bypass.sql +18 -0
  15. package/tests/mutations/954/MG2_can_send_to_board_service_bypass.sql +18 -0
  16. package/tests/mutations/954/MG3_can_access_thread_service_bypass.sql +18 -0
  17. package/tests/mutations/954/MG4_can_post_to_thread_service_bypass.sql +13 -0
  18. package/tests/mutations/954/MG5_can_access_task_service_bypass.sql +18 -0
  19. package/tests/mutations/954/MG6_can_mutate_task_service_bypass.sql +18 -0
  20. package/tests/mutations/954/MR1_post_board_message_no_release.sql +14 -0
  21. package/tests/mutations/954/MR2_send_direct_message_no_release.sql +14 -0
  22. package/tests/mutations/954/MR3_send_multicast_message_no_release.sql +14 -0
  23. package/tests/mutations/954/MR4_create_tasking_delivery_no_release.sql +14 -0
  24. package/tests/mutations/954/MR5_append_task_event_no_release.sql +14 -0
  25. package/tests/mutations/954/MR6_grant_board_role_no_release.sql +14 -0
  26. package/tests/mutations/954/MR7_set_board_authority_ceiling_no_release.sql +14 -0
  27. package/tests/mutations/954/MW1_post_board_message_unbound.sql +25 -0
  28. package/tests/mutations/954/MW2_send_direct_message_unbound.sql +25 -0
  29. package/tests/mutations/954/MW3_send_multicast_message_unbound.sql +25 -0
  30. package/tests/mutations/954/MW4_create_tasking_delivery_unbound.sql +25 -0
  31. package/tests/mutations/954/MW5_append_task_event_unbound.sql +25 -0
  32. package/tests/mutations/954/MW6_grant_board_role_unbound.sql +25 -0
  33. package/tests/mutations/954/MW7_set_board_authority_ceiling_unbound.sql +25 -0
  34. package/tests/mutations/954/MX1_bind_session_level.sql +13 -0
  35. package/tests/mutations/954/MX2_release_session_level.sql +13 -0
  36. package/tests/mutations/954/run.sh +93 -0
@@ -0,0 +1,695 @@
1
+ -- #954: a signed write is checked against the SIGNER's board seat and thread access.
2
+ --
3
+ -- THE DEFECT. Every signed_* wrapper takes its actor from p_gateway_decision.agent_id and calls the
4
+ -- unsigned RPC as service_role. The seat and access gates the RPC consults short-circuited on
5
+ -- _is_service_role() before they read anyone's membership, so the signer's own seat was never
6
+ -- checked: an agent with a valid signing key and no seat on board X could post, DM, multicast,
7
+ -- append task events and create tasking deliveries on X, and could move its own empty thread onto
8
+ -- X (post_board_message with its thread and X's board id). signed_grant_board_role and
9
+ -- signed_set_board_authority_ceiling were not affected: their inner functions check the passed
10
+ -- actor's own membership.
11
+ --
12
+ -- THE FIX, AND WHY IT IS IN THE GATES. A signed_* wrapper binds its signer as a transaction-local
13
+ -- context, and every seat/access gate evaluates THAT agent -- with the same membership and access
14
+ -- expression the authenticated path evaluates for the session -- instead of short-circuiting.
15
+ -- What is NOT the same: the session's subject is current_agent_id(), which only resolves an
16
+ -- active agent with a valid credential; the signer is the gateway's agent_id as given. Its status
17
+ -- and key are verified by the gateway before dispatch, and re-checked in the transaction only by
18
+ -- the two authority wrappers (_assert_signed_authority_signer_live, #269). Not changed here.
19
+ -- * Not in the wrappers: a wrapper-side check would have to re-derive what each delegate checks
20
+ -- (thread access, board access, board send role, post policy, task -> thread, descriptor and
21
+ -- recipient resolution, the post-lock re-checks) and would drift from it. In the gates, a gate
22
+ -- a delegate reaches tomorrow is covered the day it is reached.
23
+ -- * Not an explicit actor parameter on the gates: they are called from RLS policies and from
24
+ -- dozens of unsigned RPCs; every caller would change.
25
+ -- * Binding happens INSIDE _signed_write_actor_id, which every wrapper already calls to derive its
26
+ -- actor: a wrapper cannot obtain a signed actor without binding it. Each wrapper releases the
27
+ -- context before it returns. A refused call rolls the binding back with its (sub)transaction.
28
+ -- * The binding is TRANSACTION-local (set_config(..., true)): it cannot outlive the transaction
29
+ -- on a pooled backend. The test pins the third argument of both set_config calls.
30
+ -- * The context is honoured ONLY under service_role. Setting it in any other session changes
31
+ -- nothing: an authenticated caller is always evaluated as current_agent_id().
32
+ -- * A context left set under service_role -- a wrapper that forgot to release, or a caller that
33
+ -- set it -- only narrows what that transaction may do: the gates evaluate that agent instead
34
+ -- of passing, and _resolved_actor_agent_id accepts that agent alone and still requires it to
35
+ -- be named (a NULL actor raises 22023, as it does with no context). It never lets a call act
36
+ -- as an agent the caller did not name.
37
+ --
38
+ -- WHO IS NOT CHANGED. A service_role caller that has not entered a signed_* wrapper -- the Edge
39
+ -- Functions in supabase/functions and Portal's server-side calls (post_board_message, join_board,
40
+ -- create_or_find_thread, resolve_board_request, ...) -- binds nothing, so every gate still
41
+ -- short-circuits for it exactly as before. The authenticated path is unchanged: with no service
42
+ -- role the gates read current_agent_id(), as before.
43
+ --
44
+ -- Also bound: _resolved_actor_agent_id. Inside a signed wrapper a supplied actor that differs from
45
+ -- the signer raises 42501, and no supplied actor raises 22023 (as for any service_role caller).
46
+ -- Every call site on the signed path passes the signer already, so this changes no outcome today;
47
+ -- it removes the last service_role short-circuit on the path that resolves WHO acts.
48
+ --
49
+ -- Class: tests/agent_board_954_signed_seat_gates.test.sql derives every signed_* wrapper from
50
+ -- pg_proc and requires each to refuse an unseated signer, and classifies every service_role branch
51
+ -- reachable from a wrapper.
52
+ --
53
+ -- DEPLOY. One transaction; lock_timeout is a transaction-local 5 s when the applier left it unset.
54
+ -- CREATE OR REPLACE FUNCTION only: no table, view or policy is touched. agent_board.schema_version
55
+ -- stays 8 (no shape change).
56
+
57
+ do $s0$
58
+ begin
59
+ if current_setting('lock_timeout') in ('0', '0ms', '0s') then
60
+ perform set_config('lock_timeout', '5s', true);
61
+ end if;
62
+ end
63
+ $s0$;
64
+
65
+ -- =============================================================================
66
+ -- 1. The signer context
67
+ -- =============================================================================
68
+
69
+ -- The signer a running signed_* wrapper bound, or NULL. NULL for every session that is not
70
+ -- service_role, whatever the setting says: only service_role runs the wrappers.
71
+ create or replace function agent_board._signed_write_actor_context()
72
+ returns uuid
73
+ language sql
74
+ stable
75
+ security definer
76
+ set search_path = ''
77
+ as $fn$
78
+ select case
79
+ when agent_board._is_service_role()
80
+ then nullif(pg_catalog.current_setting('agent_board.signed_write_actor', true), '')::uuid
81
+ end
82
+ $fn$;
83
+
84
+ create or replace function agent_board._release_signed_write_actor()
85
+ returns void
86
+ language plpgsql
87
+ volatile
88
+ security definer
89
+ set search_path = ''
90
+ as $fn$
91
+ begin
92
+ perform pg_catalog.set_config('agent_board.signed_write_actor', '', true);
93
+ end;
94
+ $fn$;
95
+
96
+ -- The seat gates' two questions. Under service_role with no bound signer: bypass, as before.
97
+ -- Under service_role inside a signed wrapper: no bypass, and the subject is the signer.
98
+ -- Otherwise: no bypass, and the subject is the session's current_agent_id(), as before.
99
+ create or replace function agent_board._seat_gate_bypass()
100
+ returns boolean
101
+ language sql
102
+ stable
103
+ security definer
104
+ set search_path = ''
105
+ as $fn$
106
+ select agent_board._is_service_role()
107
+ and agent_board._signed_write_actor_context() is null
108
+ $fn$;
109
+
110
+ create or replace function agent_board._seat_gate_agent_id()
111
+ returns uuid
112
+ language sql
113
+ stable
114
+ security definer
115
+ set search_path = ''
116
+ as $fn$
117
+ select case
118
+ when agent_board._is_service_role() then agent_board._signed_write_actor_context()
119
+ else agent_board.current_agent_id()
120
+ end
121
+ $fn$;
122
+
123
+ -- =============================================================================
124
+ -- 2. Binding: _signed_write_actor_id binds the actor it returns
125
+ -- =============================================================================
126
+ create or replace function agent_board._signed_write_actor_id(p_payload jsonb, p_gateway_decision jsonb, p_actor_field text)
127
+ returns uuid
128
+ language plpgsql
129
+ security definer
130
+ set search_path = agent_board, public
131
+ as $fn$
132
+ declare
133
+ v_actor uuid;
134
+ v_payload_actor uuid;
135
+ begin
136
+ v_actor := nullif(p_gateway_decision ->> 'agent_id', '')::uuid;
137
+ if v_actor is null then
138
+ raise exception 'actor_mismatch: signed write gateway actor is required' using errcode = '42501';
139
+ end if;
140
+
141
+ v_payload_actor := nullif(p_payload ->> p_actor_field, '')::uuid;
142
+ if v_payload_actor is not null and v_payload_actor <> v_actor then
143
+ raise exception 'actor_mismatch: signed write payload actor must match gateway actor' using errcode = '42501';
144
+ end if;
145
+
146
+ -- #954: from here until the wrapper releases it, every seat gate evaluates this agent.
147
+ perform pg_catalog.set_config('agent_board.signed_write_actor', v_actor::text, true);
148
+
149
+ return v_actor;
150
+ end;
151
+ $fn$;
152
+
153
+ -- =============================================================================
154
+ -- 3. The seat and access gates
155
+ -- =============================================================================
156
+ -- Each body is its previous body with _is_service_role() replaced by _seat_gate_bypass() and
157
+ -- current_agent_id() replaced by _seat_gate_agent_id(). Nothing else changes.
158
+
159
+ create or replace function agent_board._current_agent_has_board_access(p_board_id uuid)
160
+ returns boolean
161
+ language sql
162
+ stable
163
+ security definer
164
+ set search_path = ''
165
+ as $fn$
166
+ select
167
+ agent_board._seat_gate_bypass()
168
+ or exists (
169
+ select 1
170
+ from agent_board.board_memberships bm
171
+ where bm.board_id = p_board_id
172
+ and bm.agent_id = agent_board._seat_gate_agent_id()
173
+ and bm.membership_state in ('joined', 'subscribed')
174
+ )
175
+ $fn$;
176
+
177
+ create or replace function agent_board._current_agent_can_send_to_board(p_board_id uuid)
178
+ returns boolean
179
+ language sql
180
+ stable
181
+ security definer
182
+ set search_path = ''
183
+ as $fn$
184
+ select
185
+ agent_board._seat_gate_bypass()
186
+ or exists (
187
+ select 1
188
+ from agent_board.board_memberships bm
189
+ where bm.board_id = p_board_id
190
+ and bm.agent_id = agent_board._seat_gate_agent_id()
191
+ and bm.membership_state in ('joined', 'subscribed')
192
+ and bm.role <> 'observer'
193
+ )
194
+ $fn$;
195
+
196
+ create or replace function agent_board._current_agent_can_access_thread(p_thread_id uuid)
197
+ returns boolean
198
+ language sql
199
+ stable
200
+ security definer
201
+ set search_path = ''
202
+ as $fn$
203
+ select
204
+ agent_board._seat_gate_bypass()
205
+ or agent_board._agent_can_access_thread(p_thread_id, agent_board._seat_gate_agent_id())
206
+ $fn$;
207
+
208
+ create or replace function agent_board._current_agent_can_post_to_thread(p_thread_id uuid)
209
+ returns boolean
210
+ language sql
211
+ stable
212
+ security definer
213
+ set search_path = ''
214
+ as $fn$
215
+ select agent_board._seat_gate_bypass()
216
+ or coalesce(
217
+ (
218
+ select case
219
+ when t.post_policy = 'inherit' and t.board_id is not null
220
+ then agent_board._current_agent_can_send_to_board(t.board_id)
221
+ else agent_board._current_agent_can_access_thread(p_thread_id)
222
+ end
223
+ from agent_board.threads t
224
+ where t.id = p_thread_id
225
+ ),
226
+ false
227
+ )
228
+ $fn$;
229
+
230
+ create or replace function agent_board._current_agent_can_access_task(p_task_id uuid)
231
+ returns boolean
232
+ language sql
233
+ stable
234
+ security definer
235
+ set search_path = ''
236
+ as $fn$
237
+ select
238
+ agent_board._seat_gate_bypass()
239
+ or exists (
240
+ select 1
241
+ from agent_board.tasks t
242
+ where t.id = p_task_id
243
+ and (
244
+ t.created_by_agent_id = agent_board._seat_gate_agent_id()
245
+ or t.assigned_agent_id = agent_board._seat_gate_agent_id()
246
+ or agent_board._current_agent_can_access_thread(t.thread_id)
247
+ )
248
+ )
249
+ $fn$;
250
+
251
+ create or replace function agent_board._current_agent_can_mutate_task(p_task_id uuid)
252
+ returns boolean
253
+ language sql
254
+ stable
255
+ security definer
256
+ set search_path = ''
257
+ as $fn$
258
+ select agent_board._seat_gate_bypass()
259
+ or exists (
260
+ select 1
261
+ from agent_board.tasks t
262
+ where t.id = p_task_id
263
+ and (
264
+ agent_board._current_agent_can_post_to_thread(t.thread_id)
265
+ or agent_board._seat_gate_agent_id() = t.assigned_agent_id
266
+ or agent_board._seat_gate_agent_id() = t.created_by_agent_id
267
+ )
268
+ )
269
+ $fn$;
270
+
271
+ -- =============================================================================
272
+ -- 4. Actor resolution under a bound signer
273
+ -- =============================================================================
274
+ create or replace function agent_board._resolved_actor_agent_id(p_supplied_agent_id uuid, p_param_name text)
275
+ returns uuid
276
+ language plpgsql
277
+ stable
278
+ security definer
279
+ set search_path = ''
280
+ as $fn$
281
+ declare
282
+ v_current_agent_id uuid;
283
+ v_signer uuid;
284
+ begin
285
+ if agent_board._is_service_role() then
286
+ if p_supplied_agent_id is null then
287
+ raise exception '% is required for service_role callers', p_param_name using errcode = '22023';
288
+ end if;
289
+
290
+ -- #954: inside a signed_* wrapper only the signer may act. Never resolves an actor the caller
291
+ -- did not name, so a context left set can only narrow a later service_role call.
292
+ v_signer := agent_board._signed_write_actor_context();
293
+ if v_signer is not null and p_supplied_agent_id <> v_signer then
294
+ raise exception '% must match the signed write actor', p_param_name using errcode = '42501';
295
+ end if;
296
+ return p_supplied_agent_id;
297
+ end if;
298
+
299
+ v_current_agent_id := agent_board.current_agent_id();
300
+ if v_current_agent_id is null then
301
+ raise exception 'current agent principal not resolved' using errcode = '42501';
302
+ end if;
303
+
304
+ if p_supplied_agent_id is not null and p_supplied_agent_id <> v_current_agent_id then
305
+ raise exception '% must match current_agent_id()', p_param_name using errcode = '42501';
306
+ end if;
307
+
308
+ return v_current_agent_id;
309
+ end;
310
+ $fn$;
311
+
312
+ -- =============================================================================
313
+ -- 5. The wrappers release the signer before they return
314
+ -- =============================================================================
315
+ -- Each body is its previous body with one statement added before `return query`.
316
+
317
+ create or replace function agent_board.signed_post_board_message(p_payload jsonb, p_gateway_decision jsonb)
318
+ 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)
319
+ LANGUAGE plpgsql
320
+ SECURITY DEFINER
321
+ SET search_path TO 'agent_board', 'public'
322
+ AS $function$
323
+ declare
324
+ v_row record;
325
+ v_evidence_id uuid;
326
+ v_actor uuid;
327
+ begin
328
+ v_actor := agent_board._signed_write_actor_id(p_payload, p_gateway_decision, 'p_author_agent_id');
329
+ select *
330
+ into v_row
331
+ from agent_board.post_board_message(
332
+ (p_payload ->> 'p_thread_id')::uuid,
333
+ v_actor,
334
+ (p_payload ->> 'p_board_id')::uuid,
335
+ p_payload ->> 'p_subject',
336
+ p_payload ->> 'p_body',
337
+ coalesce(p_payload ->> 'p_message_type', 'comment'),
338
+ coalesce(p_payload ->> 'p_priority', 'medium'),
339
+ nullif(p_payload ->> 'p_idempotency_key', ''),
340
+ 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)),
341
+ p_reply_to_message_id => nullif(p_payload ->> 'p_reply_to_message_id', '')::uuid
342
+ );
343
+
344
+ v_evidence_id := agent_board._record_signed_write_evidence('message', v_row.message_id, 'post_board_message', p_payload, p_gateway_decision);
345
+
346
+ perform agent_board._release_signed_write_actor();
347
+
348
+ return query
349
+ 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;
350
+ end;
351
+ $function$;
352
+
353
+ create or replace function agent_board.signed_send_direct_message(p_payload jsonb, p_gateway_decision jsonb)
354
+ 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)
355
+ LANGUAGE plpgsql
356
+ SECURITY DEFINER
357
+ SET search_path TO 'agent_board', 'public'
358
+ AS $function$
359
+ declare
360
+ v_row record;
361
+ v_evidence_id uuid;
362
+ v_actor uuid;
363
+ begin
364
+ v_actor := agent_board._signed_write_actor_id(p_payload, p_gateway_decision, 'p_author_agent_id');
365
+ select *
366
+ into v_row
367
+ from agent_board.send_direct_message(
368
+ (p_payload ->> 'p_thread_id')::uuid,
369
+ v_actor,
370
+ (p_payload ->> 'p_recipient_agent_id')::uuid,
371
+ p_payload ->> 'p_subject',
372
+ p_payload ->> 'p_body',
373
+ coalesce(p_payload ->> 'p_message_type', 'comment'),
374
+ coalesce(p_payload ->> 'p_priority', 'medium'),
375
+ nullif(p_payload ->> 'p_idempotency_key', ''),
376
+ 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)),
377
+ p_reply_to_message_id => nullif(p_payload ->> 'p_reply_to_message_id', '')::uuid
378
+ );
379
+
380
+ v_evidence_id := agent_board._record_signed_write_evidence('message', v_row.message_id, 'send_direct_message', p_payload, p_gateway_decision);
381
+
382
+ perform agent_board._release_signed_write_actor();
383
+
384
+ return query
385
+ 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;
386
+ end;
387
+ $function$;
388
+
389
+ create or replace function agent_board.signed_send_multicast_message(p_payload jsonb, p_gateway_decision jsonb)
390
+ 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)
391
+ LANGUAGE plpgsql
392
+ SECURITY DEFINER
393
+ SET search_path TO 'agent_board', 'public'
394
+ AS $function$
395
+ declare
396
+ v_row record;
397
+ v_actor uuid := agent_board._signed_write_actor_id(p_payload, p_gateway_decision, 'p_author_agent_id');
398
+ v_evidence_id uuid;
399
+ v_recipient_ids uuid[];
400
+ begin
401
+ if p_payload ? 'p_recipient_agent_ids' then
402
+ select array_agg(value::uuid) into v_recipient_ids from jsonb_array_elements_text(p_payload -> 'p_recipient_agent_ids');
403
+ select * into v_row from agent_board.send_multicast_message(
404
+ (p_payload ->> 'p_thread_id')::uuid, v_actor, v_recipient_ids,
405
+ p_payload ->> 'p_subject', p_payload ->> 'p_body', coalesce(p_payload ->> 'p_message_type', 'comment'),
406
+ coalesce(p_payload ->> 'p_priority', 'medium'), nullif(p_payload ->> 'p_idempotency_key', ''),
407
+ 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)),
408
+ p_reply_to_message_id => nullif(p_payload ->> 'p_reply_to_message_id', '')::uuid
409
+ );
410
+ else
411
+ select * into v_row from agent_board.send_multicast_message(
412
+ (p_payload ->> 'p_thread_id')::uuid, v_actor, p_payload -> 'p_recipient_descriptors',
413
+ coalesce(p_payload ->> 'p_addressing_mode', 'addressing_v1'), p_payload ->> 'p_subject', p_payload ->> 'p_body',
414
+ coalesce(p_payload ->> 'p_message_type', 'comment'), coalesce(p_payload ->> 'p_priority', 'medium'),
415
+ nullif(p_payload ->> 'p_idempotency_key', ''), coalesce(p_payload -> 'p_metadata', '{}'::jsonb),
416
+ p_reply_to_message_id => nullif(p_payload ->> 'p_reply_to_message_id', '')::uuid
417
+ );
418
+ end if;
419
+ v_evidence_id := agent_board._record_signed_write_evidence('message', v_row.message_id, 'send_multicast_message', p_payload, p_gateway_decision);
420
+ perform agent_board._release_signed_write_actor();
421
+
422
+ 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;
423
+ end;
424
+ $function$;
425
+
426
+ create or replace function agent_board.signed_create_tasking_delivery(p_payload jsonb, p_gateway_decision jsonb)
427
+ RETURNS TABLE(task_id uuid, created_event_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, updated_at timestamp with time zone)
428
+ LANGUAGE plpgsql
429
+ SECURITY DEFINER
430
+ SET search_path TO 'agent_board', 'public'
431
+ AS $function$
432
+ declare
433
+ v_row record;
434
+ v_actor uuid := agent_board._signed_write_actor_id(p_payload, p_gateway_decision, 'p_created_by_agent_id');
435
+ v_evidence_id uuid;
436
+ v_recipient_ids uuid[];
437
+ begin
438
+ if p_payload ? 'p_recipient_agent_ids' or p_payload ? 'p_board_id' then
439
+ if p_payload ? 'p_recipient_agent_ids' then
440
+ select array_agg(value::uuid) into v_recipient_ids from jsonb_array_elements_text(p_payload -> 'p_recipient_agent_ids');
441
+ end if;
442
+ select * into v_row from agent_board.create_tasking_delivery(
443
+ (p_payload ->> 'p_thread_id')::uuid, v_actor, p_payload ->> 'p_title', p_payload ->> 'p_details',
444
+ v_recipient_ids, nullif(p_payload ->> 'p_board_id', '')::uuid, coalesce(p_payload ->> 'p_priority', 'medium'),
445
+ coalesce(p_payload ->> 'p_orchestration_mode', 'distributed'), nullif(p_payload ->> 'p_idempotency_key', ''),
446
+ 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))
447
+ );
448
+ else
449
+ select * into v_row from agent_board.create_tasking_delivery(
450
+ (p_payload ->> 'p_thread_id')::uuid, v_actor, p_payload ->> 'p_title', p_payload ->> 'p_details',
451
+ p_payload -> 'p_recipient_descriptors', p_payload ->> 'p_board_slug', coalesce(p_payload ->> 'p_addressing_mode', 'addressing_v1'),
452
+ coalesce(p_payload ->> 'p_priority', 'medium'), coalesce(p_payload ->> 'p_orchestration_mode', 'distributed'),
453
+ nullif(p_payload ->> 'p_idempotency_key', ''), coalesce(p_payload -> 'p_metadata', '{}'::jsonb)
454
+ );
455
+ end if;
456
+ v_evidence_id := agent_board._record_signed_write_evidence('task_event', v_row.created_event_id, 'create_tasking_delivery', p_payload, p_gateway_decision);
457
+ perform agent_board._release_signed_write_actor();
458
+
459
+ return query select v_row.task_id, v_row.created_event_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, v_row.updated_at;
460
+ end;
461
+ $function$;
462
+
463
+ create or replace function agent_board.signed_append_task_event(p_payload jsonb, p_gateway_decision jsonb)
464
+ RETURNS TABLE(task_id uuid, thread_id uuid, event_id uuid, event_sequence bigint, signature_evidence_id uuid, verification_status text, updated_at timestamp with time zone)
465
+ LANGUAGE plpgsql
466
+ SECURITY DEFINER
467
+ SET search_path TO 'agent_board', 'public'
468
+ AS $function$
469
+ declare
470
+ v_row record;
471
+ v_evidence_id uuid;
472
+ v_actor uuid;
473
+ begin
474
+ v_actor := agent_board._signed_write_actor_id(p_payload, p_gateway_decision, 'p_actor_agent_id');
475
+ select *
476
+ into v_row
477
+ from agent_board._append_task_event('attested:evidence-row',
478
+ (p_payload ->> 'p_task_id')::uuid,
479
+ v_actor,
480
+ p_payload ->> 'p_event_type',
481
+ coalesce(p_payload -> 'p_payload', '{}'::jsonb) || jsonb_build_object('signed_write', jsonb_build_object('verification_status', coalesce(p_gateway_decision ->> 'verification_status', 'unsigned'), 'redacted', true)),
482
+ nullif(p_payload ->> 'p_status', ''),
483
+ nullif(p_payload ->> 'p_assigned_agent_id', '')::uuid,
484
+ nullif(p_payload ->> 'p_completed_at', '')::timestamptz
485
+ );
486
+
487
+ v_evidence_id := agent_board._record_signed_write_evidence('task_event', v_row.event_id, 'append_task_event', p_payload, p_gateway_decision);
488
+
489
+ perform agent_board._release_signed_write_actor();
490
+
491
+ return query
492
+ select v_row.task_id, v_row.thread_id, v_row.event_id, v_row.event_sequence, v_evidence_id, coalesce(p_gateway_decision ->> 'verification_status', 'unsigned'), v_row.updated_at;
493
+ end;
494
+ $function$;
495
+
496
+ create or replace function agent_board.signed_grant_board_role(p_payload jsonb, p_gateway_decision jsonb)
497
+ RETURNS TABLE(board_id uuid, agent_id uuid, role text, signature_evidence_id uuid, verification_status text, updated_at timestamp with time zone)
498
+ LANGUAGE plpgsql
499
+ SECURITY DEFINER
500
+ SET search_path TO 'agent_board', 'public'
501
+ AS $function$
502
+ declare
503
+ v_row record;
504
+ v_actor uuid;
505
+ v_evidence_id uuid;
506
+ v_board uuid := (p_payload ->> 'p_board_id')::uuid;
507
+ v_grantee uuid := (p_payload ->> 'p_agent_id')::uuid;
508
+ begin
509
+ -- The grantor is the gateway-verified signer. _signed_write_actor_id raises 42501 when
510
+ -- the gateway names no actor, and raises actor_mismatch when the payload names a
511
+ -- DIFFERENT one -- so a payload p_grantor_agent_id can never become the grantor. This
512
+ -- value is what grant_board_role binds (through its own _resolved_actor_agent_id) and
513
+ -- what the evidence row names; they cannot diverge.
514
+ v_actor := agent_board._signed_write_actor_id(p_payload, p_gateway_decision, 'p_grantor_agent_id');
515
+
516
+ -- BOARD ADVISORY LOCK FIRST -- this is what makes the wrapper acyclic against
517
+ -- onboard_federated_fleet_agent. Without it the wrapper's order is
518
+ -- board_memberships(grantee) -> agents(signer), while onboarding takes
519
+ -- agents(20260901000110:349) -> board_memberships(:397): a genuine ABBA between two HONEST
520
+ -- callers, reproduced as `deadlock detected` on board_memberships with an owner who both
521
+ -- created a fleet invite and concurrently grants the enrollee a role -- routine operands on
522
+ -- one board. The inner grant_board_role takes no advisory lock (the catalog-pinned set of
523
+ -- ceiling-advisory takers is exactly onboard_federated_fleet_agent and
524
+ -- set_board_authority_ceiling), so the wrapper must take it.
525
+ --
526
+ -- Mutual exclusion, NOT a re-derived ordering. Both authority wrappers now take this as
527
+ -- their FIRST lock; onboarding takes it at :290 holding only board_invite_tokens and
528
+ -- fleet_onboarding_invite_bounds -- relations no authority wrapper ever touches -- so the
529
+ -- two cannot form a cycle whatever either does afterwards. That property survives a new lock
530
+ -- being added downstream, which an ordering argument would not.
531
+ --
532
+ -- Cost, accepted: a signed grant now serialises with onboarding and with ceiling writes on
533
+ -- the SAME board. Boards are the unit of contention and these are all authority mutations.
534
+ perform agent_board._lock_board_authority_ceiling(v_board);
535
+
536
+ select *
537
+ into v_row
538
+ from agent_board.grant_board_role(
539
+ v_board,
540
+ v_grantee,
541
+ p_payload ->> 'p_grantee_role',
542
+ v_actor
543
+ );
544
+
545
+ -- #269. The gateway's decision was made in an EARLIER transaction; a suspension or key
546
+ -- revocation can have committed since. Revalidate the signer under a share lock so a
547
+ -- concurrent revoke serializes against this write instead of racing it. After the inner
548
+ -- call by design (lock order, and it keeps the inner gates' errors first) -- same
549
+ -- transaction, so a raise here rolls the grant back.
550
+ perform agent_board._assert_signed_authority_signer_live(v_actor, p_gateway_decision);
551
+
552
+ v_evidence_id := agent_board._record_signed_write_evidence(
553
+ 'external',
554
+ null,
555
+ 'grant_board_role',
556
+ p_payload,
557
+ p_gateway_decision || jsonb_build_object(
558
+ 'external_evidence_ref',
559
+ 'board-authority:grant_board_role:' || v_board::text || ':' || v_grantee::text
560
+ )
561
+ );
562
+
563
+ perform agent_board._release_signed_write_actor();
564
+
565
+ return query
566
+ select v_row.board_id, v_row.agent_id, v_row.role, v_evidence_id,
567
+ coalesce(p_gateway_decision ->> 'verification_status', 'unsigned'), v_row.updated_at;
568
+ end;
569
+ $function$;
570
+
571
+ create or replace function agent_board.signed_set_board_authority_ceiling(p_payload jsonb, p_gateway_decision jsonb)
572
+ RETURNS TABLE(ceiling_board_id uuid, ceiling_max_grantable_role text, signature_evidence_id uuid, verification_status text)
573
+ LANGUAGE plpgsql
574
+ SECURITY DEFINER
575
+ SET search_path TO 'agent_board', 'public'
576
+ AS $function$
577
+ declare
578
+ v_row record;
579
+ v_actor uuid;
580
+ v_evidence_id uuid;
581
+ v_board uuid := (p_payload ->> 'p_board_id')::uuid;
582
+ begin
583
+ v_actor := agent_board._signed_write_actor_id(p_payload, p_gateway_decision, 'p_actor_agent_id');
584
+
585
+ select *
586
+ into v_row
587
+ from agent_board.set_board_authority_ceiling(
588
+ v_board,
589
+ p_payload ->> 'p_max_grantable_role',
590
+ v_actor
591
+ );
592
+
593
+ -- #269. See signed_grant_board_role. The position matters most here: the inner setter takes
594
+ -- the board-keyed advisory lock and then reaches boards through the ceiling FK, so
595
+ -- revalidating afterwards gives advisory -> boards -> agents -> keys, which is
596
+ -- onboard_federated_fleet_agent's order. Hoisting this above the inner call would invert
597
+ -- against it on (advisory, agents).
598
+ perform agent_board._assert_signed_authority_signer_live(v_actor, p_gateway_decision);
599
+
600
+ v_evidence_id := agent_board._record_signed_write_evidence(
601
+ 'external',
602
+ null,
603
+ 'set_board_authority_ceiling',
604
+ p_payload,
605
+ p_gateway_decision || jsonb_build_object(
606
+ 'external_evidence_ref',
607
+ 'board-authority:set_board_authority_ceiling:' || v_board::text || ':' || v_actor::text
608
+ )
609
+ );
610
+
611
+ perform agent_board._release_signed_write_actor();
612
+
613
+ return query
614
+ select v_row.ceiling_board_id, v_row.ceiling_max_grantable_role, v_evidence_id,
615
+ coalesce(p_gateway_decision ->> 'verification_status', 'unsigned');
616
+ end;
617
+ $function$;
618
+
619
+ -- =============================================================================
620
+ -- 6. Privileges and comments, restated for every routine this migration creates or replaces
621
+ -- =============================================================================
622
+ -- New internals: owner only.
623
+ revoke all on function agent_board._signed_write_actor_context() from public, anon, authenticated, service_role;
624
+ revoke all on function agent_board._release_signed_write_actor() from public, anon, authenticated, service_role;
625
+ revoke all on function agent_board._seat_gate_bypass() from public, anon, authenticated, service_role;
626
+ revoke all on function agent_board._seat_gate_agent_id() from public, anon, authenticated, service_role;
627
+
628
+ -- Replaced: the same EXECUTE set each had before.
629
+ revoke all on function agent_board._signed_write_actor_id(jsonb, jsonb, text) from public, anon, authenticated, service_role;
630
+ revoke all on function agent_board._current_agent_has_board_access(uuid) from public, anon, authenticated, service_role;
631
+ grant execute on function agent_board._current_agent_has_board_access(uuid) to authenticated, service_role;
632
+ revoke all on function agent_board._current_agent_can_send_to_board(uuid) from public, anon, authenticated, service_role;
633
+ grant execute on function agent_board._current_agent_can_send_to_board(uuid) to service_role;
634
+ revoke all on function agent_board._current_agent_can_access_thread(uuid) from public, anon, authenticated, service_role;
635
+ grant execute on function agent_board._current_agent_can_access_thread(uuid) to authenticated, service_role;
636
+ revoke all on function agent_board._current_agent_can_post_to_thread(uuid) from public, anon, authenticated, service_role;
637
+ revoke all on function agent_board._current_agent_can_access_task(uuid) from public, anon, authenticated, service_role;
638
+ grant execute on function agent_board._current_agent_can_access_task(uuid) to service_role;
639
+ revoke all on function agent_board._current_agent_can_mutate_task(uuid) from public, anon, authenticated, service_role;
640
+ revoke all on function agent_board._resolved_actor_agent_id(uuid, text) from public, anon, authenticated, service_role;
641
+ grant execute on function agent_board._resolved_actor_agent_id(uuid, text) to service_role;
642
+
643
+ revoke all on function agent_board.signed_post_board_message(jsonb, jsonb) from public, anon, authenticated, service_role;
644
+ grant execute on function agent_board.signed_post_board_message(jsonb, jsonb) to service_role;
645
+ revoke all on function agent_board.signed_send_direct_message(jsonb, jsonb) from public, anon, authenticated, service_role;
646
+ grant execute on function agent_board.signed_send_direct_message(jsonb, jsonb) to service_role;
647
+ revoke all on function agent_board.signed_send_multicast_message(jsonb, jsonb) from public, anon, authenticated, service_role;
648
+ grant execute on function agent_board.signed_send_multicast_message(jsonb, jsonb) to service_role;
649
+ revoke all on function agent_board.signed_create_tasking_delivery(jsonb, jsonb) from public, anon, authenticated, service_role;
650
+ grant execute on function agent_board.signed_create_tasking_delivery(jsonb, jsonb) to service_role;
651
+ revoke all on function agent_board.signed_append_task_event(jsonb, jsonb) from public, anon, authenticated, service_role;
652
+ grant execute on function agent_board.signed_append_task_event(jsonb, jsonb) to service_role;
653
+ revoke all on function agent_board.signed_grant_board_role(jsonb, jsonb) from public, anon, authenticated, service_role;
654
+ grant execute on function agent_board.signed_grant_board_role(jsonb, jsonb) to service_role;
655
+ revoke all on function agent_board.signed_set_board_authority_ceiling(jsonb, jsonb) from public, anon, authenticated, service_role;
656
+ grant execute on function agent_board.signed_set_board_authority_ceiling(jsonb, jsonb) to service_role;
657
+
658
+ comment on function agent_board._signed_write_actor_context() is
659
+ '#954: the signer a running signed_* wrapper bound (transaction-local setting agent_board.signed_write_actor), or NULL. NULL in every session that is not service_role, whatever the setting holds. Read by the seat gates through _seat_gate_bypass/_seat_gate_agent_id and by _resolved_actor_agent_id. Internal; owner-only EXECUTE.';
660
+ comment on function agent_board._release_signed_write_actor() is
661
+ '#954: ends the signer context a signed_* wrapper bound through _signed_write_actor_id. Every signed_* wrapper calls it before it returns. Internal; owner-only EXECUTE.';
662
+ comment on function agent_board._seat_gate_bypass() is
663
+ '#954: true only for a service_role session with no bound signer (Edge Functions, Portal server-side calls). Inside a signed_* wrapper it is false, so the gates evaluate the signer. Internal; owner-only EXECUTE.';
664
+ comment on function agent_board._seat_gate_agent_id() is
665
+ '#954: the agent the seat gates evaluate: the bound signer under service_role, current_agent_id() otherwise. Internal; owner-only EXECUTE.';
666
+ comment on function agent_board._signed_write_actor_id(jsonb, jsonb, text) is
667
+ 'Derives a signed write''s actor from the gateway decision (42501 actor_mismatch when absent, or when the payload names a different actor) and, since #954, binds it as the signer context every seat gate evaluates until the wrapper calls _release_signed_write_actor. Internal; owner-only EXECUTE.';
668
+ comment on function agent_board._current_agent_has_board_access(uuid) is
669
+ 'Session-derived read predicate used by authenticated RLS policies: a joined or subscribed membership of the evaluated agent. service_role with no bound signer short-circuits true; inside a signed_* wrapper (#954) the evaluated agent is the signer, otherwise current_agent_id(). Callable by authenticated and service_role.';
670
+ comment on function agent_board._current_agent_can_send_to_board(uuid) is
671
+ 'True iff the evaluated agent may send to the board: an active board member whose role is not observer. service_role with no bound signer short-circuits true; inside a signed_* wrapper (#954) the evaluated agent is the signer, otherwise current_agent_id(). The net-new send-path authz predicate (restricted-thread ACL is inherited from _current_agent_can_access_thread).';
672
+ comment on function agent_board._current_agent_can_access_thread(uuid) is
673
+ 'Thread access for the CURRENT session: service_role with no bound signer short-circuits true; inside a signed_* wrapper (#954) _agent_can_access_thread(p_thread_id, <signer>); otherwise _agent_can_access_thread(p_thread_id, current_agent_id()). The disjunct set lives in that helper and is not restated here. ACCESS ONCE HELD IS NEVER WITHDRAWN, AND THAT IS DELIBERATE (message-board#287, extended and RATIFIED for claims on message-board#291). The read_receipts, claims and inbox_items disjuncts are all PERMANENT: no role holds DELETE or TRUNCATE on any of those tables and no function body removes a row from them, so LEAVING A BOARD, LOSING A TASK ASSIGNMENT, OR RELEASING A CLAIM DOES NOT REVOKE ACCESS TO A THREAD THE AGENT ALREADY HELD. The rule is "you keep what you saw". For claims this is sharper than it looks and was ruled on explicitly: the claims disjunct filters on (thread_id, agent_id) and NOT on status or lease_expires_at, so a RELEASED or LONG-EXPIRED claim still grants access indefinitely. Two alternatives were considered and REJECTED on #291: (a) filtering the disjunct on an active, unexpired lease -- rejected because it reverses the #287 ruling for this one case and would strip access at deploy time from every holder of a released or expired claim; (b) recording the access separately when the claim is taken, so a stale row is not itself the key -- acknowledged as the more honest design, rejected for now on cost and because agents holding historical released claims would need backfilling or would silently lose access. A future migration that adds a status or lease filter here is REVERSING A RULING, not fixing a bug. What IS closed is the mint: mark_read (#287) and acquire_claim (#291) both gate the NAMED subject through _agent_can_access_thread, so a receipt or a claim can only ever record access already held. access_mode = ''restricted'' is UNREACHABLE through the shipped API -- no function writes threads.access_mode (it defaults to ''inherit'') and authenticated/service_role hold SELECT and only SELECT on agent_board.threads -- so the inherit disjunction governs every thread in production and the per-thread ACL added in #27 is dormant. Callable by authenticated for its RLS policies and by service_role.';
674
+ comment on function agent_board._current_agent_can_post_to_thread(uuid) is
675
+ 'OBSGATE (#78): may the evaluated agent post to this thread? inherit + stamped board -> non-observer board send role; inherit + no board -> thread access (DM/multicast unaffected); service_role with no bound signer -> true. Inside a signed_* wrapper (#954) the evaluated agent is the signer. Internal-only; PUBLIC EXECUTE revoked.';
676
+ comment on function agent_board._current_agent_can_access_task(uuid) is
677
+ 'May the evaluated agent read this task: its creator, its assignee, or an agent with access to its thread. service_role with no bound signer short-circuits true; inside a signed_* wrapper (#954) the evaluated agent is the signer, otherwise current_agent_id(). service_role EXECUTE only.';
678
+ comment on function agent_board._current_agent_can_mutate_task(uuid) is
679
+ 'OBSGATE-3 (#125): may the evaluated agent mutate this task (append events / change status)? A non-observer board sender on the task''s thread (board-less participant via the access fallback), or the task''s assignee, or its creator. service_role with no bound signer short-circuits true; inside a signed_* wrapper (#954) the evaluated agent is the signer. A board observer that is not a party to the task is denied. Internal-only, PUBLIC EXECUTE revoked.';
680
+ comment on function agent_board._resolved_actor_agent_id(uuid, text) is
681
+ 'Binds the acting agent fail-closed. authenticated: current_agent_id() (42501 when unresolved or when a supplied id differs). service_role: the supplied id (22023 when null); inside a signed_* wrapper (#954) it must also equal the bound signer (42501 otherwise). service_role EXECUTE only.';
682
+ comment on function agent_board.signed_post_board_message(jsonb, jsonb) is
683
+ '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.';
684
+ comment on function agent_board.signed_send_direct_message(jsonb, jsonb) is
685
+ '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.';
686
+ comment on function agent_board.signed_send_multicast_message(jsonb, jsonb) is
687
+ '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.';
688
+ comment on function agent_board.signed_create_tasking_delivery(jsonb, jsonb) is
689
+ 'Signed-write gateway wrapper (service_role only): create_tasking_delivery as the gateway-decided actor, by recipient ids/board or descriptors, recording signature evidence. #954: the thread and board gates evaluate the signer (bound by _signed_write_actor_id, released before return).';
690
+ comment on function agent_board.signed_append_task_event(jsonb, jsonb) is
691
+ 'Signed-write gateway wrapper (service_role only): _append_task_event as the gateway-decided actor, recording signature evidence. #954: the task access and mutate gates evaluate the signer (bound by _signed_write_actor_id, released before return).';
692
+ comment on function agent_board.signed_grant_board_role(jsonb, jsonb) is
693
+ '#247 signed-write gateway wrapper for grant_board_role. Takes the board-keyed _lock_board_authority_ceiling advisory lock FIRST, before the inner grant: without it the wrapper''s order is board_memberships(grantee) then agents(signer) while onboard_federated_fleet_agent takes agents then board_memberships, a reproduced ABBA deadlock between two honest callers. Both authority wrappers now take that advisory lock first, and onboarding requests it holding only invite-scoped rows no wrapper touches, so they are serialised per board rather than merely ordered. Resolves the grantor with _signed_write_actor_id (gateway actor required; a payload p_grantor_agent_id that differs raises actor_mismatch 42501), passes THAT principal to grant_board_role so the bound grantor and the recorded one cannot diverge, and records a signature_evidence row via _record_signed_write_evidence with source_kind=external and a server-derived external_evidence_ref naming the board and grantee. #269: after the grant and before the evidence row it calls _assert_signed_authority_signer_live, which requires the decision''s verification_status to be exactly ''verified'' (so a FAILED verification can no longer complete the grant and record ''failed'' beside it), then share-locks and revalidates the signer''s agents row and the decision''s signing key inside this transaction, so a suspension or key revocation racing the gateway''s separate verification call either serializes behind this write or fails it closed. Adds no authority: grant_board_role''s membership, ceiling and TOCTOU gates are untouched. service_role only, like every other signed_* wrapper (#118).';
694
+ comment on function agent_board.signed_set_board_authority_ceiling(jsonb, jsonb) is
695
+ '#247 signed-write gateway wrapper for set_board_authority_ceiling. Resolves the actor with _signed_write_actor_id (gateway actor required; a differing payload p_actor_agent_id raises actor_mismatch 42501) and passes it as p_actor_agent_id, so the owner gate authorizes the SAME principal the evidence row names. Records a signature_evidence row via _record_signed_write_evidence with source_kind=external and a server-derived external_evidence_ref. #269: between the ceiling upsert and the evidence row it calls _assert_signed_authority_signer_live, which requires the decision''s verification_status to be exactly ''verified'' and then share-locks and revalidates the signer''s agents row and the decision''s signing key inside this transaction; it sits after the inner call so the wrapper''s lock order stays advisory -> boards -> agents -> agent_signing_keys, matching onboard_federated_fleet_agent. Adds no authority: the owner gate still rejects any actor that is not an active board owner. service_role only, like every other signed_* wrapper (#118).';