@ours.network/tg-connector 0.1.2 → 0.1.3

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 (30) hide show
  1. package/dist/mufl_code/2DA1D5F860E42C605D92F1E24E2466C70EFDDBF057BBCBA52F0ECC639EFCA387.muflo +0 -0
  2. package/dist/mufl_code/core/CLUSTER_API.md +640 -0
  3. package/dist/mufl_code/core/CLUSTER_CONTRACT.md +121 -0
  4. package/dist/mufl_code/core/CLUSTER_INTRODUCTION_PLAN.md +200 -0
  5. package/dist/mufl_code/core/CONFIGURATION_DESIGN.md +35 -0
  6. package/dist/mufl_code/core/CONFIGURATION_PLAN.md +394 -0
  7. package/dist/mufl_code/core/DEVELOPMENT.md +168 -0
  8. package/dist/mufl_code/core/EPHEMERAL_INVITE_PLAN.md +465 -0
  9. package/dist/mufl_code/core/GROUP_CHAT_DESIGN.md +520 -0
  10. package/dist/mufl_code/core/LICENSE +98 -0
  11. package/dist/mufl_code/core/README.md +76 -0
  12. package/dist/mufl_code/core/a2a_capabilities.mm +350 -0
  13. package/dist/mufl_code/core/a2a_cluster.mm +601 -0
  14. package/dist/mufl_code/core/a2a_control.mm +89 -0
  15. package/dist/mufl_code/core/a2a_messaging.mm +2103 -0
  16. package/dist/mufl_code/core/a2a_monitoring.mm +94 -0
  17. package/dist/mufl_code/core/a2a_protocol.mm +231 -0
  18. package/dist/mufl_code/core/config.mufl +26 -0
  19. package/dist/mufl_code/core/release-notes/2.0.md +268 -0
  20. package/dist/mufl_code/core/release-notes/2.1.md +92 -0
  21. package/dist/mufl_code/core/release-notes/2.2.md +94 -0
  22. package/dist/mufl_code/core/release-notes/3.0.md +162 -0
  23. package/dist/mufl_code/core/release-notes/3.1.md +43 -0
  24. package/dist/mufl_code/core/release-notes/README.md +32 -0
  25. package/dist/mufl_code/core/tests/README.md +66 -0
  26. package/dist/mufl_code/core/tests/run.sh +67 -0
  27. package/dist/mufl_code/core/tests/test.mjs +467 -0
  28. package/dist/mufl_code/core/tests/test_actor.mu +287 -0
  29. package/dist/mufl_code/core/version.mm +24 -0
  30. package/package.json +2 -1
@@ -0,0 +1,2103 @@
1
+ // Shared ours messaging library.
2
+ //
3
+ // The contact + message wire path common to every ours client: identity
4
+ // profile (name/bio), invite generation/redemption, contact registry, the
5
+ // encrypted send/receive pair, and the export/import helpers for the shared
6
+ // state. Message STORAGE stays app-side — each consumer injects storage hooks
7
+ // via init (the agent keeps its inbox lifecycle, the messenger its per-contact
8
+ // history); this library handles wire + validation + contact resolution only.
9
+ //
10
+ // Routing: this library's transactions are addressed ::a2a_messaging::<name>.
11
+ // The four NETWORK-VISIBLE inbound names stay ::actor::* for compatibility
12
+ // with pre-migration clients (Option A): consumers keep one-line ::actor::
13
+ // delegating shims, and this library keeps SENDING to the ::actor:: names
14
+ // (the *_tx constants below). Drop both only when no old clients remain.
15
+ //
16
+ // Identity-hierarchy state (delegation_cert, root_ad, root_profile,
17
+ // contact_roots) lives HERE because generate_invite/add_contact read it; the
18
+ // hierarchy transactions themselves arrive in a2a_hierarchy.mm, which loads
19
+ // this library and shares this state.
20
+ //
21
+ // The contact/identity state is deliberately non-hidden: consumers (and
22
+ // a2a_hierarchy) read and assign it directly during the migration's transition
23
+ // steps. The EXCEPTION is the monitoring + config gate state (monitoring_proxy,
24
+ // proxy_pending, app_config), which is `hidden` so neither the app nor any other
25
+ // library can switch monitoring off or rewrite the stored config by assigning it
26
+ // directly — the "app can't override" guarantee. Its mutators (the bind ceremony,
27
+ // disable, set_app_config) therefore live in THIS library.
28
+ library a2a_messaging loads libraries
29
+ address_document,
30
+ address_document_types,
31
+ key_utils,
32
+ key_storage,
33
+ current_transaction_info,
34
+ encrypted_channel,
35
+ a2a_protocol,
36
+ a2a_capabilities,
37
+ version
38
+ uses transactions
39
+ {
40
+ // Network-visible inbound transaction names (embedded in what peers send).
41
+ // Pre-migration clients listen on these, so the core keeps sending to them.
42
+ accept_contact_tx = "::actor::accept_contact".
43
+ receive_message_tx = "::actor::receive_message".
44
+ // File transfer inbound (core 3.1). NEW surface, no legacy clients, so
45
+ // LIBRARY-routed like submit_invite_response/complete_invite — no ::actor:: shim.
46
+ receive_file_tx = "::a2a_messaging::receive_file".
47
+ // Distinct inbound name on the control plane for a forced monitoring copy.
48
+ // The CP-side receiver lives in a2a_monitoring; held as a literal so this
49
+ // library keeps no code dependency on it (a2a_monitoring loads THIS library).
50
+ receive_monitoring_copy_tx = "::a2a_monitoring::receive_monitoring_copy".
51
+ // Node-side inbound for a control-plane introduction (core.connect): the CP
52
+ // relays a peer's signed address document here. Library-routed (new surface,
53
+ // no legacy clients), so introduce/introduce_to_group send to this literal.
54
+ ingest_connect_descriptor_tx = "::a2a_messaging::ingest_connect_descriptor".
55
+ // CP-side inbound for cluster enrollment (core 2.2): a root relays one of its
56
+ // children's signed AD + delegation chain here so the CP can hold peer_ads for
57
+ // the whole cluster off a single root bind. handle_enroll_delegated_node is the
58
+ // receiver; relay_enroll_delegated_node (root side) sends to this literal.
59
+ enroll_delegated_node_tx = "::a2a_messaging::enroll_delegated_node".
60
+ // core 3.0 ephemeral-invite redeem legs. NEW surfaces (no legacy clients), so
61
+ // both are LIBRARY-routed — no ::actor:: shim needed, unlike the pre-migration
62
+ // names above. leg 1 (responder->inviter) is a BARE send carrying a box; leg 3
63
+ // (inviter->responder) is ALSO a bare boxed send (NOT encrypted_channel — the
64
+ // box to the responder's kept ephemeral key is the confidentiality/integrity).
65
+ // See submit_invite_response / complete_invite below.
66
+ submit_invite_response_tx = "::a2a_messaging::submit_invite_response".
67
+ complete_invite_tx = "::a2a_messaging::complete_invite".
68
+ // contact-restore wire names (LIBRARY-routed, new surface — no ::actor:: shims).
69
+ request_contact_restore_tx = "::a2a_messaging::request_contact_restore".
70
+ submit_restore_response_tx = "::a2a_messaging::submit_restore_response".
71
+ complete_restore_tx = "::a2a_messaging::complete_restore".
72
+
73
+ // Version stamp of the portable export blob (see import_core_state for the
74
+ // migration contract). Bump ONLY on a breaking blob-shape change, together
75
+ // with a migration from the previous stamp.
76
+ core_format_version = 1.
77
+ // Give up re-requesting a restore after this many attempts per contact (the
78
+ // host sweep re-fires on its GC cadence; a peer that upgraded and came back
79
+ // online answers on the first post-upgrade attempt).
80
+ restore_max_attempts = 30.
81
+ // Per-contact cap on messages queued while its keys are being restored.
82
+ deferred_msgs_cap = 50.
83
+
84
+ // 6-digit bind ceremony limits (code is generated host-side — MUFL has no
85
+ // random source — and handed to set_proxy_pending).
86
+ proxy_code_max_age_seconds = 300.
87
+ proxy_max_attempts = 3.
88
+
89
+ // ---- shared packet state ---------------------------------------------
90
+ // The display name peers see for me (set via set_my_name).
91
+ my_name is str = "".
92
+ // My profile bio (free-text, self-asserted; carried in role invites).
93
+ my_bio is str = "".
94
+ // My LOCAL operating contract. Adopted as the bound agent's persona ONLY with
95
+ // the user's explicit consent (never silently). NEVER carried in invites; shared
96
+ // only via the control-plane cluster registry (a2a_cluster set_persona).
97
+ my_persona is str = "".
98
+ // Known contacts, keyed by their container id.
99
+ contacts is (global_id ->> a2a_protocol::contact_t) = (,).
100
+ // core 3.0: invites I generated, keyed by invite id. Holds the NON-secret
101
+ // per-invite material — the assigned contact name ("" = none), the ephemeral
102
+ // encryption PUBLIC key shipped in the slim invite, and the crypto scheme id.
103
+ // The matching ephemeral PRIVATE key lives in the hidden, non-exported
104
+ // pending_invite_keys store (INV-4) and is consumed together on first redeem.
105
+ metadef pending_invite_t: ($assigned -> str, $eph_pub -> publickey_encrypt, $scheme -> int).
106
+ pending_invites is (global_id ->> pending_invite_t) = (,).
107
+ // core 3.0: responder-side pending redemptions, keyed by invite id — who I am
108
+ // redeeming, so leg 3 (complete_invite) can name the contact and pin the
109
+ // expected inviter cid. No secrets; transient (not exported — outstanding
110
+ // invites do not survive a restart; see the 3.0 release note).
111
+ metadef pending_redemption_t: ($inviter_cid -> global_id, $inviter_name -> str, $custom_name -> str).
112
+ pending_redemptions is (global_id ->> pending_redemption_t) = (,).
113
+ // contact-restore (spec 2026-07-01): a DEGRADED contact is derivable state —
114
+ // cid present in `contacts`, absent from `peer_ads` (e.g. a breaking-change
115
+ // migration carried the contact but dropped its address document). These
116
+ // stores drive the self-heal handshake; see request_contact_restore below.
117
+ // Requester side, keyed by the TARGET cid. Non-secret half (the eph PRIVATE
118
+ // key lives in the hidden pending_restore_keys, INV-4).
119
+ metadef pending_restore_t: ($rid -> global_id, $eph_pub -> publickey_encrypt, $scheme -> int, $attempts -> int, $created -> time).
120
+ pending_restores is (global_id ->> pending_restore_t) = (,).
121
+ // Responder side, keyed by the REQUESTER cid — at most ONE outstanding reply
122
+ // per requester (bounded by the contacts set; a newer request replaces it).
123
+ metadef restore_reply_t: ($rid -> global_id, $scheme -> int, $created -> time).
124
+ pending_restore_replies is (global_id ->> restore_reply_t) = (,).
125
+ // Messages queued toward a degraded contact, flushed (host-driven,
126
+ // flush_deferred) once its AD is re-established. Plain data — EXPORTED.
127
+ metadef deferred_msg_t: ($text -> str, $wire_id -> str, $reply_to -> a2a_protocol::reply_ref_t+, $date -> time).
128
+ deferred_msgs is (global_id ->> deferred_msg_t[]) = (,).
129
+ // Peer address documents, captured when a contact is established. Self-
130
+ // signed, code-independent, and seed-stable: import_core_state replays
131
+ // them through address_document::process_address_document so encrypted
132
+ // channels survive a code upgrade with no re-handshake. Only peer PUBLIC
133
+ // keys travel here, never secrets.
134
+ peer_ads is (global_id ->> address_document_types::t_address_document) = (,).
135
+ // My delegation cert. NIL == I am a root or a legacy flat identity.
136
+ delegation_cert is a2a_protocol::delegation_cert_t+ = NIL.
137
+ // My root's address document (set with the cert; its key list is what
138
+ // sibling introductions and my own cert are verified against).
139
+ root_ad is address_document_types::t_address_document+ = NIL.
140
+ // My root's self-signed profile, embedded in the invites I generate.
141
+ root_profile is a2a_protocol::root_profile_t+ = NIL.
142
+ // My root's §3c CP binding (root half), distributed to me by the host
143
+ // (set_root_cp_binding) and carried beside root_profile in my invites so
144
+ // peers can TOFU-pin my governance edge. NIL until a CP is bound.
145
+ root_cp_binding is a2a_protocol::root_cp_binding_t+ = NIL.
146
+ // Verified root linkage per contact, keyed by the contact's container id.
147
+ contact_roots is (global_id ->> a2a_protocol::contact_root_t) = (,).
148
+ // Peers' verified §3c root bindings, keyed by the ROOT's container id (one
149
+ // edge per root, shared across its roles). Populated when a peer's invite or
150
+ // introduction carries a binding that verifies against its root key list.
151
+ contact_cp_bindings is (global_id ->> a2a_protocol::root_cp_binding_t) = (,).
152
+ // CP SIDE: the set of ROOTS this control plane manages, keyed by the root's
153
+ // container id (value is a presence marker). A child may be enrolled
154
+ // (enroll_delegated_node) ONLY when the delegation chain it presents resolves
155
+ // to a root in this set — the host asserts membership via manage_root when it
156
+ // binds a root, so the cryptographic chain + this set together authorize a
157
+ // cluster enrollment and forbid unsolicited ones. Empty on a non-CP node.
158
+ managed_roots is (global_id ->> bool) = (,).
159
+ // ---- forced monitoring + config types --------------------------------
160
+ // FORCED monitoring lives HERE, in the chokepoint, because send_message /
161
+ // handle_receive_message are the single path every app routes through —
162
+ // monitoring copies are generated as UNCONDITIONAL core code (see
163
+ // monitor_copy_actions). CRITICAL: the gate STATE (monitoring_proxy etc.) is
164
+ // declared `hidden` below, so ONLY this library can mutate it — an app or any
165
+ // other loading library cannot write `a2a_messaging::monitoring_proxy -> NIL`
166
+ // to switch monitoring off. That is why the bind ceremony + disable + the
167
+ // config writers all live IN THIS library (hidden state is mutable only by its
168
+ // declaring library); a2a_monitoring keeps only the CP-side copy RECEIVER.
169
+ //
170
+ // One monitored message copy, re-encrypted to the bound control plane. The
171
+ // source is the channel-authenticated envelope $from on the receiver, so it
172
+ // is not carried in the body. (Types are public; only the STATE is hidden.)
173
+ metadef monitoring_copy_t: (
174
+ $version -> int,
175
+ $direction -> str, // "out" (I sent) | "in" (I received)
176
+ $peer_cid -> global_id,
177
+ $peer_name -> str,
178
+ $date -> time,
179
+ $body -> str
180
+ ).
181
+ metadef proxy_pending_t: ($code -> str, $proxy_cid -> global_id, $created_at -> time, $attempts -> int).
182
+ metadef proxy_binding_t: ($proxy_cid -> global_id, $bound_at -> time).
183
+
184
+ hidden
185
+ {
186
+ // ---- monitoring + config gate state (NON-app-writable) -----------
187
+ // Hidden so only this library mutates it (the "app can't override"
188
+ // guarantee). A pending 6-digit bind, and the verified control plane that
189
+ // replaces it on success.
190
+ proxy_pending is proxy_pending_t+ = NIL.
191
+ // The verified control plane: set ONLY by verify_proxy_code, cleared ONLY
192
+ // by the CP-authenticated disable_monitoring (both in this library). It is
193
+ // also the configuration authority for set_app_config.
194
+ monitoring_proxy is proxy_binding_t+ = NIL.
195
+ // Opaque, app-custom JSON config the TS wrapper owns; the core NEVER parses
196
+ // it and bakes in NO policy semantics — per-application policy (e.g. anything
197
+ // like "outgoing-only") is the application's job, implemented in the wrapper
198
+ // from this blob. Written ONLY by the bound CP via set_app_config.
199
+ app_config is str = "".
200
+
201
+ // core 3.2 cluster roster push: monotonic sequence bumped on every real
202
+ // roster change. Carried in each push and in the list/bind result so the CP
203
+ // can order/dedup. No opt-in flag — push is gated only on monitoring_proxy.
204
+ roster_push_seq is int = 0.
205
+
206
+ // core 3.0: per-outstanding-invite ephemeral PRIVATE keys, keyed by invite id.
207
+ // hidden ⇒ only this library mutates it AND it is structurally invisible to the
208
+ // export record builder, but `hidden` governs VISIBILITY, not persistence — it
209
+ // is deliberately NEVER added to export_core_state (INV-4: secrets must not ride
210
+ // the portable export blob; empirically the SDK export serializer also corrupts
211
+ // raw secret keys). Consumed (deleted) together with pending_invites[id] on the
212
+ // first valid redemption. Outstanding entries do not survive a daemon restart.
213
+ pending_invite_keys is (global_id ->> secretkey_encrypt) = (,).
214
+
215
+ // core 3.0: RESPONDER-side per-redemption ephemeral PRIVATE keys, keyed by
216
+ // invite id. The responder keeps its leg-1 ephemeral private key here so it
217
+ // can OPEN the inviter's leg-3 reply (which is a bare send boxed to the
218
+ // responder's ephemeral PUBLIC key — leg 3 cannot ride encrypted_channel
219
+ // because the responder has not registered the inviter yet, and the stdlib
220
+ // never exposes a raw long-term encryption privkey to box against instead).
221
+ // Same INV-4 treatment as pending_invite_keys: hidden AND never exported;
222
+ // consumed with pending_redemptions[id] on the leg-3 completion.
223
+ pending_redemption_keys is (global_id ->> secretkey_encrypt) = (,).
224
+
225
+ // contact-restore ephemeral PRIVATE keys — same INV-4 treatment as the
226
+ // invite stores: hidden AND never exported; consumed with their public-half
227
+ // records on the first valid completion. Requester side keyed by target cid,
228
+ // responder side keyed by requester cid.
229
+ pending_restore_keys is (global_id ->> secretkey_encrypt) = (,).
230
+ pending_restore_reply_keys is (global_id ->> secretkey_encrypt) = (,).
231
+
232
+ _read_or_abort is (bin->any) = fn (_: bin) { abort "_read_or_abort is unset in a2a_messaging (call a2a_messaging::init)." when TRUE. }
233
+
234
+ // App-injected storage hooks. Each receives one record and returns the
235
+ // transaction actions to append (storage writes + notify/save actions).
236
+ //
237
+ // on_message_received ($sender_id, $sender_name, $text, $date,
238
+ // $wire_id, $reply_to):
239
+ // $sender_name is NIL when the sender is NOT a known contact — the
240
+ // app decides what an unknown sender means (the agent checks its
241
+ // pending-introduction queue; a plain client aborts). $wire_id is the
242
+ // message's stable cross-side id ("" from pre-1.4 senders) and
243
+ // $reply_to is its optional reply pointer (NIL when not a reply).
244
+ on_message_received is (any -> transaction::action::type[]) = fn (_: any) -> transaction::action::type[] { abort "on_message_received hook is unset in a2a_messaging (call a2a_messaging::init)." when TRUE. return []. }
245
+ // on_message_sent ($target_id, $text, $date, $wire_id, $reply_to):
246
+ // fired after the wire send is queued (agent: no-op; messenger:
247
+ // append "out" history, keyed by $wire_id so a peer's reply pointer
248
+ // resolves back to it). $reply_to is NIL unless this send is a reply.
249
+ on_message_sent is (any -> transaction::action::type[]) = fn (_: any) -> transaction::action::type[] { abort "on_message_sent hook is unset in a2a_messaging (call a2a_messaging::init)." when TRUE. return []. }
250
+ // on_contact_removed ($container_id): fired after a contact is dropped
251
+ // (agent: no-op; messenger: delete that contact's history).
252
+ on_contact_removed is (any -> transaction::action::type[]) = fn (_: any) -> transaction::action::type[] { abort "on_contact_removed hook is unset in a2a_messaging (call a2a_messaging::init)." when TRUE. return []. }
253
+ // on_file_received ($sender_id, $sender_name, $filename, $mime, $data,
254
+ // $date, $wire_id, $reply_to): the file analogue of on_message_received.
255
+ // $sender_name is NIL for an unknown sender; $mime is "" when omitted;
256
+ // $wire_id shares the message namespace; $reply_to is NIL unless a reply.
257
+ on_file_received is (any -> transaction::action::type[]) = fn (_: any) -> transaction::action::type[] { abort "on_file_received hook is unset in a2a_messaging (call a2a_messaging::init)." when TRUE. return []. }
258
+ // on_file_sent ($target_id, $filename, $mime, $data, $date, $wire_id,
259
+ // $reply_to): fired after the wire send is queued (agent: no-op;
260
+ // messenger: append an outgoing file history entry keyed by $wire_id).
261
+ on_file_sent is (any -> transaction::action::type[]) = fn (_: any) -> transaction::action::type[] { abort "on_file_sent hook is unset in a2a_messaging (call a2a_messaging::init)." when TRUE. return []. }
262
+ }
263
+
264
+ init = fn (_:(
265
+ $_read_or_abort -> read: (bin->any),
266
+ $on_message_received -> received_cb: (any -> transaction::action::type[]),
267
+ $on_message_sent -> sent_cb: (any -> transaction::action::type[]),
268
+ $on_contact_removed -> removed_cb: (any -> transaction::action::type[]),
269
+ $on_file_received -> file_received_cb: (any -> transaction::action::type[]),
270
+ $on_file_sent -> file_sent_cb: (any -> transaction::action::type[])
271
+ ))
272
+ {
273
+ _read_or_abort -> read.
274
+ on_message_received -> received_cb.
275
+ on_message_sent -> sent_cb.
276
+ on_contact_removed -> removed_cb.
277
+ on_file_received -> file_received_cb.
278
+ on_file_sent -> file_sent_cb.
279
+ }
280
+
281
+ // ---- shared action builders -------------------------------------------
282
+ // Signal the host to persist the packet. Only emitted at the end of a
283
+ // complete procedure — intermediate states (e.g. channel handshake) are
284
+ // never saved, so a crash mid-handshake restores to the last stable point.
285
+ fn _save_state (_) = (transaction::action::return_data ($kind -> $save_state)).
286
+ fn _return_data (payload: any) = (transaction::action::return_data ($kind -> $data, $payload -> payload)).
287
+ fn _notify_agent (payload: any) = (transaction::action::return_data ($kind -> $notify_agent, $payload -> payload)).
288
+
289
+ // ---- forced monitoring copy (UNCONDITIONAL core; see a2a_monitoring) ----
290
+ // Uniform rule: if a control plane is bound, fire-and-forget ONE re-encrypted
291
+ // copy of this message to it; otherwise nothing. No local queue and no
292
+ // liveness wait — if the control plane is offline the ADAPT broker holds the
293
+ // pending message (delivery is the framework's job, not the app's). The copy
294
+ // rides a DISTINCT transaction name (receive_monitoring_copy), never
295
+ // send_message, so the copy traffic is not itself monitored (no recursion).
296
+ // Called unconditionally by send_message + handle_receive_message; it
297
+ // self-gates on monitoring_proxy, which only the bind ceremony can set.
298
+ fn monitor_copy_actions (direction: str, peer_cid: global_id, date: time, body: str) -> transaction::action::type[]
299
+ {
300
+ if monitoring_proxy == NIL { return []. }
301
+ peer_name is str = "".
302
+ p = contacts peer_cid.
303
+ if p != NIL { peer_name -> p? $name. }
304
+ copy is monitoring_copy_t = (
305
+ $version -> 1,
306
+ $direction -> direction,
307
+ $peer_cid -> peer_cid,
308
+ $peer_name -> peer_name,
309
+ $date -> date,
310
+ $body -> body
311
+ ).
312
+ // The control plane is a registered contact (the bind established its
313
+ // channel), so this is a plain encrypted send action — ciphertext on the
314
+ // wire under the control-plane key, never plaintext.
315
+ return [
316
+ encrypted_channel::send_encrypted_tx (monitoring_proxy? $proxy_cid) (
317
+ $name -> receive_monitoring_copy_tx,
318
+ $targ -> ($copy -> copy)
319
+ )
320
+ ].
321
+ }
322
+
323
+ // core 3.2: generic fire-and-forget push to the bound control plane. Same rule
324
+ // as monitor_copy_actions: self-gates on monitoring_proxy, rides a DISTINCT trn
325
+ // name (so the push is not itself monitored), native record (no JSON).
326
+ fn push_to_cp_actions (tx_name: str, targ: any) -> transaction::action::type[]
327
+ {
328
+ if monitoring_proxy == NIL { return []. }
329
+ return [
330
+ encrypted_channel::send_encrypted_tx (monitoring_proxy? $proxy_cid) (
331
+ $name -> tx_name,
332
+ $targ -> targ
333
+ )
334
+ ].
335
+ }
336
+
337
+ // Authorize a control-plane configuration write: the sender must BE the bound
338
+ // control plane (monitoring_proxy). Config authority == the same CP that
339
+ // monitoring is bound to. Aborts otherwise.
340
+ fn require_bound_cp_or_abort (sender_id: global_id) -> nil
341
+ {
342
+ abort "No control plane is bound." when monitoring_proxy == NIL.
343
+ abort "Only the bound control plane may configure this node." when sender_id != (monitoring_proxy? $proxy_cid).
344
+ }
345
+
346
+ // RR-9 single pre-dispatch authz gate (CLUSTER_API.md §3). The STATEFUL half:
347
+ // a2a_capabilities holds the pure control_auth_class policy (it cannot read
348
+ // monitoring_proxy — hidden HERE, and a2a_capabilities is the lower layer);
349
+ // this fn combines that class with the bound-proxy identity. Wired into
350
+ // a2a_capabilities::init as $authorizer, called by dispatch BEFORE routing any
351
+ // controller-class verb. Returns TRUE iff the sender may run (cap,verb):
352
+ // public/bootstrap -> TRUE (bind's own 6-digit check is in its handler);
353
+ // deny -> FALSE;
354
+ // controller -> the sender must BE the bound control proxy.
355
+ // Takes `any` (not a typed arg record) so it is DIRECTLY assignable to
356
+ // a2a_capabilities::init's $authorizer field, which is (any -> bool): a typed
357
+ // arg signature is not assignable there under function-arg contravariance, so
358
+ // an app would otherwise need a wrapper. Extract the fields here instead.
359
+ fn authorize_control (args: any) -> bool
360
+ {
361
+ cap = (args $cap) safe str.
362
+ verb = (args $verb) safe str.
363
+ klass = a2a_capabilities::control_auth_class ($cap -> cap, $verb -> verb).
364
+ if klass == "public" || klass == "bootstrap" { return TRUE. }
365
+ if klass == "deny" { return FALSE. }
366
+ return monitoring_proxy != NIL && ((args $sender_id) safe global_id) == (monitoring_proxy? $proxy_cid).
367
+ }
368
+
369
+ // This node's ceremony-pinned cluster CP (its monitoring_proxy $proxy_cid), or
370
+ // NIL if unbound. The cluster set_monitoring handler DERIVES the CP a child is
371
+ // host-bound to from THIS — never a caller parameter (critic's load-bearing
372
+ // condition): a child's monitoring_proxy is only ever set to the root's OWN
373
+ // ceremony-pinned CP, so host-mediation cannot bind a child to an un-ceremonied
374
+ // CP (which would be a developer-held-credential equivalent / ceremony bypass).
375
+ fn bound_cp_cid (_) -> global_id+
376
+ {
377
+ if monitoring_proxy == NIL { return NIL. }
378
+ return monitoring_proxy? $proxy_cid.
379
+ }
380
+
381
+ fn next_roster_seq (_) -> int { roster_push_seq -> roster_push_seq + 1. return roster_push_seq. }
382
+ fn current_roster_seq (_) -> int { return roster_push_seq. }
383
+
384
+ // Host-mediated REVOCATION of a CHILD's monitoring (origin::user, host-fired on
385
+ // the child packet). CHILD-ONLY: aborts on a root/standalone (delegation_cert==NIL)
386
+ // so the standalone "only the bound CP may disable" property is preserved —
387
+ // cluster children's monitoring is host-propagated-from-the-root-ceremony, so the
388
+ // root-operator (host-control posture, SECURITY-MODEL.md) revokes it. REAL
389
+ // revocation (criterion e): clears monitoring_proxy so monitor_copy_actions stops
390
+ // forwarding immediately. (Enable reuses set_proxy_pending+verify_proxy_code,
391
+ // host-run on the child — no new bind path, ceremony pin preserved.)
392
+ trn host_clear_child_monitoring _
393
+ {
394
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
395
+ abort "host_clear_child_monitoring is cluster-children-only (a root/standalone node's monitoring is CP-cleared, not host-cleared)." when delegation_cert == NIL.
396
+ // RR9-C12 full teardown (minimal-exposure): also DROP the CP contact that
397
+ // host_register_monitoring_cp injected, so the child↔CP relationship does not
398
+ // outlive the monitoring it was established for. Read the cp from monitoring_proxy
399
+ // BEFORE clearing it. Re-enable cheaply re-injects via host_register_monitoring_cp.
400
+ if monitoring_proxy != NIL
401
+ {
402
+ cp_cid = monitoring_proxy? $proxy_cid.
403
+ peer_ads cp_cid -> NIL.
404
+ contacts cp_cid -> NIL.
405
+ }
406
+ monitoring_proxy -> NIL.
407
+ proxy_pending -> NIL.
408
+ // Trivial ack so the daemon's mutatingTx await resolves immediately (a
409
+ // save-only trn emits no $data → await blocks to timeout under the root lock).
410
+ return transaction::success [ _return_data ($ok -> TRUE), _save_state NIL ].
411
+ }
412
+
413
+ // Host-mediated delivery of the cluster CP as a CONTACT to a CHILD packet
414
+ // (origin::user, host-fired), so per-child monitoring can RESOLVE and FORWARD to
415
+ // the CP. Why host-mediated, not a network introduce: the child's introduction
416
+ // acceptance gate (ingest_connect_descriptor / require_cluster_cp_or_abort) only
417
+ // accepts a relay FROM the child's own CP, so a ROOT-relayed introduce is rejected
418
+ // (the root isn't the child's CP) AND a network introduce would race the ceremony.
419
+ // The daemon, which hosts the child, injects the CP contact directly. SECURITY: the
420
+ // CP AD is still VERIFIED here (process_address_document = self-sig + proof-of-
421
+ // possession, aborts on a forged/inconsistent document), so a forged CP cannot be
422
+ // injected. Stores peer_ads + a contacts entry so resolve_contact(cp) resolves and
423
+ // monitor_copy_actions' encrypted send can establish the child->CP channel. Only the
424
+ // host (origin::user) can call it; ordered by the daemon BEFORE the bind ceremony.
425
+ trn host_register_monitoring_cp _:($cp_ad -> cp_ad: address_document_types::t_address_document)
426
+ {
427
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
428
+ address_document::process_address_document cp_ad TRUE.
429
+ cp_cid = cp_ad $identity $container_id.
430
+ peer_ads cp_cid -> cp_ad.
431
+ if (contacts cp_cid) == NIL { contacts cp_cid -> ($name -> "control-plane", $container_id -> cp_cid). }
432
+ // Trivial ack so the daemon's mutatingTx await resolves immediately (save-only
433
+ // → no $data → await blocks to timeout under the root lock).
434
+ return transaction::success [ _return_data ($ok -> TRUE), _save_state NIL ].
435
+ }
436
+
437
+ // Authorize an introduction relay (core.connect) — ADDITIVE successor to
438
+ // require_bound_cp_or_abort. A relay is accepted on EITHER of two grounds:
439
+ // (a) Legacy direct bind — this node ran the 6-digit ceremony itself, so the
440
+ // sender IS its own monitoring_proxy. Unchanged behaviour, non-breaking.
441
+ // (b) Inherited cluster CP — the sender is the CP my ROOT designated. The role
442
+ // binds nothing itself: it inherits root_cp_binding (the root-signed edge)
443
+ // and root_ad (the root's pinned keys), and verifies the edge LOCALLY, with
444
+ // no round-trip and no per-child ceremony.
445
+ // Security (critic invariant #3): the inherited branch re-derives trust from the
446
+ // pinned root_ad on EVERY call — verify_root_cp_binding does NOT check cid_cp, so
447
+ // we (1) assert sender_id == root_cp_binding.cid_cp AND (2) verify the binding's
448
+ // signature/context/root_cid against root_ad's OWN container id + key list (never
449
+ // the cid_cp stored in the binding, never keys carried by the binding). A
450
+ // signature-valid binding whose cid_cp is unpinned, or that verifies against the
451
+ // wrong root keys, is rejected.
452
+ fn require_cluster_cp_or_abort (sender_id: global_id) -> nil
453
+ {
454
+ // (a) legacy direct bind: short-circuit, leave the inherited path unevaluated.
455
+ legacy_ok = monitoring_proxy != NIL && sender_id == (monitoring_proxy? $proxy_cid).
456
+ if legacy_ok != TRUE
457
+ {
458
+ // (b) inherited cluster CP — require both the binding and the pinned root.
459
+ abort "Unauthorized introduction relay: no bound control plane and no inherited root CP binding." when root_cp_binding == NIL || root_ad == NIL.
460
+ // (1) the relay must come from the exact CP my root designated.
461
+ abort "Unauthorized introduction relay: sender is not the CP my root designated." when sender_id != (root_cp_binding? $c $cid_cp).
462
+ // (2) re-verify the root-signed edge against my pinned root identity every call.
463
+ abort "Unauthorized introduction relay: root CP binding does not verify against my pinned root identity." when a2a_protocol::verify_root_cp_binding (root_cp_binding?) (root_ad? $identity $container_id) (root_ad? $identity $key_list) != TRUE.
464
+ }
465
+ }
466
+
467
+ // Resolve a contact reference (a display name or stringified container id)
468
+ // to a container id; aborts if no contact matches.
469
+ fn resolve_contact (ref: str) -> global_id
470
+ {
471
+ found is global_id+ = NIL.
472
+ sc contacts -- (cid -> c) ?? found == NIL && ((c $name) == ref || (_str cid) == ref)
473
+ {
474
+ found -> cid.
475
+ }
476
+ abort "Unknown contact: " + ref when found == NIL.
477
+ return found?.
478
+ }
479
+
480
+ // ---- user transactions --------------------------------------------------
481
+
482
+ trn set_my_name _:($name -> name: str)
483
+ {
484
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
485
+ my_name -> name.
486
+ return transaction::success [
487
+ _return_data ($name -> name),
488
+ _save_state NIL
489
+ ].
490
+ }
491
+
492
+ trn set_my_bio _:($bio -> bio: str)
493
+ {
494
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
495
+ my_bio -> bio.
496
+ return transaction::success [
497
+ _return_data ($bio -> bio),
498
+ _save_state NIL
499
+ ].
500
+ }
501
+
502
+ trn set_my_persona _:($persona -> persona: str)
503
+ {
504
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
505
+ my_persona -> persona.
506
+ return transaction::success [
507
+ _return_data ($persona -> persona),
508
+ _save_state NIL
509
+ ].
510
+ }
511
+
512
+ // Host-fired (ROOT only, core 2.2): mint this root's §3c CP binding. The root
513
+ // self-signs {context_tag, root_cid=me, cid_cp} so its roles can TOFU-pin "my
514
+ // root designated CP X" and accept that CP's introductions locally. STATELESS and
515
+ // root-only, mirroring sign_delegation: it returns the signed blob; the daemon
516
+ // stores it on the root via set_root_cp_binding (own-identity verify) and pushes
517
+ // the SAME blob to each role via set_root_cp_binding (root_ad verify). This is the
518
+ // root-side PRODUCER core 2.1 deferred (it shipped only the verifier + store + the
519
+ // accept gate); without it nothing could create the binding the cluster needs.
520
+ trn sign_root_cp_binding _:($proxy -> proxy_ref: str)
521
+ {
522
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
523
+ abort "Only a root identity can mint a CP binding." when delegation_cert != NIL.
524
+
525
+ cid_cp = resolve_contact proxy_ref.
526
+ core is a2a_protocol::root_cp_binding_core_t = (
527
+ $version -> 1,
528
+ $context_tag -> a2a_protocol::cp_attestation_context_tag,
529
+ $root_cid -> _get_container_id(),
530
+ $cid_cp -> cid_cp
531
+ ).
532
+ binding is a2a_protocol::root_cp_binding_t = ($c -> core, $s -> key_storage::default_sign (_value_id core)).
533
+ return transaction::success [
534
+ _return_data ($binding -> (_write binding), $cid_cp -> (_str cid_cp))
535
+ ].
536
+ }
537
+
538
+ // Host-fired: store a root-signed CP binding for THIS node's root edge. DUAL-MODE
539
+ // (core 2.2 widened the verify path — additive, rejects strictly more):
540
+ // • ROOT (delegation_cert == NIL): the binding is the root's OWN self-signed edge
541
+ // (sign_root_cp_binding above); verified against this node's own identity —
542
+ // unchanged from 2.1.
543
+ // • ROLE (delegation_cert != NIL): the binding is the root's edge INHERITED by the
544
+ // role; verified against the role's PINNED root_ad — the SAME keys and verifier
545
+ // the require_cluster_cp_or_abort accept gate uses, so a role can store only an
546
+ // edge its OWN root actually signed. This fills root_cp_binding (which the gate
547
+ // reads), letting a child accept CP introductions with zero per-child ceremony.
548
+ // verify_root_cp_binding enforces, on the role path: (a) binding.root_cid == the
549
+ // pinned root_ad's container id — an edge signed by ANY other root is rejected;
550
+ // (b) the signature against root_ad's key list under the domain-separated context_tag,
551
+ // which also covers (c) cid_cp integrity (cid_cp is inside the signed core record).
552
+ // Fails CLOSED on any mismatch. The binding also rides the existing invite/state-push
553
+ // paths (generate_invite $rpb, export/import_core_state).
554
+ trn set_root_cp_binding _:($binding -> binding_blob: bin)
555
+ {
556
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
557
+ binding = (_read_or_abort binding_blob) safe a2a_protocol::root_cp_binding_t.
558
+ if delegation_cert != NIL
559
+ {
560
+ abort "Cannot inherit a root CP binding without pinned root material." when root_ad == NIL.
561
+ abort "Inherited root CP binding does not verify against my pinned root identity." when a2a_protocol::verify_root_cp_binding binding (root_ad? $identity $container_id) (root_ad? $identity $key_list) != TRUE.
562
+ }
563
+ else
564
+ {
565
+ my_ad = address_document::get_my_address_document().
566
+ abort "Root CP binding does not verify against this node's own root identity." when a2a_protocol::verify_root_cp_binding binding (my_ad $identity $container_id) (my_ad $identity $key_list) != TRUE.
567
+ }
568
+ root_cp_binding -> binding.
569
+ return transaction::success [
570
+ _return_data ($cid_cp -> _str (binding $c $cid_cp)),
571
+ _save_state NIL
572
+ ].
573
+ }
574
+
575
+ // ---- shared identity-bundle helpers (invite legs + contact-restore legs) ----
576
+ // My identity bundle payload fields: my AD plus, when I am a delegated role,
577
+ // my chain blobs (cert / root profile / optional §3c cp binding). The caller
578
+ // appends its own correlation id ($invite_id or $rid) and _write's the record.
579
+ fn my_identity_bundle_fields (_) -> ($ad -> address_document_types::t_address_document, $cert -> bin+, $root_profile -> bin+, $cp_binding -> bin+)
580
+ {
581
+ my_cert_blob is bin+ = NIL.
582
+ my_rp_blob is bin+ = NIL.
583
+ my_rpb_blob is bin+ = NIL.
584
+ if delegation_cert != NIL && root_profile != NIL
585
+ {
586
+ my_cert_blob -> (_write delegation_cert?).
587
+ my_rp_blob -> (_write root_profile?).
588
+ if root_cp_binding != NIL { my_rpb_blob -> (_write root_cp_binding?). }
589
+ }
590
+ return ($ad -> address_document::get_my_address_document(), $cert -> my_cert_blob, $root_profile -> my_rp_blob, $cp_binding -> my_rpb_blob).
591
+ }
592
+
593
+ // Verify a received identity bundle against the authenticated sender: D8
594
+ // cid-bind + PoP self-sig (process_address_document aborts on a forged or
595
+ // inconsistent document), then the OPTIONAL delegation chain (an invalid
596
+ // chain aborts; a verifying §3c cp binding is STAGED in the returned record,
597
+ // never written here — INV-5: the CALLER performs all registration writes
598
+ // together after every gate has passed).
599
+ metadef verified_bundle_t: ($ad -> address_document_types::t_address_document, $root -> a2a_protocol::contact_root_t+, $pin_binding -> a2a_protocol::root_cp_binding_t+, $pin_binding_root -> global_id+).
600
+ fn verify_identity_bundle (payload: any, sender_id: global_id) -> verified_bundle_t
601
+ {
602
+ ad = (payload $ad) safe address_document_types::t_address_document.
603
+ abort "Address document does not belong to the sender." when (ad $identity $container_id) != sender_id.
604
+ address_document::process_address_document ad TRUE.
605
+ peer_root is a2a_protocol::contact_root_t+ = NIL.
606
+ pin_binding is a2a_protocol::root_cp_binding_t+ = NIL.
607
+ pin_binding_root is global_id+ = NIL.
608
+ if (payload $cert) != NIL
609
+ {
610
+ cert = (_read_or_abort ((payload $cert) safe bin)) safe a2a_protocol::delegation_cert_t.
611
+ rp = (_read_or_abort ((payload $root_profile) safe bin)) safe a2a_protocol::root_profile_t.
612
+ peer_root -> a2a_protocol::verify_peer_delegation sender_id (_value_id ad) cert rp.
613
+ if (payload $cp_binding) != NIL
614
+ {
615
+ binding = (_read_or_abort ((payload $cp_binding) safe bin)) safe a2a_protocol::root_cp_binding_t.
616
+ if a2a_protocol::verify_root_cp_binding binding (rp $p $root_cid) (rp $p $keys) == TRUE
617
+ {
618
+ pin_binding -> binding.
619
+ pin_binding_root -> (rp $p $root_cid).
620
+ }
621
+ }
622
+ }
623
+ return ($ad -> ad, $root -> peer_root, $pin_binding -> pin_binding, $pin_binding_root -> pin_binding_root).
624
+ }
625
+
626
+ // core 3.0: mint a SLIM ephemeral-key invite assigned to `assigned` (empty
627
+ // string = no assigned name). Reusable fn so BOTH generate_invite (user trn)
628
+ // and the core.cluster `contact` verb (a2a_cluster, which relays the blob
629
+ // OPAQUELY) share ONE construction path. Generates a fresh ephemeral encryption
630
+ // keypair, registers its PUBLIC half (+ assigned name + scheme) in pending_invites
631
+ // and its PRIVATE half in the hidden, non-exported pending_invite_keys store, and
632
+ // emits ONLY {invite_id, inviter_cid, name, eph_pub, scheme} — no keys, no cert,
633
+ // no root profile (those move to the encrypted two-message redeem hop). No role
634
+ // branch: roles emit the same slim shape. Side effect: registers both stores; the
635
+ // CALLER must emit _save_state. Returns the _write'd blob + its invite_id.
636
+ fn mint_eph_invite (assigned: str) -> ($blob -> bin, $invite_id -> global_id)
637
+ {
638
+ scheme = _crypto_default_scheme_id().
639
+ kp = _crypto_construct_encryption_keypair scheme.
640
+ invite_id = _new_id "ours invite".
641
+
642
+ pending_invites invite_id -> ($assigned -> assigned, $eph_pub -> (kp $public_key), $scheme -> scheme).
643
+ pending_invite_keys invite_id -> (kp $secret_key).
644
+
645
+ my_ad = address_document::get_my_address_document().
646
+ invite is a2a_protocol::invite_eph_t = (
647
+ $d -> invite_id,
648
+ $c -> (my_ad $identity $container_id),
649
+ $n -> my_name,
650
+ $k -> (kp $public_key),
651
+ $v -> scheme
652
+ ).
653
+ return ($blob -> (_write invite), $invite_id -> invite_id).
654
+ }
655
+
656
+ trn generate_invite _:($name -> name: str+)
657
+ {
658
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
659
+ // Empty string is the "no assigned name" sentinel: accept_contact then
660
+ // registers the joiner under its self-announced name instead.
661
+ assigned = (name == NIL ?? "" ; name?).
662
+ minted = mint_eph_invite assigned.
663
+ return transaction::success [
664
+ _return_data (
665
+ $invite -> (minted $blob),
666
+ $invite_id -> (minted $invite_id),
667
+ $peer_name -> assigned
668
+ ),
669
+ _save_state NIL
670
+ ].
671
+ }
672
+
673
+ // core 3.0 LEG 1 (responder): redeem a slim ephemeral invite. Generate a
674
+ // one-shot responder ephemeral keypair, BOX my identity bundle (AD + optional
675
+ // role chain) to the invite's ephemeral pubkey, and BARE-send it to the inviter
676
+ // — the inviter is not registered yet, so confidentiality/integrity come from
677
+ // the box and authenticity from the cid-bind + PoP the inviter enforces at leg 2.
678
+ // The contact is NOT final here: it is registered when the inviter's leg-3
679
+ // complete_invite arrives (pending_redemptions remembers the chosen name +
680
+ // expected inviter cid; pending_redemption_keys keeps my ephemeral PRIVATE key
681
+ // so I can open the inviter's leg-3, which is boxed to my ephemeral pubkey — see
682
+ // the leg-3 handler for why encrypted_channel cannot carry it). Disclosure order
683
+ // flips vs the old fat invite — the responder discloses first — see
684
+ // EPHEMERAL_INVITE_PLAN.md §2/§6.
685
+ trn add_contact _:($invite -> invite_blob: bin, $name -> custom_name: str+)
686
+ {
687
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
688
+
689
+ inv = (_read_or_abort invite_blob) safe a2a_protocol::invite_eph_t.
690
+ inviter_cid = inv $c.
691
+ abort "This invite is your own — you cannot add yourself." when inviter_cid == _get_container_id().
692
+ invite_id = inv $d.
693
+ inviter_name = inv $n.
694
+ eph_pub_inviter = inv $k.
695
+ scheme = inv $v.
696
+
697
+ // Responder ephemeral keypair. The PUBLIC half travels (cleartext, beside
698
+ // the box); the PRIVATE half is KEPT in pending_redemption_keys so I can open
699
+ // the inviter's leg-3 reply (boxed to this pubkey). Forward secrecy for the
700
+ // leg-1 "who is connecting" metadata; both halves are dropped at leg 3.
701
+ kpr = _crypto_construct_encryption_keypair scheme.
702
+
703
+ // My identity bundle: my AD plus, if I am a delegated role, my chain so the
704
+ // inviter learns my root linkage symmetrically. All inside the box.
705
+ b = my_identity_bundle_fields NIL.
706
+ payload = _write (
707
+ $ad -> (b $ad),
708
+ $cert -> (b $cert),
709
+ $root_profile -> (b $root_profile),
710
+ $cp_binding -> (b $cp_binding),
711
+ $invite_id -> invite_id
712
+ ).
713
+ data = _crypto_encrypt_message (kpr $secret_key) eph_pub_inviter payload.
714
+
715
+ // Remember who I am redeeming (name + expected inviter cid; no secrets) and
716
+ // KEEP my ephemeral private key (secret store) so leg 3 can be opened.
717
+ contact_name = (custom_name == NIL ?? "" ; custom_name?).
718
+ pending_redemptions invite_id -> ($inviter_cid -> inviter_cid, $inviter_name -> inviter_name, $custom_name -> contact_name).
719
+ pending_redemption_keys invite_id -> (kpr $secret_key).
720
+
721
+ // BARE send (NOT send_encrypted_tx): the inviter is not registered, so the
722
+ // box is the protection. Established pattern, cf. encrypted_channel.mm:73.
723
+ return transaction::success [
724
+ transaction::action::send inviter_cid (
725
+ $name -> submit_invite_response_tx,
726
+ $targ -> (
727
+ $invite_id -> invite_id,
728
+ $epk -> (kpr $public_key),
729
+ $v -> scheme,
730
+ $data -> data
731
+ )
732
+ ),
733
+ _return_data (
734
+ $pending -> contact_name,
735
+ $invite_id -> invite_id,
736
+ $container_id -> inviter_cid,
737
+ $inviter_name -> inviter_name,
738
+ // PUBLIC ephemeral key (already on the wire in leg 1) — surfaced so a
739
+ // caller can correlate the outstanding redemption; carries no secret.
740
+ $resp_eph_pub -> (kpr $public_key)
741
+ ),
742
+ _save_state NIL
743
+ ].
744
+ }
745
+
746
+ // Mint (or RE-mint) a restore request toward a degraded contact: fresh
747
+ // ephemeral keypair + correlation id, REPLACING any outstanding attempt (the
748
+ // superseded eph key makes a stale leg-1 reply fail both the rid check and
749
+ // the unbox). Returns the bare signed send action (leg 0); #77 signs every
750
+ // envelope, so the receiver authenticates us from the envelope alone. The
751
+ // CALLER emits _save_state.
752
+ fn begin_contact_restore (target: global_id) -> transaction::action::type[]
753
+ {
754
+ attempts is int = 0.
755
+ prev = pending_restores target.
756
+ if prev != NIL { attempts -> (prev? $attempts). }
757
+ scheme = _crypto_default_scheme_id().
758
+ kp = _crypto_construct_encryption_keypair scheme.
759
+ rid = _new_id "ours restore".
760
+ now = (current_transaction_info::get_transaction_time())?.
761
+ pending_restores target -> ($rid -> rid, $eph_pub -> (kp $public_key), $scheme -> scheme, $attempts -> attempts + 1, $created -> now).
762
+ pending_restore_keys target -> (kp $secret_key).
763
+ return [
764
+ transaction::action::send target (
765
+ $name -> request_contact_restore_tx,
766
+ $targ -> ($rid -> rid, $epk -> (kp $public_key), $v -> scheme)
767
+ )
768
+ ].
769
+ }
770
+
771
+ // $reply_to is optional: when set, it points at the message this one
772
+ // replies to (its stamped wire id + an optional sentence index). Every
773
+ // message gets a fresh stringified wire id — the stable, cross-side handle
774
+ // a reply can reference (the receiver's msg_id is local to its own inbox).
775
+ trn send_message _:($contact -> contact_ref: str, $text -> text: str, $reply_to -> reply_to: a2a_protocol::reply_ref_t+)
776
+ {
777
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
778
+
779
+ target_id = resolve_contact contact_ref.
780
+ sent_date = (current_transaction_info::get_transaction_time())?.
781
+ wire_id = _str (_new_id "ours message").
782
+
783
+ // DEGRADED contact (known cid, no address document — e.g. a breaking-change
784
+ // migration dropped peer_ads): queue the message and (re)issue a restore
785
+ // request instead of failing the send. flush_deferred (host-driven, fired
786
+ // on the $contact_restored notify) drains the queue once the peer's AD is
787
+ // re-established.
788
+ if (peer_ads target_id) == NIL
789
+ {
790
+ q is deferred_msg_t[] = [].
791
+ cur = deferred_msgs target_id.
792
+ if cur != NIL { q -> cur?. }
793
+ abort "Deferred queue for this contact is full (" + (_str deferred_msgs_cap) + ") — contact restore still pending." when (_count q|) >= deferred_msgs_cap.
794
+ q (_count q|) -> ($text -> text, $wire_id -> wire_id, $reply_to -> reply_to, $date -> sent_date).
795
+ deferred_msgs target_id -> q.
796
+ actions is transaction::action::type[] = begin_contact_restore target_id.
797
+ actions (_count actions|) -> _return_data ($sent_to -> target_id, $wire_id -> wire_id, $deferred -> TRUE, $queued -> (_count q|)).
798
+ actions (_count actions|) -> _save_state NIL.
799
+ return transaction::success actions.
800
+ }
801
+
802
+ return encrypted_channel::execute_transaction target_id (fn (_) -> transaction::results::type {
803
+ actions is transaction::action::type[] = [
804
+ encrypted_channel::send_encrypted_tx target_id (
805
+ $name -> receive_message_tx,
806
+ $targ -> ($text -> text, $wire_id -> wire_id, $reply_to -> reply_to)
807
+ )
808
+ ].
809
+ sc on_message_sent ($target_id -> target_id, $text -> text, $date -> sent_date, $wire_id -> wire_id, $reply_to -> reply_to) -- ( -> a)
810
+ {
811
+ actions (_count actions|) -> a.
812
+ }
813
+ // FORCED: emit the outbound monitoring copy as core code, after the app
814
+ // hook, so the app cannot suppress it (self-gates on monitoring_proxy).
815
+ sc monitor_copy_actions "out" target_id sent_date text -- ( -> a)
816
+ {
817
+ actions (_count actions|) -> a.
818
+ }
819
+ actions (_count actions|) -> _return_data ($sent_to -> target_id, $text -> text, $wire_id -> wire_id).
820
+ actions (_count actions|) -> _save_state NIL.
821
+ return transaction::success actions.
822
+ }).
823
+ }
824
+
825
+ // Metadata-only monitoring line for a file (NEVER the bytes): the bound control
826
+ // plane learns that a file moved + its name/mime/size, nothing more. monitoring_
827
+ // copy_t.$body stays str, so no copy-shape change.
828
+ fn file_monitor_summary (filename: str, mime: str, data: bin) -> str
829
+ {
830
+ return "[file] " + filename + " (" + mime + ", " + (_str (_binlen data)) + " B)".
831
+ }
832
+
833
+ // File transfer (core 3.1): a separate transaction from send_message — files and
834
+ // text are always distinct messages. Mirrors send_message exactly: a wire_id from
835
+ // the SAME _new_id namespace (so a reply_to can cross between messages and files),
836
+ // an optional reply_to, and the app-side on_file_sent storage hook. Both send_file
837
+ // and handle_receive_file emit a forced metadata-only monitoring copy (name/mime/size).
838
+ trn send_file _:($contact -> contact_ref: str, $filename -> filename: str, $mime -> mime: str+, $data -> data: bin, $reply_to -> reply_to: a2a_protocol::reply_ref_t+)
839
+ {
840
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
841
+
842
+ target_id = resolve_contact contact_ref.
843
+ // Files do NOT queue (bulk binary); fail fast with the real reason instead
844
+ // of an opaque channel error. send_message toward this contact will queue
845
+ // and drive the restore.
846
+ abort "Contact \"" + contact_ref + "\" is awaiting key restore (degraded) — retry the file after a message to it is delivered." when (peer_ads target_id) == NIL.
847
+ sent_date = (current_transaction_info::get_transaction_time())?.
848
+ wire_id = _str (_new_id "ours file").
849
+ mime_s is str = "".
850
+ if mime != NIL { mime_s -> mime safe str. }
851
+
852
+ return encrypted_channel::execute_transaction target_id (fn (_) -> transaction::results::type {
853
+ actions is transaction::action::type[] = [
854
+ encrypted_channel::send_encrypted_tx target_id (
855
+ $name -> receive_file_tx,
856
+ $targ -> ($filename -> filename, $mime -> mime_s, $data -> data, $wire_id -> wire_id, $reply_to -> reply_to)
857
+ )
858
+ ].
859
+ sc on_file_sent ($target_id -> target_id, $filename -> filename, $mime -> mime_s, $data -> data, $date -> sent_date, $wire_id -> wire_id, $reply_to -> reply_to) -- ( -> a)
860
+ {
861
+ actions (_count actions|) -> a.
862
+ }
863
+ // FORCED metadata-only monitoring copy (app cannot suppress; self-gates on
864
+ // monitoring_proxy). Mirrors send_message's forced "out" copy.
865
+ sc monitor_copy_actions "out" target_id sent_date (file_monitor_summary filename mime_s data) -- ( -> a)
866
+ {
867
+ actions (_count actions|) -> a.
868
+ }
869
+ actions (_count actions|) -> _return_data ($sent_to -> target_id, $filename -> filename, $wire_id -> wire_id).
870
+ actions (_count actions|) -> _save_state NIL.
871
+ return transaction::success actions.
872
+ }).
873
+ }
874
+
875
+ trn remove_contact _:($contact -> contact_ref: str)
876
+ {
877
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
878
+
879
+ target_id = resolve_contact contact_ref.
880
+ // Guard the monitoring invariant "monitoring_proxy != NIL ⇒ the proxy is a
881
+ // registered contact": removing the bound control plane would leave a
882
+ // dangling monitoring_proxy, so the next send_message's forced copy would
883
+ // fire send_encrypted_tx at an unregistered peer and ABORT the user's send —
884
+ // and disable_monitoring is CP-only, so with the CP gone there is no
885
+ // recovery (all messaging bricked). Block the removal instead; this is NOT
886
+ // an app-callable clear (removal is refused, monitoring is not switched off).
887
+ abort "Cannot remove the bound control plane while monitoring is active — the control plane must disable monitoring first." when monitoring_proxy != NIL && target_id == (monitoring_proxy? $proxy_cid).
888
+ removed = contacts target_id.
889
+ removed_name = removed? $name.
890
+
891
+ delete contacts target_id.
892
+ if peer_ads target_id != NIL { delete peer_ads target_id. }
893
+ if contact_roots target_id != NIL { delete contact_roots target_id. }
894
+
895
+ // Contact-restore stores too: an orphaned deferred queue would persist in
896
+ // every export and, on a later RE-ADD of the same peer, the boot/GC sweep
897
+ // would silently deliver the stale queued messages.
898
+ if (deferred_msgs target_id) != NIL { delete deferred_msgs target_id. }
899
+ if (pending_restores target_id) != NIL { delete pending_restores target_id. }
900
+ if (pending_restore_keys target_id) != NIL { delete pending_restore_keys target_id. }
901
+ if (pending_restore_replies target_id) != NIL { delete pending_restore_replies target_id. }
902
+ if (pending_restore_reply_keys target_id) != NIL { delete pending_restore_reply_keys target_id. }
903
+
904
+ actions is transaction::action::type[] = [].
905
+ sc on_contact_removed ($container_id -> target_id) -- ( -> a)
906
+ {
907
+ actions (_count actions|) -> a.
908
+ }
909
+ actions (_count actions|) -> _return_data ($removed -> removed_name, $container_id -> target_id).
910
+ actions (_count actions|) -> _save_state NIL.
911
+ return transaction::success actions.
912
+ }
913
+
914
+ trn readonly list_contacts _
915
+ {
916
+ return contacts.
917
+ }
918
+
919
+ trn readonly list_contact_roots _
920
+ {
921
+ return contact_roots.
922
+ }
923
+
924
+ // ---- monitoring bind ceremony (writes hidden gate state) -----------------
925
+ // These live HERE, not in a2a_monitoring, because monitoring_proxy/proxy_pending
926
+ // are hidden and hidden state is mutable only by its declaring library — that is
927
+ // the enforcement of "no app/library can flip monitoring off by direct assignment."
928
+
929
+ // Start a proxy binding (host-fired): remember the host-generated 6-digit code
930
+ // for one specific contact (the control plane). Restart overwrites any pending.
931
+ trn set_proxy_pending _:($code -> code: str, $proxy -> proxy_ref: str)
932
+ {
933
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
934
+
935
+ pid = resolve_contact proxy_ref.
936
+ proxy_pending -> (
937
+ $code -> code,
938
+ $proxy_cid -> pid,
939
+ $created_at -> (current_transaction_info::get_transaction_time())?,
940
+ $attempts -> 0
941
+ ).
942
+ return transaction::success [
943
+ _return_data ($pending -> TRUE, $proxy_cid -> (_str pid)),
944
+ _save_state NIL
945
+ ].
946
+ }
947
+
948
+ // Verify a proxy's code attempt (host-fired when the control plane's bind
949
+ // request arrives; $sender is the channel-authenticated control-plane id the
950
+ // daemon relays). Failures are returned as DATA — not aborts — so the attempt
951
+ // counter and expiry clearing PERSIST atomically; an abort would roll them back
952
+ // and reopen the brute-force window. On success, binds monitoring_proxy.
953
+ //
954
+ // Trust boundary (asymmetry vs disable_monitoring, intentional): BIND is
955
+ // user-origin and trusts the daemon to relay the true $sender — a hostile
956
+ // DAEMON could sham-bind — the accepted self-assertion limitation (ours
957
+ // monitoring design, MCP repo). The
958
+ // "app can't override" guarantee is against the app PACKET, which cannot issue
959
+ // user-origin transactions at all. DISABLE is external-direct (sender == $from).
960
+ // Core of the 6-digit bind ceremony, SHARED by the verify_proxy_code trn (the
961
+ // legacy direct entry) and the core.monitoring `bind` verb handler (a2a_cluster).
962
+ // ONE ceremony definition — no divergence. Verifies `code` from `sid` against
963
+ // proxy_pending; on success SETS monitoring_proxy (sid becomes the controller).
964
+ // Mutates hidden gate state, so it MUST live here. Returns the outcome; the
965
+ // caller emits _save_state. $attempts_left is meaningful only for "wrong_code".
966
+ fn do_verify_proxy_code (code: str, sid: global_id) -> ($verified -> bool, $reason -> str, $attempts_left -> int)
967
+ {
968
+ if proxy_pending == NIL { return ($verified -> FALSE, $reason -> "no_pending", $attempts_left -> 0). }
969
+ p = proxy_pending?.
970
+ now = (current_transaction_info::get_transaction_time())?.
971
+
972
+ if (_substract_seconds now (p $created_at)) > proxy_code_max_age_seconds
973
+ {
974
+ proxy_pending -> NIL.
975
+ return ($verified -> FALSE, $reason -> "expired", $attempts_left -> 0).
976
+ }
977
+ if sid != (p $proxy_cid) { return ($verified -> FALSE, $reason -> "wrong_sender", $attempts_left -> 0). }
978
+ if code != (p $code)
979
+ {
980
+ attempts = (p $attempts) + 1.
981
+ if attempts >= proxy_max_attempts
982
+ {
983
+ proxy_pending -> NIL.
984
+ return ($verified -> FALSE, $reason -> "too_many_attempts", $attempts_left -> 0).
985
+ }
986
+ proxy_pending -> ($code -> p $code, $proxy_cid -> p $proxy_cid, $created_at -> p $created_at, $attempts -> attempts).
987
+ return ($verified -> FALSE, $reason -> "wrong_code", $attempts_left -> proxy_max_attempts - attempts).
988
+ }
989
+ monitoring_proxy -> ($proxy_cid -> sid, $bound_at -> now).
990
+ proxy_pending -> NIL.
991
+ return ($verified -> TRUE, $reason -> "ok", $attempts_left -> 0).
992
+ }
993
+
994
+ // Clear the monitoring binding if `sid` IS the bound proxy. Shared by the
995
+ // core.monitoring `disable` verb handler. Returns TRUE iff disabled.
996
+ fn do_disable_monitoring (sid: global_id) -> bool
997
+ {
998
+ if monitoring_proxy == NIL { return FALSE. }
999
+ if sid != (monitoring_proxy? $proxy_cid) { return FALSE. }
1000
+ monitoring_proxy -> NIL.
1001
+ proxy_pending -> NIL.
1002
+ return TRUE.
1003
+ }
1004
+
1005
+ trn verify_proxy_code _:($code -> code: str, $sender -> sender_ref: str)
1006
+ {
1007
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1008
+ sid = resolve_contact sender_ref.
1009
+ r = do_verify_proxy_code code sid.
1010
+ if (r $verified) == TRUE
1011
+ {
1012
+ return transaction::success [ _return_data ($verified -> TRUE, $proxy_cid -> (_str sid)), _save_state NIL ].
1013
+ }
1014
+ if (r $reason) == "wrong_code"
1015
+ {
1016
+ return transaction::success [ _return_data ($verified -> FALSE, $reason -> "wrong_code", $attempts_left -> (r $attempts_left)), _save_state NIL ].
1017
+ }
1018
+ return transaction::success [ _return_data ($verified -> FALSE, $reason -> (r $reason)), _save_state NIL ].
1019
+ }
1020
+
1021
+ // Disable monitoring. CP-AUTHENTICATED: only the bound control plane may clear
1022
+ // the binding — EXTERNAL, encrypted, sender must BE the bound proxy. There is
1023
+ // deliberately no user-origin / app-callable clear.
1024
+ trn disable_monitoring _
1025
+ {
1026
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1027
+ encrypted_channel::check_encrypted_or_abort().
1028
+
1029
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1030
+ abort "Monitoring is not bound." when monitoring_proxy == NIL.
1031
+ abort "Only the bound control plane can disable monitoring." when sender_id != (monitoring_proxy? $proxy_cid).
1032
+
1033
+ monitoring_proxy -> NIL.
1034
+ proxy_pending -> NIL.
1035
+ return transaction::success [
1036
+ _notify_agent ($event -> $monitoring_disabled, $cid -> sender_id),
1037
+ _save_state NIL
1038
+ ].
1039
+ }
1040
+
1041
+ // Observable monitoring state (readonly). monitored == a control plane is bound.
1042
+ trn readonly get_monitoring_status _
1043
+ {
1044
+ pending is bool = FALSE.
1045
+ if proxy_pending != NIL { pending -> TRUE. }
1046
+ proxy_out is str = "".
1047
+ if monitoring_proxy != NIL { proxy_out -> _str (monitoring_proxy? $proxy_cid). }
1048
+ return (
1049
+ $monitored -> (monitoring_proxy != NIL),
1050
+ $proxy_pending -> pending,
1051
+ $proxy_cid -> proxy_out
1052
+ ).
1053
+ }
1054
+
1055
+ // ---- control-plane configuration (CP-gated; see config state above) ------
1056
+
1057
+ // Store the opaque app config blob pushed by the bound control plane after the
1058
+ // user fills the schema form on the CP frontend. CP-AUTHENTICATED: external,
1059
+ // encrypted, sender must be the bound control plane. The blob is opaque to the
1060
+ // core; a $config_updated notify wakes the wrapper, which pulls it via
1061
+ // get_app_config and applies the operational parts.
1062
+ fn handle_set_app_config (args: any) -> transaction::results::type
1063
+ {
1064
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1065
+ encrypted_channel::check_encrypted_or_abort().
1066
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1067
+ require_bound_cp_or_abort sender_id.
1068
+
1069
+ app_config -> (args $config) safe str.
1070
+ return transaction::success [
1071
+ _notify_agent ($event -> $config_updated),
1072
+ _save_state NIL
1073
+ ].
1074
+ }
1075
+
1076
+ trn set_app_config args: any
1077
+ {
1078
+ return handle_set_app_config args.
1079
+ }
1080
+
1081
+ trn readonly get_app_config _
1082
+ {
1083
+ return ($config -> app_config).
1084
+ }
1085
+
1086
+ // NOTE: the core intentionally stores ONLY the opaque app_config blob and bakes
1087
+ // in NO policy semantics. Per-application policy (e.g. "outgoing-only to a
1088
+ // contact") is application logic, implemented in the wrapper from its own custom
1089
+ // config schema — it is deliberately NOT a protocol feature (human ruling).
1090
+
1091
+ // ---- cluster enrollment: managed roots (core 2.1) -------------------------
1092
+ // CP SIDE, host-fired: record that this control plane manages a root. The daemon
1093
+ // calls this when a root binds the CP (one call conveys the whole cluster — every
1094
+ // child of the root becomes enrollable). It is the authorization half of
1095
+ // enroll_delegated_node: a child enrolls only when its delegation chain resolves
1096
+ // to a root recorded here. Idempotent; the root id is supplied by the host (the CP
1097
+ // learns it from the root-bind it just completed), so no chain is verified at this
1098
+ // step — the cryptographic check happens per-child in enroll_delegated_node.
1099
+ trn manage_root _:($root_cid -> root_cid: global_id)
1100
+ {
1101
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1102
+ managed_roots root_cid -> TRUE.
1103
+ return transaction::success [
1104
+ _return_data ($managed_root -> (_str root_cid)),
1105
+ _save_state NIL
1106
+ ].
1107
+ }
1108
+
1109
+ // CP SIDE, external inbound: a root relays one of its children's signed address
1110
+ // document so the CP can hold peer_ads[child] WITHOUT the child binding the CP
1111
+ // itself — the receiver half of "one root bind conveys the whole cluster". The
1112
+ // child never participates here; the root presents the child's public material
1113
+ // (AD + delegation cert + root profile) it already holds via the delegation chain.
1114
+ //
1115
+ // Authorization is TWO independent checks, all required (delegation material is
1116
+ // semi-public, so possession must not equal authorization):
1117
+ // (1) the channel-authenticated sender IS the root named in the delegation chain
1118
+ // (the root relays its OWN children — no third-party relay of a valid chain),
1119
+ // (2) verify_peer_delegation proves the child's container id AND its AD hash
1120
+ // chain to that root, root-signed.
1121
+ // There is deliberately NO managed_roots authorization gate: a bound host's children
1122
+ // are introduceable by default once it advertises core.connect; the operator clicking
1123
+ // Introduce is the consent. Authenticity is still fully enforced by (1) + (2), so a
1124
+ // node can only ever enroll children it legitimately delegated.
1125
+ // Plus the child AD's own self-signature is re-checked (proof-of-possession). Any
1126
+ // failure aborts; nothing is stored. Idempotent: a re-enroll just refreshes the AD.
1127
+ fn handle_enroll_delegated_node (args: any) -> transaction::results::type
1128
+ {
1129
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1130
+ encrypted_channel::check_encrypted_or_abort().
1131
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1132
+
1133
+ child_ad = (args $child_ad) safe address_document_types::t_address_document.
1134
+ child_cid = child_ad $identity $container_id.
1135
+ abort "Cannot enroll myself." when child_cid == _get_container_id().
1136
+
1137
+ // Proof-of-possession: re-authorize the child's own self-signed document before
1138
+ // storing it (child_cid is key-derived, so an existing contact's keyset can
1139
+ // never be silently overwritten with a different one).
1140
+ address_document::process_address_document child_ad TRUE.
1141
+
1142
+ cert = (_read_or_abort ((args $delegation_cert) safe bin)) safe a2a_protocol::delegation_cert_t.
1143
+ rp = (_read_or_abort ((args $root_profile) safe bin)) safe a2a_protocol::root_profile_t.
1144
+
1145
+ // (3) Verify the delegation chain: binds child_cid AND _value_id(child_ad) to a
1146
+ // root, root-signed (aborts on any mismatch). Returns the verified root linkage.
1147
+ child_root = a2a_protocol::verify_peer_delegation child_cid (_value_id child_ad) cert rp.
1148
+ enroll_root_cid = child_root $root_cid.
1149
+
1150
+ // (1) The relayer must BE that root — possession of a valid chain is not enough.
1151
+ abort "Only a node's own root may enroll it." when sender_id != enroll_root_cid.
1152
+ // (managed_roots authorization gate intentionally removed: a bound host's children
1153
+ // enroll by default; authenticity is enforced by (1) + verify_peer_delegation above.)
1154
+
1155
+ // Idempotent re-enrollment: refresh the stored AD/linkage, keep the contact.
1156
+ if (contacts child_cid) != NIL
1157
+ {
1158
+ peer_ads child_cid -> child_ad.
1159
+ contact_roots child_cid -> child_root.
1160
+ return transaction::success [
1161
+ _notify_agent ($event -> $reenrolled, $container_id -> child_cid, $root_cid -> enroll_root_cid),
1162
+ _save_state NIL
1163
+ ].
1164
+ }
1165
+
1166
+ // New cluster child: register under the verified role label (root_name/role_id
1167
+ // are advisory display strings; the AD self-signature is the only trusted id).
1168
+ contacts child_cid -> ($name -> (child_root $root_name) + "/" + (child_root $role_id), $container_id -> child_cid).
1169
+ peer_ads child_cid -> child_ad.
1170
+ contact_roots child_cid -> child_root.
1171
+
1172
+ return transaction::success [
1173
+ _notify_agent ($event -> $enrolled, $container_id -> child_cid, $root_cid -> enroll_root_cid),
1174
+ _save_state NIL
1175
+ ].
1176
+ }
1177
+
1178
+ trn enroll_delegated_node args: any
1179
+ {
1180
+ return handle_enroll_delegated_node args.
1181
+ }
1182
+
1183
+ // Host-fired (ROOT side, core 2.2): relay one of my children's signed AD +
1184
+ // delegation chain to my bound control plane — the SEND that drives the CP's
1185
+ // handle_enroll_delegated_node inbound above, so a single root bind enrolls the
1186
+ // whole cluster. The root presents PUBLIC material it already holds via the
1187
+ // delegation chain it signed; the child never participates. This carries NO new
1188
+ // trust: it is an authenticated relay over my existing CP channel, and the CP
1189
+ // independently re-verifies the chain, that I am the child's root, and that it
1190
+ // manages me. Root-only here too (a role's relay would fail the CP's sender==root
1191
+ // check anyway). Payload matches handle_enroll_delegated_node field-for-field:
1192
+ // $child_ad is the AD VALUE; the cert + root profile ride as blobs (the receiver
1193
+ // _read_or_abort's them). The CP derives the "root_name/role_id" display label from
1194
+ // the cert's role_id + the root profile's name — no name field is carried here.
1195
+ trn relay_enroll_delegated_node _:($proxy -> proxy_ref: str, $child_ad -> child_ad_blob: bin, $delegation_cert -> cert_blob: bin, $root_profile -> rp_blob: bin)
1196
+ {
1197
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1198
+ abort "Only a root identity can relay a cluster enrollment." when delegation_cert != NIL.
1199
+
1200
+ cp_cid = resolve_contact proxy_ref.
1201
+ child_ad = (_read_or_abort child_ad_blob) safe address_document_types::t_address_document.
1202
+ return encrypted_channel::execute_transaction cp_cid (fn (_) -> transaction::results::type {
1203
+ return transaction::success [
1204
+ encrypted_channel::send_encrypted_tx cp_cid (
1205
+ $name -> enroll_delegated_node_tx,
1206
+ $targ -> ($child_ad -> child_ad, $delegation_cert -> cert_blob, $root_profile -> rp_blob)
1207
+ ),
1208
+ _return_data ($enroll_relayed -> (_str cp_cid), $child -> (_str (child_ad $identity $container_id)))
1209
+ ].
1210
+ }).
1211
+ }
1212
+
1213
+ // ---- control-plane introduction: core.connect ----------------------------
1214
+ // The control plane, bound to BOTH parties, introduces two nodes that are not
1215
+ // yet in each other's contacts. The CP already holds each managed node's peer-
1216
+ // signed address document (captured in peer_ads when the node bound the CP), so
1217
+ // an introduction is simply: send each node the OTHER's signed AD. The receiving
1218
+ // node verifies the AD's own self-signature (proof-of-possession), checks the
1219
+ // relay came from its bound CP, checks its OWN manifest still advertises
1220
+ // core.connect, and registers the contact immediately. No SAS, no confirmation
1221
+ // step, no CP signature on the introduction — the bound-CP channel IS the
1222
+ // authorization, and the node-side capability gate is the authoritative "do I
1223
+ // accept introductions". The CP-side manifest pre-check (refuse to introduce a
1224
+ // node whose app does not support it) is the daemon's job: it pulls get_manifest
1225
+ // for each target before calling introduce.
1226
+
1227
+ // Pure helper: the two bare encrypted sends that make up one introduction — node
1228
+ // A receives B's address document (+ B's CP-supplied display name) and node B
1229
+ // receives A's. Bare send_encrypted_tx is sound here because both channels are
1230
+ // already established (each node bound the CP), so no execute_transaction
1231
+ // handshake is needed; the caller guards peer_ads presence before emitting.
1232
+ fn emit_pair (
1233
+ a_id: global_id, ad_a: address_document_types::t_address_document, name_a: str,
1234
+ b_id: global_id, ad_b: address_document_types::t_address_document, name_b: str
1235
+ ) -> transaction::action::type[]
1236
+ {
1237
+ return [
1238
+ encrypted_channel::send_encrypted_tx a_id (
1239
+ $name -> ingest_connect_descriptor_tx,
1240
+ $targ -> ($peer_ad -> ad_b, $peer_name -> name_b)
1241
+ ),
1242
+ encrypted_channel::send_encrypted_tx b_id (
1243
+ $name -> ingest_connect_descriptor_tx,
1244
+ $targ -> ($peer_ad -> ad_a, $peer_name -> name_a)
1245
+ )
1246
+ ].
1247
+ }
1248
+
1249
+ // The display name the CP advertises for a managed node when introducing it: the
1250
+ // CP's own contact label, falling back to the stringified container id. This is
1251
+ // unauthenticated by design (a receiver-chosen display string); the AD self-
1252
+ // signature is the only authenticated identity the receiver actually trusts.
1253
+ fn introduce_name (cid: global_id) -> str
1254
+ {
1255
+ if (contacts cid) != NIL { return (contacts cid)? $name. }
1256
+ return _str cid.
1257
+ }
1258
+
1259
+ // CP SIDE: introduce two managed nodes to each other (host-fired). Both must be
1260
+ // established contacts of the CP (peer_ads holds their signed ADs). The manifest
1261
+ // "supports introductions" pre-check is the daemon's job (it pulls get_manifest
1262
+ // for each before calling this); the node-side gate in ingest_connect_descriptor
1263
+ // is the authoritative enforcement. Emits both relays in one transaction.
1264
+ trn introduce _:($peer_a -> ref_a: str, $peer_b -> ref_b: str)
1265
+ {
1266
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1267
+
1268
+ a_id = resolve_contact ref_a.
1269
+ b_id = resolve_contact ref_b.
1270
+ abort "Cannot introduce a node to itself." when a_id == b_id.
1271
+
1272
+ ad_a = peer_ads a_id.
1273
+ abort "First node is not an established contact (no stored address document)." when ad_a == NIL.
1274
+ ad_b = peer_ads b_id.
1275
+ abort "Second node is not an established contact (no stored address document)." when ad_b == NIL.
1276
+
1277
+ actions is transaction::action::type[] = emit_pair a_id ad_a? (introduce_name a_id) b_id ad_b? (introduce_name b_id).
1278
+ actions (_count actions|) -> _return_data ($introduced -> ($peer_a -> (_str a_id), $peer_b -> (_str b_id))).
1279
+ return transaction::success actions.
1280
+ }
1281
+
1282
+ // CP SIDE: introduce one joiner to every member of a group (cluster-root fan-out,
1283
+ // e.g. a new subagent under a cluster root). For each member it emits the same
1284
+ // pair of relays as introduce(joiner, member). All targets must be established
1285
+ // contacts. O(members) bare sends in a single transaction.
1286
+ trn introduce_to_group _:($joiner -> joiner_ref: str, $members -> member_refs: str[])
1287
+ {
1288
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1289
+
1290
+ j_id = resolve_contact joiner_ref.
1291
+ ad_j = peer_ads j_id.
1292
+ abort "Joiner is not an established contact (no stored address document)." when ad_j == NIL.
1293
+ j_name = introduce_name j_id.
1294
+
1295
+ actions is transaction::action::type[] = [].
1296
+ introduced is str[] = [].
1297
+ sc member_refs -- ( -> mref)
1298
+ {
1299
+ m_id = resolve_contact mref.
1300
+ abort "Cannot introduce the joiner to itself." when m_id == j_id.
1301
+ ad_m = peer_ads m_id.
1302
+ abort "A group member is not an established contact (no stored address document)." when ad_m == NIL.
1303
+ sc emit_pair j_id ad_j? j_name m_id ad_m? (introduce_name m_id) -- ( -> act)
1304
+ {
1305
+ actions (_count actions|) -> act.
1306
+ }
1307
+ introduced (_count introduced|) -> (_str m_id).
1308
+ }
1309
+ actions (_count actions|) -> _return_data ($joiner -> (_str j_id), $introduced -> introduced).
1310
+ return transaction::success actions.
1311
+ }
1312
+
1313
+ // Ingest a peer's signed address document relayed by my control plane (core.connect).
1314
+ // Authorization model (radically simple): the relay must come from my bound CP
1315
+ // (require_bound_cp_or_abort) AND this node must itself advertise core.connect (the
1316
+ // node-side capability gate — the authoritative "I accept introductions"). The AD
1317
+ // carries its own self-signatures, re-checked by process_address_document (proof-of-
1318
+ // possession; aborts on a forged/inconsistent document). No SAS, no CP signature, no
1319
+ // confirmation step — the contact is established immediately. The CP-supplied
1320
+ // $peer_name is an unauthenticated display label.
1321
+ fn handle_ingest_connect_descriptor (args: any) -> transaction::results::type
1322
+ {
1323
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1324
+ encrypted_channel::check_encrypted_or_abort().
1325
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1326
+ // The relay must come from a CP authorized for me — EITHER one I bound directly
1327
+ // (legacy 6-digit ceremony) OR one my root designated and I inherited (core 2.1
1328
+ // cluster CP, verified locally against my pinned root_ad). Additive: the legacy
1329
+ // direct-bind path is unchanged.
1330
+ require_cluster_cp_or_abort sender_id.
1331
+ // Node-side capability gate (authoritative): refuse unless my OWN live manifest
1332
+ // advertises core.connect. Without this the manifest boolean would be a pure
1333
+ // CP-side courtesy rather than enforced.
1334
+ abort "This node does not support introductions (core.connect not in its manifest)." when a2a_capabilities::self_supports a2a_capabilities::cap_connect != TRUE.
1335
+
1336
+ peer_ad = (args $peer_ad) safe address_document_types::t_address_document.
1337
+ peer_cid = peer_ad $identity $container_id.
1338
+ abort "Cannot introduce me to myself." when peer_cid == _get_container_id().
1339
+
1340
+ // Proof-of-possession: re-authorize the peer's own self-signed document before
1341
+ // storing it (idempotent; peer_cid is key-derived, so an existing contact's keys
1342
+ // can never be silently overwritten with a different keyset).
1343
+ address_document::process_address_document peer_ad TRUE.
1344
+
1345
+ // Idempotent re-introduction: if peer_cid is already a contact, just refresh the
1346
+ // stored AD and keep the existing name — never clobber it or re-notify as new.
1347
+ if (contacts peer_cid) != NIL
1348
+ {
1349
+ peer_ads peer_cid -> peer_ad.
1350
+ return transaction::success [
1351
+ _notify_agent ($event -> $reintroduced, $container_id -> peer_cid, $by_cp -> sender_id),
1352
+ _save_state NIL
1353
+ ].
1354
+ }
1355
+
1356
+ // New contact: register under the CP-supplied display name (cid as last resort).
1357
+ peer_name is str = "".
1358
+ if (args $peer_name) != NIL { peer_name -> (args $peer_name) safe str. }
1359
+ contact_label is str = (peer_name == "" ?? (_str peer_cid) ; peer_name).
1360
+ contacts peer_cid -> ($name -> contact_label, $container_id -> peer_cid).
1361
+ peer_ads peer_cid -> peer_ad.
1362
+
1363
+ return transaction::success [
1364
+ _notify_agent ($event -> $introduced, $container_id -> peer_cid, $name -> contact_label, $by_cp -> sender_id),
1365
+ _save_state NIL
1366
+ ].
1367
+ }
1368
+
1369
+ trn ingest_connect_descriptor args: any
1370
+ {
1371
+ return handle_ingest_connect_descriptor args.
1372
+ }
1373
+
1374
+ // The shared-core version this packet was compiled with (see version.mm).
1375
+ trn readonly get_version _
1376
+ {
1377
+ return ($core -> version::get_core_version()).
1378
+ }
1379
+
1380
+ // ---- external (inbound) transactions ------------------------------------
1381
+ // Each inbound transaction's body is an exported handle_* fn so consumers'
1382
+ // ::actor:: compat shims (Option A) delegate to the exact same code path —
1383
+ // the stdlib trn-delegates-to-fn pattern (see address_document::handshake_init).
1384
+
1385
+ // Args are taken as `any` (not a destructured shape) so old clients — whose
1386
+ // accept_contact payload has no hierarchy fields — keep working unchanged.
1387
+ fn handle_accept_contact (args: any) -> transaction::results::type
1388
+ {
1389
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1390
+ encrypted_channel::check_encrypted_or_abort().
1391
+
1392
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1393
+ invite_id = (args $invite_id) safe global_id.
1394
+ joiner_ad = (args $joiner_ad) safe address_document_types::t_address_document.
1395
+
1396
+ // Only an invite I generated (and have not yet consumed) authorizes a
1397
+ // contact registration. Without this gate any invite blob would be a
1398
+ // multi-use bearer credential: anyone who ever saw one could register
1399
+ // themselves as my contact with a self-chosen name.
1400
+ // core 3.0: pending_invites is now a pending_invite_t record map; the
1401
+ // assigned name is its $assigned field. (This legacy accept path is removed
1402
+ // in M2 with the rest of the old redeem flow.)
1403
+ invite_rec = pending_invites invite_id.
1404
+ abort "Unknown or already-redeemed invite." when invite_rec == NIL.
1405
+ // D8: joiner_ad is attacker-supplied. Bind it to the channel-authenticated
1406
+ // sender and prove it is the joiner's OWN self-signed document before we
1407
+ // store it as the peer's identity. The cid gate stops a redeemer from
1408
+ // registering SOMEONE ELSE's address document under this contact, and
1409
+ // process_address_document re-authorizes the self-signatures (it aborts on
1410
+ // a forged/inconsistent document).
1411
+ abort "Address document does not belong to the sender." when (joiner_ad $identity $container_id) != sender_id.
1412
+ address_document::process_address_document joiner_ad TRUE.
1413
+ // An empty assigned name means the invite was generated without one:
1414
+ // the joiner's self-announced name wins (container id as a last resort
1415
+ // when the joiner never set a name either).
1416
+ contact_name is str = (invite_rec?) $assigned.
1417
+ if contact_name == ""
1418
+ {
1419
+ joiner_self = (args $joiner_name) safe str.
1420
+ contact_name -> (joiner_self == "" ?? (_str sender_id) ; joiner_self).
1421
+ }
1422
+
1423
+ // A delegated-role joiner carries its chain so I learn its root linkage
1424
+ // symmetrically; an invalid chain rejects the redemption outright.
1425
+ joiner_root is a2a_protocol::contact_root_t+ = NIL.
1426
+ if (args $joiner_cert) != NIL
1427
+ {
1428
+ cert = (_read_or_abort ((args $joiner_cert) safe bin)) safe a2a_protocol::delegation_cert_t.
1429
+ rp = (_read_or_abort ((args $joiner_root_profile) safe bin)) safe a2a_protocol::root_profile_t.
1430
+ joiner_root -> a2a_protocol::verify_peer_delegation sender_id (_value_id joiner_ad) cert rp.
1431
+ // §3c symmetric: pin the joiner's root binding if it carries one and
1432
+ // verifies against its root key list. Non-enforcing — a bad/absent
1433
+ // binding never rejects the redemption.
1434
+ if (args $joiner_cp_binding) != NIL
1435
+ {
1436
+ binding = (_read_or_abort ((args $joiner_cp_binding) safe bin)) safe a2a_protocol::root_cp_binding_t.
1437
+ if a2a_protocol::verify_root_cp_binding binding (rp $p $root_cid) (rp $p $keys) == TRUE
1438
+ {
1439
+ contact_cp_bindings (rp $p $root_cid) -> binding.
1440
+ }
1441
+ }
1442
+ }
1443
+
1444
+ contacts sender_id -> ($name -> contact_name, $container_id -> sender_id).
1445
+ // Remember the joiner's address document for upgrade-time re-registration.
1446
+ peer_ads sender_id -> joiner_ad.
1447
+ if joiner_root != NIL
1448
+ {
1449
+ contact_roots sender_id -> joiner_root?.
1450
+ }
1451
+ delete pending_invites invite_id.
1452
+
1453
+ return transaction::success [
1454
+ _notify_agent ($event -> $contact_accepted, $name -> contact_name, $container_id -> sender_id),
1455
+ _save_state NIL
1456
+ ].
1457
+ }
1458
+
1459
+ trn accept_contact args: any
1460
+ {
1461
+ return handle_accept_contact args.
1462
+ }
1463
+
1464
+ // core 3.0 LEG 2 (inviter): a responder redeemed my slim invite. The body is a
1465
+ // BARE inbound carrying a box, so this is the ONE inbound that intentionally
1466
+ // SKIPS check_encrypted_or_abort — confidentiality/integrity come from the box,
1467
+ // authenticity from the cid-bind + PoP below. INV-5: NO contact/peer_ads/
1468
+ // contact_roots write happens before ALL gates pass (lookup -> decrypt ->
1469
+ // cid-bind -> PoP -> chain). Single-use: the first valid leg-2 consumes BOTH
1470
+ // pending_invites AND pending_invite_keys; a failed gate consumes nothing.
1471
+ fn handle_submit_invite_response (args: any) -> transaction::results::type
1472
+ {
1473
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1474
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1475
+ invite_id = (args $invite_id) safe global_id.
1476
+
1477
+ // --- gates (no state mutation until all pass) ---
1478
+ // single-use lookup: the invite must be one I minted and not yet redeemed.
1479
+ rec = pending_invites invite_id.
1480
+ abort "Unknown or already-redeemed invite." when rec == NIL.
1481
+ eph_priv = pending_invite_keys invite_id.
1482
+ abort "Invite ephemeral key missing (already consumed or not persisted)." when eph_priv == NIL.
1483
+
1484
+ epk_r = (args $epk) safe publickey_encrypt.
1485
+ ct = (args $data) safe crypto_message.
1486
+ // box-open: aborts on tamper / wrong key BEFORE anything is consumed.
1487
+ payload = _read_or_abort (_crypto_decrypt_message eph_priv? epk_r ct).
1488
+
1489
+ // D8 cid-bind + PoP self-sig, then the optional delegation chain — an
1490
+ // invalid chain or forged/inconsistent AD aborts before any write.
1491
+ vb = verify_identity_bundle payload sender_id.
1492
+
1493
+ // --- all gates passed: register + single-use consume (INV-5) ---
1494
+ contact_name is str = (rec?) $assigned.
1495
+ if contact_name == "" { contact_name -> (_str sender_id). }
1496
+ contacts sender_id -> ($name -> contact_name, $container_id -> sender_id).
1497
+ peer_ads sender_id -> (vb $ad).
1498
+ if (vb $root) != NIL { contact_roots sender_id -> (vb $root)?. }
1499
+ if (vb $pin_binding) != NIL { contact_cp_bindings ((vb $pin_binding_root)?) -> (vb $pin_binding)?. }
1500
+ delete pending_invites invite_id.
1501
+ delete pending_invite_keys invite_id.
1502
+
1503
+ // reply leg 3 as a BARE BOXED send (NOT encrypted_channel): the responder
1504
+ // has NOT registered me yet, so it could not resolve my source key to open a
1505
+ // send_encrypted_tx (the M0 spike's "Unknown source key" on the receiver is
1506
+ // exactly this — see the leg-3 correction). Instead I box my identity bundle
1507
+ // to the responder's EPHEMERAL pubkey (epk_r, carried in leg 1) with a fresh
1508
+ // inviter ephemeral; the responder opens it with the ephemeral private key it
1509
+ // kept. encrypted_channel resumes for all post-contact traffic, both sides
1510
+ // being registered after leg 3.
1511
+ b = my_identity_bundle_fields NIL.
1512
+ kpi = _crypto_construct_encryption_keypair (rec? $scheme).
1513
+ leg3_payload = _write (
1514
+ $ad -> (b $ad),
1515
+ $cert -> (b $cert),
1516
+ $root_profile -> (b $root_profile),
1517
+ $cp_binding -> (b $cp_binding),
1518
+ $invite_id -> invite_id
1519
+ ).
1520
+ leg3_data = _crypto_encrypt_message (kpi $secret_key) epk_r leg3_payload.
1521
+ return transaction::success [
1522
+ transaction::action::send sender_id (
1523
+ $name -> complete_invite_tx,
1524
+ $targ -> (
1525
+ $invite_id -> invite_id,
1526
+ $epk -> (kpi $public_key),
1527
+ $v -> (rec? $scheme),
1528
+ $data -> leg3_data
1529
+ )
1530
+ ),
1531
+ _notify_agent ($event -> $contact_accepted, $name -> contact_name, $container_id -> sender_id),
1532
+ _save_state NIL
1533
+ ].
1534
+ }
1535
+
1536
+ // core 3.0 LEG 3 (responder): the inviter completed the exchange. It is a BARE
1537
+ // BOXED send (NOT encrypted_channel — see the leg-2 reply), so it intentionally
1538
+ // SKIPS check_encrypted_or_abort; the box (to my kept ephemeral key) is the
1539
+ // confidentiality/integrity, and authenticity comes from the inviter-cid pin +
1540
+ // cid-bind + PoP. Gate discipline (INV-5): pend lookup -> inviter-cid pin ->
1541
+ // decrypt -> cid-bind -> PoP -> chain, all before the contact is registered.
1542
+ // Clears BOTH responder stores (pending_redemptions + pending_redemption_keys).
1543
+ fn handle_complete_invite (args: any) -> transaction::results::type
1544
+ {
1545
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1546
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1547
+ invite_id = (args $invite_id) safe global_id.
1548
+
1549
+ // --- gates (no state mutation until all pass) ---
1550
+ pend = pending_redemptions invite_id.
1551
+ abort "Unsolicited completion." when pend == NIL.
1552
+ abort "Completion from unexpected inviter." when sender_id != (pend?) $inviter_cid.
1553
+ eph_priv_r = pending_redemption_keys invite_id.
1554
+ abort "Redemption ephemeral key missing (already completed or not persisted)." when eph_priv_r == NIL.
1555
+
1556
+ epk_i = (args $epk) safe publickey_encrypt.
1557
+ ct = (args $data) safe crypto_message.
1558
+ // box-open with the kept responder ephemeral private key (aborts on tamper).
1559
+ payload = _read_or_abort (_crypto_decrypt_message eph_priv_r? epk_i ct).
1560
+
1561
+ // D8 cid-bind + PoP self-sig, then the optional delegation chain — an
1562
+ // invalid chain or forged/inconsistent AD aborts before any write.
1563
+ vb = verify_identity_bundle payload sender_id.
1564
+
1565
+ // --- all gates passed: register + clear the pending redemption ---
1566
+ // name: my chosen custom name, else the inviter's invite name, else its cid.
1567
+ contact_name is str = (pend?) $custom_name.
1568
+ if contact_name == "" { contact_name -> (pend?) $inviter_name. }
1569
+ if contact_name == "" { contact_name -> (_str sender_id). }
1570
+ contacts sender_id -> ($name -> contact_name, $container_id -> sender_id).
1571
+ peer_ads sender_id -> (vb $ad).
1572
+ if (vb $root) != NIL { contact_roots sender_id -> (vb $root)?. }
1573
+ if (vb $pin_binding) != NIL { contact_cp_bindings ((vb $pin_binding_root)?) -> (vb $pin_binding)?. }
1574
+ delete pending_redemptions invite_id.
1575
+ delete pending_redemption_keys invite_id.
1576
+
1577
+ return transaction::success [
1578
+ _notify_agent ($event -> $contact_added, $name -> contact_name, $container_id -> sender_id),
1579
+ _save_state NIL
1580
+ ].
1581
+ }
1582
+
1583
+ // Inbound trn stubs (declared AFTER their handlers — mufl requires
1584
+ // define-before-use, as with accept_contact/handle_accept_contact above).
1585
+ trn submit_invite_response args: any
1586
+ {
1587
+ return handle_submit_invite_response args.
1588
+ }
1589
+
1590
+ trn complete_invite args: any
1591
+ {
1592
+ return handle_complete_invite args.
1593
+ }
1594
+
1595
+ // ==== contact restore (spec 2026-07-01): re-run the key exchange between
1596
+ // MUTUALLY KNOWN addresses after a breaking change dropped peer_ads. Same
1597
+ // machinery as the eph-invite legs (bundle, box-to-eph-key, INV-5 gate
1598
+ // ordering); the trust gate is "#77-origin-verified signed request from an
1599
+ // address already in my contacts" instead of an OOB invite token.
1600
+
1601
+ // LEG 0 (responder): a contact lost my address document and asks me to
1602
+ // re-exchange keys. BARE inbound — #77 signs every envelope and rejects
1603
+ // unsigned/forged origin, so the envelope $from IS the authenticated
1604
+ // requester. Gate: requester ∈ contacts, else a SILENT no-op (success with
1605
+ // no actions — no error reply, so whether an address is known never leaks).
1606
+ // NON-DESTRUCTIVE: nothing is installed or replaced here; my stored peer_ad
1607
+ // for the requester (possibly stale, possibly absent) is only replaced at
1608
+ // leg 2 after its bundle verifies. At most ONE outstanding reply record per
1609
+ // requester — a newer request replaces it (bounded by the contacts set).
1610
+ // Accepted trade-off: a replayed/duplicate leg 0 supersedes the previous
1611
+ // reply record, so an in-flight leg 2 for the older rid then fails its gate
1612
+ // — transient, self-heals on the next sweep; nothing is installable by the
1613
+ // replayer.
1614
+ fn handle_request_contact_restore (args: any) -> transaction::results::type
1615
+ {
1616
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1617
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1618
+ if (contacts sender_id) == NIL { return transaction::success []. }
1619
+
1620
+ rid = (args $rid) safe global_id.
1621
+ epk_requester = (args $epk) safe publickey_encrypt.
1622
+ scheme = (args $v) safe int.
1623
+ now = (current_transaction_info::get_transaction_time())?.
1624
+
1625
+ kpr = _crypto_construct_encryption_keypair scheme.
1626
+ pending_restore_replies sender_id -> ($rid -> rid, $scheme -> scheme, $created -> now).
1627
+ pending_restore_reply_keys sender_id -> (kpr $secret_key).
1628
+
1629
+ b = my_identity_bundle_fields NIL.
1630
+ payload = _write (
1631
+ $ad -> (b $ad), $cert -> (b $cert), $root_profile -> (b $root_profile),
1632
+ $cp_binding -> (b $cp_binding), $rid -> rid
1633
+ ).
1634
+ data = _crypto_encrypt_message (kpr $secret_key) epk_requester payload.
1635
+ return transaction::success [
1636
+ transaction::action::send sender_id (
1637
+ $name -> submit_restore_response_tx,
1638
+ $targ -> ($rid -> rid, $epk -> (kpr $public_key), $v -> scheme, $data -> data)
1639
+ ),
1640
+ _save_state NIL
1641
+ ].
1642
+ }
1643
+
1644
+ trn request_contact_restore args: any
1645
+ {
1646
+ return handle_request_contact_restore args.
1647
+ }
1648
+
1649
+ // LEG 1 (requester): the contact answered with its identity bundle boxed to
1650
+ // my leg-0 ephemeral pubkey. Gate discipline (INV-5): pend lookup -> rid pin
1651
+ // -> decrypt -> cid-bind -> PoP -> chain, all before any write. Single-use:
1652
+ // the first valid leg 1 consumes BOTH pending_restores and the hidden eph
1653
+ // key; a failed gate consumes nothing. Replies leg 2 as a BARE BOXED send —
1654
+ // the responder may not hold MY current AD until that bundle arrives, so the
1655
+ // encrypted channel cannot carry it (same reasoning as the invite leg 3).
1656
+ fn handle_submit_restore_response (args: any) -> transaction::results::type
1657
+ {
1658
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1659
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1660
+ rid = (args $rid) safe global_id.
1661
+
1662
+ // --- gates (no state mutation until all pass) ---
1663
+ pend = pending_restores sender_id.
1664
+ abort "Unsolicited restore response." when pend == NIL.
1665
+ abort "Restore response does not match the outstanding request." when rid != ((pend?) $rid).
1666
+ eph_priv = pending_restore_keys sender_id.
1667
+ abort "Restore ephemeral key missing (superseded or already completed)." when eph_priv == NIL.
1668
+ abort "Restore response from a removed contact." when (contacts sender_id) == NIL.
1669
+
1670
+ epk_r = (args $epk) safe publickey_encrypt.
1671
+ scheme = (args $v) safe int.
1672
+ ct = (args $data) safe crypto_message.
1673
+ payload = _read_or_abort (_crypto_decrypt_message eph_priv? epk_r ct).
1674
+ abort "Restore payload correlation mismatch." when ((payload $rid) safe global_id) != rid.
1675
+ vb = verify_identity_bundle payload sender_id.
1676
+
1677
+ // --- all gates passed: (re)install the peer's keys + single-use consume ---
1678
+ peer_ads sender_id -> (vb $ad).
1679
+ if (vb $root) != NIL { contact_roots sender_id -> (vb $root)?. }
1680
+ if (vb $pin_binding) != NIL { contact_cp_bindings ((vb $pin_binding_root)?) -> (vb $pin_binding)?. }
1681
+ delete pending_restores sender_id.
1682
+ delete pending_restore_keys sender_id.
1683
+
1684
+ b = my_identity_bundle_fields NIL.
1685
+ kp2 = _crypto_construct_encryption_keypair scheme.
1686
+ leg2_payload = _write (
1687
+ $ad -> (b $ad), $cert -> (b $cert), $root_profile -> (b $root_profile),
1688
+ $cp_binding -> (b $cp_binding), $rid -> rid
1689
+ ).
1690
+ leg2_data = _crypto_encrypt_message (kp2 $secret_key) epk_r leg2_payload.
1691
+ contact_name = ((contacts sender_id)?) $name.
1692
+ return transaction::success [
1693
+ transaction::action::send sender_id (
1694
+ $name -> complete_restore_tx,
1695
+ $targ -> ($rid -> rid, $epk -> (kp2 $public_key), $v -> scheme, $data -> leg2_data)
1696
+ ),
1697
+ _notify_agent ($event -> $contact_restored, $name -> contact_name, $container_id -> sender_id),
1698
+ _save_state NIL
1699
+ ].
1700
+ }
1701
+
1702
+ trn submit_restore_response args: any
1703
+ {
1704
+ return handle_submit_restore_response args.
1705
+ }
1706
+
1707
+ // LEG 2 (responder): the requester completed with ITS bundle boxed to my
1708
+ // leg-1 ephemeral pubkey. Same gate discipline; only HERE do I REPLACE my
1709
+ // stored peer_ad for the requester — required even when one is present: a
1710
+ // #77 reseed rolls the peer a fresh ENCRYPT key, so a surviving stale AD
1711
+ // would break my sends toward it. Single-use consume of the reply stores.
1712
+ fn handle_complete_restore (args: any) -> transaction::results::type
1713
+ {
1714
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1715
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1716
+ rid = (args $rid) safe global_id.
1717
+
1718
+ // --- gates (no state mutation until all pass) ---
1719
+ pend = pending_restore_replies sender_id.
1720
+ abort "Unsolicited restore completion." when pend == NIL.
1721
+ abort "Restore completion does not match the outstanding reply." when rid != ((pend?) $rid).
1722
+ eph_priv = pending_restore_reply_keys sender_id.
1723
+ abort "Restore reply key missing (superseded or already completed)." when eph_priv == NIL.
1724
+ abort "Restore completion from a removed contact." when (contacts sender_id) == NIL.
1725
+
1726
+ epk_i = (args $epk) safe publickey_encrypt.
1727
+ ct = (args $data) safe crypto_message.
1728
+ payload = _read_or_abort (_crypto_decrypt_message eph_priv? epk_i ct).
1729
+ abort "Restore payload correlation mismatch." when ((payload $rid) safe global_id) != rid.
1730
+ vb = verify_identity_bundle payload sender_id.
1731
+
1732
+ // --- all gates passed: replace + single-use consume ---
1733
+ peer_ads sender_id -> (vb $ad).
1734
+ if (vb $root) != NIL { contact_roots sender_id -> (vb $root)?. }
1735
+ if (vb $pin_binding) != NIL { contact_cp_bindings ((vb $pin_binding_root)?) -> (vb $pin_binding)?. }
1736
+ delete pending_restore_replies sender_id.
1737
+ delete pending_restore_reply_keys sender_id.
1738
+
1739
+ contact_name = ((contacts sender_id)?) $name.
1740
+ return transaction::success [
1741
+ _notify_agent ($event -> $contact_restored, $name -> contact_name, $container_id -> sender_id),
1742
+ _save_state NIL
1743
+ ].
1744
+ }
1745
+
1746
+ trn complete_restore args: any
1747
+ {
1748
+ return handle_complete_restore args.
1749
+ }
1750
+
1751
+ metadef degraded_contact_t: ($container_id -> global_id, $name -> str, $attempts -> int, $queued -> int).
1752
+ metadef deferred_queue_info_t: ($container_id -> global_id, $name -> str, $queued -> int, $degraded -> bool).
1753
+
1754
+ // Degraded contacts (known cid, no AD) with their restore-attempt counts and
1755
+ // queued-message counts — the host's boot/GC sweep + list_contacts marker.
1756
+ trn readonly list_degraded_contacts _
1757
+ {
1758
+ out is degraded_contact_t[] = [].
1759
+ sc contacts -- (cid -> c) ?? (peer_ads cid) == NIL
1760
+ {
1761
+ att is int = 0.
1762
+ pr = pending_restores cid.
1763
+ if pr != NIL { att -> ((pr?) $attempts). }
1764
+ nq is int = 0.
1765
+ dq = deferred_msgs cid.
1766
+ if dq != NIL { nq -> (_count dq?|). }
1767
+ out (_count out|) -> ($container_id -> cid, $name -> (c $name), $attempts -> att, $queued -> nq).
1768
+ }
1769
+ return ($degraded -> out).
1770
+ }
1771
+
1772
+ // Every non-empty deferred queue + whether its contact is still degraded —
1773
+ // lets the host flush queues whose contact healed without a notify (e.g. a
1774
+ // daemon restart between restore and flush).
1775
+ trn readonly list_deferred_queues _
1776
+ {
1777
+ out is deferred_queue_info_t[] = [].
1778
+ sc deferred_msgs -- (cid -> q) ?? (_count q|) > 0
1779
+ {
1780
+ nm is str = "".
1781
+ c = contacts cid.
1782
+ if c != NIL { nm -> ((c?) $name). }
1783
+ out (_count out|) -> ($container_id -> cid, $name -> nm, $queued -> (_count q|), $degraded -> ((peer_ads cid) == NIL)).
1784
+ }
1785
+ return ($queues -> out).
1786
+ }
1787
+
1788
+ // Host-fired sweep (boot + GC cadence): (re)issue a restore request for every
1789
+ // degraded contact, up to restore_max_attempts each. A peer that is offline
1790
+ // or not yet running a restore-capable version simply never answers — the
1791
+ // sweep retries on the host's cadence; no reply is a normal condition.
1792
+ trn restore_degraded_contacts _
1793
+ {
1794
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1795
+ actions is transaction::action::type[] = [].
1796
+ requested is int = 0.
1797
+ exhausted is int = 0.
1798
+ sc contacts -- (cid -> c) ?? (peer_ads cid) == NIL
1799
+ {
1800
+ prev = pending_restores cid.
1801
+ if prev != NIL && ((prev?) $attempts) >= restore_max_attempts
1802
+ {
1803
+ exhausted -> exhausted + 1.
1804
+ }
1805
+ else
1806
+ {
1807
+ sc begin_contact_restore cid -- ( -> a) { actions (_count actions|) -> a. }
1808
+ requested -> requested + 1.
1809
+ }
1810
+ }
1811
+ actions (_count actions|) -> _return_data ($requested -> requested, $exhausted -> exhausted).
1812
+ if requested > 0 { actions (_count actions|) -> _save_state NIL. }
1813
+ return transaction::success actions.
1814
+ }
1815
+
1816
+ // Drain the deferred queue toward a contact whose AD is re-established.
1817
+ // HOST-DRIVEN (fired on the $contact_restored notify + the boot/GC sweep) so
1818
+ // the encrypted sends never race the restore legs' bare sends on the wire —
1819
+ // the host round-trip guarantees leg 2 delivery precedes the flush.
1820
+ // Idempotent: an empty or still-degraded queue is a no-op result, not an error.
1821
+ trn flush_deferred _:($contact -> contact_ref: str)
1822
+ {
1823
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1824
+ target_id = resolve_contact contact_ref.
1825
+ q = deferred_msgs target_id.
1826
+ if q == NIL || (_count q?|) == 0 { return transaction::success [ _return_data ($flushed -> 0) ]. }
1827
+ if (peer_ads target_id) == NIL { return transaction::success [ _return_data ($flushed -> 0, $degraded -> TRUE) ]. }
1828
+
1829
+ return encrypted_channel::execute_transaction target_id (fn (_) -> transaction::results::type {
1830
+ actions is transaction::action::type[] = [].
1831
+ sc q? -- ( -> m)
1832
+ {
1833
+ actions (_count actions|) -> encrypted_channel::send_encrypted_tx target_id (
1834
+ $name -> receive_message_tx,
1835
+ $targ -> ($text -> (m $text), $wire_id -> (m $wire_id), $reply_to -> (m $reply_to))
1836
+ ).
1837
+ sc on_message_sent ($target_id -> target_id, $text -> (m $text), $date -> (m $date), $wire_id -> (m $wire_id), $reply_to -> (m $reply_to)) -- ( -> a)
1838
+ {
1839
+ actions (_count actions|) -> a.
1840
+ }
1841
+ sc monitor_copy_actions "out" target_id (m $date) (m $text) -- ( -> a)
1842
+ {
1843
+ actions (_count actions|) -> a.
1844
+ }
1845
+ }
1846
+ n = _count q?|.
1847
+ delete deferred_msgs target_id.
1848
+ actions (_count actions|) -> _return_data ($flushed -> n).
1849
+ actions (_count actions|) -> _save_state NIL.
1850
+ return transaction::success actions.
1851
+ }).
1852
+ }
1853
+
1854
+ // Validation + contact resolution only; STORAGE is the app's, through the
1855
+ // on_message_received hook. $sender_name is NIL for an unknown sender —
1856
+ // the hook decides whether that is queueable (agent: pending-introduction
1857
+ // queue) or a rejection. Args are taken as `any` (not a destructured shape)
1858
+ // so a pre-wire_id sender — whose payload carries only $text — keeps working
1859
+ // unchanged, and so new optional fields ($wire_id, $reply_to) are tolerated.
1860
+ fn handle_receive_message (args: any) -> transaction::results::type
1861
+ {
1862
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1863
+ encrypted_channel::check_encrypted_or_abort().
1864
+
1865
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1866
+ msg_date = (current_transaction_info::get_transaction_time())?.
1867
+ text = (args $text) safe str.
1868
+
1869
+ // Optional, absent from pre-1.4 senders: the message's stable wire id
1870
+ // and an optional reply pointer. Default to "" / NIL so old payloads and
1871
+ // the agent storage hook behave exactly as before.
1872
+ wire_id is str = "".
1873
+ if (args $wire_id) != NIL { wire_id -> (args $wire_id) safe str. }
1874
+ reply_to is a2a_protocol::reply_ref_t+ = NIL.
1875
+ if (args $reply_to) != NIL { reply_to -> (args $reply_to) safe a2a_protocol::reply_ref_t. }
1876
+
1877
+ sender = contacts sender_id.
1878
+ sender_name is str+ = NIL.
1879
+ if sender != NIL
1880
+ {
1881
+ sender_name -> sender? $name.
1882
+ }
1883
+
1884
+ // The app hook owns storage; it may abort (unknown sender rejected) — in
1885
+ // which case nothing is delivered and no copy is emitted. When it accepts,
1886
+ // we append the FORCED inbound monitoring copy as core code (after the hook,
1887
+ // self-gating on monitoring_proxy) so the app cannot suppress it.
1888
+ actions is transaction::action::type[] = [].
1889
+ sc on_message_received (
1890
+ $sender_id -> sender_id,
1891
+ $sender_name -> sender_name,
1892
+ $text -> text,
1893
+ $date -> msg_date,
1894
+ $wire_id -> wire_id,
1895
+ $reply_to -> reply_to
1896
+ ) -- ( -> a)
1897
+ {
1898
+ actions (_count actions|) -> a.
1899
+ }
1900
+ sc monitor_copy_actions "in" sender_id msg_date text -- ( -> a)
1901
+ {
1902
+ actions (_count actions|) -> a.
1903
+ }
1904
+ return transaction::success actions.
1905
+ }
1906
+
1907
+ trn receive_message args: any
1908
+ {
1909
+ return handle_receive_message args.
1910
+ }
1911
+
1912
+ // File analogue of handle_receive_message: validate + resolve sender, then hand
1913
+ // the file to the app's on_file_received storage hook (the app owns storage; it
1914
+ // may abort an unknown sender). $mime/$wire_id/$reply_to are optional and default
1915
+ // to ""/""/NIL so a looser sender is tolerated. Forced metadata-only monitoring copy is appended after the hook.
1916
+ fn handle_receive_file (args: any) -> transaction::results::type
1917
+ {
1918
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1919
+ encrypted_channel::check_encrypted_or_abort().
1920
+
1921
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1922
+ file_date = (current_transaction_info::get_transaction_time())?.
1923
+ filename = (args $filename) safe str.
1924
+ data = (args $data) safe bin.
1925
+ mime is str = "".
1926
+ if (args $mime) != NIL { mime -> (args $mime) safe str. }
1927
+ wire_id is str = "".
1928
+ if (args $wire_id) != NIL { wire_id -> (args $wire_id) safe str. }
1929
+ reply_to is a2a_protocol::reply_ref_t+ = NIL.
1930
+ if (args $reply_to) != NIL { reply_to -> (args $reply_to) safe a2a_protocol::reply_ref_t. }
1931
+
1932
+ sender = contacts sender_id.
1933
+ sender_name is str+ = NIL.
1934
+ if sender != NIL
1935
+ {
1936
+ sender_name -> sender? $name.
1937
+ }
1938
+
1939
+ actions is transaction::action::type[] = [].
1940
+ sc on_file_received (
1941
+ $sender_id -> sender_id,
1942
+ $sender_name -> sender_name,
1943
+ $filename -> filename,
1944
+ $mime -> mime,
1945
+ $data -> data,
1946
+ $date -> file_date,
1947
+ $wire_id -> wire_id,
1948
+ $reply_to -> reply_to
1949
+ ) -- ( -> a)
1950
+ {
1951
+ actions (_count actions|) -> a.
1952
+ }
1953
+ sc monitor_copy_actions "in" sender_id file_date (file_monitor_summary filename mime data) -- ( -> a)
1954
+ {
1955
+ actions (_count actions|) -> a.
1956
+ }
1957
+ return transaction::success actions.
1958
+ }
1959
+
1960
+ trn receive_file args: any
1961
+ {
1962
+ return handle_receive_file args.
1963
+ }
1964
+
1965
+ // ---- upgrade: state export / import helpers ------------------------------
1966
+ // NOT transactions: each app's export_state/import_state trn composes these
1967
+ // with its own app-side fields (inbox / chat history / local book). Field
1968
+ // names match the historical app-level blobs exactly, so a PRE-migration
1969
+ // export imports through here unchanged.
1970
+
1971
+ fn export_core_state (_) -> any
1972
+ {
1973
+ return (
1974
+ $my_name -> my_name,
1975
+ $contacts -> contacts,
1976
+ $pending_invites -> pending_invites,
1977
+ $peer_ads -> peer_ads,
1978
+ $my_bio -> my_bio,
1979
+ $my_persona -> my_persona,
1980
+ $delegation_cert -> delegation_cert,
1981
+ $root_ad -> root_ad,
1982
+ $root_profile -> root_profile,
1983
+ $root_cp_binding -> root_cp_binding,
1984
+ $contact_roots -> contact_roots,
1985
+ $contact_cp_bindings -> contact_cp_bindings,
1986
+ $managed_roots -> managed_roots,
1987
+ $proxy_pending -> proxy_pending,
1988
+ $monitoring_proxy -> monitoring_proxy,
1989
+ $app_config -> app_config,
1990
+ $format_version -> core_format_version,
1991
+ $deferred_msgs -> deferred_msgs
1992
+ ).
1993
+ }
1994
+
1995
+ fn import_core_state (data: any) -> nil
1996
+ {
1997
+ // ---- format stamp + THE MIGRATION CONTRACT -------------------------------
1998
+ // Absent stamp == version 0 (every pre-stamp blob); all shipped migrations so
1999
+ // far are additive/field-optional, so 0 imports through the optional reads
2000
+ // below. The stamp exists so a future BREAKING blob change dispatches on an
2001
+ // explicit key instead of shape-sniffing. CONTRACT (binding on every future
2002
+ // format bump): a migration from version N MUST carry forward `contacts`,
2003
+ // `my_name`, `my_bio`, `my_persona` (and SHOULD carry contact_roots and the
2004
+ // consumer app's inbox/files); `peer_ads` is BEST-EFFORT — when a crypto/AD
2005
+ // change makes old documents unusable, DROP them: each dropped peer becomes a
2006
+ // degraded contact (contacts entry, no peer_ads entry) and self-heals through
2007
+ // request_contact_restore. NEVER let an incompatible optional field abort the
2008
+ // whole import — degrade, don't reset.
2009
+ fmt is int = 0.
2010
+ if (data $format_version) != NIL { fmt -> (data $format_version) safe int. }
2011
+ abort "State blob format_version " + (_str fmt) + " is newer than this code (supports up to " + (_str core_format_version) + ") — upgrade the software before importing." when fmt > core_format_version.
2012
+
2013
+ // The original schema's fields are required; everything that arrived
2014
+ // with a later schema is optional and defaults stay in place when
2015
+ // absent (the whole point of code-independent state is that an old
2016
+ // export upgrades, never resets).
2017
+ my_name -> (data $my_name) safe str.
2018
+ contacts -> (data $contacts) safe (global_id ->> a2a_protocol::contact_t).
2019
+ // core 3.0 migration: pending_invites changed shape (pre-3.0 (global_id ->>
2020
+ // str) → (global_id ->> pending_invite_t)). It is reset to EMPTY on import,
2021
+ // unconditionally and for BOTH shapes: a pre-3.0 str-map is incompatible (so
2022
+ // it is dropped rather than safe-cast, which would abort), and even a 3.0
2023
+ // record-map entry is unredeemable after import because its matching
2024
+ // ephemeral private key (pending_invite_keys) is hidden + NEVER exported
2025
+ // (INV-4). The responder-side stores (pending_redemptions /
2026
+ // pending_redemption_keys) are likewise not exported and default to empty
2027
+ // here. Net: outstanding invites/redemptions are transient — they do not
2028
+ // survive export/import or a daemon restart, fail-closed (plan §4.4).
2029
+ pending_invites -> (,).
2030
+ // Restore handshake state is transient exactly like pending_invites: the eph
2031
+ // PRIVATE halves are hidden + never exported, so imported records would be
2032
+ // unanswerable. The boot sweep (restore_degraded_contacts) re-mints them.
2033
+ pending_restores -> (,).
2034
+ pending_restore_replies -> (,).
2035
+ peer_ads -> (data $peer_ads) safe (global_id ->> address_document_types::t_address_document).
2036
+
2037
+ if (data $my_bio) != NIL
2038
+ {
2039
+ my_bio -> (data $my_bio) safe str.
2040
+ }
2041
+ if (data $my_persona) != NIL
2042
+ {
2043
+ my_persona -> (data $my_persona) safe str.
2044
+ }
2045
+ if (data $delegation_cert) != NIL
2046
+ {
2047
+ delegation_cert -> (data $delegation_cert) safe a2a_protocol::delegation_cert_t.
2048
+ }
2049
+ if (data $root_ad) != NIL
2050
+ {
2051
+ root_ad -> (data $root_ad) safe address_document_types::t_address_document.
2052
+ }
2053
+ if (data $root_profile) != NIL
2054
+ {
2055
+ root_profile -> (data $root_profile) safe a2a_protocol::root_profile_t.
2056
+ }
2057
+ if (data $root_cp_binding) != NIL
2058
+ {
2059
+ root_cp_binding -> (data $root_cp_binding) safe a2a_protocol::root_cp_binding_t.
2060
+ }
2061
+ if (data $contact_roots) != NIL
2062
+ {
2063
+ contact_roots -> (data $contact_roots) safe (global_id ->> a2a_protocol::contact_root_t).
2064
+ }
2065
+ if (data $contact_cp_bindings) != NIL
2066
+ {
2067
+ contact_cp_bindings -> (data $contact_cp_bindings) safe (global_id ->> a2a_protocol::root_cp_binding_t).
2068
+ }
2069
+ // CP-side managed roots (absent from pre-2.1 exports → stays empty, i.e. this
2070
+ // node enrolls no cluster children until a root is registered via manage_root).
2071
+ if (data $managed_roots) != NIL
2072
+ {
2073
+ managed_roots -> (data $managed_roots) safe (global_id ->> bool).
2074
+ }
2075
+ // Forced-monitoring state (absent from pre-monitoring exports → defaults
2076
+ // stay NIL, i.e. unmonitored, until a control plane binds).
2077
+ if (data $proxy_pending) != NIL
2078
+ {
2079
+ proxy_pending -> (data $proxy_pending) safe proxy_pending_t.
2080
+ }
2081
+ if (data $monitoring_proxy) != NIL
2082
+ {
2083
+ monitoring_proxy -> (data $monitoring_proxy) safe proxy_binding_t.
2084
+ }
2085
+ // Control-plane config state (absent from pre-config exports → defaults).
2086
+ if (data $app_config) != NIL
2087
+ {
2088
+ app_config -> (data $app_config) safe str.
2089
+ }
2090
+ if (data $deferred_msgs) != NIL
2091
+ {
2092
+ deferred_msgs -> (data $deferred_msgs) safe (global_id ->> deferred_msg_t[]).
2093
+ }
2094
+
2095
+ // Re-register every peer's keys so encrypted channels keep working after
2096
+ // the upgrade — no handshake needed (my own keys are unchanged, and the
2097
+ // peers' self-signed address documents re-authorize on this fresh packet).
2098
+ sc peer_ads -- ( -> ad)
2099
+ {
2100
+ address_document::process_address_document ad TRUE.
2101
+ }
2102
+ }
2103
+ }