@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
@@ -0,0 +1,991 @@
1
+ -- STEPUP PR-B pgTAP (#669, migration 20261124000100_agent_board_step_up_enforcement.sql).
2
+ --
3
+ -- THE CONTRACT (plans/STEPUP-669-plan.md §5, §6.2, §7, §10.1-§10.3 and §11.2, with the §14
4
+ -- binding errata E-1, E-2, E-3, E-5 and E-6(a)). PR-A's direct helper rows live in
5
+ -- agent_board_step_up_helper.test.sql; every row HERE goes through the real RPC.
6
+ -- * GATED (the helper is the last statement before return, D1): grant_board_role,
7
+ -- set_board_role_gate, set_board_authority_ceiling (always), create_invite_link (admin
8
+ -- preset), readmit_session_identity (a written role above member, D4), update_board_membership
9
+ -- (another actor takes an owner/admin out of active standing, keyed on the sink's result, E-5).
10
+ -- * REFUSED: mint_delegated_child for a human true root with an owner/admin room (D5).
11
+ -- * E-3: provision_agent refuses an API kind change on an existing principal.
12
+ -- * D7: the migration revoked every unexpired, unrevoked admin-preset token (seeded before it by
13
+ -- tests/seeds/20261124000100_agent_board_step_up_enforcement.sql.pre.sql).
14
+ -- * The frozen allowlist is {otp,totp} (owner, 2026-11-21: magic-link clicks, which also write
15
+ -- otp, are accepted); passkey/mfa-webauthn/mfa-phone stay off (unmeasured).
16
+ --
17
+ -- METHOD (AGENTS.md rules 1-3).
18
+ -- * Allow-side rows are lives_ok followed by a SEPARATE state query; refusals are throws_ok
19
+ -- with the SQLSTATE and the message. pg_temp.call raises inside throws_ok/lives_ok's own
20
+ -- subtransaction, so a refusal rolls back exactly that call and its claims.
21
+ -- * Class assertions are catalog-derived (fn_call_closure / stripped_body / the shared
22
+ -- matchers) and compared BY NAME with a printed difference, so a new route names itself.
23
+ -- * Rows are named by plan id. TAP numbers are counted by the receipts, never written here.
24
+ create extension if not exists pgtap with schema extensions;
25
+ set search_path = extensions, public, agent_board;
26
+
27
+ begin;
28
+
29
+ select plan(198);
30
+
31
+ do $$
32
+ begin
33
+ if not (select rolsuper from pg_roles where rolname = current_user) then
34
+ execute format('grant agent_board_delegate, anon, authenticated, service_role to %I with set true', current_user);
35
+ end if;
36
+ end $$;
37
+ grant usage on schema extensions to authenticated, service_role;
38
+ grant execute on function public.test_pubkey(text) to authenticated, service_role;
39
+
40
+ create temp table _h(k text primary key, v text);
41
+ create function pg_temp.v(p_k text) returns text language sql as $$ select v from _h where k = p_k $$;
42
+ create function pg_temp.u(p_k text) returns uuid language sql as $$
43
+ select case when v ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' then v::uuid end from _h where k = p_k $$;
44
+ create function pg_temp.put(p_k text, p_v text) returns void language sql as $$
45
+ insert into _h values (p_k, p_v) on conflict (k) do update set v = excluded.v $$;
46
+ create function pg_temp.now_s() returns bigint language sql volatile as $$
47
+ select floor(extract(epoch from clock_timestamp()))::bigint $$;
48
+ -- A ledger row written directly as the table owner (a fixture, not the writer); returns T.
49
+ create function pg_temp.ledger(p_who text, p_t bigint) returns bigint language sql volatile as $$
50
+ insert into agent_board.portal_step_up_proofs(agent_id, proof_at) values (pg_temp.u(p_who), p_t)
51
+ on conflict do nothing;
52
+ select p_t $$;
53
+
54
+ -- p_who's base claims (role authenticated unless recorded, sub, aud) merged with p_extra.
55
+ create function pg_temp.c(p_who text, p_extra jsonb default '{}'::jsonb) returns text language sql as $$
56
+ select (jsonb_strip_nulls(jsonb_build_object(
57
+ 'role', coalesce(pg_temp.v(p_who || '.role'), 'authenticated'),
58
+ 'sub', pg_temp.v(p_who || '.auth'),
59
+ 'aud', 'authenticated')) || p_extra)::text $$;
60
+ -- Portal-class claims: T with its ledger row, p_age seconds old.
61
+ create function pg_temp.pc(p_who text, p_age int) returns text language sql volatile as $$
62
+ select pg_temp.c(p_who, jsonb_build_object('agent_board_step_up_at', pg_temp.ledger(p_who, pg_temp.now_s() - p_age))) $$;
63
+ -- Local-class claims: one amr element (p_method, p_age seconds old).
64
+ create function pg_temp.lc(p_who text, p_age int, p_method text default 'totp') returns text language sql volatile as $$
65
+ select pg_temp.c(p_who, jsonb_build_object('amr', jsonb_build_array(
66
+ jsonb_build_object('method', p_method, 'timestamp', pg_temp.now_s() - p_age)))) $$;
67
+ -- A relay token: role service_role with p_who's sub.
68
+ create function pg_temp.relay(p_who text) returns text language sql as $$
69
+ select jsonb_build_object('role', 'service_role', 'sub', pg_temp.v(p_who || '.auth'))::text $$;
70
+
71
+ create function pg_temp.set_claims(p_claims text, p_legacy_name text default null, p_legacy_value text default null)
72
+ returns void language plpgsql as $$
73
+ begin
74
+ perform set_config('request.jwt.claim.sub', '', true);
75
+ perform set_config('request.jwt.claim.role', '', true);
76
+ perform set_config('request.jwt.claim.agent_credential_id', '', true);
77
+ perform set_config('request.jwt.claim.agent_board_step_up_at', '', true);
78
+ perform set_config('request.jwt.claim.amr', '', true);
79
+ if p_legacy_name is not null then
80
+ perform set_config('request.jwt.claim.' || p_legacy_name, p_legacy_value, true);
81
+ end if;
82
+ perform set_config('request.jwt.claims', coalesce(p_claims, ''), true);
83
+ end $$;
84
+ -- Run p_sql under p_claims. A raise propagates into the caller's throws_ok/lives_ok
85
+ -- subtransaction (which reverts the GUCs); on success the claims are cleared.
86
+ create function pg_temp.call(p_claims text, p_sql text, p_legacy_name text default null, p_legacy_value text default null)
87
+ returns void language plpgsql as $$
88
+ begin
89
+ perform pg_temp.set_claims(p_claims, p_legacy_name, p_legacy_value);
90
+ execute p_sql;
91
+ perform pg_temp.set_claims(null);
92
+ end $$;
93
+ -- The same as role p_role (the subtransaction rollback also reverts SET LOCAL ROLE on a raise).
94
+ create function pg_temp.call_as(p_role text, p_claims text, p_sql text) returns void language plpgsql as $$
95
+ begin
96
+ perform pg_temp.set_claims(p_claims);
97
+ execute format('set local role %I', p_role);
98
+ execute p_sql;
99
+ reset role;
100
+ perform pg_temp.set_claims(null);
101
+ end $$;
102
+ create function pg_temp.t(p_claims text, p_sql text) returns text language sql as $$
103
+ select format('select pg_temp.call(%L, %L)', p_claims, p_sql) $$;
104
+
105
+ -- The four RPC shapes (§10.2 "4 RPCs"), with literal ids so a role switch needs no fixture read.
106
+ create function pg_temp.q_grant(p_b text, p_target text, p_role text default 'admin', p_grantor text default null)
107
+ returns text language sql as $$
108
+ select format('select * from agent_board.grant_board_role(%L::uuid, %L::uuid, %L, %L::uuid)',
109
+ pg_temp.v(p_b), pg_temp.v(p_target), p_role, pg_temp.v(p_grantor)) $$;
110
+ create function pg_temp.q_gate(p_b text, p_on boolean) returns text language sql as $$
111
+ select format('select * from agent_board.set_board_role_gate(%L::uuid, %L)', pg_temp.v(p_b), p_on) $$;
112
+ create function pg_temp.q_ceil(p_b text, p_role text default 'member') returns text language sql as $$
113
+ select format('select * from agent_board.set_board_authority_ceiling(%L::uuid, %L)', pg_temp.v(p_b), p_role) $$;
114
+ create temp table _tok(label text, code text);
115
+ create function pg_temp.q_inv(p_b text, p_preset text default 'admin', p_label text default 'x') returns text language sql as $$
116
+ select format($f$insert into _tok select %L, code from agent_board.create_invite_link(%L::uuid, %L, 'joined', 3, now() + interval '1 day')$f$,
117
+ p_label, pg_temp.v(p_b), p_preset) $$;
118
+ create function pg_temp.q_mem(p_b text, p_target text, p_state text) returns text language sql as $$
119
+ select format('select * from agent_board.update_board_membership(%L::uuid, %L::uuid, %L)', pg_temp.v(p_b), pg_temp.v(p_target), p_state) $$;
120
+
121
+ -- State readers.
122
+ create function pg_temp.st(p_b text, p_who text) returns text language sql as $$
123
+ select coalesce((select bm.membership_state || ':' || bm.role from agent_board.board_memberships bm
124
+ where bm.board_id = pg_temp.u(p_b) and bm.agent_id = pg_temp.u(p_who)
125
+ order by case when bm.membership_state in ('joined', 'subscribed') then 0 else 1 end,
126
+ bm.created_at desc, bm.id desc limit 1), 'NONE') $$;
127
+ create function pg_temp.snap(p_b text, p_target text default 'M') returns text language sql as $$
128
+ select format('target=%s gate=%s ceiling=%s admin_tokens=%s', pg_temp.st(p_b, p_target),
129
+ (select role_gate_enforced::text from agent_board.boards where id = pg_temp.u(p_b)),
130
+ coalesce((select max_grantable_role from agent_board.board_authority_ceilings where board_id = pg_temp.u(p_b)), 'none'),
131
+ (select count(*) from agent_board.board_invite_tokens where board_id = pg_temp.u(p_b) and preset_role = 'admin')) $$;
132
+
133
+ -- ===========================================================================
134
+ -- Fixtures (§10 fixtures)
135
+ -- P, P2 Portal humans (kind human + a fedsession audit row)
136
+ -- L local human, also a platform admin (R-20/A-12); Ad, M, M2, MR, Rv, X, X2, W, Y local humans
137
+ -- G, T agents; SUS a suspended human; H a local human owning the agent root RT
138
+ -- Rv a fleet-revoked human owner on every board
139
+ -- Boards: BP (owner P), BL (owner L), BG (owner G), BO (owner P, open), BH (owner RT).
140
+ -- ===========================================================================
141
+ do $$
142
+ declare
143
+ v_who text[] := array['P','P2','L','G','T','M','M2','MR','Ad','Rv','SUS','X','X2','W','Y','H','RT','W2','W3'];
144
+ v_kind text[] := array['human','human','human','agent','agent','human','human','human','human','human','human','human','human','human','human','human','agent','human','human'];
145
+ i int;
146
+ begin
147
+ for i in 1 .. array_length(v_who, 1) loop
148
+ perform pg_temp.put(v_who[i], '669b1000-0000-4000-8000-' || lpad(i::text, 12, '0'));
149
+ perform pg_temp.put(v_who[i] || '.auth', '669b0000-0000-4000-8000-' || lpad(i::text, 12, '0'));
150
+ insert into auth.users(id, instance_id, aud, role, email)
151
+ values (pg_temp.u(v_who[i] || '.auth'), '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated',
152
+ 'su669b-' || lower(v_who[i]) || '@t.test');
153
+ insert into agent_board.agents(id, agent_type, kind, handle, display_name, status, auth_user_id, owner_user_id)
154
+ values (pg_temp.u(v_who[i]), v_kind[i], v_kind[i]::agent_board.agent_kind, 'su669b-' || lower(v_who[i]), 'SU669B ' || v_who[i],
155
+ case when v_who[i] = 'SUS' then 'suspended' else 'active' end, pg_temp.u(v_who[i] || '.auth'),
156
+ case when v_who[i] = 'RT' then pg_temp.u('H.auth') when v_kind[i] = 'human' then pg_temp.u(v_who[i] || '.auth') end);
157
+ end loop;
158
+ -- An auth user with no agent row (self_enroll_human's caller).
159
+ perform pg_temp.put('LU.auth', '669b0000-0000-4000-8000-000000000099');
160
+ insert into auth.users(id, instance_id, aud, role, email)
161
+ values (pg_temp.u('LU.auth'), '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated', 'su669b-lu@t.test');
162
+ -- Portal class evidence (§3.3) for P and P2.
163
+ insert into agent_board.enrollment_federation_audit(
164
+ issuer, audience, subject, human_identity_claim, agent_id, auth_user_id, requested_scopes, granted_scopes, mode)
165
+ select 'https://su669b-portal.test', 'message-board', 'su669b-' || w || '-subject',
166
+ jsonb_build_object('iss', 'https://su669b-portal.test', 'sub', 'su669b-' || w || '-subject'),
167
+ pg_temp.u(w), pg_temp.u(w || '.auth'), '{}', '{}', 'fedsession'
168
+ from unnest(array['P', 'P2']) w;
169
+ -- L is a platform admin (provision_agent's caller in R-20 / A-12).
170
+ insert into public.user_org_roles(user_id, role) values (pg_temp.u('L.auth'), 'platform_admin');
171
+ -- Boards.
172
+ perform pg_temp.put('BP', '669b2000-0000-4000-8000-000000000001');
173
+ perform pg_temp.put('BL', '669b2000-0000-4000-8000-000000000002');
174
+ perform pg_temp.put('BG', '669b2000-0000-4000-8000-000000000003');
175
+ perform pg_temp.put('BO', '669b2000-0000-4000-8000-000000000004');
176
+ perform pg_temp.put('BH', '669b2000-0000-4000-8000-000000000005');
177
+ insert into agent_board.boards(id, slug, name, created_by_agent_id, visibility, status) values
178
+ (pg_temp.u('BP'), 'su669b-bp', 'SU669B BP', pg_temp.u('P'), 'private', 'active'),
179
+ (pg_temp.u('BL'), 'su669b-bl', 'SU669B BL', pg_temp.u('L'), 'private', 'active'),
180
+ (pg_temp.u('BG'), 'su669b-bg', 'SU669B BG', pg_temp.u('G'), 'private', 'active'),
181
+ (pg_temp.u('BO'), 'su669b-bo', 'SU669B BO', pg_temp.u('P'), 'open', 'active'),
182
+ (pg_temp.u('BH'), 'su669b-bh', 'SU669B BH', pg_temp.u('RT'), 'private', 'active');
183
+ insert into agent_board.board_memberships(board_id, agent_id, role, membership_state, created_by_agent_id)
184
+ select pg_temp.u(b), pg_temp.u(w), r, 'joined', pg_temp.u(o)
185
+ from (values
186
+ ('BP','P','owner','P'), ('BP','Ad','admin','P'), ('BP','M','member','P'), ('BP','M2','member','P'),
187
+ ('BP','MR','member','P'), ('BP','Rv','owner','P'), ('BP','T','member','P'), ('BP','P2','member','P'),
188
+ ('BP','G','member','P'),
189
+ ('BL','L','owner','L'), ('BL','Ad','admin','L'), ('BL','M','member','L'), ('BL','Rv','owner','L'), ('BL','T','member','L'),
190
+ ('BG','G','owner','G'), ('BG','Ad','admin','G'), ('BG','M','member','G'), ('BG','Rv','owner','G'), ('BG','T','member','G'),
191
+ ('BO','P','owner','P'), ('BO','Y','admin','P'),
192
+ ('BH','RT','owner','RT')) m(b, w, r, o);
193
+ -- Rv is fleet-revoked (agent-subject ledger row); its agents.status stays active.
194
+ insert into agent_board.fleet_revocation_events(subject_kind, subject_id, agent_id, revoked_by_agent_id, revocation_reason)
195
+ values ('agent', pg_temp.u('Rv'), pg_temp.u('Rv'), pg_temp.u('Rv'), 'su669b-rv');
196
+ -- A live credential for P (R-8).
197
+ insert into agent_board.agent_credentials(id, agent_id, refresh_token_hash, hash_version, credential_label, expires_at)
198
+ values ('669b3000-0000-4000-8000-000000000001', pg_temp.u('P'), decode(md5('su669b-p-refresh'), 'hex'), 1, 'su669b-p', now() + interval '1 day');
199
+ -- P's signing key, so a gateway decision can name P (R-19).
200
+ insert into agent_board.agent_signing_keys(id, agent_id, key_id, key_version, public_key, public_key_format, fingerprint, status, proof_state)
201
+ values ('669b4000-0000-4000-8000-000000000001', pg_temp.u('P'), 'primary', 1, public.test_pubkey('su669b-p'),
202
+ 'raw_ed25519_base64url', public.test_key_fingerprint('su669b-p'), 'active', 'proven');
203
+ end $$;
204
+
205
+ do $$
206
+ begin
207
+ if agent_board._step_up_is_portal_human(pg_temp.u('P')) is not true
208
+ or agent_board._step_up_is_portal_human(pg_temp.u('P2')) is not true
209
+ or agent_board._step_up_is_portal_human(pg_temp.u('L')) is not false then
210
+ raise exception 'fixture: classifier does not see P/P2 as portal and L as local';
211
+ end if;
212
+ end $$;
213
+
214
+ create function pg_temp.gw(p_actor text) returns jsonb language sql as $$
215
+ select jsonb_build_object(
216
+ 'agent_id', pg_temp.v(p_actor), 'signing_key_id', '669b4000-0000-4000-8000-000000000001', 'key_id', 'primary',
217
+ 'key_version', 1, 'algorithm', 'Ed25519', 'verification_status', 'verified',
218
+ 'payload_digest', 'sha256:' || repeat('a', 64), 'signature_digest', 'sha256:' || repeat('b', 64),
219
+ 'canonicalization_version', 'agent-provenance-jcs.v1', 'enforcement_mode', 'require_for_agent_writes', 'redacted', true) $$;
220
+
221
+ -- ===========================================================================
222
+ -- §10.1 catalog class (EC-SU-1 ... EC-SU-4), derived at PR-B time (§11.4)
223
+ -- ===========================================================================
224
+ create temp table _cl as select * from agent_board_test.fn_call_closure();
225
+ -- The §7.4 property: a function's own stripped body writes board_memberships.role,
226
+ -- boards.role_gate_enforced or board_authority_ceilings, or inserts board_invite_tokens.
227
+ create temp table _direct as
228
+ select p.oid, p.proname::text as name
229
+ from pg_proc p
230
+ where p.pronamespace = 'agent_board'::regnamespace and p.prokind in ('f', 'p')
231
+ and p.prolang <> (select oid from pg_language where lanname = 'internal')
232
+ and (agent_board_test.stripped_body(p.oid) ~ agent_board_test.col_write_re('board_memberships', 'role')
233
+ or agent_board_test.stripped_body(p.oid) ~ agent_board_test.col_write_re('boards', 'role_gate_enforced')
234
+ or agent_board_test.stripped_body(p.oid) ~ agent_board_test.writes_any_re(array['board_authority_ceilings'])
235
+ or agent_board_test.stripped_body(p.oid) ~ agent_board_test.stmt_re('insert into', 'board_invite_tokens'));
236
+ -- F is in scope when its call closure reaches a direct writer.
237
+ create temp table _cls as
238
+ select distinct c.root_oid as oid, (select proname::text from pg_proc where oid = c.root_oid) as name,
239
+ exists (select 1 from unnest(array['anon', 'authenticated', 'agent_board_delegate']) r
240
+ where has_function_privilege(r, c.root_oid, 'EXECUTE')) as api
241
+ from _cl c join _direct d on d.oid = c.reached_oid;
242
+ -- GATED by the catalog: the functions whose OWN stripped body calls the helper (E-1(2)).
243
+ create temp table _gated as
244
+ select p.oid, p.proname::text as name from pg_proc p
245
+ where p.pronamespace = 'agent_board'::regnamespace and p.prokind in ('f', 'p')
246
+ and p.oid <> 'agent_board._require_human_step_up(text)'::regprocedure
247
+ and agent_board_test.stripped_body(p.oid) ~ agent_board_test.call_re('_require_human_step_up');
248
+
249
+ create temp table _decl(name text primary key, cls text not null);
250
+ insert into _decl values
251
+ ('grant_board_role', 'GATED'), ('set_board_role_gate', 'GATED'), ('set_board_authority_ceiling', 'GATED'),
252
+ ('create_invite_link', 'GATED'), ('readmit_session_identity', 'GATED'), ('update_board_membership', 'GATED'),
253
+ ('signed_grant_board_role', 'INHERIT'), ('signed_set_board_authority_ceiling', 'INHERIT'),
254
+ ('mint_delegated_child', 'REFUSED'),
255
+ ('create_board', 'EXEMPT-API'), ('redeem_invite_link', 'EXEMPT-API'), ('create_fleet_onboarding_invite', 'EXEMPT-API'),
256
+ ('join_board', 'EXEMPT-API'), ('request_join_board', 'EXEMPT-API'), ('resolve_board_request', 'EXEMPT-API'),
257
+ ('invite_board_member', 'EXEMPT-API'), ('add_delegate_to_board', 'EXEMPT-API'), ('leave_board', 'EXEMPT-API'),
258
+ ('link_session_alias', 'EXEMPT-SVC'), ('_redeem_invite_for_agent', 'EXEMPT-SVC'),
259
+ ('_redeem_fleet_invite_for_agent', 'EXEMPT-SVC'), ('_redeem_unbounded_invite_for_agent', 'EXEMPT-SVC'),
260
+ ('_fedsession_autojoin_default_board', 'EXEMPT-SVC'), ('_upsert_board_membership_state', 'EXEMPT-SVC'),
261
+ ('bootstrap_board_owner_memberships', 'EXEMPT-SVC'), ('onboard_federated_fleet_agent', 'EXEMPT-SVC'),
262
+ -- Returned by the catalog at PR-B time and not named by the plan's §7.5 (classified here, E-1):
263
+ ('enroll_federated_human', 'EXEMPT-SVC'), ('_enroll_federated_human_after_revocation_gate', 'EXEMPT-SVC'),
264
+ ('enroll_federated_identity', 'EXEMPT-SVC'), ('_enroll_federated_identity_once', 'EXEMPT-SVC'),
265
+ ('tombstone_delegate_instance', 'EXEMPT-SVC');
266
+
267
+ -- EC-SU-1: the §7.4 class, by name, equals GATED ∪ INHERIT ∪ REFUSED ∪ EXEMPT-API ∪ EXEMPT-SVC.
268
+ select is(
269
+ (select coalesce(nullif(concat_ws(' ',
270
+ (select 'catalog-only: ' || string_agg(distinct name, ', ' order by name) from _cls where name not in (select name from _decl)),
271
+ (select 'declared-only: ' || string_agg(name, ', ' order by name) from _decl where name not in (select name from _cls))), ''), '(none)')),
272
+ '(none)',
273
+ 'EC-SU-1: the catalog-derived conferral class equals GATED ∪ INHERIT ∪ REFUSED ∪ EXEMPT-API ∪ EXEMPT-SVC, by name');
274
+ -- EC-SU-1 control: the class query inspected the expected volume (not vacuous).
275
+ select is((select count(distinct name)::int from _cls), (select count(*)::int from _decl),
276
+ 'EC-SU-1 control: the catalog class and the declaration have the same number of names');
277
+ -- EC-SU-1 (P-4): API-reachability matches the declared class: GATED/EXEMPT-API are API-executable,
278
+ -- INHERIT/REFUSED/EXEMPT-SVC are service-only.
279
+ select is(
280
+ (select coalesce(string_agg(d.name || ':' || d.cls || ':api=' || c.api::text, ', ' order by d.name), '(none)')
281
+ from _decl d join (select name, bool_or(api) api from _cls group by name) c using (name)
282
+ where c.api <> (d.cls in ('GATED', 'EXEMPT-API'))),
283
+ '(none)',
284
+ 'EC-SU-1 (P-4): every GATED/EXEMPT-API member is API-executable and every INHERIT/REFUSED/EXEMPT-SVC member is not');
285
+
286
+ -- EC-SU-1b: each named non-member exists and does not match the property.
287
+ select is(
288
+ (select coalesce(string_agg(n || case when not exists (select 1 from pg_proc p where p.pronamespace = 'agent_board'::regnamespace and p.proname = n)
289
+ then ':MISSING' else ':MATCHES' end, ', ' order by n), '(none)')
290
+ from unnest(array['set_board_claim_policy', 'block_board_inviter', 'unblock_board_inviter', 'revoke_invite_link']) n
291
+ where not exists (select 1 from pg_proc p where p.pronamespace = 'agent_board'::regnamespace and p.proname = n)
292
+ or n in (select name from _cls)),
293
+ '(none)',
294
+ 'EC-SU-1b: set_board_claim_policy, block/unblock_board_inviter and revoke_invite_link exist and are outside the class');
295
+
296
+ -- EC-SU-2 (replaces PR-A's EC-SU-0): the functions whose own body calls the helper are exactly GATED.
297
+ select is(
298
+ (select string_agg(name, ' ' order by name) from _gated),
299
+ (select string_agg(name, ' ' order by name) from _decl where cls = 'GATED'),
300
+ 'EC-SU-2: exactly the six GATED functions call _require_human_step_up in their own body');
301
+ -- EC-SU-2 (D1): in every GATED body nothing that writes follows the LAST helper call: no direct
302
+ -- write statement, and no call to a function whose call closure reaches one (the membership
303
+ -- chokepoint writes only through the sink, so a direct-DML scan alone would miss its write).
304
+ create temp table _wtables as
305
+ select array_agg(c.relname::text) as t from pg_class c where c.relnamespace = 'agent_board'::regnamespace and c.relkind in ('r', 'p');
306
+ create temp table _wdirect as
307
+ select p.oid from pg_proc p
308
+ where p.pronamespace = 'agent_board'::regnamespace and p.prokind in ('f', 'p')
309
+ and p.prolang <> (select oid from pg_language where lanname = 'internal')
310
+ and agent_board_test.stripped_body(p.oid) ~ agent_board_test.writes_any_re((select t from _wtables));
311
+ create temp table _wreach as
312
+ select distinct p.proname::text as name
313
+ from _cl c join pg_proc p on p.oid = c.root_oid
314
+ where c.reached_oid in (select oid from _wdirect);
315
+ create temp table _gsplit as
316
+ select g.name, cnt.n, substr(sb.b, 1, greatest(pos.p - 1, 0)) as head, substr(sb.b, pos.p) as tail
317
+ from _gated g
318
+ cross join lateral (select agent_board_test.stripped_body(g.oid) as b) sb
319
+ cross join lateral (select regexp_count(sb.b, agent_board_test.call_re('_require_human_step_up')) as n) cnt
320
+ cross join lateral (select case when cnt.n > 0 then regexp_instr(sb.b, agent_board_test.call_re('_require_human_step_up'), 1, cnt.n) else 0 end as p) pos;
321
+ select is(
322
+ (select coalesce(string_agg(name, ', ' order by name), '(none)') from _gsplit g
323
+ where g.n = 0
324
+ or g.tail ~ agent_board_test.writes_any_re((select t from _wtables))
325
+ or exists (select 1 from _wreach r where r.name <> g.name and g.tail ~ agent_board_test.call_re(r.name))),
326
+ '(none)',
327
+ 'EC-SU-2 (D1): no GATED body writes, or calls a writer, after its last _require_human_step_up call');
328
+ -- EC-SU-2 control: the same matchers DO find a write (direct or through a writer call) BEFORE the
329
+ -- call in each of the six bodies, so the tail check is not vacuous.
330
+ select is(
331
+ (select count(*)::int from _gsplit g
332
+ where g.head ~ agent_board_test.writes_any_re((select t from _wtables))
333
+ or exists (select 1 from _wreach r where r.name <> g.name and g.head ~ agent_board_test.call_re(r.name))),
334
+ 6,
335
+ 'EC-SU-2 control: each GATED body writes (directly or through a writer) before its helper call');
336
+
337
+ -- E-1(2): the reflexive reverse call closure of GATED (E-11's forbidden set) is exactly this set.
338
+ -- create_fleet_onboarding_invite (member literal), leave_board (self transition) and
339
+ -- tombstone_delegate_instance (service-only, a delegate target) reach a GATED function but can
340
+ -- never satisfy its gate condition; each has a positive row below. The tree check
341
+ -- (scripts/check-step-up-tree.mjs) enforces this set against supabase/functions/**, and the
342
+ -- catalog snapshot tests/catalog/step_up_gated_closure.json pins it so the two cannot drift.
343
+ select is(
344
+ (select string_agg(distinct (select proname::text from pg_proc where oid = c.root_oid), ' '
345
+ order by (select proname::text from pg_proc where oid = c.root_oid))
346
+ from _cl c where c.reached_oid in (select oid from _gated)),
347
+ 'create_fleet_onboarding_invite create_invite_link grant_board_role leave_board readmit_session_identity set_board_authority_ceiling set_board_role_gate signed_grant_board_role signed_set_board_authority_ceiling tombstone_delegate_instance update_board_membership',
348
+ 'E-1: the reflexive reverse call closure of GATED is exactly the E-11 forbidden set');
349
+
350
+ -- E-11 exemption premises (plan-owner ruling 1, 2026-11-21). tombstone_delegate_instance is the
351
+ -- single positively-claimed exemption: it is service-only (EC-SU-3b names it otherwise) and its
352
+ -- only route to a GATED function is update_board_membership on a hosted delegate, which the HOSTED
353
+ -- role-writer class keeps at member, so the owner/admin gate condition cannot hold. Both premises
354
+ -- are asserted HERE, positively, so a change to either names itself.
355
+ -- TX-1: its call closure reaches exactly one GATED function.
356
+ select is(
357
+ (select coalesce(string_agg(distinct g.name, ' ' order by g.name), '(none)')
358
+ from _cl c join _gated g on g.oid = c.reached_oid
359
+ where c.root_oid = 'agent_board.tombstone_delegate_instance(text,text,text,text)'::regprocedure),
360
+ 'update_board_membership',
361
+ 'TX-1 (E-11 exemption): tombstone_delegate_instance reaches exactly one GATED function, update_board_membership');
362
+ -- TX-2: its one call to it passes v_row.agent_id, and v_row is a delegate_instances row filled only
363
+ -- from delegate_instances.
364
+ select is(
365
+ (select format('calls=%s delegate_target_calls=%s v_row_rowtype=%s v_row_sources=%s/%s',
366
+ regexp_count(b, agent_board_test.call_re('update_board_membership')),
367
+ regexp_count(b, agent_board_test.call_re('update_board_membership') || '\s*v_board\s*,\s*v_row\.agent_id\s*,'),
368
+ (b ~* '\mv_row\s+agent_board\.delegate_instances%rowtype')::text,
369
+ regexp_count(b, '(?i)\minto\s+v_row\M'),
370
+ regexp_count(b, '(?i)\minto\s+v_row\s+from\s+agent_board\.delegate_instances\M'))
371
+ from (select agent_board_test.stripped_body('agent_board.tombstone_delegate_instance(text,text,text,text)'::regprocedure) as b) x),
372
+ 'calls=1 delegate_target_calls=1 v_row_rowtype=true v_row_sources=1/1',
373
+ 'TX-2 (E-11 exemption): tombstone''s only update_board_membership call targets v_row.agent_id, a delegate_instances row filled only from delegate_instances');
374
+
375
+ -- EC-SU-3a: every INHERIT wrapper is service-only and its closure reaches a GATED function.
376
+ select is(
377
+ (select string_agg(d.name || '->' || coalesce((select string_agg(distinct g.name, '+' order by g.name)
378
+ from _cl c join _gated g on g.oid = c.reached_oid
379
+ join pg_proc p on p.oid = c.root_oid
380
+ where p.proname = d.name and p.pronamespace = 'agent_board'::regnamespace), 'NONE')
381
+ || case when exists (select 1 from pg_proc p, unnest(array['anon', 'authenticated', 'agent_board_delegate']) r
382
+ where p.proname = d.name and p.pronamespace = 'agent_board'::regnamespace
383
+ and has_function_privilege(r, p.oid, 'EXECUTE')) then ':API' else '' end,
384
+ ' ' order by d.name)
385
+ from _decl d where d.cls = 'INHERIT'),
386
+ 'signed_grant_board_role->grant_board_role signed_set_board_authority_ceiling->set_board_authority_ceiling',
387
+ 'EC-SU-3a: each INHERIT wrapper is service-only and reaches its GATED chokepoint');
388
+
389
+ -- EC-SU-3b: every EXEMPT-SVC and REFUSED member is service-only.
390
+ select is(
391
+ (select coalesce(string_agg(distinct d.name, ', ' order by d.name), '(none)')
392
+ from _decl d join pg_proc p on p.proname = d.name and p.pronamespace = 'agent_board'::regnamespace
393
+ where d.cls in ('EXEMPT-SVC', 'REFUSED')
394
+ and exists (select 1 from unnest(array['anon', 'authenticated', 'agent_board_delegate']) r where has_function_privilege(r, p.oid, 'EXECUTE'))),
395
+ '(none)',
396
+ 'EC-SU-3b: no EXEMPT-SVC or REFUSED member is executable by anon, authenticated or agent_board_delegate');
397
+ -- EC-SU-3b: the EXEMPT-SVC members whose OWN body writes the property are exactly these five, each
398
+ -- with a positive row below (SVC-1..SVC-5); the rest reach the property only through them.
399
+ select is(
400
+ (select string_agg(d.name, ' ' order by d.name) from _decl d where d.cls = 'EXEMPT-SVC' and d.name in (select name from _direct)),
401
+ '_fedsession_autojoin_default_board _redeem_unbounded_invite_for_agent _upsert_board_membership_state bootstrap_board_owner_memberships link_session_alias',
402
+ 'EC-SU-3b: the direct EXEMPT-SVC writers are exactly the five with behaviour rows');
403
+ -- EC-SU-3b (composites): an EXEMPT-SVC member that is not a direct writer reaches the property ONLY
404
+ -- through direct writers that are themselves classified and rowed (EXEMPT-SVC direct, GATED).
405
+ select is(
406
+ (select coalesce(string_agg(distinct d.name || '->' || dw.name, ', ' order by d.name || '->' || dw.name), '(none)')
407
+ from _decl d join pg_proc p on p.proname = d.name and p.pronamespace = 'agent_board'::regnamespace
408
+ join _cl c on c.root_oid = p.oid join _direct dw on dw.oid = c.reached_oid
409
+ where d.cls = 'EXEMPT-SVC' and d.name not in (select name from _direct)
410
+ and dw.name not in (select name from _decl where cls in ('EXEMPT-SVC', 'GATED'))),
411
+ '(none)',
412
+ 'EC-SU-3b: every composite EXEMPT-SVC member reaches the property only through rowed writers');
413
+
414
+ -- EC-SU-4 (E-2): W(O) and the reflexive reverse closure R(O) over fn_call_closure().
415
+ create temp table _protected as
416
+ with fns as (
417
+ select p.oid, agent_board_test.stripped_body(p.oid) as body from pg_proc p
418
+ where p.pronamespace = 'agent_board'::regnamespace and p.prokind in ('f', 'p')
419
+ and p.prolang <> (select oid from pg_language where lanname = 'internal'))
420
+ select 'enrollment_federation_audit' as obj, oid from fns where body ~ agent_board_test.writes_any_re(array['enrollment_federation_audit'])
421
+ union all select 'portal_step_up_proofs', oid from fns where body ~ agent_board_test.writes_any_re(array['portal_step_up_proofs'])
422
+ union all select 'agents.kind', oid from fns where body ~ agent_board_test.col_write_re('agents', 'kind')
423
+ union all select 'agents.agent_type', oid from fns where body ~ agent_board_test.col_write_re('agents', 'agent_type')
424
+ union all select 'agents.auth_user_id', oid from fns where body ~ agent_board_test.col_write_re('agents', 'auth_user_id');
425
+ create temp table _protected_api as
426
+ select distinct w.obj, c.root_oid, (select proname::text from pg_proc where oid = c.root_oid) as name
427
+ from _protected w join _cl c on c.reached_oid = w.oid
428
+ where exists (select 1 from unnest(array['anon', 'authenticated', 'agent_board_delegate']) r where has_function_privilege(r, c.root_oid, 'EXECUTE'));
429
+ -- EC-SU-4: the two tables have NO API-executable member of R(O).
430
+ select is(
431
+ (select coalesce(string_agg(obj || '<-' || name, ', ' order by obj, name), '(none)')
432
+ from _protected_api where obj in ('enrollment_federation_audit', 'portal_step_up_proofs')),
433
+ '(none)',
434
+ 'EC-SU-4 (E-2): no API role can execute a function whose closure writes enrollment_federation_audit or portal_step_up_proofs');
435
+ -- EC-SU-4 control: W(enrollment_federation_audit) is non-empty.
436
+ select ok((select count(*) >= 1 from _protected where obj = 'enrollment_federation_audit'),
437
+ 'EC-SU-4 control: the audit table has writers, so the closure check inspected something');
438
+ -- EC-SU-4: the agents-column members of R(O) that an API role can execute are exactly the named
439
+ -- exception set, each asserted POSITIVELY by a behaviour row below (X-1..X-4).
440
+ select is(
441
+ (select string_agg(distinct name, ' ' order by name) from _protected_api where obj like 'agents.%'),
442
+ 'provision_agent readmit_session_identity register_agent self_enroll_human',
443
+ 'EC-SU-4 (E-2(4)): the API-executable writers of agents.kind/agent_type/auth_user_id are exactly the four exception rows');
444
+ -- EC-SU-4: no API role holds a write privilege on the audit table or the three agents columns.
445
+ select is(
446
+ (select coalesce(string_agg(r.role || ':' || pv.priv, ' ' order by r.role, pv.priv), '(none)')
447
+ from (values ('anon'), ('authenticated'), ('agent_board_delegate')) r(role)
448
+ cross join (values ('INSERT'), ('UPDATE'), ('DELETE'), ('TRUNCATE')) pv(priv)
449
+ where has_table_privilege(r.role, 'agent_board.enrollment_federation_audit', pv.priv)),
450
+ '(none)',
451
+ 'EC-SU-4: no API role holds INSERT/UPDATE/DELETE/TRUNCATE on enrollment_federation_audit');
452
+ select is(
453
+ (select coalesce(string_agg(r.role || ':' || col || ':' || pv.priv, ' ' order by r.role, col, pv.priv), '(none)')
454
+ from (values ('anon'), ('authenticated'), ('agent_board_delegate')) r(role)
455
+ cross join unnest(array['kind', 'agent_type', 'auth_user_id']) col
456
+ cross join (values ('INSERT'), ('UPDATE')) pv(priv)
457
+ where has_column_privilege(r.role, 'agent_board.agents', col, pv.priv)),
458
+ '(none)',
459
+ 'EC-SU-4: no API role holds INSERT/UPDATE on agents.kind, agents.agent_type or agents.auth_user_id');
460
+ select is(
461
+ (select coalesce(string_agg(r.role || ':' || pv.priv, ' ' order by r.role, pv.priv), '(none)')
462
+ from (values ('anon'), ('authenticated'), ('agent_board_delegate')) r(role)
463
+ cross join (values ('DELETE'), ('TRUNCATE')) pv(priv)
464
+ where has_table_privilege(r.role, 'agent_board.agents', pv.priv)),
465
+ '(none)',
466
+ 'EC-SU-4: no API role can DELETE or TRUNCATE agents (an audit-bearing principal cannot be removed)');
467
+
468
+ -- EC-SU-4t (#802 P-2): TRIGGERS AS ROOTS. fn_call_closure follows calls only, but a function that
469
+ -- writes a table also runs that table's triggers, so a trigger function is reached by every
470
+ -- writer of its table. The trigger edges come from pg_trigger (every user trigger, every schema's
471
+ -- table, enabled or not: a disabled trigger can be re-enabled) and the writers from the shared
472
+ -- write matcher; the closure is then re-taken over calls AND trigger edges. Over-approximate on
473
+ -- purpose: any write to the table is an edge, whatever the trigger's event or WHEN clause.
474
+ create temp table _abody as
475
+ select p.oid, agent_board_test.stripped_body(p.oid) as body from pg_proc p
476
+ where p.pronamespace = 'agent_board'::regnamespace and p.prokind in ('f', 'p')
477
+ and p.prolang <> (select oid from pg_language where lanname = 'internal');
478
+ create temp table _trg_rel as
479
+ select distinct t.tgrelid as rel_oid, n.nspname || '.' || c.relname as rel
480
+ from pg_trigger t join pg_class c on c.oid = t.tgrelid join pg_namespace n on n.oid = c.relnamespace
481
+ where not t.tgisinternal;
482
+ create temp table _trg_edges as
483
+ select distinct b.oid as caller, t.tgfoid as callee, r.rel
484
+ from _trg_rel as r join pg_trigger t on t.tgrelid = r.rel_oid and not t.tgisinternal
485
+ cross join _abody as b
486
+ where b.body ~ agent_board_test.writes_any_re(array[r.rel]);
487
+ -- hop: root reaches (by calls) a writer of a table whose trigger function is reached_oid; then
488
+ -- again from that trigger function, to a fixpoint. _cl is reflexive, so a writer is its own root.
489
+ create temp table _cl_trg as
490
+ with recursive hop(root_oid, reached_oid) as (
491
+ select c.root_oid, e.callee from _cl c join _trg_edges e on e.caller = c.reached_oid
492
+ union
493
+ select h.root_oid, e.callee from hop h join _cl c on c.root_oid = h.reached_oid join _trg_edges e on e.caller = c.reached_oid
494
+ )
495
+ select root_oid, reached_oid from _cl
496
+ union select h.root_oid, c.reached_oid from hop h join _cl c on c.root_oid = h.reached_oid
497
+ union select root_oid, reached_oid from hop;
498
+ create temp table _protected_api_trg as
499
+ select distinct w.obj, c.root_oid, (select proname::text from pg_proc where oid = c.root_oid) as name
500
+ from _protected w join _cl_trg c on c.reached_oid = w.oid
501
+ where exists (select 1 from unnest(array['anon', 'authenticated', 'agent_board_delegate']) r where has_function_privilege(r, c.root_oid, 'EXECUTE'));
502
+ -- EC-SU-4t: trigger edges add NO API-executable route to the audit table, the ledger or the three
503
+ -- agents columns: R(O) over calls+triggers has exactly the API members R(O) over calls has, so
504
+ -- the exact sets EC-SU-4 pins above hold with triggers as roots too.
505
+ select is(
506
+ (select coalesce(string_agg(x.obj || '<-' || x.name, ', ' order by x.obj, x.name), '(none)')
507
+ from (select obj, root_oid, name from _protected_api_trg except select obj, root_oid, name from _protected_api) x),
508
+ '(none)',
509
+ 'EC-SU-4t (#802 P-2): with trigger edges in the closure, no further API-executable function reaches enrollment_federation_audit, portal_step_up_proofs or agents.kind/agent_type/auth_user_id');
510
+ -- EC-SU-4t control: the trigger edges are real. A writer of agents reaches trg_sync_agent_principal_columns'
511
+ -- function through them, so the row above inspected trigger routes and is not vacuous.
512
+ select ok(
513
+ (select count(*) >= 1 from _trg_edges e join pg_proc p on p.oid = e.callee
514
+ where e.rel = 'agent_board.agents' and p.proname = 'sync_agent_principal_columns'),
515
+ 'EC-SU-4t control: some agent_board writer of agents reaches sync_agent_principal_columns through a trigger edge');
516
+ -- EC-SU-4t: a BEFORE trigger writes a row by ASSIGNING NEW, which no statement matcher sees. The
517
+ -- trigger functions on agents that assign NEW.kind, NEW.agent_type or NEW.auth_user_id (`:=` or
518
+ -- `=`, so a comparison may over-match; fail-closed) are exactly the one sync function.
519
+ select is(
520
+ (select coalesce(string_agg(distinct p.proname::text, ' ' order by p.proname::text), '(none)')
521
+ from pg_trigger t join pg_proc p on p.oid = t.tgfoid
522
+ join _abody as b on b.oid = p.oid
523
+ where t.tgrelid = 'agent_board.agents'::regclass and not t.tgisinternal
524
+ and b.body ~ agent_board_test.re('\mnew\s*\.\s*' || agent_board_test.ident_re('kind') || '\s*:?='
525
+ || '|\mnew\s*\.\s*' || agent_board_test.ident_re('agent_type') || '\s*:?='
526
+ || '|\mnew\s*\.\s*' || agent_board_test.ident_re('auth_user_id') || '\s*:?=')),
527
+ 'sync_agent_principal_columns',
528
+ 'EC-SU-4t (#802 P-2): the only trigger function on agents that assigns NEW.kind/agent_type/auth_user_id is sync_agent_principal_columns');
529
+ -- EC-SU-4t, the exemption asserted POSITIVELY: sync_agent_principal_columns' `:=` assignments to
530
+ -- those columns are exactly the derived copies. kind is set only from the same row's agent_type,
531
+ -- agent_type only from its kind, and auth_user_id only to NULL; so a writer reaching it through
532
+ -- the trigger already writes kind or agent_type itself (and is in EC-SU-4's R(agents.*)), and it
533
+ -- never sets a principal's auth binding to a value.
534
+ select is(
535
+ (select string_agg(distinct a, ' ' order by a)
536
+ from pg_trigger t join pg_proc p on p.oid = t.tgfoid join _abody as b on b.oid = p.oid
537
+ cross join lateral regexp_matches(b.body, agent_board_test.re('\mnew\s*\.\s*(' || agent_board_test.ci_re('kind') || '|'
538
+ || agent_board_test.ci_re('agent_type') || '|' || agent_board_test.ci_re('auth_user_id')
539
+ || ')\s*:=\s*([^;]*);'), 'g') m
540
+ cross join lateral (select lower(regexp_replace(m[1] || ':=' || m[2], '\s+', '', 'g')) as a) x
541
+ where t.tgrelid = 'agent_board.agents'::regclass and not t.tgisinternal and p.proname = 'sync_agent_principal_columns'),
542
+ 'agent_type:=new.kind::text auth_user_id:=null kind:=new.agent_type::agent_board.agent_kind',
543
+ 'EC-SU-4t (#802 P-2): sync_agent_principal_columns sets kind only from agent_type, agent_type only from kind, and auth_user_id only to NULL');
544
+
545
+ -- The frozen allowlist (D11/Q3) and every chokepoint's ACL and COMMENT (restated in the migration).
546
+ select is(agent_board._step_up_amr_methods(), '{otp,totp}'::text[], 'D11/Q3: the frozen allowlist is {otp,totp} (Q3 ∩ measured; otp/magic-link collision accepted by the owner)');
547
+ select is(
548
+ (select coalesce(string_agg(p.oid::regprocedure::text, ', ' order by p.oid::regprocedure::text), '(none)')
549
+ from pg_proc p where p.pronamespace = 'agent_board'::regnamespace
550
+ and p.proname in ('grant_board_role', 'set_board_role_gate', 'set_board_authority_ceiling', 'create_invite_link',
551
+ 'readmit_session_identity', 'update_board_membership', 'mint_delegated_child', 'provision_agent', '_step_up_amr_methods')
552
+ and (has_function_privilege('public', p.oid, 'EXECUTE') or has_function_privilege('anon', p.oid, 'EXECUTE')
553
+ or has_function_privilege('agent_board_delegate', p.oid, 'EXECUTE')
554
+ or coalesce(obj_description(p.oid, 'pg_proc'), '') not like '%#669%')),
555
+ '(none)',
556
+ 'ACL/COMMENT: no re-created function is executable by PUBLIC, anon or agent_board_delegate, and each COMMENT carries its #669 text');
557
+ select is(
558
+ (select string_agg(p.proname || '=' || (case when has_function_privilege('authenticated', p.oid, 'EXECUTE') then 'A' else '-' end)
559
+ || (case when has_function_privilege('service_role', p.oid, 'EXECUTE') then 'S' else '-' end), ' ' order by p.proname)
560
+ from pg_proc p where p.pronamespace = 'agent_board'::regnamespace
561
+ and p.proname in ('grant_board_role', 'set_board_role_gate', 'set_board_authority_ceiling', 'create_invite_link',
562
+ 'readmit_session_identity', 'update_board_membership', 'mint_delegated_child', 'provision_agent')),
563
+ 'create_invite_link=AS grant_board_role=AS mint_delegated_child=-S provision_agent=AS readmit_session_identity=A- set_board_authority_ceiling=AS set_board_role_gate=AS update_board_membership=AS',
564
+ 'ACL: each re-created chokepoint keeps exactly its pre-PR-B authenticated/service_role EXECUTE');
565
+
566
+ -- ===========================================================================
567
+ -- D7 upgrade test (§11.2): the seeded tokens after the shipped revocation DML
568
+ -- ===========================================================================
569
+ select is(
570
+ (select (revoked_at is not null)::text || '/' || coalesce(revoked_by_agent_id::text, 'NULL')
571
+ from agent_board.board_invite_tokens where code = 'su669b-seed-admin-live'),
572
+ 'true/NULL',
573
+ 'D7-1: the seeded unexpired, unrevoked admin token was revoked by the migration, revoker NULL (system)');
574
+ select is(
575
+ (select revoked_at::text || '/' || revoked_by_agent_id::text from agent_board.board_invite_tokens where code = 'su669b-seed-admin-gone'),
576
+ (timestamptz '2026-11-01 00:00:00+00')::text || '/669bd100-0000-4000-8000-000000000001',
577
+ 'D7-2: an admin token revoked before the cutover keeps its original revoked_at and revoker');
578
+ select is(
579
+ (select (revoked_at is null)::text from agent_board.board_invite_tokens where code = 'su669b-seed-member-live'),
580
+ 'true',
581
+ 'D7-3: a member-preset token is not revoked (D7 is admin-only)');
582
+ select is(
583
+ (select (revoked_at is null)::text from agent_board.board_invite_tokens where code = 'su669b-seed-admin-old'),
584
+ 'true',
585
+ 'D7-4: an expired admin token is left as it is (already unusable)');
586
+ select is(
587
+ (select count(*)::int from agent_board.board_invite_tokens where preset_role = 'admin' and revoked_at is null and expires_at > now()
588
+ and board_id = '669bd200-0000-4000-8000-000000000001'),
589
+ 0,
590
+ 'D7-5: no unexpired, unrevoked admin token remains on the seeded board (the receipt''s after-count)');
591
+ -- R-18: redeeming the revoked admin token is refused, and writes no membership.
592
+ select throws_ok(pg_temp.t(pg_temp.lc('X', 301), $$select * from agent_board.redeem_invite_link('su669b-seed-admin-live')$$),
593
+ '42501', 'invite is not usable', 'R-18: redeeming a D7-revoked admin token is refused');
594
+ select is((select count(*)::int from agent_board.board_memberships
595
+ where board_id = '669bd200-0000-4000-8000-000000000001' and agent_id = pg_temp.u('X')),
596
+ 0, 'R-18 state: no membership was written for the redeemer');
597
+ -- R-18 control: the SAME creator's member token still redeems, so the refusal above is the revocation.
598
+ select lives_ok(pg_temp.t(pg_temp.lc('X', 301), $$select * from agent_board.redeem_invite_link('su669b-seed-member-live')$$),
599
+ 'R-18 control: the same creator''s unrevoked member token still redeems');
600
+ select is((select role || '/' || membership_state from agent_board.board_memberships
601
+ where board_id = '669bd200-0000-4000-8000-000000000001' and agent_id = pg_temp.u('X')),
602
+ 'member/joined', 'R-18 control state: the member token seated the redeemer as member');
603
+
604
+ -- ===========================================================================
605
+ -- §10.2 REJECT rows through the RPCs
606
+ -- ===========================================================================
607
+ select pg_temp.put('snapBP', pg_temp.snap('BP'));
608
+ -- R-1: P, T = clock - 301 with a ledger row, on all four RPCs.
609
+ select throws_ok(pg_temp.t(pg_temp.pc('P', 301), pg_temp.q_grant('BP', 'M')), 'MBS01', 'step_up_required', 'R-1: stale Portal proof refuses grant_board_role');
610
+ select throws_ok(pg_temp.t(pg_temp.pc('P', 301), pg_temp.q_gate('BP', true)), 'MBS01', 'step_up_required', 'R-1: stale Portal proof refuses set_board_role_gate');
611
+ select throws_ok(pg_temp.t(pg_temp.pc('P', 301), pg_temp.q_ceil('BP')), 'MBS01', 'step_up_required', 'R-1: stale Portal proof refuses set_board_authority_ceiling');
612
+ select throws_ok(pg_temp.t(pg_temp.pc('P', 301), pg_temp.q_inv('BP')), 'MBS01', 'step_up_required', 'R-1: stale Portal proof refuses an admin create_invite_link');
613
+ select is(pg_temp.snap('BP'), pg_temp.v('snapBP'), 'R-1 state: role, gate, ceiling and admin tokens are unchanged');
614
+ -- R-2: P, no claim, a fresh ledger row present.
615
+ select pg_temp.ledger('P', pg_temp.now_s() - 5);
616
+ select throws_ok(pg_temp.t(pg_temp.c('P'), pg_temp.q_grant('BP', 'M')), 'MBS01', 'step_up_required', 'R-2: a Portal human with a ledger row but no claim is refused');
617
+ -- R-2b: L, amr absent and amr [].
618
+ select throws_ok(pg_temp.t(pg_temp.c('L'), pg_temp.q_grant('BL', 'M')), 'MBS01', 'step_up_required', 'R-2b: a local human with no amr is refused');
619
+ select throws_ok(pg_temp.t(pg_temp.c('L', '{"amr":[]}'), pg_temp.q_grant('BL', 'M')), 'MBS01', 'step_up_required', 'R-2b: a local human with amr [] is refused');
620
+ -- R-3: L, a stale totp (301 s).
621
+ select throws_ok(pg_temp.t(pg_temp.lc('L', 301), pg_temp.q_grant('BL', 'M')), 'MBS01', 'step_up_required', 'R-3: a stale totp is refused');
622
+ -- R-4: P, re-mint without a ceremony: iat = clock, T = clock - 301 with a ledger row.
623
+ select throws_ok(pg_temp.t(pg_temp.c('P', jsonb_build_object('iat', pg_temp.now_s(), 'agent_board_step_up_at', pg_temp.ledger('P', pg_temp.now_s() - 301))),
624
+ pg_temp.q_grant('BP', 'M')), 'MBS01', 'step_up_required', 'R-4: a fresh iat with a stale T is refused');
625
+ -- R-4b: L, silent refresh: [{totp, clock - 301}, {token_refresh, clock}].
626
+ select throws_ok(pg_temp.t(pg_temp.c('L', jsonb_build_object('iat', pg_temp.now_s(), 'amr', jsonb_build_array(
627
+ jsonb_build_object('method', 'totp', 'timestamp', pg_temp.now_s() - 301), jsonb_build_object('method', 'token_refresh', 'timestamp', pg_temp.now_s())))),
628
+ pg_temp.q_grant('BL', 'M')), 'MBS01', 'step_up_required', 'R-4b: a fresh token_refresh over a stale totp is refused');
629
+ -- R-4c: fresh non-qualifying methods (Q3 exclusions, plus passkey, which is not yet measured).
630
+ select throws_ok(pg_temp.t(pg_temp.lc('L', 0, m), pg_temp.q_grant('BL', 'M')), 'MBS01', 'step_up_required', 'R-4c: a fresh ' || m || ' is not a step-up')
631
+ from unnest(array['oauth', 'password', 'magiclink', 'mfa/recovery_code', 'passkey', 'mfa/webauthn', 'mfa/phone']) m;
632
+ select throws_ok(pg_temp.t(pg_temp.c('L', jsonb_build_object('aal', 'aal2', 'amr', jsonb_build_array(jsonb_build_object('method', 'totp', 'timestamp', pg_temp.now_s() - 301)))),
633
+ pg_temp.q_grant('BL', 'M')), 'MBS01', 'step_up_required', 'R-4c: aal2 with a stale totp is refused');
634
+ -- R-5: L, fresh proofs under user_metadata, top-level stale.
635
+ select throws_ok(pg_temp.t(pg_temp.c('L', jsonb_build_object('user_metadata', jsonb_build_object(
636
+ 'amr', jsonb_build_array(jsonb_build_object('method', 'totp', 'timestamp', pg_temp.now_s())), 'agent_board_step_up_at', pg_temp.now_s()),
637
+ 'amr', jsonb_build_array(jsonb_build_object('method', 'totp', 'timestamp', pg_temp.now_s() - 301)))),
638
+ pg_temp.q_grant('BL', 'M')), 'MBS01', 'step_up_required', 'R-5: fresh proofs under user_metadata are ignored');
639
+ -- R-5b: P, fresh app_metadata.agent_board_step_up_at with a ledger row, no top-level claim.
640
+ select throws_ok(pg_temp.t(pg_temp.c('P', jsonb_build_object('app_metadata', jsonb_build_object('agent_board_step_up_at', pg_temp.ledger('P', pg_temp.now_s() - 7)))),
641
+ pg_temp.q_grant('BP', 'M')), 'MBS01', 'step_up_required', 'R-5b: a claim under app_metadata is ignored');
642
+ -- R-5c: P, the legacy flattened GUC carries a fresh T with a ledger row.
643
+ select throws_ok(format('select pg_temp.call(%L, %L, %L, %L)', pg_temp.c('P'), pg_temp.q_grant('BP', 'M'), 'agent_board_step_up_at',
644
+ pg_temp.ledger('P', pg_temp.now_s() - 8)::text), 'MBS01', 'step_up_required', 'R-5c: the legacy request.jwt.claim.* GUC is never freshness');
645
+ -- R-5d: L, a fresh top-level agent_board_step_up_at with a ledger row (cross-class).
646
+ select throws_ok(pg_temp.t(pg_temp.pc('L', 9), pg_temp.q_grant('BL', 'M')), 'MBS01', 'step_up_required', 'R-5d: a Portal-style claim buys a local human nothing');
647
+ -- R-5e: P, a fresh allowlisted amr (cross-class).
648
+ select throws_ok(pg_temp.t(pg_temp.lc('P', 0), pg_temp.q_grant('BP', 'M')), 'MBS01', 'step_up_required', 'R-5e: a fresh totp buys a Portal human nothing');
649
+ -- R-5f: P, a fresh T with NO ledger row (P's rows removed first, so no earlier T collides).
650
+ delete from agent_board.portal_step_up_proofs where agent_id = pg_temp.u('P');
651
+ select throws_ok(pg_temp.t(pg_temp.c('P', jsonb_build_object('agent_board_step_up_at', pg_temp.now_s() - 11)), pg_temp.q_grant('BP', 'M')),
652
+ 'MBS01', 'step_up_required', 'R-5f: a fresh Portal claim without its ledger row is refused');
653
+ -- R-6: P, T = clock + 31 with a ledger row.
654
+ select throws_ok(pg_temp.t(pg_temp.pc('P', -31), pg_temp.q_grant('BP', 'M')), 'MBS01', 'step_up_required', 'R-6: a proof 31 s in the future is refused');
655
+ -- R-8: P with a live agent_credential_id and no proof: kind decides.
656
+ select throws_ok(pg_temp.t(pg_temp.c('P', jsonb_build_object('agent_credential_id', '669b3000-0000-4000-8000-000000000001')), pg_temp.q_grant('BP', 'M')),
657
+ 'MBS01', 'step_up_required', 'R-8: a human carrying a credential claim is still a human');
658
+ select is(pg_temp.snap('BP'), pg_temp.v('snapBP'), 'R-2..R-8 state: nothing on BP changed');
659
+
660
+ -- R-9 (D1 precedence): M, a stale non-owner human: the existing 42501 comes first, on all four.
661
+ select throws_ok(pg_temp.t(pg_temp.lc('M', 301), pg_temp.q_grant('BP', 'T')), '42501', 'grant exceeds grantor role or board authority ceiling', 'R-9: grant by a stale member keeps its 42501');
662
+ select throws_ok(pg_temp.t(pg_temp.lc('M', 301), pg_temp.q_gate('BP', true)), '42501', 'only a board owner may set the role gate', 'R-9: gate by a stale member keeps its 42501');
663
+ select throws_ok(pg_temp.t(pg_temp.lc('M', 301), pg_temp.q_ceil('BP')), '42501', 'only a board owner may set the board authority ceiling', 'R-9: ceiling by a stale member keeps its 42501');
664
+ select throws_ok(pg_temp.t(pg_temp.lc('M', 301), pg_temp.q_inv('BP')), '42501', 'preset role exceeds creator role or board authority ceiling', 'R-9: admin link by a stale member keeps its 42501');
665
+ -- R-10 (D1 precedence): Rv, a stale fleet-revoked human owner: fleet_revoked: comes first, on all four.
666
+ select throws_ok(pg_temp.t(pg_temp.lc('Rv', 301), pg_temp.q_grant('BP', 'T')), '42501', 'fleet_revoked: grant_board_role is not permitted for a fleet-revoked agent', 'R-10: grant by a revoked owner keeps fleet_revoked:');
667
+ select throws_ok(pg_temp.t(pg_temp.lc('Rv', 301), pg_temp.q_gate('BP', true)), '42501', 'fleet_revoked: set_board_role_gate is not permitted for a fleet-revoked agent', 'R-10: gate by a revoked owner keeps fleet_revoked:');
668
+ select throws_ok(pg_temp.t(pg_temp.lc('Rv', 301), pg_temp.q_ceil('BP')), '42501', 'fleet_revoked: set_board_authority_ceiling is not permitted for a fleet-revoked agent', 'R-10: ceiling by a revoked owner keeps fleet_revoked:');
669
+ select throws_ok(pg_temp.t(pg_temp.lc('Rv', 301), pg_temp.q_inv('BP')), '42501', 'fleet_revoked: create_invite_link is not permitted for a fleet-revoked agent', 'R-10: admin link by a revoked owner keeps fleet_revoked:');
670
+ -- R-11: a hosted-delegate session (role agent_board_delegate), any claims: 42501 on all four.
671
+ select throws_ok(format('select pg_temp.call_as(%L, %L, %L)', 'agent_board_delegate', pg_temp.c('T', '{"role":"agent_board_delegate"}'), q), '42501', null,
672
+ 'R-11: a delegate session is refused ' || split_part(split_part(q, 'agent_board.', 2), '(', 1))
673
+ from unnest(array[pg_temp.q_grant('BP', 'M'), pg_temp.q_gate('BP', true), pg_temp.q_ceil('BP'), pg_temp.q_inv('BP')]) q;
674
+ -- R-12: G's agent as a member on P's board, no claims: 42501 on all four.
675
+ select throws_ok(pg_temp.t(pg_temp.c('G'), pg_temp.q_grant('BP', 'T')), '42501', 'grant exceeds grantor role or board authority ceiling', 'R-12: a non-owner agent cannot grant');
676
+ select throws_ok(pg_temp.t(pg_temp.c('G'), pg_temp.q_gate('BP', true)), '42501', 'only a board owner may set the role gate', 'R-12: a non-owner agent cannot set the gate');
677
+ select throws_ok(pg_temp.t(pg_temp.c('G'), pg_temp.q_ceil('BP')), '42501', 'only a board owner may set the board authority ceiling', 'R-12: a non-owner agent cannot set the ceiling');
678
+ select throws_ok(pg_temp.t(pg_temp.c('G'), pg_temp.q_inv('BP')), '42501', 'preset role exceeds creator role or board authority ceiling', 'R-12: a non-owner agent cannot mint an admin link');
679
+ -- R-13 (D2): stale P and stale L grant admin to the AGENT T: the actor's proof decides.
680
+ select throws_ok(pg_temp.t(pg_temp.pc('P', 301), pg_temp.q_grant('BP', 'T')), 'MBS01', 'step_up_required', 'R-13: a stale Portal owner cannot grant an agent admin');
681
+ select throws_ok(pg_temp.t(pg_temp.lc('L', 301), pg_temp.q_grant('BL', 'T')), 'MBS01', 'step_up_required', 'R-13: a stale local owner cannot grant an agent admin');
682
+ -- R-13b (D2): P presents a fresh T whose ledger row belongs to the TARGET P2, not to P.
683
+ select pg_temp.put('T13b', (pg_temp.now_s() - 4)::text);
684
+ select pg_temp.ledger('P2', pg_temp.v('T13b')::bigint);
685
+ select throws_ok(pg_temp.t(pg_temp.c('P', jsonb_build_object('agent_board_step_up_at', pg_temp.v('T13b')::bigint)), pg_temp.q_grant('BP', 'P2')),
686
+ 'MBS01', 'step_up_required', 'R-13b: only the actor''s proof counts, never the target''s');
687
+ -- R-14 (D3): a relay token (service_role, sub = P), grantor P supplied.
688
+ select throws_ok(pg_temp.t(pg_temp.relay('P'), pg_temp.q_grant('BP', 'T', 'admin', 'P')), 'MBS01', 'step_up_required', 'R-14: a relay token carrying a human sub is not the operator');
689
+ -- R-14b (§5.4): a relay token whose sub is a suspended human, grantor P supplied.
690
+ select throws_ok(pg_temp.t(pg_temp.relay('SUS'), pg_temp.q_grant('BP', 'T', 'admin', 'P')), 'MBS01', 'step_up_required', 'R-14b: a relay token naming a suspended human is refused');
691
+ select is(pg_temp.st('BP', 'T') || ' ' || pg_temp.st('BP', 'P2'), 'joined:member joined:member', 'R-13/R-14 state: neither target was raised');
692
+
693
+ -- R-19 (E-1(6)): each INHERIT wrapper, relay claims for P and a gateway decision naming P.
694
+ select throws_ok(pg_temp.t(pg_temp.relay('P'), format('select * from agent_board.signed_grant_board_role(%L::jsonb, %L::jsonb)',
695
+ jsonb_build_object('p_board_id', pg_temp.v('BP'), 'p_agent_id', pg_temp.v('T'), 'p_grantee_role', 'admin'), pg_temp.gw('P'))),
696
+ 'MBS01', 'step_up_required', 'R-19: signed_grant_board_role under a relay token for a stale human is refused');
697
+ select throws_ok(pg_temp.t(pg_temp.relay('P'), format('select * from agent_board.signed_set_board_authority_ceiling(%L::jsonb, %L::jsonb)',
698
+ jsonb_build_object('p_board_id', pg_temp.v('BP'), 'p_max_grantable_role', 'member'), pg_temp.gw('P'))),
699
+ 'MBS01', 'step_up_required', 'R-19: signed_set_board_authority_ceiling under a relay token for a stale human is refused');
700
+ select is(
701
+ (select count(*)::text from agent_board.signature_evidence where agent_id = pg_temp.u('P')) || ' ' || pg_temp.snap('BP', 'T'),
702
+ '0 target=joined:member gate=false ceiling=none admin_tokens=0',
703
+ 'R-19 state: no signature_evidence row, no role change and no ceiling change');
704
+
705
+ -- R-17 / R-17b (Q1, E-5): a stale owner takes an ACTIVE admin out of active standing.
706
+ select throws_ok(pg_temp.t(pg_temp.pc('P', 301), pg_temp.q_mem('BP', 'Ad', 'removed')), 'MBS01', 'step_up_required', 'R-17: a stale owner cannot remove an admin');
707
+ -- R-17b (E-5(2)) runs through a RELAY token: an authenticated owner setting another member to
708
+ -- `left` is refused 42501 before the gate on this tree (v_principal_withdraw is NULL for a
709
+ -- non-delegate target, so the actor-role read is skipped and the rank check sees rank 0). The
710
+ -- precedence row below records that; the relay path (no rank checks under service_role, D3) is
711
+ -- the one route where `left` reaches the gate.
712
+ select throws_ok(pg_temp.t(pg_temp.relay('P'), pg_temp.q_mem('BP', 'Ad', 'left')), 'MBS01', 'step_up_required', 'R-17b: a relay token for a stale owner cannot set an admin to left');
713
+ select throws_ok(pg_temp.t(pg_temp.pc('P', 301), pg_temp.q_mem('BP', 'Ad', 'left')), '42501', 'board membership change requires a higher board role than the target',
714
+ 'R-17b precedence: an authenticated owner setting an admin to left is refused 42501 before the gate (pre-existing)');
715
+ select is(pg_temp.st('BP', 'Ad'), 'joined:admin', 'R-17/R-17b state: Ad is still a joined admin');
716
+ -- E-6(a) removal R-9: a stale member removing an admin keeps its 42501 (no fleet_revoked assert
717
+ -- exists in update_board_membership, so there is no R-10 analogue).
718
+ select throws_ok(pg_temp.t(pg_temp.lc('M', 301), pg_temp.q_mem('BP', 'Ad', 'removed')), '42501', 'board membership change requires owner or admin role',
719
+ 'E-6(a) removal R-9: a stale member removing an admin keeps its 42501');
720
+
721
+ -- R-20 (E-3): a stale platform-admin human re-provisions its own handle as an agent.
722
+ select throws_ok(pg_temp.t(pg_temp.lc('L', 301), format($$select * from agent_board.provision_agent('su669b-l', 'agent', '[]'::jsonb, %L::uuid)$$, pg_temp.v('L.auth'))),
723
+ '42501', 'kind_change_requires_operator', 'R-20: an API kind change on an existing principal is refused');
724
+ select is((select kind::text || '/' || agent_type from agent_board.agents where id = pg_temp.u('L')), 'human/human', 'R-20 state: L is still kind human');
725
+ select throws_ok(pg_temp.t(pg_temp.lc('L', 301), pg_temp.q_grant('BL', 'M')), 'MBS01', 'step_up_required', 'R-20: and its next grant still needs a step-up');
726
+
727
+ -- ===========================================================================
728
+ -- §10.3 ALLOW rows (lives_ok, then a separate state check)
729
+ -- ===========================================================================
730
+ -- A-1: P, T = clock - 10 with a ledger row: the four RPCs (gate on, then off).
731
+ select lives_ok(pg_temp.t(pg_temp.pc('P', 10), pg_temp.q_grant('BP', 'M')), 'A-1: a fresh Portal owner grants admin');
732
+ select lives_ok(pg_temp.t(pg_temp.pc('P', 10), pg_temp.q_gate('BP', true)), 'A-1: a fresh Portal owner sets the gate on');
733
+ select is((select role_gate_enforced from agent_board.boards where id = pg_temp.u('BP')), true, 'A-1 state: the gate is on');
734
+ select lives_ok(pg_temp.t(pg_temp.pc('P', 10), pg_temp.q_gate('BP', false)), 'A-1: and off');
735
+ select lives_ok(pg_temp.t(pg_temp.pc('P', 10), pg_temp.q_inv('BP', 'admin', 'A1')), 'A-1: a fresh Portal owner mints an admin link');
736
+ select lives_ok(pg_temp.t(pg_temp.pc('P', 10), pg_temp.q_ceil('BP')), 'A-1: a fresh Portal owner sets the ceiling');
737
+ select is(pg_temp.snap('BP'), 'target=joined:admin gate=false ceiling=member admin_tokens=1', 'A-1 state: role admin, gate off, ceiling member, one admin token');
738
+ delete from agent_board.board_authority_ceilings where board_id = pg_temp.u('BP');
739
+ -- A-1b: T = clock + 20 (inside the skew).
740
+ select lives_ok(pg_temp.t(pg_temp.pc('P', -20), pg_temp.q_grant('BP', 'M2')), 'A-1b: a Portal proof 20 s in the future passes');
741
+ select is(pg_temp.st('BP', 'M2'), 'joined:admin', 'A-1b state: M2 is admin');
742
+ -- A-2: L, [{oauth, clock - 3000}, {totp, clock - 10}]: the four RPCs.
743
+ select pg_temp.put('A2c', pg_temp.c('L', jsonb_build_object('amr', jsonb_build_array(
744
+ jsonb_build_object('method', 'oauth', 'timestamp', pg_temp.now_s() - 3000), jsonb_build_object('method', 'totp', 'timestamp', pg_temp.now_s() - 10)))));
745
+ select lives_ok(pg_temp.t(pg_temp.v('A2c'), pg_temp.q_grant('BL', 'M')), 'A-2: a fresh local owner grants admin');
746
+ select lives_ok(pg_temp.t(pg_temp.v('A2c'), pg_temp.q_gate('BL', true)), 'A-2: sets the gate on');
747
+ select lives_ok(pg_temp.t(pg_temp.v('A2c'), pg_temp.q_gate('BL', false)), 'A-2: and off');
748
+ select lives_ok(pg_temp.t(pg_temp.v('A2c'), pg_temp.q_inv('BL', 'admin', 'A2')), 'A-2: mints an admin link');
749
+ select lives_ok(pg_temp.t(pg_temp.v('A2c'), pg_temp.q_ceil('BL')), 'A-2: sets the ceiling');
750
+ select is(pg_temp.snap('BL'), 'target=joined:admin gate=false ceiling=member admin_tokens=1', 'A-2 state: the same as A-1');
751
+ delete from agent_board.board_authority_ceilings where board_id = pg_temp.u('BL');
752
+ -- A-2b: L, [{totp, clock - 10}] (authenticator app).
753
+ select lives_ok(pg_temp.t(pg_temp.lc('L', 10), pg_temp.q_grant('BL', 'T')), 'A-2b: a fresh totp passes');
754
+ select is(pg_temp.st('BL', 'T'), 'joined:admin', 'A-2b state: T is admin on BL');
755
+ -- A-2c: L, [{otp, clock - 10}] (email code; the owner admitted otp on 2026-11-21).
756
+ select lives_ok(pg_temp.t(pg_temp.lc('L', 10, 'otp'), pg_temp.q_grant('BL', 'M')), 'A-2c: a fresh otp (email code) passes');
757
+ select is(pg_temp.st('BL', 'M'), 'joined:admin', 'A-2c state: M is admin on BL');
758
+ -- A-3: G, an agent owner with no claims: the four RPCs.
759
+ select lives_ok(pg_temp.t(pg_temp.c('G'), pg_temp.q_grant('BG', 'M')), 'A-3: an agent owner grants admin with no proof');
760
+ select lives_ok(pg_temp.t(pg_temp.c('G'), pg_temp.q_gate('BG', true)), 'A-3: sets the gate on');
761
+ select lives_ok(pg_temp.t(pg_temp.c('G'), pg_temp.q_gate('BG', false)), 'A-3: and off');
762
+ select lives_ok(pg_temp.t(pg_temp.c('G'), pg_temp.q_inv('BG', 'admin', 'A3')), 'A-3: mints an admin link');
763
+ select lives_ok(pg_temp.t(pg_temp.c('G'), pg_temp.q_ceil('BG')), 'A-3: sets the ceiling');
764
+ select is(pg_temp.snap('BG'), 'target=joined:admin gate=false ceiling=member admin_tokens=1', 'A-3 state: the same as A-1');
765
+ delete from agent_board.board_authority_ceilings where board_id = pg_temp.u('BG');
766
+ -- A-4: P with no claim mints a MEMBER link (ungated).
767
+ select lives_ok(pg_temp.t(pg_temp.c('P'), pg_temp.q_inv('BP', 'member', 'A4')), 'A-4: a member-preset link needs no step-up');
768
+ select is((select t.preset_role from agent_board.board_invite_tokens t join _tok k on k.code = t.code where k.label = 'A4'), 'member', 'A-4 state: a member token');
769
+ -- A-5: the operator key (service_role, no sub), grantor P.
770
+ select lives_ok(pg_temp.t('{"role":"service_role"}', pg_temp.q_grant('BP', 'T', 'admin', 'P')), 'A-5: the operator key grants with no proof');
771
+ select is(pg_temp.st('BP', 'T'), 'joined:admin', 'A-5 state: T is admin on BP');
772
+ -- A-6: a stale human redeems A-1's admin link (redemption is EXEMPT: the preset came from a gated mint).
773
+ select lives_ok(pg_temp.t(pg_temp.lc('X2', 301), format('select * from agent_board.redeem_invite_link(%L)', (select code from _tok where label = 'A1'))),
774
+ 'A-6: the redeemer of a post-cutover admin link needs no step-up');
775
+ select is(pg_temp.st('BP', 'X2'), 'joined:admin', 'A-6 state: the redeemer holds exactly the preset (admin)');
776
+ -- A-8: a fresh admin grants the same role twice: the second is refused by #674 C-B, as before.
777
+ select lives_ok(pg_temp.t(pg_temp.lc('Ad', 10), pg_temp.q_grant('BG', 'T')), 'A-8: a fresh admin grants a member admin');
778
+ select throws_ok(pg_temp.t(pg_temp.lc('Ad', 10), pg_temp.q_grant('BG', 'T')), '42501', 'grant requires a higher board role than the target',
779
+ 'A-8: the same grant again is refused by C-B, not by step-up');
780
+
781
+ -- A-11 / A-11d / A-11b / A-11c (Q1, E-5).
782
+ select lives_ok(pg_temp.t(pg_temp.pc('P', 301), pg_temp.q_mem('BP', 'MR', 'removed')), 'A-11: a stale owner removes an ordinary member');
783
+ select is(pg_temp.st('BP', 'MR'), 'removed:member', 'A-11 state: MR is removed');
784
+ select lives_ok(pg_temp.t(pg_temp.pc('P', 301), pg_temp.q_mem('BP', 'Ad', 'invited')), 'A-11d: a stale owner re-invites an active admin (the sink suppresses the offer)');
785
+ select is(pg_temp.st('BP', 'Ad'), 'joined:admin', 'A-11d state: Ad is still a joined admin');
786
+ select lives_ok(pg_temp.t(pg_temp.pc('P', 10), pg_temp.q_mem('BP', 'Ad', 'removed')), 'A-11b: a fresh owner removes an admin');
787
+ select is(pg_temp.st('BP', 'Ad'), 'removed:admin', 'A-11b state: Ad is removed');
788
+ select lives_ok(pg_temp.t(pg_temp.lc('Ad', 301), pg_temp.q_mem('BL', 'Ad', 'left')), 'A-11c: a stale admin leaves by itself');
789
+ select is(pg_temp.st('BL', 'Ad'), 'left:admin', 'A-11c state: Ad left BL');
790
+
791
+ -- A-12 (E-3): a same-kind re-provision by a platform admin is unchanged.
792
+ select lives_ok(pg_temp.t(pg_temp.lc('L', 301), format($$select * from agent_board.provision_agent('su669b-l', 'human', '[]'::jsonb, %L::uuid)$$, pg_temp.v('L.auth'))),
793
+ 'A-12: a same-kind re-provision by a platform admin still succeeds');
794
+ select is((select kind::text || '/' || auth_user_id::text from agent_board.agents where id = pg_temp.u('L')), 'human/' || pg_temp.v('L.auth'),
795
+ 'A-12 state: kind and auth binding unchanged');
796
+
797
+ -- ===========================================================================
798
+ -- E-2(4) exception rows: each API-executable writer of agents.kind/agent_type/auth_user_id,
799
+ -- with a stale-human caller, measured on the row.
800
+ -- ===========================================================================
801
+ -- X-1 register_agent: a type change is refused (42501) and the row is unchanged.
802
+ select throws_ok(pg_temp.t(pg_temp.lc('X', 301), $$select * from agent_board.register_agent('agent', 'su669b-x', 'SU669B X')$$),
803
+ '42501', 'register_agent may not change agent_type after provisioning', 'X-1: register_agent refuses an API type change');
804
+ select is((select kind::text || '/' || agent_type || '/' || auth_user_id::text from agent_board.agents where id = pg_temp.u('X')),
805
+ 'human/human/' || pg_temp.v('X.auth'), 'X-1 state: kind, agent_type and auth_user_id unchanged');
806
+ -- X-1 (same kind): the allowed update changes none of the three columns.
807
+ select lives_ok(pg_temp.t(pg_temp.lc('X', 301), $$select * from agent_board.register_agent('human', 'su669b-x', 'SU669B X renamed')$$),
808
+ 'X-1: a same-type register_agent update is allowed');
809
+ select is((select kind::text || '/' || agent_type || '/' || auth_user_id::text from agent_board.agents where id = pg_temp.u('X')),
810
+ 'human/human/' || pg_temp.v('X.auth'), 'X-1 state: still unchanged');
811
+ -- X-2 self_enroll_human: inserts a literal 'human' bound to auth.uid().
812
+ select lives_ok(pg_temp.t(jsonb_build_object('role', 'authenticated', 'sub', pg_temp.v('LU.auth'))::text, $$select * from agent_board.self_enroll_human('SU669B LU')$$),
813
+ 'X-2: self_enroll_human enrols the caller');
814
+ select is((select string_agg(kind::text || '/' || (auth_user_id = pg_temp.u('LU.auth'))::text, ',') from agent_board.agents where auth_user_id = pg_temp.u('LU.auth')),
815
+ 'human/true', 'X-2 state: exactly one row, kind human, bound to the caller');
816
+ -- X-3 provision_agent: an existing principal with NO auth binding cannot gain one through the API.
817
+ insert into agent_board.agents(id, agent_type, kind, handle, display_name, status)
818
+ values ('669b1000-0000-4000-8000-0000000000aa', 'agent', 'agent', 'su669b-unbound', 'SU669B unbound', 'active');
819
+ select throws_ok(pg_temp.t(pg_temp.lc('L', 301), format($$select * from agent_board.provision_agent('su669b-unbound', 'agent', '[]'::jsonb, %L::uuid)$$, pg_temp.v('L.auth'))),
820
+ '42501', 'auth_binding_change_requires_operator', 'X-3: an API re-provision cannot bind an auth user to an existing principal');
821
+ select is((select coalesce(auth_user_id::text, 'NULL') from agent_board.agents where id = '669b1000-0000-4000-8000-0000000000aa'), 'NULL',
822
+ 'X-3 state: the principal still has no auth binding');
823
+ -- X-3 (new principal): a fresh provision inserts a literal kind with a fresh agent auth user.
824
+ select lives_ok(pg_temp.t(pg_temp.lc('L', 301), format($$select * from agent_board.provision_agent('su669b-fresh', 'agent', '[]'::jsonb, %L::uuid)$$, pg_temp.v('L.auth'))),
825
+ 'X-3: a new principal is provisioned');
826
+ select is((select kind::text || '/' || (auth_user_id is not null and auth_user_id <> pg_temp.u('L.auth'))::text from agent_board.agents where handle = 'su669b-fresh'),
827
+ 'agent/true', 'X-3 state: kind agent, bound to its own fresh auth user, never the caller''s');
828
+
829
+ -- ===========================================================================
830
+ -- §7.5 EXEMPT rows (A-7): a STALE human caller, measured on the row written
831
+ -- ===========================================================================
832
+ select lives_ok(pg_temp.t(pg_temp.lc('X', 301), format($$insert into _tok select 'BX', board_id::text from agent_board.create_board(%L::uuid, 'su669b-bx', 'SU669B BX')$$, pg_temp.v('X'))),
833
+ 'A-7 create_board: a stale human creates a board');
834
+ select is((select string_agg(bm.agent_id::text || ':' || bm.role || ':' || bm.membership_state, ',') from agent_board.board_memberships bm
835
+ where bm.board_id = (select code::uuid from _tok where label = 'BX')),
836
+ pg_temp.v('X') || ':owner:joined', 'A-7 create_board state: exactly one membership, the creator as owner');
837
+ select lives_ok(pg_temp.t(pg_temp.pc('P', 301), format('select * from agent_board.invite_board_member(%L::uuid, %L::uuid, %L::uuid)', pg_temp.v('BP'), pg_temp.v('X'), pg_temp.v('P'))),
838
+ 'A-7 invite_board_member: a stale owner invites');
839
+ select is(pg_temp.st('BP', 'X'), 'invited:member', 'A-7 invite_board_member state: invited as member');
840
+ select lives_ok(pg_temp.t(pg_temp.lc('X', 301), format('select * from agent_board.join_board(%L::uuid, %L::uuid)', pg_temp.v('BP'), pg_temp.v('X'))),
841
+ 'A-7 join_board: a stale invitee joins');
842
+ select is(pg_temp.st('BP', 'X'), 'joined:member', 'A-7 join_board state: joined as member');
843
+ select lives_ok(pg_temp.t(pg_temp.lc('X', 301), format('select * from agent_board.leave_board(%L::uuid, %L::uuid)', pg_temp.v('BP'), pg_temp.v('X'))),
844
+ 'A-7 leave_board: a stale member leaves');
845
+ select is(pg_temp.st('BP', 'X'), 'left:member', 'A-7 leave_board state: left');
846
+ select lives_ok(pg_temp.t(pg_temp.lc('W3', 301), format('select * from agent_board.request_join_board(%L::uuid, %L::uuid)', pg_temp.v('BO'), pg_temp.v('W3'))),
847
+ 'A-7 request_join_board: a stale human requests an open board');
848
+ select is(pg_temp.st('BO', 'W3'), 'requested:member', 'A-7 request_join_board state: requested as member');
849
+ select lives_ok(pg_temp.t(pg_temp.pc('P', 301), format($$select * from agent_board.resolve_board_request(%L::uuid, %L::uuid, 'joined', %L::uuid)$$, pg_temp.v('BO'), pg_temp.v('W3'), pg_temp.v('P'))),
850
+ 'A-7 resolve_board_request: a stale owner admits the request');
851
+ select is(pg_temp.st('BO', 'W3'), 'joined:member', 'A-7 resolve_board_request state: joined as member');
852
+ -- Re-entry clamp (ROLERESET): Y was an admin on BO; the operator removes it, then a stale owner
853
+ -- re-invites and Y re-joins: the re-entered row is a member, never the removed row's admin.
854
+ select lives_ok(pg_temp.t('{"role":"service_role"}', pg_temp.q_mem('BO', 'Y', 'removed')), 'A-7 re-entry setup: the operator removes the admin Y');
855
+ select lives_ok(pg_temp.t(pg_temp.pc('P', 301), format('select * from agent_board.invite_board_member(%L::uuid, %L::uuid, %L::uuid)', pg_temp.v('BO'), pg_temp.v('Y'), pg_temp.v('P'))),
856
+ 'A-7 re-entry: a stale owner re-invites the removed admin');
857
+ select lives_ok(pg_temp.t(pg_temp.lc('Y', 301), format('select * from agent_board.join_board(%L::uuid, %L::uuid)', pg_temp.v('BO'), pg_temp.v('Y'))),
858
+ 'A-7 re-entry: the removed admin re-joins');
859
+ select is(pg_temp.st('BO', 'Y'), 'joined:member', 'A-7 re-entry state: the re-entered row is a member (the clamp), never admin');
860
+ -- add_delegate_to_board and create_fleet_onboarding_invite: positive claims on the body (their live
861
+ -- fixtures need a hosted delegate instance and a fleet machine; their behaviour is pinned by
862
+ -- agent_board_delegate_role_class / agent_board_atomic_fleet_onboarding).
863
+ select ok(agent_board_test.stripped_body('agent_board.create_fleet_onboarding_invite(uuid,uuid,text,text,text,text,text,text,text,integer,timestamp with time zone,uuid,jsonb)'::regprocedure, true)
864
+ ~ (agent_board_test.call_re('create_invite_link') || '\s*p_board_id\s*,\s*''member''\s*,'),
865
+ 'A-7 create_fleet_onboarding_invite: its only invite mint passes the literal member preset');
866
+ select is(
867
+ (select string_agg(distinct d.name, ' ' order by d.name) from _cl c join _direct d on d.oid = c.reached_oid
868
+ where c.root_oid = 'agent_board.add_delegate_to_board(uuid,uuid)'::regprocedure),
869
+ '_upsert_board_membership_state',
870
+ 'A-7 add_delegate_to_board: it reaches the property only through the sink (SVC-1)');
871
+
872
+ -- ===========================================================================
873
+ -- EXEMPT-SVC rows (EC-SU-3b): the five direct writers
874
+ -- ===========================================================================
875
+ -- SVC-1 _upsert_board_membership_state: an INSERT seats a member; a re-entry clamps to member.
876
+ select lives_ok($$select * from agent_board._upsert_board_membership_state('669b2000-0000-4000-8000-000000000003'::uuid, '669b1000-0000-4000-8000-000000000014'::uuid, 'joined')$$,
877
+ 'SVC-1: the sink seats a new row');
878
+ select is(pg_temp.st('BG', 'W'), 'joined:member', 'SVC-1 state: a new row is a member (the INSERT omits role)');
879
+ update agent_board.board_memberships set role = 'admin' where board_id = pg_temp.u('BG') and agent_id = pg_temp.u('W');
880
+ select lives_ok($$select * from agent_board._upsert_board_membership_state('669b2000-0000-4000-8000-000000000003'::uuid, '669b1000-0000-4000-8000-000000000014'::uuid, 'removed')$$,
881
+ 'SVC-1: the sink removes the (now admin) row');
882
+ select lives_ok($$select * from agent_board._upsert_board_membership_state('669b2000-0000-4000-8000-000000000003'::uuid, '669b1000-0000-4000-8000-000000000014'::uuid, 'joined')$$,
883
+ 'SVC-1: the sink re-enters it');
884
+ select is(pg_temp.st('BG', 'W'), 'joined:member', 'SVC-1 state: re-entry is clamped to member');
885
+ -- SVC-2 _fedsession_autojoin_default_board: seats the table default, member.
886
+ insert into agent_board.identity_providers(id, issuer, audience, default_board_id)
887
+ values ('su669b-provider', 'https://su669b-autojoin.test', 'message-board', pg_temp.u('BO'));
888
+ select lives_ok($$select agent_board._fedsession_autojoin_default_board(p, '669b1000-0000-4000-8000-000000000018'::uuid)
889
+ from agent_board.identity_providers p where p.id = 'su669b-provider'$$,
890
+ 'SVC-2: the fedsession auto-join seats the agent');
891
+ select is(pg_temp.st('BO', 'W2'), 'joined:member', 'SVC-2 state: the auto-joined row is a member');
892
+ -- SVC-3 _redeem_unbounded_invite_for_agent: writes exactly the token's preset and refuses a revoked one.
893
+ select lives_ok(format('select * from agent_board._redeem_unbounded_invite_for_agent(%L, %L::uuid)', (select code from _tok where label = 'A4'), pg_temp.v('W2')),
894
+ 'SVC-3: the redeem writer seats a member token''s redeemer');
895
+ select is(pg_temp.st('BP', 'W2'), 'joined:member', 'SVC-3 state: the redeemer holds exactly the preset (member)');
896
+ select throws_ok(format('select * from agent_board._redeem_unbounded_invite_for_agent(%L, %L::uuid)', 'su669b-seed-admin-live', pg_temp.v('W2')),
897
+ '42501', 'invite is not usable', 'SVC-3: the redeem writer refuses a revoked token');
898
+ -- SVC-4 bootstrap_board_owner_memberships: no API role holds EXECUTE (the privilege claim).
899
+ select is(
900
+ (select coalesce(string_agg(r, ',' order by r), '(none)') from unnest(array['public', 'anon', 'authenticated', 'agent_board_delegate']) r
901
+ where has_function_privilege(r, 'agent_board.bootstrap_board_owner_memberships()'::regprocedure, 'EXECUTE')),
902
+ '(none)', 'SVC-4: bootstrap_board_owner_memberships is executable by no API role');
903
+ -- SVC-5 link_session_alias: its only role write lowers the row, never raises it (positive body claim;
904
+ -- its behaviour is pinned by the session-identity suites, which need a held lease and live PoP).
905
+ select ok(agent_board_test.stripped_body('agent_board.link_session_alias(uuid,text,text)'::regprocedure)
906
+ ~ '_role_rank\(r\)\s*<=\s*agent_board\._role_rank\(v_membership\.role\)',
907
+ 'SVC-5: link_session_alias picks a role no higher than the row''s current role');
908
+
909
+ -- ===========================================================================
910
+ -- Readmission (D4) and the D5 refusal, on a real agent root RT owned by the human H
911
+ -- ===========================================================================
912
+ create temp table _sid(label text primary key, agent_id uuid, key_id uuid);
913
+ create temp table _readmit(label text, child_agent_id uuid, grant_expires_at timestamptz, signing_key_id uuid);
914
+ insert into agent_board.session_identities(agent_id, root_agent_id, depth, approved_risky_digest, current_risky_digest)
915
+ values (pg_temp.u('RT'), pg_temp.u('RT'), 0, 'approved', 'approved');
916
+ create function pg_temp.mint(p_root text, p_label text, p_fork text, p_role text) returns text language sql as $$
917
+ select format($f$insert into _sid select %L, m.child_agent_id, m.signing_key_id from agent_board.mint_delegated_child(
918
+ %L::uuid, %L, '["read"]', %L, interval '8 hours', false, 'claude', %L, null,
919
+ jsonb_build_array(jsonb_build_object('board_id', %L, 'role', %L)),
920
+ '{"resolution":"resolved","risky_digest":"approved","recorded":{"version":"one"}}', %L::uuid) m$f$,
921
+ p_label, pg_temp.v(p_root), 'su669b-sid-' || p_label, public.test_pubkey('su669b-' || p_label), 'su669b-' || p_label,
922
+ pg_temp.v('BH'), p_role, (select agent_id::text from _sid where label = p_fork)) $$;
923
+ create function pg_temp.readmit(p_label text, p_target text, p_role text) returns text language sql as $$
924
+ select format($f$insert into _readmit select %L, r.* from agent_board.readmit_session_identity(%L::uuid, %L, %L, '["read"]',
925
+ jsonb_build_array(jsonb_build_object('board_id', %L, 'role', %L)), interval '1 hour') r$f$,
926
+ p_label, (select agent_id::text from _sid where label = p_target), 'su669b-new-' || p_label, public.test_pubkey('su669b-new-' || p_label),
927
+ pg_temp.v('BH'), p_role) $$;
928
+ select lives_ok(pg_temp.t('{"role":"service_role"}', format($$select agent_board.upsert_delegation_policy(%L::uuid, 'root_minted', '["read","write"]', 200, interval '7 days', true)$$, pg_temp.v('RT'))),
929
+ 'readmit fixture: the agent root RT gets a root_minted policy');
930
+ -- A-10: an AGENT root mints a child with an admin room (the root is the board's owner).
931
+ select lives_ok(pg_temp.t('{"role":"service_role"}', pg_temp.mint('RT', 'source', null, 'admin')), 'A-10: an agent root mints an admin child');
932
+ select is((select bm.role from agent_board.board_memberships bm join _sid s on s.agent_id = bm.agent_id
933
+ where s.label = 'source' and bm.board_id = pg_temp.u('BH')), 'admin', 'A-10 state: the child is admin');
934
+ select lives_ok(pg_temp.t('{"role":"service_role"}', pg_temp.mint('RT', 'fork1', 'source', 'admin') || '; ' || pg_temp.mint('RT', 'fork2', 'source', 'admin')),
935
+ 'readmit fixture: two admin forks of the source');
936
+ select lives_ok(pg_temp.t(pg_temp.lc('H', 301), format('select agent_board.revoke_session_identity(%L::uuid); select agent_board.revoke_session_identity(%L::uuid)',
937
+ (select agent_id from _sid where label = 'fork1'), (select agent_id from _sid where label = 'fork2'))),
938
+ 'readmit fixture: the human owner H revokes both forks');
939
+ select pg_temp.put('agents0', (select count(*)::text from agent_board.agents));
940
+ -- E-6(a) readmit R-9: a stale human who is not the fork's owner keeps the owner refusal.
941
+ select throws_ok(pg_temp.t(pg_temp.lc('L', 301), pg_temp.readmit('r9', 'fork1', 'admin')), '42501', 'identity readmission requires the human owner',
942
+ 'E-6(a) readmit R-9: a non-owner human keeps its 42501');
943
+ -- R-15 (D4): the stale human owner readmits with an admin room.
944
+ select throws_ok(pg_temp.t(pg_temp.lc('H', 301), pg_temp.readmit('r15', 'fork1', 'admin')), 'MBS01', 'step_up_required', 'R-15: a stale owner cannot readmit above member');
945
+ select is((select count(*)::text from agent_board.agents) || '/' || (select count(*) from agent_board.agent_signing_keys k join agent_board.agents a on a.id = k.agent_id where a.handle = 'su669b-new-r15')::text
946
+ || '/' || (select count(*) from agent_board.session_identities where readmitted_from = (select agent_id from _sid where label = 'fork1'))::text
947
+ || '/' || (select count(*) from _readmit)::text,
948
+ pg_temp.v('agents0') || '/0/0/0', 'R-15 state: no new agent, key, identity or result row survived the refusal');
949
+ -- E-6(a) readmit R-10: a fleet-revoked human owner keeps fleet_revoked:.
950
+ insert into agent_board.fleet_revocation_events(subject_kind, subject_id, agent_id, revoked_by_agent_id, revocation_reason)
951
+ values ('agent', pg_temp.u('H'), pg_temp.u('H'), pg_temp.u('H'), 'su669b-h');
952
+ select throws_ok(pg_temp.t(pg_temp.lc('H', 301), pg_temp.readmit('r10', 'fork1', 'admin')), '42501', 'fleet_revoked: readmit_session_identity is not permitted for a fleet-revoked agent',
953
+ 'E-6(a) readmit R-10: a fleet-revoked owner keeps fleet_revoked:');
954
+ delete from agent_board.fleet_revocation_events where revocation_reason = 'su669b-h';
955
+ -- A-9: the FRESH owner readmits with an admin room.
956
+ select lives_ok(pg_temp.t(pg_temp.lc('H', 10), pg_temp.readmit('a9', 'fork1', 'admin')), 'A-9: a fresh owner readmits above member');
957
+ select is((select bm.role from agent_board.board_memberships bm join _readmit r on r.child_agent_id = bm.agent_id where r.label = 'a9' and bm.board_id = pg_temp.u('BH')),
958
+ 'admin', 'A-9 state: the readmitted principal is admin');
959
+ -- A-9b: the STALE owner readmits with a member room (ungated).
960
+ select lives_ok(pg_temp.t(pg_temp.lc('H', 301), pg_temp.readmit('a9b', 'fork2', 'member')), 'A-9b: a stale owner readmits at member');
961
+ select is((select bm.role from agent_board.board_memberships bm join _readmit r on r.child_agent_id = bm.agent_id where r.label = 'a9b' and bm.board_id = pg_temp.u('BH')),
962
+ 'member', 'A-9b state: the readmitted principal is member');
963
+ -- R-16 (D5): the HUMAN H as a true root, through a relay token, asks for an admin room.
964
+ select lives_ok(pg_temp.t('{"role":"service_role"}', format($$select agent_board.upsert_delegation_policy(%L::uuid, 'root_minted', '["read"]', 200, interval '7 days', true)$$, pg_temp.v('H'))),
965
+ 'R-16 fixture: the human H gets a root_minted policy');
966
+ select throws_ok(pg_temp.t(pg_temp.relay('H'), pg_temp.mint('H', 'r16', null, 'admin')), '42501', 'human_root_room_elevation_refused',
967
+ 'R-16: a human root cannot mint a child above member');
968
+ select is((select count(*)::int from agent_board.agents where handle = 'su669b-sid-r16'), 0, 'R-16 state: no child was created');
969
+
970
+ -- ===========================================================================
971
+ -- M14 row and the DETAIL (through the RPC)
972
+ -- ===========================================================================
973
+ select pg_sleep(2);
974
+ select throws_ok(pg_temp.t(pg_temp.pc('P', 301), pg_temp.q_grant('BP', 'P2')), 'MBS01', 'step_up_required',
975
+ 'M14 row: after a 2 s in-transaction wait a clock - 301 proof is stale (freshness is clock_timestamp(), not now())');
976
+ create function pg_temp.diag(p_claims text, p_sql text) returns text language plpgsql as $$
977
+ declare v_state text; v_msg text; v_detail text;
978
+ begin
979
+ begin
980
+ perform pg_temp.call(p_claims, p_sql);
981
+ return 'ok';
982
+ exception when others then
983
+ get stacked diagnostics v_state = returned_sqlstate, v_msg = message_text, v_detail = pg_exception_detail;
984
+ return v_state || '|' || v_msg || '|' || coalesce(v_detail, '(null)');
985
+ end;
986
+ end $$;
987
+ select is(pg_temp.diag(pg_temp.pc('P', 301), pg_temp.q_mem('BP', 'M', 'removed')), 'MBS01|step_up_required|update_board_membership',
988
+ '§6.1: the RPC refusal is MBS01 step_up_required with DETAIL = the operation name');
989
+
990
+ select * from finish();
991
+ rollback;