@consiliency/agent-board-schema 1.75.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 (166) hide show
  1. package/fixtures/already-applied.json +16 -0
  2. package/migrations/20261109000100_agent_board_step_up_groundwork.sql +343 -0
  3. package/migrations/20261120000200_agent_board_thread_key_serialize.sql +118 -0
  4. package/migrations/20261121000100_agent_board_thread_key_guards.sql +196 -0
  5. package/migrations/20261124000100_agent_board_step_up_enforcement.sql +1213 -0
  6. package/package.json +1 -1
  7. package/schema-manifest.json +39 -3
  8. package/src/deployment-drift-main.test.mjs +89 -6
  9. package/src/deployment-drift.test.mjs +20 -1
  10. package/src/tooling.test.mjs +10 -2
  11. package/tests/agent_board_717_message_replay_scope.test.sql +39 -2
  12. package/tests/agent_board_717_tasking_replay_scope.test.sql +21 -2
  13. package/tests/agent_board_enrollment_audit_content.test.sql +6 -1
  14. package/tests/agent_board_role_guard.test.sql +3 -1
  15. package/tests/agent_board_send_outcome.test.sql +39 -1
  16. package/tests/agent_board_session_identity_approval_revocation.test.sql +5 -0
  17. package/tests/agent_board_step_up.test.sql +991 -0
  18. package/tests/agent_board_step_up_helper.test.sql +815 -0
  19. package/tests/agent_board_thread_key_guards.test.sql +186 -0
  20. package/tests/agent_board_thread_key_serialize.test.sql +182 -0
  21. package/tests/agent_board_write_enforcement_class.test.sql +8 -4
  22. package/tests/catalog/function_execute_privileges.json +72 -0
  23. package/tests/catalog/p_metadata_parameters.json +32 -0
  24. package/tests/catalog/step_up_gated_closure.json +24 -0
  25. package/tests/fixtures/pgtap-unexposed.sql +9 -4
  26. package/tests/isolation/expected/create_or_find_thread_same_key_race.out +641 -0
  27. package/tests/isolation/expected/session_identity_links.out +4 -0
  28. package/tests/isolation/specs/create_or_find_thread_same_key_race.spec +252 -0
  29. package/tests/isolation/specs/session_identity_links.spec +5 -0
  30. package/tests/mutations/669/M10_service_role_blanket.sql +10 -0
  31. package/tests/mutations/669/M12a_no_parse_wrapper.sql +17 -0
  32. package/tests/mutations/669/M12b_no_session_wrapper.sql +23 -0
  33. package/tests/mutations/669/M12c_no_claim_type_guard.sql +13 -0
  34. package/tests/mutations/669/M12d_no_amr_element_guards.sql +15 -0
  35. package/tests/mutations/669/M14_now_not_clock.sql +9 -0
  36. package/tests/mutations/669/M15_classifier_reads_metadata.sql +17 -0
  37. package/tests/mutations/669/M17_skip_ledger.sql +15 -0
  38. package/tests/mutations/669/M18_service_role_sub_insensitive.sql +9 -0
  39. package/tests/mutations/669/M18b_drop_uid_conjunct.sql +9 -0
  40. package/tests/mutations/669/M23_definer_wrapper_over_writer.sql +5 -0
  41. package/tests/mutations/669/M3_age_from_iat.sql +9 -0
  42. package/tests/mutations/669/M4_window_900.sql +9 -0
  43. package/tests/mutations/669/M4b_lt_to_le.sql +9 -0
  44. package/tests/mutations/669/M5_no_skew_bound.sql +9 -0
  45. package/tests/mutations/669/M6a_user_metadata_amr.sql +9 -0
  46. package/tests/mutations/669/M6b_app_metadata_claim.sql +9 -0
  47. package/tests/mutations/669/M6c_legacy_guc.sql +9 -0
  48. package/tests/mutations/669/M7_either_claim_any_human.sql +9 -0
  49. package/tests/mutations/669/M8_any_amr_method.sql +9 -0
  50. package/tests/mutations/669/M8b_accept_aal2.sql +9 -0
  51. package/tests/mutations/669/M9_every_kind.sql +9 -0
  52. package/tests/mutations/669/MAL_allowlist_nonempty.sql +9 -0
  53. package/tests/mutations/669/MAR_writer_arg_renamed.sql +14 -0
  54. package/tests/mutations/669/MAU_audit_mode_retyped.sql +2 -0
  55. package/tests/mutations/669/MA_helper_always_raises.sql +10 -0
  56. package/tests/mutations/669/MDX_dynamic_execute_definer.sql +5 -0
  57. package/tests/mutations/669/MD_detail_carries_value.sql +12 -0
  58. package/tests/mutations/669/MEC0_caller_of_helper.sql +4 -0
  59. package/tests/mutations/669/MEC0b_overload_caller.sql +4 -0
  60. package/tests/mutations/669/MG1_helper_granted_authenticated.sql +2 -0
  61. package/tests/mutations/669/MG2_ledger_insert_authenticated.sql +2 -0
  62. package/tests/mutations/669/MG3_ledger_policy.sql +2 -0
  63. package/tests/mutations/669/MR1_writer_no_class_check.sql +9 -0
  64. package/tests/mutations/669/MR2_writer_wide_window.sql +9 -0
  65. package/tests/mutations/669/MR3_writer_prunes_everyone.sql +11 -0
  66. package/tests/mutations/669/MR4_writer_lower_exclusive.sql +9 -0
  67. package/tests/mutations/669/MR5_writer_upper_exclusive.sql +9 -0
  68. package/tests/mutations/669/MR6_writer_upper_61.sql +9 -0
  69. package/tests/mutations/669/MW2_second_ledger_writer.sql +4 -0
  70. package/tests/mutations/669/MXS_cross_schema_wrapper.sql +4 -0
  71. package/tests/mutations/669/run.sh +80 -0
  72. package/tests/mutations/669b/M11_ceil_first.sql +10 -0
  73. package/tests/mutations/669b/M11_gate_first.sql +10 -0
  74. package/tests/mutations/669b/M11_grant_first.sql +10 -0
  75. package/tests/mutations/669b/M11_inv_first.sql +10 -0
  76. package/tests/mutations/669b/M11_mem_first.sql +10 -0
  77. package/tests/mutations/669b/M11_readmit_first.sql +10 -0
  78. package/tests/mutations/669b/M13a_gate_member_preset.sql +12 -0
  79. package/tests/mutations/669b/M13b_ungate_admin_preset.sql +12 -0
  80. package/tests/mutations/669b/M16_actor_is_target.sql +14 -0
  81. package/tests/mutations/669b/M19_drop_readmit.sql +9 -0
  82. package/tests/mutations/669b/M1_drop_grant.sql +9 -0
  83. package/tests/mutations/669b/M20_drop_d5_refusal.sql +9 -0
  84. package/tests/mutations/669b/M21_drop_removal.sql +9 -0
  85. package/tests/mutations/669b/M21b_only_removed.sql +9 -0
  86. package/tests/mutations/669b/M21c_gate_members.sql +12 -0
  87. package/tests/mutations/669b/M21d_requested_state.sql +9 -0
  88. package/tests/mutations/669b/M23b_api_wrapper_over_audit_writer.sql +6 -0
  89. package/tests/mutations/669b/M23c_drop_register_type_refusal.sql +9 -0
  90. package/tests/mutations/669b/M24_drop_kind_refusal.sql +9 -0
  91. package/tests/mutations/669b/M24b_drop_auth_bind_refusal.sql +9 -0
  92. package/tests/mutations/669b/M2a_drop_gate.sql +9 -0
  93. package/tests/mutations/669b/M2b_drop_ceiling.sql +9 -0
  94. package/tests/mutations/669b/M2c_drop_invite.sql +9 -0
  95. package/tests/mutations/669b/MAL2_drop_otp.sql +9 -0
  96. package/tests/mutations/669b/MAL3_admit_passkey.sql +9 -0
  97. package/tests/mutations/669b/MD7a_no_revocation.sql +2 -0
  98. package/tests/mutations/669b/MD7b_overwrite_revoked.sql +2 -0
  99. package/tests/mutations/669b/MD7c_revoke_members.sql +2 -0
  100. package/tests/mutations/669b/MD7d_revoke_expired.sql +2 -0
  101. package/tests/mutations/669b/ME1_wrapper_over_gate.sql +7 -0
  102. package/tests/mutations/669b/MEC2_write_after_helper.sql +10 -0
  103. package/tests/mutations/669b/MQX_query_to_xml_definer.sql +6 -0
  104. package/tests/mutations/669b/MQXb_ts_stat_other_schema.sql +4 -0
  105. package/tests/mutations/669b/MTR_trigger_route.sql +9 -0
  106. package/tests/mutations/669b/MTRb_new_assign.sql +11 -0
  107. package/tests/mutations/669b/MTRc_sync_assigns_value.sql +47 -0
  108. package/tests/mutations/669b/MTX1_tombstone_second_gated_call.sql +15 -0
  109. package/tests/mutations/669b/MTX2_tombstone_non_delegate_target.sql +10 -0
  110. package/tests/mutations/669b/MXS_other_schema_names_gated.sql +5 -0
  111. package/tests/mutations/669b/run.sh +83 -0
  112. package/tests/mutations/670/M18a_read_operation_default_dropped.sql +11 -0
  113. package/tests/mutations/670/M18b_read_operation_default_changed.sql +7 -0
  114. package/tests/mutations/670/M3-DM_helper_on_replay_branch.sql +10 -0
  115. package/tests/mutations/670/M3-MC_helper_on_replay_branch.sql +10 -0
  116. package/tests/mutations/s12/M0_identity.sql +56 -0
  117. package/tests/mutations/s12/M1_serialise_actor_key.sql +57 -0
  118. package/tests/mutations/s12/M1b_serialise_key_only.sql +57 -0
  119. package/tests/mutations/s12/M2_unique_index_no_handler.sql +9 -0
  120. package/tests/mutations/s12/M3_no_trim.sql +56 -0
  121. package/tests/mutations/s12/M4_casefold.sql +56 -0
  122. package/tests/mutations/s12/M5_lookup_ignores_actor.sql +56 -0
  123. package/tests/mutations/s12/M6_reuse_reports_false.sql +56 -0
  124. package/tests/mutations/s12/run.sh +112 -0
  125. package/tests/mutations/s12-fix/M0_identity.sql +83 -0
  126. package/tests/mutations/s12-fix/M10_security_invoker.sql +9 -0
  127. package/tests/mutations/s12-fix/M11_search_path_changed.sql +9 -0
  128. package/tests/mutations/s12-fix/M12_reuse_writes_task.sql +84 -0
  129. package/tests/mutations/s12-fix/M13_dead_inbox_write.sql +84 -0
  130. package/tests/mutations/s12-fix/M14_metadata_unchecked.sql +78 -0
  131. package/tests/mutations/s12-fix/M15_metadata_check_after_lock.sql +84 -0
  132. package/tests/mutations/s12-fix/M16_sql_null_metadata_refused.sql +83 -0
  133. package/tests/mutations/s12-fix/M17_isolation_unchecked.sql +70 -0
  134. package/tests/mutations/s12-fix/M18_isolation_check_after_lock.sql +82 -0
  135. package/tests/mutations/s12-fix/M19_isolation_rr_only.sql +83 -0
  136. package/tests/mutations/s12-fix/M1_lock_dropped.sql +78 -0
  137. package/tests/mutations/s12-fix/M1b_lock_key_only.sql +83 -0
  138. package/tests/mutations/s12-fix/M20_isolation_unsafe_levels_only.sql +83 -0
  139. package/tests/mutations/s12-fix/M21_isolation_check_miss_path_only.sql +83 -0
  140. package/tests/mutations/s12-fix/M22_isolation_inverted.sql +83 -0
  141. package/tests/mutations/s12-fix/M23_isolation_wrong_sqlstate.sql +83 -0
  142. package/tests/mutations/s12-fix/M24_create_thread_key_unchecked.sql +37 -0
  143. package/tests/mutations/s12-fix/M25_create_thread_key_nonnull_only.sql +45 -0
  144. package/tests/mutations/s12-fix/M26_create_thread_key_casefold.sql +45 -0
  145. package/tests/mutations/s12-fix/M27_create_thread_no_object_guard.sql +45 -0
  146. package/tests/mutations/s12-fix/M28_create_thread_key_stripped.sql +40 -0
  147. package/tests/mutations/s12-fix/M29_create_thread_key_nested_refused.sql +45 -0
  148. package/tests/mutations/s12-fix/M2_lock_actor_only.sql +83 -0
  149. package/tests/mutations/s12-fix/M30_create_thread_security_invoker.sql +9 -0
  150. package/tests/mutations/s12-fix/M31_create_thread_search_path_changed.sql +9 -0
  151. package/tests/mutations/s12-fix/M32_class_new_thread_inserter.sql +14 -0
  152. package/tests/mutations/s12-fix/M33_class_metadata_update.sql +12 -0
  153. package/tests/mutations/s12-fix/M33b_class_metadata_update_upper.sql +17 -0
  154. package/tests/mutations/s12-fix/M33c_class_metadata_update_row_form.sql +16 -0
  155. package/tests/mutations/s12-fix/M33d_class_metadata_merge_update.sql +16 -0
  156. package/tests/mutations/s12-fix/M33e_class_metadata_upsert.sql +16 -0
  157. package/tests/mutations/s12-fix/M34_class_api_role_insert.sql +9 -0
  158. package/tests/mutations/s12-fix/M3_lock_after_lookup.sql +83 -0
  159. package/tests/mutations/s12-fix/M4_lock_raw_key.sql +83 -0
  160. package/tests/mutations/s12-fix/M5_no_trim.sql +83 -0
  161. package/tests/mutations/s12-fix/M6_casefold.sql +83 -0
  162. package/tests/mutations/s12-fix/M7_lookup_ignores_actor.sql +82 -0
  163. package/tests/mutations/s12-fix/M8_reuse_reports_false.sql +83 -0
  164. package/tests/mutations/s12-fix/M9_blank_key_admitted.sql +83 -0
  165. package/tests/mutations/s12-fix/run.sh +288 -0
  166. package/tests/seeds/20261124000100_agent_board_step_up_enforcement.sql.pre.sql +47 -0
@@ -692,6 +692,22 @@
692
692
  {
693
693
  "id": "20261108000100_agent_board_send_outcome",
694
694
  "sha256": "f3e14b1bf7e8aa9f4a89a8ae0723dd63f21383477d321070d0736ff1e6912e8a"
695
+ },
696
+ {
697
+ "id": "20261109000100_agent_board_step_up_groundwork",
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"
695
711
  }
696
712
  ]
697
713
  }
@@ -0,0 +1,343 @@
1
+ -- #669 STEPUP PR-A: authority-neutral groundwork for server-side step-up (X4).
2
+ --
3
+ -- Ruling: plans/STEPUP-669-plan.md R1 (§14 binding errata E-0..E-6 supersede conflicting text),
4
+ -- president rulings R1 (D1-D16) and R2 (PERMIT-WITH-ERRATA). This migration is PR-A (§11.1 as
5
+ -- amended by E-4/E-6(d)): it adds the step-up helper, the pure freshness predicate, the window,
6
+ -- skew and amr-allowlist functions, and the Portal proof ledger with its single writer.
7
+ --
8
+ -- AUTHORITY-NEUTRAL (E-6(d)). No chokepoint body changes: NOTHING calls
9
+ -- _require_human_step_up, so no gated function can raise MBS01 (EC-SU-0 asserts it from the
10
+ -- catalog). What PR-A does change, stated rather than implied:
11
+ -- * /portal-session may put agent_board_step_up_at into the MB token (Edge Function change);
12
+ -- * portal_step_up_proofs rows persist (written by /portal-session through
13
+ -- record_portal_step_up; nothing reads them until PR-B);
14
+ -- * the /portal-session mint log gains `step_up: boolean`.
15
+ -- The allowlist starts EMPTY (§11.1): nothing calls it, and empty is fail-closed if anything did.
16
+ -- None of these functions is executable by an API role (anon, authenticated,
17
+ -- agent_board_delegate); record_portal_step_up is EXECUTE-able by service_role only.
18
+ --
19
+ -- Writes no agent_board.schema_version (stays 8).
20
+
21
+ -- =============================================================================
22
+ -- 1. The window (D9, §4): IMMUTABLE, no table, GUC or argument. A change takes a migration.
23
+ -- =============================================================================
24
+ create or replace function agent_board._step_up_max_age_seconds()
25
+ returns numeric
26
+ language sql
27
+ immutable
28
+ parallel safe
29
+ set search_path = ''
30
+ as $$
31
+ select 300::numeric
32
+ $$;
33
+
34
+ revoke all on function agent_board._step_up_max_age_seconds()
35
+ from public, anon, authenticated, service_role, agent_board_delegate;
36
+ comment on function agent_board._step_up_max_age_seconds() is
37
+ '#669 D9: the step-up freshness window, 300 seconds. A proof is fresh while now - proof < this value. IMMUTABLE; changing it takes a reviewed migration. No API-role EXECUTE.';
38
+
39
+ create or replace function agent_board._step_up_future_skew_seconds()
40
+ returns numeric
41
+ language sql
42
+ immutable
43
+ parallel safe
44
+ set search_path = ''
45
+ as $$
46
+ select 30::numeric
47
+ $$;
48
+
49
+ revoke all on function agent_board._step_up_future_skew_seconds()
50
+ from public, anon, authenticated, service_role, agent_board_delegate;
51
+ comment on function agent_board._step_up_future_skew_seconds() is
52
+ '#669 D9: the tolerated future clock skew for a step-up proof, 30 seconds (proof - now <= this value). IMMUTABLE. No API-role EXECUTE.';
53
+
54
+ -- =============================================================================
55
+ -- 2. The pure predicate (D9). Boundary semantics are pinned on this function with exact
56
+ -- numerics (P-1..P-4), because integer-second claims against a moving clock cannot pin
57
+ -- `<` against `<=`. NULL in, false out.
58
+ -- =============================================================================
59
+ create or replace function agent_board._step_up_is_fresh(p_proof numeric, p_now numeric)
60
+ returns boolean
61
+ language sql
62
+ immutable
63
+ parallel safe
64
+ set search_path = ''
65
+ as $$
66
+ select coalesce(
67
+ p_now - p_proof < agent_board._step_up_max_age_seconds()
68
+ and p_proof - p_now <= agent_board._step_up_future_skew_seconds(),
69
+ false)
70
+ $$;
71
+
72
+ revoke all on function agent_board._step_up_is_fresh(numeric, numeric)
73
+ from public, anon, authenticated, service_role, agent_board_delegate;
74
+ comment on function agent_board._step_up_is_fresh(numeric, numeric) is
75
+ '#669 D9: pure step-up freshness predicate. True iff p_now - p_proof < _step_up_max_age_seconds() and p_proof - p_now <= _step_up_future_skew_seconds(); false (never NULL) otherwise. IMMUTABLE. The helper calls it with extract(epoch from clock_timestamp()). No API-role EXECUTE.';
76
+
77
+ -- =============================================================================
78
+ -- 3. The LOCALAUTH amr allowlist (D11, Q3). EMPTY in PR-A (§11.1): a string is admitted only
79
+ -- when the owner's Q3 answer admits it AND the §10.5 GoTrue measurement has seen that exact
80
+ -- string on the pinned image. PR-B freezes the measured list.
81
+ -- =============================================================================
82
+ create or replace function agent_board._step_up_amr_methods()
83
+ returns text[]
84
+ language sql
85
+ immutable
86
+ parallel safe
87
+ set search_path = ''
88
+ as $$
89
+ select '{}'::text[]
90
+ $$;
91
+
92
+ revoke all on function agent_board._step_up_amr_methods()
93
+ from public, anon, authenticated, service_role, agent_board_delegate;
94
+ comment on function agent_board._step_up_amr_methods() is
95
+ '#669 D11: GoTrue amr methods that count as a fresh LOCALAUTH step-up. EMPTY until PR-B freezes the Q3 candidates (otp, totp, passkey, mfa/webauthn, mfa/phone) intersected with the strings measured on the pinned GoTrue image (plan §10.5). password, magiclink, recovery, mfa/recovery_code, oauth, sso, token_refresh and unseen strings are never admitted. IMMUTABLE. No API-role EXECUTE.';
96
+
97
+ -- =============================================================================
98
+ -- 4. The Portal proof ledger (D8, §9.1). Service-written evidence that /portal-session verified
99
+ -- a Portal token carrying agent_board_step_up_at = proof_at for this agent. RLS on, zero
100
+ -- policies, no privilege for any role but the owner: record_portal_step_up is its only
101
+ -- writer.
102
+ -- =============================================================================
103
+ create table agent_board.portal_step_up_proofs (
104
+ agent_id uuid not null,
105
+ proof_at bigint not null,
106
+ recorded_at timestamptz not null default clock_timestamp(),
107
+ constraint portal_step_up_proofs_pkey primary key (agent_id, proof_at)
108
+ );
109
+
110
+ alter table agent_board.portal_step_up_proofs enable row level security;
111
+ revoke all on table agent_board.portal_step_up_proofs
112
+ from public, anon, authenticated, service_role, agent_board_delegate;
113
+
114
+ comment on table agent_board.portal_step_up_proofs is
115
+ '#669 D8: service-only ledger of Portal step-up proofs. One row per (agent, proof instant) that /portal-session verified in a Portal RS256 token and copied into an MB token. Written only by record_portal_step_up (service_role); RLS on with zero policies and no API-role privilege. A Portal-class human''s agent_board_step_up_at claim counts only with a matching row. Rows older than one day are pruned per agent on write.';
116
+
117
+ -- =============================================================================
118
+ -- 5. The class binding (§3.3). A `portal` human is kind='human' with a service-written
119
+ -- enrollment_federation_audit row in mode 'fedsession'. agents.metadata is NOT evidence
120
+ -- (caller metadata is merged into it). Shared by the helper and the ledger writer so the two
121
+ -- can never disagree about the class.
122
+ -- =============================================================================
123
+ create or replace function agent_board._step_up_is_portal_human(p_agent_id uuid)
124
+ returns boolean
125
+ language sql
126
+ stable
127
+ security invoker
128
+ set search_path = ''
129
+ as $$
130
+ select exists (
131
+ select 1
132
+ from agent_board.agents a
133
+ where a.id = p_agent_id
134
+ and a.kind = 'human'::agent_board.agent_kind
135
+ and exists (
136
+ select 1
137
+ from agent_board.enrollment_federation_audit f
138
+ where f.agent_id = a.id
139
+ and f.mode = 'fedsession'))
140
+ $$;
141
+
142
+ revoke all on function agent_board._step_up_is_portal_human(uuid)
143
+ from public, anon, authenticated, service_role, agent_board_delegate;
144
+ comment on function agent_board._step_up_is_portal_human(uuid) is
145
+ '#669 §3.3: true iff the agent is kind=human AND has a service-written enrollment_federation_audit row with mode=fedsession (a Portal-federated human). agents.metadata is never consulted. No API-role EXECUTE.';
146
+
147
+ -- =============================================================================
148
+ -- 6a. The writer's instant window (§9.1), as a pure predicate so its boundaries are pinned with
149
+ -- exact numerics (inclusive: [now - 330, now + 60]), as D9 does for the freshness window.
150
+ -- =============================================================================
151
+ create or replace function agent_board._step_up_proof_recordable(p_proof numeric, p_now numeric)
152
+ returns boolean
153
+ language sql
154
+ immutable
155
+ parallel safe
156
+ set search_path = ''
157
+ as $$
158
+ select coalesce(p_proof >= p_now - 330 and p_proof <= p_now + 60, false)
159
+ $$;
160
+
161
+ revoke all on function agent_board._step_up_proof_recordable(numeric, numeric)
162
+ from public, anon, authenticated, service_role, agent_board_delegate;
163
+ comment on function agent_board._step_up_proof_recordable(numeric, numeric) is
164
+ '#669 §9.1: true iff p_now - 330 <= p_proof <= p_now + 60 (inclusive); false, never NULL, otherwise. The ledger writer accepts a proof instant only inside this window. IMMUTABLE. No API-role EXECUTE.';
165
+
166
+ -- =============================================================================
167
+ -- 6. The ledger writer (D8, §9.1). service_role only; the only caller is /portal-session, which
168
+ -- passes the agent it provisioned from the subject of the Portal token it verified. Returns
169
+ -- false, never an error, when a bound fails.
170
+ -- =============================================================================
171
+ create or replace function agent_board.record_portal_step_up(p_agent_id uuid, p_proof_at bigint)
172
+ returns boolean
173
+ language plpgsql
174
+ security definer
175
+ set search_path = ''
176
+ as $$
177
+ declare
178
+ v_now numeric := extract(epoch from clock_timestamp());
179
+ begin
180
+ if p_agent_id is null or p_proof_at is null then
181
+ return false;
182
+ end if;
183
+
184
+ -- Re-validate the class: only a Portal-federated human can hold a Portal proof.
185
+ if agent_board._step_up_is_portal_human(p_agent_id) is not true then
186
+ return false;
187
+ end if;
188
+
189
+ -- The instant must be about the present: [clock - 330, clock + 60].
190
+ if agent_board._step_up_proof_recordable(p_proof_at::numeric, v_now) is not true then
191
+ return false;
192
+ end if;
193
+
194
+ insert into agent_board.portal_step_up_proofs(agent_id, proof_at)
195
+ values (p_agent_id, p_proof_at)
196
+ on conflict (agent_id, proof_at) do nothing;
197
+
198
+ -- Prune this agent's proofs older than one day. A fresh proof is at most 300 s old.
199
+ delete from agent_board.portal_step_up_proofs p
200
+ where p.agent_id = p_agent_id
201
+ and p.proof_at::numeric < v_now - 86400;
202
+
203
+ return true;
204
+ end;
205
+ $$;
206
+
207
+ revoke all on function agent_board.record_portal_step_up(uuid, bigint)
208
+ from public, anon, authenticated, service_role, agent_board_delegate;
209
+ grant execute on function agent_board.record_portal_step_up(uuid, bigint) to service_role;
210
+ comment on function agent_board.record_portal_step_up(uuid, bigint) is
211
+ '#669 D8: the only writer of portal_step_up_proofs. EXECUTE for service_role only; its only caller is /portal-session, which passes the agent it provisioned from a verified Portal token. Returns false (no error) unless the agent is a Portal-class human and p_proof_at lies in [clock - 330, clock + 60]; otherwise inserts (on conflict do nothing), prunes that agent''s rows older than one day, and returns true.';
212
+
213
+ -- =============================================================================
214
+ -- 7. The helper (D2, D3, D8, D10; §6.1). NOT CALLED BY ANY FUNCTION IN PR-A (EC-SU-0).
215
+ --
216
+ -- No actor parameter: its inputs are _is_service_role(), auth.uid(), current_agent_id() and
217
+ -- request.jwt.claims only. Exempt: (a) the operator key -- service_role with no principal and
218
+ -- no sub; (b) an agent or system principal. Every other caller must present a fresh proof of
219
+ -- its class, or gets MBS01:
220
+ -- portal human: top-level JSON-number agent_board_step_up_at T, fresh by
221
+ -- _step_up_is_fresh(T, clock), AND a ledger row (actor, T);
222
+ -- local human: top-level amr array; the max timestamp over object elements whose method
223
+ -- is an allowlisted string and whose timestamp is a JSON number, fresh.
224
+ -- Never consulted: aal, iat, auth_time, user_metadata, app_metadata, agents.metadata and the
225
+ -- legacy request.jwt.claim.* GUCs (for freshness). One guard per statement; the only raise
226
+ -- is MBS01, with the operation name (never a value) as DETAIL. Plain SELECTs, no row locks.
227
+ -- =============================================================================
228
+ create or replace function agent_board._require_human_step_up(p_operation text)
229
+ returns void
230
+ language plpgsql
231
+ volatile
232
+ security invoker
233
+ set search_path = ''
234
+ as $$
235
+ declare
236
+ v_raw text;
237
+ v_claims jsonb;
238
+ v_service boolean;
239
+ v_uid uuid;
240
+ v_actor uuid;
241
+ v_kind text;
242
+ v_now numeric;
243
+ v_t jsonb;
244
+ v_proof numeric;
245
+ v_amr jsonb;
246
+ v_methods text[];
247
+ v_e jsonb;
248
+ v_ts numeric;
249
+ v_best numeric;
250
+ begin
251
+ -- Claims: parsed in their own guarded block. Unparseable claims are no claims.
252
+ v_raw := current_setting('request.jwt.claims', true);
253
+ if v_raw is not null and v_raw <> '' then
254
+ begin
255
+ v_claims := v_raw::jsonb;
256
+ exception when others then
257
+ v_claims := null;
258
+ end;
259
+ end if;
260
+ if jsonb_typeof(v_claims) is distinct from 'object' then
261
+ v_claims := null;
262
+ end if;
263
+
264
+ -- The session. These readers cast the raw claims themselves; any failure is no proof.
265
+ begin
266
+ v_service := agent_board._is_service_role();
267
+ v_uid := auth.uid();
268
+ v_actor := agent_board.current_agent_id();
269
+ exception when others then
270
+ raise exception 'step_up_required' using errcode = 'MBS01', detail = p_operation;
271
+ end;
272
+
273
+ -- (a) The operator key: service_role, no principal, no sub (§5.4 tightening).
274
+ if v_service is true and v_actor is null and v_uid is null then
275
+ return;
276
+ end if;
277
+
278
+ if v_actor is null then
279
+ raise exception 'step_up_required' using errcode = 'MBS01', detail = p_operation;
280
+ end if;
281
+
282
+ select a.kind::text into v_kind
283
+ from agent_board.agents a
284
+ where a.id = v_actor;
285
+
286
+ -- (b) An agent or system principal.
287
+ if v_kind in ('agent', 'system') then
288
+ return;
289
+ end if;
290
+
291
+ if v_kind is distinct from 'human' then
292
+ raise exception 'step_up_required' using errcode = 'MBS01', detail = p_operation;
293
+ end if;
294
+
295
+ v_now := extract(epoch from clock_timestamp());
296
+
297
+ if agent_board._step_up_is_portal_human(v_actor) is true then
298
+ -- Portal class: claim AND ledger row (D8). Type check in its own statement.
299
+ v_t := v_claims -> 'agent_board_step_up_at';
300
+ if jsonb_typeof(v_t) is distinct from 'number' then
301
+ raise exception 'step_up_required' using errcode = 'MBS01', detail = p_operation;
302
+ end if;
303
+ v_proof := (v_claims ->> 'agent_board_step_up_at')::numeric;
304
+ if agent_board._step_up_is_fresh(v_proof, v_now) is not true then
305
+ raise exception 'step_up_required' using errcode = 'MBS01', detail = p_operation;
306
+ end if;
307
+ if not exists (
308
+ select 1
309
+ from agent_board.portal_step_up_proofs p
310
+ where p.agent_id = v_actor
311
+ and p.proof_at::numeric = v_proof
312
+ ) then
313
+ raise exception 'step_up_required' using errcode = 'MBS01', detail = p_operation;
314
+ end if;
315
+ return;
316
+ end if;
317
+
318
+ -- Local class: GoTrue top-level amr (D10), filtered by the allowlist (D11).
319
+ v_amr := v_claims -> 'amr';
320
+ if jsonb_typeof(v_amr) is distinct from 'array' then
321
+ raise exception 'step_up_required' using errcode = 'MBS01', detail = p_operation;
322
+ end if;
323
+ v_methods := agent_board._step_up_amr_methods();
324
+ for v_e in select e.value from jsonb_array_elements(v_amr) as e(value) loop
325
+ continue when jsonb_typeof(v_e) is distinct from 'object';
326
+ continue when jsonb_typeof(v_e -> 'method') is distinct from 'string';
327
+ continue when ((v_e ->> 'method') = any (v_methods)) is not true;
328
+ continue when jsonb_typeof(v_e -> 'timestamp') is distinct from 'number';
329
+ v_ts := (v_e ->> 'timestamp')::numeric;
330
+ if v_best is null or v_ts > v_best then
331
+ v_best := v_ts;
332
+ end if;
333
+ end loop;
334
+ if agent_board._step_up_is_fresh(v_best, v_now) is not true then
335
+ raise exception 'step_up_required' using errcode = 'MBS01', detail = p_operation;
336
+ end if;
337
+ end;
338
+ $$;
339
+
340
+ revoke all on function agent_board._require_human_step_up(text)
341
+ from public, anon, authenticated, service_role, agent_board_delegate;
342
+ comment on function agent_board._require_human_step_up(text) is
343
+ '#669 D2/D3: raises MBS01 step_up_required (DETAIL = the operation name) unless the session is the operator key (service_role, no principal, no sub), an agent/system principal, or a human with a fresh proof of its class: Portal humans need a fresh top-level agent_board_step_up_at AND a matching portal_step_up_proofs row; local humans need a fresh allowlisted top-level amr entry. No actor parameter. Not called by any function until PR-B. No API-role EXECUTE.';
@@ -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
+ $$;