@consiliency/agent-board-schema 1.76.0 → 1.79.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 (121) hide show
  1. package/fixtures/already-applied.json +12 -0
  2. package/migrations/20261120000200_agent_board_thread_key_serialize.sql +118 -0
  3. package/migrations/20261121000100_agent_board_thread_key_guards.sql +196 -0
  4. package/migrations/20261124000100_agent_board_step_up_enforcement.sql +1213 -0
  5. package/package.json +1 -1
  6. package/schema-manifest.json +30 -3
  7. package/src/deployment-drift-main.test.mjs +89 -6
  8. package/src/deployment-drift.test.mjs +20 -1
  9. package/src/tooling.test.mjs +9 -2
  10. package/tests/agent_board_717_message_replay_scope.test.sql +39 -2
  11. package/tests/agent_board_717_tasking_replay_scope.test.sql +21 -2
  12. package/tests/agent_board_role_guard.test.sql +3 -1
  13. package/tests/agent_board_send_outcome.test.sql +39 -1
  14. package/tests/agent_board_session_identity_approval_revocation.test.sql +5 -0
  15. package/tests/agent_board_step_up.test.sql +991 -0
  16. package/tests/agent_board_step_up_helper.test.sql +132 -28
  17. package/tests/agent_board_thread_key_guards.test.sql +186 -0
  18. package/tests/agent_board_thread_key_serialize.test.sql +182 -0
  19. package/tests/agent_board_write_enforcement_class.test.sql +3 -2
  20. package/tests/catalog/step_up_gated_closure.json +24 -0
  21. package/tests/fixtures/pgtap-unexposed.sql +9 -4
  22. package/tests/isolation/expected/create_or_find_thread_same_key_race.out +641 -0
  23. package/tests/isolation/expected/session_identity_links.out +4 -0
  24. package/tests/isolation/specs/create_or_find_thread_same_key_race.spec +252 -0
  25. package/tests/isolation/specs/session_identity_links.spec +5 -0
  26. package/tests/mutations/669/run.sh +12 -4
  27. package/tests/mutations/669b/M11_ceil_first.sql +10 -0
  28. package/tests/mutations/669b/M11_gate_first.sql +10 -0
  29. package/tests/mutations/669b/M11_grant_first.sql +10 -0
  30. package/tests/mutations/669b/M11_inv_first.sql +10 -0
  31. package/tests/mutations/669b/M11_mem_first.sql +10 -0
  32. package/tests/mutations/669b/M11_readmit_first.sql +10 -0
  33. package/tests/mutations/669b/M13a_gate_member_preset.sql +12 -0
  34. package/tests/mutations/669b/M13b_ungate_admin_preset.sql +12 -0
  35. package/tests/mutations/669b/M16_actor_is_target.sql +14 -0
  36. package/tests/mutations/669b/M19_drop_readmit.sql +9 -0
  37. package/tests/mutations/669b/M1_drop_grant.sql +9 -0
  38. package/tests/mutations/669b/M20_drop_d5_refusal.sql +9 -0
  39. package/tests/mutations/669b/M21_drop_removal.sql +9 -0
  40. package/tests/mutations/669b/M21b_only_removed.sql +9 -0
  41. package/tests/mutations/669b/M21c_gate_members.sql +12 -0
  42. package/tests/mutations/669b/M21d_requested_state.sql +9 -0
  43. package/tests/mutations/669b/M23b_api_wrapper_over_audit_writer.sql +6 -0
  44. package/tests/mutations/669b/M23c_drop_register_type_refusal.sql +9 -0
  45. package/tests/mutations/669b/M24_drop_kind_refusal.sql +9 -0
  46. package/tests/mutations/669b/M24b_drop_auth_bind_refusal.sql +9 -0
  47. package/tests/mutations/669b/M2a_drop_gate.sql +9 -0
  48. package/tests/mutations/669b/M2b_drop_ceiling.sql +9 -0
  49. package/tests/mutations/669b/M2c_drop_invite.sql +9 -0
  50. package/tests/mutations/669b/MAL2_drop_otp.sql +9 -0
  51. package/tests/mutations/669b/MAL3_admit_passkey.sql +9 -0
  52. package/tests/mutations/669b/MD7a_no_revocation.sql +2 -0
  53. package/tests/mutations/669b/MD7b_overwrite_revoked.sql +2 -0
  54. package/tests/mutations/669b/MD7c_revoke_members.sql +2 -0
  55. package/tests/mutations/669b/MD7d_revoke_expired.sql +2 -0
  56. package/tests/mutations/669b/ME1_wrapper_over_gate.sql +7 -0
  57. package/tests/mutations/669b/MEC2_write_after_helper.sql +10 -0
  58. package/tests/mutations/669b/MQX_query_to_xml_definer.sql +6 -0
  59. package/tests/mutations/669b/MQXb_ts_stat_other_schema.sql +4 -0
  60. package/tests/mutations/669b/MTR_trigger_route.sql +9 -0
  61. package/tests/mutations/669b/MTRb_new_assign.sql +11 -0
  62. package/tests/mutations/669b/MTRc_sync_assigns_value.sql +47 -0
  63. package/tests/mutations/669b/MTX1_tombstone_second_gated_call.sql +15 -0
  64. package/tests/mutations/669b/MTX2_tombstone_non_delegate_target.sql +10 -0
  65. package/tests/mutations/669b/MXS_other_schema_names_gated.sql +5 -0
  66. package/tests/mutations/669b/run.sh +83 -0
  67. package/tests/mutations/670/M18a_read_operation_default_dropped.sql +11 -0
  68. package/tests/mutations/670/M18b_read_operation_default_changed.sql +7 -0
  69. package/tests/mutations/670/M3-DM_helper_on_replay_branch.sql +10 -0
  70. package/tests/mutations/670/M3-MC_helper_on_replay_branch.sql +10 -0
  71. package/tests/mutations/s12/M0_identity.sql +56 -0
  72. package/tests/mutations/s12/M1_serialise_actor_key.sql +57 -0
  73. package/tests/mutations/s12/M1b_serialise_key_only.sql +57 -0
  74. package/tests/mutations/s12/M2_unique_index_no_handler.sql +9 -0
  75. package/tests/mutations/s12/M3_no_trim.sql +56 -0
  76. package/tests/mutations/s12/M4_casefold.sql +56 -0
  77. package/tests/mutations/s12/M5_lookup_ignores_actor.sql +56 -0
  78. package/tests/mutations/s12/M6_reuse_reports_false.sql +56 -0
  79. package/tests/mutations/s12/run.sh +112 -0
  80. package/tests/mutations/s12-fix/M0_identity.sql +83 -0
  81. package/tests/mutations/s12-fix/M10_security_invoker.sql +9 -0
  82. package/tests/mutations/s12-fix/M11_search_path_changed.sql +9 -0
  83. package/tests/mutations/s12-fix/M12_reuse_writes_task.sql +84 -0
  84. package/tests/mutations/s12-fix/M13_dead_inbox_write.sql +84 -0
  85. package/tests/mutations/s12-fix/M14_metadata_unchecked.sql +78 -0
  86. package/tests/mutations/s12-fix/M15_metadata_check_after_lock.sql +84 -0
  87. package/tests/mutations/s12-fix/M16_sql_null_metadata_refused.sql +83 -0
  88. package/tests/mutations/s12-fix/M17_isolation_unchecked.sql +70 -0
  89. package/tests/mutations/s12-fix/M18_isolation_check_after_lock.sql +82 -0
  90. package/tests/mutations/s12-fix/M19_isolation_rr_only.sql +83 -0
  91. package/tests/mutations/s12-fix/M1_lock_dropped.sql +78 -0
  92. package/tests/mutations/s12-fix/M1b_lock_key_only.sql +83 -0
  93. package/tests/mutations/s12-fix/M20_isolation_unsafe_levels_only.sql +83 -0
  94. package/tests/mutations/s12-fix/M21_isolation_check_miss_path_only.sql +83 -0
  95. package/tests/mutations/s12-fix/M22_isolation_inverted.sql +83 -0
  96. package/tests/mutations/s12-fix/M23_isolation_wrong_sqlstate.sql +83 -0
  97. package/tests/mutations/s12-fix/M24_create_thread_key_unchecked.sql +37 -0
  98. package/tests/mutations/s12-fix/M25_create_thread_key_nonnull_only.sql +45 -0
  99. package/tests/mutations/s12-fix/M26_create_thread_key_casefold.sql +45 -0
  100. package/tests/mutations/s12-fix/M27_create_thread_no_object_guard.sql +45 -0
  101. package/tests/mutations/s12-fix/M28_create_thread_key_stripped.sql +40 -0
  102. package/tests/mutations/s12-fix/M29_create_thread_key_nested_refused.sql +45 -0
  103. package/tests/mutations/s12-fix/M2_lock_actor_only.sql +83 -0
  104. package/tests/mutations/s12-fix/M30_create_thread_security_invoker.sql +9 -0
  105. package/tests/mutations/s12-fix/M31_create_thread_search_path_changed.sql +9 -0
  106. package/tests/mutations/s12-fix/M32_class_new_thread_inserter.sql +14 -0
  107. package/tests/mutations/s12-fix/M33_class_metadata_update.sql +12 -0
  108. package/tests/mutations/s12-fix/M33b_class_metadata_update_upper.sql +17 -0
  109. package/tests/mutations/s12-fix/M33c_class_metadata_update_row_form.sql +16 -0
  110. package/tests/mutations/s12-fix/M33d_class_metadata_merge_update.sql +16 -0
  111. package/tests/mutations/s12-fix/M33e_class_metadata_upsert.sql +16 -0
  112. package/tests/mutations/s12-fix/M34_class_api_role_insert.sql +9 -0
  113. package/tests/mutations/s12-fix/M3_lock_after_lookup.sql +83 -0
  114. package/tests/mutations/s12-fix/M4_lock_raw_key.sql +83 -0
  115. package/tests/mutations/s12-fix/M5_no_trim.sql +83 -0
  116. package/tests/mutations/s12-fix/M6_casefold.sql +83 -0
  117. package/tests/mutations/s12-fix/M7_lookup_ignores_actor.sql +82 -0
  118. package/tests/mutations/s12-fix/M8_reuse_reports_false.sql +83 -0
  119. package/tests/mutations/s12-fix/M9_blank_key_admitted.sql +83 -0
  120. package/tests/mutations/s12-fix/run.sh +288 -0
  121. package/tests/seeds/20261124000100_agent_board_step_up_enforcement.sql.pre.sql +47 -0
@@ -696,6 +696,18 @@
696
696
  {
697
697
  "id": "20261109000100_agent_board_step_up_groundwork",
698
698
  "sha256": "ce1a878aa752f2f7047958984019030ac7d4c2244c114113e52c8a2abc6dd9d9"
699
+ },
700
+ {
701
+ "id": "20261120000200_agent_board_thread_key_serialize",
702
+ "sha256": "5eaf5e3af345d4c0913a99491f5fb4d2b1109152f669a752e401b6027d484639"
703
+ },
704
+ {
705
+ "id": "20261121000100_agent_board_thread_key_guards",
706
+ "sha256": "0921646160fd23878162d6d053c2ac2631ccb8d80d96c98dfffe58a8a627dd8f"
707
+ },
708
+ {
709
+ "id": "20261124000100_agent_board_step_up_enforcement",
710
+ "sha256": "26c02cb8797d059b18f5e81d1db0be237126f48a0598b30e36e683763021384a"
699
711
  }
700
712
  ]
701
713
  }
@@ -0,0 +1,118 @@
1
+ -- THREADKEYSERIALIZE (S-12): one thread per (actor, normalized idempotency key) under concurrency.
2
+ --
3
+ -- `create_or_find_thread` looked the key up with `select ... for update` and, on a miss, did a
4
+ -- plain INSERT. Under READ COMMITTED the FOR UPDATE matches nothing while another session's row
5
+ -- for the same key is still uncommitted, so two concurrent calls with the same actor and the same
6
+ -- trim-normalized key BOTH missed, BOTH inserted, and both returned reused=false: two threads,
7
+ -- silently, with no wait and no error. Measured, not inferred, by
8
+ -- tests/isolation/specs/create_or_find_thread_same_key_race.spec (#808), whose permutations 1
9
+ -- and 2 pinned the defect.
10
+ --
11
+ -- TWO behavioural changes, and only two:
12
+ -- 1. the miss path is serialised on a transaction-scoped advisory lock taken BEFORE the reuse
13
+ -- lookup, so the second caller waits for the first to commit, then finds its row and returns
14
+ -- reused=true;
15
+ -- 2. non-object `p_metadata` is refused with 22023, before the lock. The key is stored by
16
+ -- `p_metadata || jsonb_build_object('addressingThreadKey', key)`, and for a JSON ARRAY that
17
+ -- concatenation yields an array (`'[]' || '{"k":1}'` is `[{"k":1}]`), so the top-level
18
+ -- `metadata ->> 'addressingThreadKey'` the lookup reads is NULL and even a SERIAL retry with
19
+ -- the same key inserted another thread. A scalar or JSON `null` has the same shape problem.
20
+ -- SQL NULL keeps meaning "no metadata" (`coalesce(p_metadata, '{}')`), as before; PostgREST
21
+ -- sends a JSON-body `null` as SQL NULL, and the client and MCP send only objects.
22
+ --
23
+ -- THE KEY IS (actor, key), NEVER key alone. It goes through the house helper
24
+ -- `_lock_idempotency_key(namespace, key)` with the namespace `'create_or_find_thread:' || actor`,
25
+ -- the same shape every other idempotent writer already uses (send_direct_message,
26
+ -- send_multicast_message, post_board_message, create_tasking_delivery all namespace by RPC name
27
+ -- and actor). The hashed text is `create_or_find_thread:<uuid>:<key>`; a uuid's text form is
28
+ -- fixed-length and has no ':', so distinct (actor, key) pairs never produce the same text, and two
29
+ -- different actors can contend only on a 64-bit hashtextextended collision. A lock on the key
30
+ -- alone would serialise DIFFERENT actors that happen to pick the same key -- #808's mutation M1b,
31
+ -- which the spec's permutation 5 catches.
32
+ --
33
+ -- Unchanged, deliberately: signature, return type, SECURITY DEFINER, search_path, the 22023
34
+ -- refusal of an empty subject or key (there is no null/empty-key insert path; the lock is taken
35
+ -- after both refusals, so a refused call takes no lock), trim-only normalization (case preserved),
36
+ -- the actor-scoped lookup, and the `for update` on the reused row. CREATE OR REPLACE keeps the
37
+ -- existing ACL (authenticated, service_role, agent_board_delegate) and owner; the function has no
38
+ -- COMMENT to lose. The function-EXECUTE snapshot pins the ACL.
39
+ --
40
+ -- NOT A UNIQUE INDEX, ON PURPOSE. A unique index on (created_by_agent_id,
41
+ -- metadata->>'addressingThreadKey') would fail to build on any database that already holds
42
+ -- duplicates from this race, and the race was live; without an ON CONFLICT handler it would also
43
+ -- surface 23505 to the losing caller (#808's M2). The advisory lock prevents NEW duplicates only.
44
+ -- Duplicates written before this migration stay; the lookup's `order by created_at desc limit 1`
45
+ -- keeps returning the newest one for that pair, as it always did -- except that rows with EQUAL
46
+ -- created_at (now() is the transaction start, so two racers can tie) have no defined order, and
47
+ -- which of them is returned is unspecified and may differ between calls.
48
+ --
49
+ -- WHAT THE GUARANTEE COVERS, and what it does not:
50
+ -- * READ COMMITTED callers only. That is what PostgREST and every Message Board client use. At
51
+ -- REPEATABLE READ or SERIALIZABLE the waiter's snapshot is taken before the winner commits, so
52
+ -- after the lock is granted its lookup still cannot see the winner's row and it inserts a
53
+ -- duplicate (SERIALIZABLE may instead raise 40001). Whether to refuse those levels is a
54
+ -- follow-up, not decided here (Consiliency/message-board#815).
55
+ -- * `create_or_find_thread` callers only. `create_thread` copies caller metadata -- including an
56
+ -- `addressingThreadKey` -- with no lock, so it can still write a thread this function would
57
+ -- have reused. Also a follow-up (Consiliency/message-board#816).
58
+ --
59
+ -- Rollback is a forward-corrective migration (re-create the previous body), never an edit here.
60
+
61
+ create or replace function agent_board.create_or_find_thread(
62
+ p_created_by_agent_id uuid,
63
+ p_subject text,
64
+ p_idempotency_key text,
65
+ p_thread_type text default 'coordination',
66
+ p_metadata jsonb default '{}'::jsonb
67
+ )
68
+ returns table(thread_id uuid, thread_type text, subject text, status text, last_message_sequence bigint, created_at timestamptz, updated_at timestamptz, reused boolean)
69
+ language plpgsql
70
+ security definer
71
+ set search_path = agent_board, public
72
+ as $$
73
+ declare
74
+ v_actor_agent_id uuid;
75
+ v_key text := nullif(trim(p_idempotency_key), '');
76
+ v_thread agent_board.threads%rowtype;
77
+ begin
78
+ v_actor_agent_id := agent_board._resolved_actor_agent_id(p_created_by_agent_id, 'p_created_by_agent_id');
79
+ if nullif(trim(p_subject), '') is null or v_key is null then
80
+ raise exception 'subject and idempotency key are required' using errcode = '22023';
81
+ end if;
82
+ -- S-12: a non-object would make the stored metadata an array or scalar with no top-level
83
+ -- addressingThreadKey, so the lookup below could never find it again. SQL NULL means "none".
84
+ if p_metadata is not null and jsonb_typeof(p_metadata) <> 'object' then
85
+ raise exception 'metadata must be a JSON object' using errcode = '22023';
86
+ end if;
87
+
88
+ -- S-12: serialise the lookup-then-insert on (actor, key) so a concurrent caller with the same
89
+ -- pair waits for this transaction and then reuses its row. Scoped by actor: different actors
90
+ -- never wait on each other.
91
+ perform agent_board._lock_idempotency_key('create_or_find_thread:' || v_actor_agent_id::text, v_key);
92
+
93
+ select *
94
+ into v_thread
95
+ from agent_board.threads t
96
+ where t.created_by_agent_id = v_actor_agent_id
97
+ and t.metadata ->> 'addressingThreadKey' = v_key
98
+ order by t.created_at desc
99
+ limit 1
100
+ for update;
101
+
102
+ if v_thread.id is not null then
103
+ return query select v_thread.id, v_thread.thread_type, v_thread.subject, v_thread.status, v_thread.last_message_sequence, v_thread.created_at, v_thread.updated_at, true;
104
+ return;
105
+ end if;
106
+
107
+ insert into agent_board.threads(thread_type, created_by_agent_id, subject, metadata)
108
+ values (
109
+ coalesce(nullif(trim(p_thread_type), ''), 'coordination'),
110
+ v_actor_agent_id,
111
+ trim(p_subject),
112
+ coalesce(p_metadata, '{}'::jsonb) || jsonb_build_object('addressingThreadKey', v_key)
113
+ )
114
+ returning * into v_thread;
115
+
116
+ return query select v_thread.id, v_thread.thread_type, v_thread.subject, v_thread.status, v_thread.last_message_sequence, v_thread.created_at, v_thread.updated_at, false;
117
+ end;
118
+ $$;
@@ -0,0 +1,196 @@
1
+ -- THREADKEYGUARDS (S-12 follow-ups): close the two holes 20261120000200 left open and named.
2
+ --
3
+ -- 20261120000200 serialises `create_or_find_thread` on a transaction-scoped advisory lock keyed by
4
+ -- (actor, normalized key), so concurrent same-pair callers end with one thread. Its header listed
5
+ -- two limits of that guarantee. This migration turns both into refusals.
6
+ --
7
+ -- 1. `create_or_find_thread` REFUSES A TRANSACTION THAT IS NOT READ COMMITTED
8
+ -- (Consiliency/message-board#815).
9
+ --
10
+ -- The mechanism is "take the lock, then look the key up in a NEW statement". That works because
11
+ -- under READ COMMITTED each statement takes a fresh snapshot, so the lookup issued after the
12
+ -- wait sees the row the winner committed. Under REPEATABLE READ and SERIALIZABLE the snapshot
13
+ -- is fixed at the transaction's first statement: the wait does not advance it, the lookup still
14
+ -- cannot see the winner's row, and the waiter inserts a duplicate (SERIALIZABLE may raise 40001
15
+ -- instead). Nothing errors and nothing waits incorrectly. The lock is a delay, not a guard.
16
+ --
17
+ -- So the function now raises 0A000, naming the level, when
18
+ -- `current_setting('transaction_isolation') <> 'read committed'`. SQLSTATE, comparison and
19
+ -- message shape are the ones `_claimgate_lock_board_policy` (20260930000100) already uses for
20
+ -- the same dependency, pinned there by tests/isolation/specs/claimpolicy_isolation_refusal.spec.
21
+ -- No new convention. As there, READ UNCOMMITTED is refused too: PostgreSQL runs it AS read
22
+ -- committed, so admitting it would not reopen the race, but one accepted spelling is a rule a
23
+ -- reader can check without an equivalence argument.
24
+ --
25
+ -- The refusal comes after the argument refusals (blank subject or key, non-object metadata) and
26
+ -- BEFORE the lock and the lookup. A refused caller therefore never waits on another caller's
27
+ -- lock, and is refused whether or not a thread for the pair already exists: it is the level
28
+ -- that is refused, not the miss path.
29
+ --
30
+ -- Who this refuses: no caller in this repository. PostgREST and every Message Board client run
31
+ -- at READ COMMITTED, and no migration, package or Edge Function sets another level for this
32
+ -- call. A caller that does appear fails loudly at its first call instead of quietly
33
+ -- duplicating.
34
+ --
35
+ -- It cannot be a pgTAP assertion: the level must be chosen by a transaction's first statement
36
+ -- and a pgTAP file is already inside one. The S-12 isolation spec carries it (permutations
37
+ -- 8-12).
38
+ --
39
+ -- 2. `create_thread` REFUSES OBJECT METADATA CARRYING `addressingThreadKey`, with 22023
40
+ -- (Consiliency/message-board#816).
41
+ --
42
+ -- `create_thread` copies caller metadata into the new thread and takes no lock. A caller could
43
+ -- therefore write a thread under a key `create_or_find_thread` would have reused, concurrently
44
+ -- or later, and put a second row under one (actor, key) pair.
45
+ --
46
+ -- WHY REFUSE, rather than strip the key or take the same lock and reuse. A census of this
47
+ -- repository found NO caller that sends the key through `create_thread`: the string
48
+ -- `addressingThreadKey` occurs in no package source (client, cli, mcp, pi, opencode, runtime),
49
+ -- in no Edge Function under supabase/functions and in no script. In the migrations it is read
50
+ -- and written only by `create_or_find_thread` and read by `expand_recipients_dry_run` (defined
51
+ -- in 20260517000000 and redefined in 20260804000100; on a built database `pg_get_functiondef`
52
+ -- shows these two functions plus `create_thread` as the only ones whose bodies name the key).
53
+ -- The client, the CLI `create-thread --metadata` and the
54
+ -- MCP `agent_board.create_thread` tool pass caller metadata through unchanged; none of them
55
+ -- builds the key. So the key in `create_thread` metadata is either a mistake or an attempt to
56
+ -- plant a thread under someone's idempotency key, and the fail-closed answer is to say so.
57
+ -- Stripping would accept the call and silently drop a field the caller sent. Locking and
58
+ -- reusing would give `create_thread` a second meaning (find) that its return type cannot
59
+ -- report: it has no `reused` column.
60
+ --
61
+ -- The key is RESERVED BY NAME: any top-level `addressingThreadKey` in an object is refused,
62
+ -- whatever its value (a JSON null included). The match is on exactly the spelling the lookup
63
+ -- reads (`metadata ->> 'addressingThreadKey'`), top level only. A differently cased key or a
64
+ -- nested one is not read by the lookup and is not refused. Non-object metadata is left exactly
65
+ -- as it was: `->>` with a text key reads nothing from an array or a scalar, so such a value
66
+ -- cannot stand in for a keyed thread. (`?` is true for an ARRAY holding that string, which is
67
+ -- why the test is guarded by `jsonb_typeof(...) = 'object'`.)
68
+ --
69
+ -- The other ways a row could get the key, checked rather than assumed, and pinned by
70
+ -- tests/agent_board_thread_key_guards.test.sql from pg_catalog:
71
+ -- * `create_thread` and `create_or_find_thread` are the only functions in the schema that
72
+ -- INSERT into `agent_board.threads`;
73
+ -- * no function in the schema assigns `threads.metadata` in an UPDATE;
74
+ -- * `anon`, `authenticated` and `agent_board_delegate` hold neither INSERT nor UPDATE on the
75
+ -- table.
76
+ -- NOT covered: the table owner, and any role an operator grants direct DML on the table. That
77
+ -- is the operator, not a caller. The function scans read function BODIES, so a writer built
78
+ -- with dynamic SQL would not be seen by them.
79
+ --
80
+ -- Unchanged, deliberately, for both functions: signature, return type, SECURITY DEFINER,
81
+ -- search_path, and every existing refusal with its SQLSTATE and message. CREATE OR REPLACE keeps
82
+ -- each function's ACL, owner and COMMENT (neither function has a COMMENT today); nothing is
83
+ -- dropped, so nothing has to be restated. The function-EXECUTE snapshot pins the ACLs.
84
+ --
85
+ -- Duplicates already written by either route stay, as 20261120000200 explains. These are
86
+ -- refusals of NEW writes only.
87
+ --
88
+ -- Rollback is a forward-corrective migration (re-create the previous bodies), never an edit here.
89
+
90
+ create or replace function agent_board.create_or_find_thread(
91
+ p_created_by_agent_id uuid,
92
+ p_subject text,
93
+ p_idempotency_key text,
94
+ p_thread_type text default 'coordination',
95
+ p_metadata jsonb default '{}'::jsonb
96
+ )
97
+ returns table(thread_id uuid, thread_type text, subject text, status text, last_message_sequence bigint, created_at timestamptz, updated_at timestamptz, reused boolean)
98
+ language plpgsql
99
+ security definer
100
+ set search_path = agent_board, public
101
+ as $$
102
+ declare
103
+ v_actor_agent_id uuid;
104
+ v_key text := nullif(trim(p_idempotency_key), '');
105
+ v_thread agent_board.threads%rowtype;
106
+ v_isolation text := current_setting('transaction_isolation');
107
+ begin
108
+ v_actor_agent_id := agent_board._resolved_actor_agent_id(p_created_by_agent_id, 'p_created_by_agent_id');
109
+ if nullif(trim(p_subject), '') is null or v_key is null then
110
+ raise exception 'subject and idempotency key are required' using errcode = '22023';
111
+ end if;
112
+ -- S-12: a non-object would make the stored metadata an array or scalar with no top-level
113
+ -- addressingThreadKey, so the lookup below could never find it again. SQL NULL means "none".
114
+ if p_metadata is not null and jsonb_typeof(p_metadata) <> 'object' then
115
+ raise exception 'metadata must be a JSON object' using errcode = '22023';
116
+ end if;
117
+ -- S-12 (#815): READ COMMITTED IS A PRECONDITION, NOT A PREFERENCE. The lock below only helps if
118
+ -- the lookup after it sees the winner's COMMITTED row, and that needs a fresh snapshot per
119
+ -- statement. Under repeatable read / serializable the snapshot is fixed, the wait does not
120
+ -- advance it, and this caller would insert a duplicate. Refuse, before the lock and the lookup.
121
+ if v_isolation <> 'read committed' then
122
+ raise exception
123
+ 'create_or_find_thread requires transaction isolation level read committed (got %)',
124
+ v_isolation
125
+ using errcode = '0A000',
126
+ hint = 'The (actor, key) lock only prevents a duplicate thread under READ COMMITTED, '
127
+ 'where each statement takes a fresh snapshot. Retry this call in a READ '
128
+ 'COMMITTED transaction.';
129
+ end if;
130
+
131
+ -- S-12: serialise the lookup-then-insert on (actor, key) so a concurrent caller with the same
132
+ -- pair waits for this transaction and then reuses its row. Scoped by actor: different actors
133
+ -- never wait on each other.
134
+ perform agent_board._lock_idempotency_key('create_or_find_thread:' || v_actor_agent_id::text, v_key);
135
+
136
+ select *
137
+ into v_thread
138
+ from agent_board.threads t
139
+ where t.created_by_agent_id = v_actor_agent_id
140
+ and t.metadata ->> 'addressingThreadKey' = v_key
141
+ order by t.created_at desc
142
+ limit 1
143
+ for update;
144
+
145
+ if v_thread.id is not null then
146
+ return query select v_thread.id, v_thread.thread_type, v_thread.subject, v_thread.status, v_thread.last_message_sequence, v_thread.created_at, v_thread.updated_at, true;
147
+ return;
148
+ end if;
149
+
150
+ insert into agent_board.threads(thread_type, created_by_agent_id, subject, metadata)
151
+ values (
152
+ coalesce(nullif(trim(p_thread_type), ''), 'coordination'),
153
+ v_actor_agent_id,
154
+ trim(p_subject),
155
+ coalesce(p_metadata, '{}'::jsonb) || jsonb_build_object('addressingThreadKey', v_key)
156
+ )
157
+ returning * into v_thread;
158
+
159
+ return query select v_thread.id, v_thread.thread_type, v_thread.subject, v_thread.status, v_thread.last_message_sequence, v_thread.created_at, v_thread.updated_at, false;
160
+ end;
161
+ $$;
162
+
163
+ create or replace function agent_board.create_thread(
164
+ p_created_by_agent_id uuid,
165
+ p_subject text,
166
+ p_thread_type text default 'coordination',
167
+ p_metadata jsonb default '{}'::jsonb
168
+ )
169
+ returns table(thread_id uuid, thread_type text, subject text, status text, last_message_sequence bigint, created_at timestamptz, updated_at timestamptz)
170
+ language plpgsql
171
+ security definer
172
+ set search_path = agent_board, public
173
+ as $$
174
+ declare
175
+ v_actor_agent_id uuid;
176
+ begin
177
+ v_actor_agent_id := agent_board._resolved_actor_agent_id(p_created_by_agent_id, 'p_created_by_agent_id');
178
+
179
+ if nullif(trim(p_subject), '') is null then
180
+ raise exception 'subject is required' using errcode = '22023';
181
+ end if;
182
+ -- S-12 (#816): addressingThreadKey is the idempotency key create_or_find_thread stores and looks
183
+ -- up under its (actor, key) lock. This function takes no lock, so letting a caller write the
184
+ -- key here would put a second thread under a pair that function serialises. Reserved by name,
185
+ -- top level of an object only: that is exactly what the lookup reads.
186
+ if jsonb_typeof(p_metadata) = 'object' and p_metadata ? 'addressingThreadKey' then
187
+ raise exception 'metadata key addressingThreadKey is reserved for create_or_find_thread'
188
+ using errcode = '22023';
189
+ end if;
190
+
191
+ return query
192
+ insert into agent_board.threads(created_by_agent_id, subject, thread_type, metadata)
193
+ values (v_actor_agent_id, trim(p_subject), coalesce(p_thread_type, 'coordination'), coalesce(p_metadata, '{}'::jsonb))
194
+ returning id, threads.thread_type, threads.subject, threads.status, threads.last_message_sequence, threads.created_at, threads.updated_at;
195
+ end;
196
+ $$;