@ours.network/tg-connector 0.1.7 → 0.1.8-nightly.2

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 (99) hide show
  1. package/dist/connector.js +74 -0
  2. package/dist/mufl_code/D812C6070397B0EB11D66D6D33D931C35E9442ACC141C35C51A7904A082B19E0.muflo +0 -0
  3. package/dist/mufl_code/actor.mu +27 -0
  4. package/dist/mufl_code/core/COMMERCIAL-LICENCE.md +25 -0
  5. package/dist/mufl_code/core/COMPATIBILITY.md +221 -0
  6. package/dist/mufl_code/core/CONTRIBUTING.md +37 -0
  7. package/dist/mufl_code/core/LICENSE +1 -1
  8. package/dist/mufl_code/core/NOTIFICATIONS_CONTRACT.md +290 -0
  9. package/dist/mufl_code/core/README.md +64 -49
  10. package/dist/mufl_code/core/SECURITY.md +40 -0
  11. package/dist/mufl_code/core/TRADEMARKS.md +24 -0
  12. package/dist/mufl_code/core/a2a_capabilities.mm +76 -1
  13. package/dist/mufl_code/core/a2a_control.mm +2 -1
  14. package/dist/mufl_code/core/a2a_messaging.mm +1677 -25
  15. package/dist/mufl_code/core/a2a_notifications.mm +1102 -0
  16. package/dist/mufl_code/core/a2a_protocol.mm +16 -1
  17. package/dist/mufl_code/core/a2a_versions.mm +801 -0
  18. package/dist/mufl_code/core/config.mufl +2 -0
  19. package/dist/mufl_code/core/docs/.vitepress/config.mts +58 -0
  20. package/dist/mufl_code/core/docs/citations.json +688 -0
  21. package/dist/mufl_code/core/docs/guide/01-vendor-the-core.md +50 -0
  22. package/dist/mufl_code/core/docs/guide/02-configure-and-compile.md +100 -0
  23. package/dist/mufl_code/core/docs/guide/03-wire-the-host.md +154 -0
  24. package/dist/mufl_code/core/docs/guide/04-connect-and-message.md +156 -0
  25. package/dist/mufl_code/core/docs/guide/05-test-your-app.md +75 -0
  26. package/dist/mufl_code/core/docs/guide/index.md +63 -0
  27. package/dist/mufl_code/core/docs/how-it-works/capabilities-and-control.md +77 -0
  28. package/dist/mufl_code/core/docs/how-it-works/cluster.md +65 -0
  29. package/dist/mufl_code/core/docs/how-it-works/identity.md +56 -0
  30. package/dist/mufl_code/core/docs/how-it-works/invites-and-contacts.md +76 -0
  31. package/dist/mufl_code/core/docs/how-it-works/messaging.md +55 -0
  32. package/dist/mufl_code/core/docs/how-it-works/monitoring-and-config.md +72 -0
  33. package/dist/mufl_code/core/docs/how-it-works/overview.md +45 -0
  34. package/dist/mufl_code/core/docs/how-it-works/versioning.md +116 -0
  35. package/dist/mufl_code/core/docs/index.md +27 -0
  36. package/dist/mufl_code/core/docs/package-lock.json +3467 -0
  37. package/dist/mufl_code/core/docs/package.json +15 -0
  38. package/dist/mufl_code/core/docs/reference/contributing.md +26 -0
  39. package/dist/mufl_code/core/docs/reference/glossary.md +108 -0
  40. package/dist/mufl_code/core/docs/reference/implementations.md +23 -0
  41. package/dist/mufl_code/core/docs/reference/modules.md +19 -0
  42. package/dist/mufl_code/core/docs/scripts/check-citations.mjs +36 -0
  43. package/dist/mufl_code/core/docs/scripts/check-denylist.mjs +30 -0
  44. package/dist/mufl_code/core/docs/scripts/gen-llms.mjs +32 -0
  45. package/dist/mufl_code/core/docs/workflows/cluster.md +89 -0
  46. package/dist/mufl_code/core/docs/workflows/contact-exchange.md +60 -0
  47. package/dist/mufl_code/core/docs/workflows/contact-restore.md +60 -0
  48. package/dist/mufl_code/core/docs/workflows/control-verbs.md +70 -0
  49. package/dist/mufl_code/core/docs/workflows/index.md +57 -0
  50. package/dist/mufl_code/core/docs/workflows/introductions.md +60 -0
  51. package/dist/mufl_code/core/docs/workflows/messaging.md +75 -0
  52. package/dist/mufl_code/core/docs/workflows/monitoring.md +84 -0
  53. package/dist/mufl_code/core/docs/workflows/notifications.md +109 -0
  54. package/dist/mufl_code/core/release-notes/0.1.md +60 -0
  55. package/dist/mufl_code/core/release-notes/0.3.md +22 -0
  56. package/dist/mufl_code/core/release-notes/0.4.md +97 -0
  57. package/dist/mufl_code/core/tests/README.md +17 -0
  58. package/dist/mufl_code/core/tests/corpus.mjs +139 -0
  59. package/dist/mufl_code/core/tests/corpus_actor.mu +242 -0
  60. package/dist/mufl_code/core/tests/fatcompile_actor.mu +52 -0
  61. package/dist/mufl_code/core/tests/mig.mjs +664 -0
  62. package/dist/mufl_code/core/tests/mig_actor.mu +466 -0
  63. package/dist/mufl_code/core/tests/migapp.mjs +431 -0
  64. package/dist/mufl_code/core/tests/migapp_actor.mu +294 -0
  65. package/dist/mufl_code/core/tests/mufl_semantics/run.sh +69 -0
  66. package/dist/mufl_code/core/tests/mufl_semantics/t11_three_version.mufl +47 -0
  67. package/dist/mufl_code/core/tests/mufl_semantics/t2_extra_fields.mufl +11 -0
  68. package/dist/mufl_code/core/tests/mufl_semantics/t7_runtime.mufl +30 -0
  69. package/dist/mufl_code/core/tests/mufl_semantics/t9_passthrough.mufl +19 -0
  70. package/dist/mufl_code/core/tests/mufl_semantics/t_str_order.mufl +19 -0
  71. package/dist/mufl_code/core/tests/notif.mjs +689 -0
  72. package/dist/mufl_code/core/tests/notif_actor.mu +458 -0
  73. package/dist/mufl_code/core/tests/protocol_container.mm +18 -0
  74. package/dist/mufl_code/core/tests/run.sh +8 -10
  75. package/dist/mufl_code/core/tests/run_corpus.sh +51 -0
  76. package/dist/mufl_code/core/tests/run_fatcompile.sh +40 -0
  77. package/dist/mufl_code/core/tests/run_mig.sh +51 -0
  78. package/dist/mufl_code/core/tests/run_migapp.sh +51 -0
  79. package/dist/mufl_code/core/tests/run_notif.sh +55 -0
  80. package/dist/mufl_code/core/tests/test.mjs +291 -49
  81. package/dist/mufl_code/core/tests/test_actor.mu +240 -7
  82. package/dist/mufl_code/core/tests/test_common.mjs +93 -0
  83. package/dist/mufl_code/core/version.mm +1 -1
  84. package/package.json +4 -4
  85. package/dist/mufl_code/2DA1D5F860E42C605D92F1E24E2466C70EFDDBF057BBCBA52F0ECC639EFCA387.muflo +0 -0
  86. package/dist/mufl_code/core/CLUSTER_API.md +0 -640
  87. package/dist/mufl_code/core/CLUSTER_CONTRACT.md +0 -121
  88. package/dist/mufl_code/core/CLUSTER_INTRODUCTION_PLAN.md +0 -200
  89. package/dist/mufl_code/core/CONFIGURATION_DESIGN.md +0 -35
  90. package/dist/mufl_code/core/CONFIGURATION_PLAN.md +0 -394
  91. package/dist/mufl_code/core/DEVELOPMENT.md +0 -168
  92. package/dist/mufl_code/core/EPHEMERAL_INVITE_PLAN.md +0 -465
  93. package/dist/mufl_code/core/GROUP_CHAT_DESIGN.md +0 -520
  94. package/dist/mufl_code/core/release-notes/2.0.md +0 -268
  95. package/dist/mufl_code/core/release-notes/2.1.md +0 -92
  96. package/dist/mufl_code/core/release-notes/2.2.md +0 -94
  97. package/dist/mufl_code/core/release-notes/3.0.md +0 -162
  98. package/dist/mufl_code/core/release-notes/3.1.md +0 -43
  99. package/dist/mufl_code/core/release-notes/README.md +0 -32
@@ -32,6 +32,8 @@ library a2a_messaging loads libraries
32
32
  key_storage,
33
33
  current_transaction_info,
34
34
  encrypted_channel,
35
+ e2e,
36
+ a2a_versions,
35
37
  a2a_protocol,
36
38
  a2a_capabilities,
37
39
  version
@@ -69,17 +71,44 @@ library a2a_messaging loads libraries
69
71
  request_contact_restore_tx = "::a2a_messaging::request_contact_restore".
70
72
  submit_restore_response_tx = "::a2a_messaging::submit_restore_response".
71
73
  complete_restore_tx = "::a2a_messaging::complete_restore".
74
+ // core 0.7.0 receipts inbound (LIBRARY-routed, new surface, no legacy
75
+ // listeners; reachable only behind positive core.receipts.* caps).
76
+ receive_receipt_tx = "::a2a_messaging::receive_receipt".
77
+ // core 0.9.0 E2E-migration inbound (LIBRARY-routed, wire 9). offer/ack ride the
78
+ // legacy encrypted_channel; commit/confirm are inner txs on the fresh e2e session.
79
+ e2e_migrate_offer_tx = "::a2a_messaging::e2e_migrate_offer".
80
+ e2e_migrate_ack_tx = "::a2a_messaging::e2e_migrate_ack".
81
+ e2e_migrate_commit_tx = "::a2a_messaging::e2e_migrate_commit".
82
+ e2e_migrate_confirm_tx = "::a2a_messaging::e2e_migrate_confirm".
83
+ // core 0.10 (B1): stateless AD re-advertise pushed to pre-existing legacy contacts on
84
+ // upgrade, so an idle legacy pair learns both sides are now v2 and the migration FSM fires.
85
+ readvertise_ad_tx = "::a2a_messaging::readvertise_ad".
86
+ // core 0.9.0 boxed APP-E2E (Option B): app data over the MIGRATED session rides these named
87
+ // boxes ($targ = the e2e_signed_message). DISTINCT from legacy receive_message_tx so the wire
88
+ // separates e2e-carrying box from legacy box (an attacker cannot confuse them).
89
+ receive_e2e_message_tx = "::a2a_messaging::receive_e2e_message".
90
+ receive_e2e_file_tx = "::a2a_messaging::receive_e2e_file".
72
91
 
73
92
  // Version stamp of the portable export blob (see import_core_state for the
74
93
  // migration contract). Bump ONLY on a breaking blob-shape change, together
75
94
  // with a migration from the previous stamp.
76
95
  core_format_version = 1.
96
+ // Invite-format version stamped on every invite this build mints (invite_eph_t
97
+ // $iv). A redeemer that reads NIL there treats the inviter as pre-versioning and
98
+ // down-levels its address document to v1. See invite_eph_t in a2a_protocol for
99
+ // the exact cases that bump this.
100
+ invite_current_version = 1.
77
101
  // Give up re-requesting a restore after this many attempts per contact (the
78
102
  // host sweep re-fires on its GC cadence; a peer that upgraded and came back
79
103
  // online answers on the first post-upgrade attempt).
80
104
  restore_max_attempts = 30.
81
105
  // Per-contact cap on messages queued while its keys are being restored.
82
106
  deferred_msgs_cap = 50.
107
+ // core 0.9.0: give up re-driving a per-contact E2E migration after this many
108
+ // host-sweep attempts (mirrors restore_max_attempts). Exhaustion surfaces a
109
+ // $migration_stalled notify and KEEPS the FSM state — legacy still flows in
110
+ // offered/acknowledged; committed keeps queueing — nothing silently downgrades.
111
+ mig_max_attempts = 30.
83
112
 
84
113
  // 6-digit bind ceremony limits (code is generated host-side — MUFL has no
85
114
  // random source — and handed to set_proxy_pending).
@@ -97,6 +126,28 @@ library a2a_messaging loads libraries
97
126
  my_persona is str = "".
98
127
  // Known contacts, keyed by their container id.
99
128
  contacts is (global_id ->> a2a_protocol::contact_t) = (,).
129
+ // core 0.5.0: passively learned peer wire dialects + capability ids
130
+ // (SPEC §3/§4). Written on every inbound that carries version evidence
131
+ // (last-seen wins); absent = nothing learned, 0 = pre-0.5 peer. $pv is
132
+ // peer-asserted — these gate send-side feature selection and diagnostics,
133
+ // NEVER authz (REG-6). Both maps are additive in the export blob and
134
+ // guarded on import (pre-0.5 exports import unchanged).
135
+ contact_pv is (global_id ->> int) = (,).
136
+ contact_caps is (global_id ->> str[]) = (,).
137
+ // core 0.8.0: monotonic E2E anti-downgrade pin (SPEC §4). Positive-evidence,
138
+ // set TRUE the first time a peer advertises core.e2e and NEVER cleared — it
139
+ // CANNOT be derived from contact_caps (which is last-seen-wins, so a later
140
+ // caps-absent inbound would erase the evidence and permit a silent downgrade).
141
+ // Exported so the guarantee survives restart/migration. Gates send-side routing
142
+ // (e2e_route), never authz (REG-6).
143
+ contact_e2e_seen is (global_id ->> bool) = (,).
144
+ // core 0.10: born-on-DR marker. TRUE when a contact was FIRST established with a
145
+ // v2 (bundle-carrying) address document — it started on the double ratchet
146
+ // (born-DR), never on a legacy session. A pre-existing LEGACY contact (a v1 AD at
147
+ // registration, INCLUDING an A-down-levelled peer) is NEVER marked. Read by
148
+ // mig_should_trigger to keep migration STRICTLY for legacy sessions: a born-DR
149
+ // contact is already on the ratchet and must not be "migrated". Exported.
150
+ contact_born_dr is (global_id ->> bool) = (,).
100
151
  // core 3.0: invites I generated, keyed by invite id. Holds the NON-secret
101
152
  // per-invite material — the assigned contact name ("" = none), the ephemeral
102
153
  // encryption PUBLIC key shipped in the slim invite, and the crypto scheme id.
@@ -126,6 +177,47 @@ library a2a_messaging loads libraries
126
177
  // flush_deferred) once its AD is re-established. Plain data — EXPORTED.
127
178
  metadef deferred_msg_t: ($text -> str, $wire_id -> str, $reply_to -> a2a_protocol::reply_ref_t+, $date -> time).
128
179
  deferred_msgs is (global_id ->> deferred_msg_t[]) = (,).
180
+
181
+ // ---- core 0.9.0: per-connection E2E migration FSM (spec §5) -----------
182
+ // ABSENCE = legacy (pre-migration, or the peer is not yet capable). Every
183
+ // store is keyed by cid, so mixed-contact independence is structural: no
184
+ // global mode flag exists anywhere. Exported/imported additively (guarded,
185
+ // absent -> empty); a pre-0.9 blob imports with all three empty = legacy.
186
+ // Phase A lands the TYPES + STORES + export/import wiring only — NO handlers,
187
+ // NO route change, NO advertise wiring (those are phases C/D).
188
+ metadef mig_state_t: (
189
+ $phase -> str, // "offered" | "acknowledged" | "committed" | "active"
190
+ $initiator -> bool, // deterministic election result (mig_initiator; lower cid initiates)
191
+ $local_nonce -> bin, // my proposal nonce (agreement uniquifier, not key material)
192
+ $peer_nonce -> bin+, // set from acknowledged on
193
+ $epoch -> bin+, // set from acknowledged on (mig_epoch)
194
+ $session_id -> bin+, // CANONICAL session-id BYTES (adapt session_id()); set from committed on
195
+ $local_bundle -> bin+, // _write'd SNAPSHOT of ($ad,$cert,$root_profile,$cp_binding) THIS attempt —
196
+ // retransmits reuse it byte-identically (§5.4-5); PUBLIC signed material
197
+ // only, so INV-4 holds (no session pickle ever rides the FSM entry)
198
+ $local_fp -> bin+, // e2e_bundle_fp of the snapshot — the epoch input AND the rotation
199
+ // detector (live-fp != $local_fp at retransmit => supersede)
200
+ $attempts -> int, // sweep re-send counter (cap: mig_max_attempts)
201
+ $updated -> time
202
+ ).
203
+ // $local_bundle/$local_fp are bin+ ONLY for import compatibility (pre-0.9
204
+ // blobs lack them); semantically offered/acknowledged REQUIRE both non-NIL —
205
+ // they are written together with the phase in one record assignment, so no
206
+ // code path produces the phase without the snapshot (spec §5.4 phase invariant).
207
+ contact_migration is (global_id ->> mig_state_t) = (,).
208
+
209
+ // The COMMITTED-EPOCH pin — the §5.7 split of contact_e2e_seen. Set ONLY at
210
+ // the `active` transition (cryptographic commit); superseded only by a NEWER
211
+ // committed epoch via a full FSM run; NEVER cleared. Once set, legacy APP-DATA
212
+ // transport to this contact is PROHIBITED (§5.6 carves out migration-CONTROL
213
+ // legs). Strictly stronger than contact_e2e_seen (which is advertisement-class
214
+ // and kept, unchanged, with its 0.8.0 refusal semantics). Canonical bytes.
215
+ metadef e2e_epoch_t: ($epoch -> bin, $session_id -> bin).
216
+ contact_e2e_epoch is (global_id ->> e2e_epoch_t) = (,).
217
+
218
+ // Sends queued during the initiator's commit window; flushed E2E on `active`.
219
+ // Reuses deferred_msg_t; bounded by deferred_msgs_cap (same overflow abort).
220
+ mig_deferred is (global_id ->> deferred_msg_t[]) = (,).
129
221
  // Peer address documents, captured when a contact is established. Self-
130
222
  // signed, code-independent, and seed-stable: import_core_state replays
131
223
  // them through address_document::process_address_document so encrypted
@@ -134,6 +226,15 @@ library a2a_messaging loads libraries
134
226
  peer_ads is (global_id ->> address_document_types::t_address_document) = (,).
135
227
  // My delegation cert. NIL == I am a root or a legacy flat identity.
136
228
  delegation_cert is a2a_protocol::delegation_cert_t+ = NIL.
229
+ // My delegation cert bound to my v1 (down-levelled, bundle-less) address
230
+ // document — the SAME chain, but its $role_ad_hash commits to _value_id of
231
+ // produce_v1_address_document() instead of the current v2 AD. Sent INSTEAD of
232
+ // delegation_cert whenever I down-level my AD to v1 for a pre-E2E (0.11.2)
233
+ // peer, so that peer's verify_peer_delegation (which hashes the v1 AD it
234
+ // actually received) finds a matching cert. NIL for a root, a legacy flat
235
+ // identity, or a role whose host has not yet minted the v1 cert (in which
236
+ // case the down-level omits the chain rather than send a mismatching v2 cert).
237
+ delegation_cert_v1 is a2a_protocol::delegation_cert_t+ = NIL.
137
238
  // My root's address document (set with the cert; its key list is what
138
239
  // sibling introductions and my own cert are verified against).
139
240
  root_ad is address_document_types::t_address_document+ = NIL.
@@ -259,6 +360,14 @@ library a2a_messaging loads libraries
259
360
  // $reply_to): fired after the wire send is queued (agent: no-op;
260
361
  // messenger: append an outgoing file history entry keyed by $wire_id).
261
362
  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 []. }
363
+ // on_receipt_received ($sender_id, $kind "delivered"|"read", $wire_ids
364
+ // str[], $date time+): a peer confirmed delivery/read of messages we
365
+ // sent (core 0.7.0 receipts). DEFAULT NO-OP — receipts are best-effort
366
+ // UX, never load-bearing; an app that doesn't wire the hook silently
367
+ // drops them. Hook contract (normative): application is MONOTONIC per
368
+ // (peer, wire_id) on unknown < sent < delivered < read — duplicates
369
+ // and out-of-order arrivals collapse to no-ops.
370
+ on_receipt_received is (any -> transaction::action::type[]) = fn (_: any) -> transaction::action::type[] { return []. }
262
371
  }
263
372
 
264
373
  init = fn (_:(
@@ -267,7 +376,9 @@ library a2a_messaging loads libraries
267
376
  $on_message_sent -> sent_cb: (any -> transaction::action::type[]),
268
377
  $on_contact_removed -> removed_cb: (any -> transaction::action::type[]),
269
378
  $on_file_received -> file_received_cb: (any -> transaction::action::type[]),
270
- $on_file_sent -> file_sent_cb: (any -> transaction::action::type[])
379
+ $on_file_sent -> file_sent_cb: (any -> transaction::action::type[]),
380
+ // core 0.7.0, OPTIONAL (absent from pre-0.7 callers): receipt consumer.
381
+ $on_receipt_received -> receipt_cb: (any -> transaction::action::type[])+
271
382
  ))
272
383
  {
273
384
  _read_or_abort -> read.
@@ -276,6 +387,20 @@ library a2a_messaging loads libraries
276
387
  on_contact_removed -> removed_cb.
277
388
  on_file_received -> file_received_cb.
278
389
  on_file_sent -> file_sent_cb.
390
+ if receipt_cb != NIL { on_receipt_received -> receipt_cb?. }
391
+ // core 0.9.0 (spec §5.5): register the decode-seam migration-pending predicate so
392
+ // the adapt e2e receive path STAGES an inbound migration-commit PRE_KEY (instead of
393
+ // unilaterally replacing the live session). TRUE only while a migration is genuinely
394
+ // IN-FLIGHT for the cid (offered/acknowledged/committed) — NEVER post-active: an
395
+ // epoch-pinned contact's self-heal pre-key must go through recovery/route, not raw
396
+ // staging. Empty FSM (no migration) -> FALSE -> pure 0.8.0 decode behavior.
397
+ e2e::set_mig_pending_hook (fn (c: global_id) -> bool
398
+ {
399
+ st = contact_migration c.
400
+ if st == NIL { return FALSE. }
401
+ ph = (st?) $phase.
402
+ return ph == "offered" || ph == "acknowledged" || ph == "committed".
403
+ }).
279
404
  }
280
405
 
281
406
  // ---- shared action builders -------------------------------------------
@@ -315,7 +440,7 @@ library a2a_messaging loads libraries
315
440
  return [
316
441
  encrypted_channel::send_encrypted_tx (monitoring_proxy? $proxy_cid) (
317
442
  $name -> receive_monitoring_copy_tx,
318
- $targ -> ($copy -> copy)
443
+ $targ -> ($copy -> copy, $pv -> a2a_versions::wire_version)
319
444
  )
320
445
  ].
321
446
  }
@@ -576,7 +701,123 @@ library a2a_messaging loads libraries
576
701
  // My identity bundle payload fields: my AD plus, when I am a delegated role,
577
702
  // my chain blobs (cert / root profile / optional §3c cp binding). The caller
578
703
  // 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+)
704
+ // peer_is_v1 (NULLABLE): TRUE emits a v1 (down-levelled, bundle-less) address
705
+ // document so an older peer accepts it; NIL/FALSE emits the current AD. The
706
+ // invite/handshake down-level sites pass a computed bool; the contact-restore
707
+ // sites pass NIL (unchanged behaviour).
708
+ fn my_identity_bundle_fields (peer_is_v1: bool+) -> ($ad -> address_document_types::t_address_document, $cert -> bin+, $root_profile -> bin+, $cp_binding -> bin+)
709
+ {
710
+ my_cert_blob is bin+ = NIL.
711
+ my_rp_blob is bin+ = NIL.
712
+ my_rpb_blob is bin+ = NIL.
713
+ down_level = (peer_is_v1 != NIL) && (peer_is_v1?).
714
+ // The cert I attach MUST commit to the same AD version I attach: a v1 peer
715
+ // hashes the v1 AD it receives and compares it to cert.$role_ad_hash, so a
716
+ // down-level MUST carry the v1-AD-bound cert (delegation_cert_v1). If it is
717
+ // absent (a role whose host predates the v1-cert mint), send the AD WITHOUT
718
+ // a chain rather than a mismatching v2 cert — a bundle-less contact with no
719
+ // recorded root linkage still connects (verify_identity_bundle treats a NIL
720
+ // cert as a flat identity); attaching the v2 cert would abort the peer.
721
+ eff_cert is a2a_protocol::delegation_cert_t+ = delegation_cert.
722
+ if down_level { eff_cert -> delegation_cert_v1. }
723
+ if eff_cert != NIL && root_profile != NIL
724
+ {
725
+ my_cert_blob -> (_write eff_cert?).
726
+ my_rp_blob -> (_write root_profile?).
727
+ if root_cp_binding != NIL { my_rpb_blob -> (_write root_cp_binding?). }
728
+ }
729
+ return ($ad -> address_document::get_my_address_document_versioned(peer_is_v1), $cert -> my_cert_blob, $root_profile -> my_rp_blob, $cp_binding -> my_rpb_blob).
730
+ }
731
+
732
+ // ---- core 0.8.0 E2E capability + monotonic anti-downgrade ----------------
733
+ // Positive-evidence pin: the FIRST time a peer's advertised caps include
734
+ // core.e2e, mark it — and never unmark. Called from every version-learning
735
+ // leg (via learn_contact_version), so the pin tracks the same evidence as
736
+ // contact_caps but MONOTONICALLY (contact_caps is last-seen-wins and would
737
+ // lose the evidence on a caps-absent inbound). A no-op when caps lack core.e2e.
738
+ // Inline cap-scan (not caps_contains, which is defined later — MUFL resolves
739
+ // symbols define-before-use).
740
+ fn note_e2e_seen (cid: global_id, caps: str[]) -> nil
741
+ {
742
+ sc caps -- ( -> c) { if c == a2a_capabilities::cap_e2e { contact_e2e_seen cid -> TRUE. return. } }
743
+ }
744
+ fn e2e_pinned (cid: global_id) -> bool { return (contact_e2e_seen cid) == TRUE. }
745
+
746
+ // Does the peer's cached AD carry an AD v2 $e2e_bundle (adapt owns the type
747
+ // and populates it via process_address_document)? Read via `as any` so this
748
+ // compiles against a pre-v2 address_document type and lights up once adapt's
749
+ // AD v2 lands. NIL/absent -> FALSE (no bundle -> cannot establish a session).
750
+ fn peer_has_e2e_bundle (cid: global_id) -> bool
751
+ {
752
+ ad = peer_ads cid.
753
+ if ad == NIL { return FALSE. }
754
+ return (((ad?) as any) $identity $e2e_bundle) != NIL.
755
+ }
756
+
757
+ // Send-side APP-DATA routing (spec §5.6, five-state, error-as-data — NOT a hard
758
+ // abort; cf. receipt_gate which returns without aborting). Core is the single
759
+ // routing authority; the daemon obeys this verdict for its e2e app-send path.
760
+ // The four e2e_migrate_* CONTROL legs are EXEMPT (carve-out, must-fix #5): they
761
+ // ride encrypted_channel (mgb offer/ack) / the fresh e2e session (mgc commit/
762
+ // confirm) BY CONSTRUCTION and never pass through this route.
763
+ // "e2e" -> app data rides the migrated e2e session (daemon path)
764
+ // "legacy" -> first-contact / genuinely-v1 peer / pre-commit: box
765
+ // (or a pre-epoch e2e session for already-E2E pairs)
766
+ // "migrating" -> initiator commit window: QUEUE in mig_deferred, flush on active
767
+ // "downgrade_refused" -> once E2E (pinned) but no current v2 bundle: fail CLOSED
768
+ // (never silently box a migrated peer) → typed refusal + recovery
769
+ fn e2e_route (cid: global_id) -> str
770
+ {
771
+ ep = contact_migration cid.
772
+ if (contact_e2e_epoch cid) != NIL
773
+ { // cryptographically committed (epoch pinned): legacy PROHIBITED, irreversibly.
774
+ if peer_has_e2e_bundle cid { return "e2e". } // session errors surface at the adapt seam
775
+ return "downgrade_refused".
776
+ }
777
+ // Only the INITIATOR sits in a committed app-send window (the responder's
778
+ // committed->active is atomic in one tx, so it never queues app data).
779
+ if ep != NIL && ((ep?) $phase) == "committed" && ((ep?) $initiator) == TRUE { return "migrating". }
780
+ seen = e2e_pinned cid. v2 = peer_has_e2e_bundle cid.
781
+ if seen && v2 != TRUE { return "downgrade_refused". } // imported 0.8.0 pin, AD absent
782
+ return ((seen || v2) ?? "e2e" ; "legacy").
783
+ }
784
+
785
+ // ---- core 0.9.0 migration helpers (spec §5.2) ----------------------------
786
+ // Deterministic total order on the hex container ids. MUFL '<' is lexicographic
787
+ // on strings (pinned in tests/mufl_semantics), which is a total order — both
788
+ // sides compute the same answer from the pinned cids (§5.9-2: any deterministic
789
+ // shared order works). Used ONLY to elect exactly one proposer; never authz.
790
+ fn str_lt (a: str, b: str) -> bool { return a < b. }
791
+
792
+ // Exactly-once agreement needs exactly one proposer: the LOWER cid initiates.
793
+ // Stable across restarts/imports/simultaneous upgrades — both sides derive it
794
+ // from the pinned ids, so no tie-breaking state is ever needed.
795
+ fn mig_initiator (peer: global_id) -> bool
796
+ { return str_lt (_str (_get_container_id())) (_str peer). }
797
+
798
+ // Fingerprint of an AD's E2E prekey bundle — the epoch input AND the rotation
799
+ // detector (a live-vs-snapshot fp mismatch at retransmit forces supersession).
800
+ fn e2e_bundle_fp (ad: address_document_types::t_address_document) -> bin
801
+ { return _hash_code_to_binary (_value_id (((ad as any) $identity $e2e_bundle))). }
802
+
803
+ // Epoch: both parties derive the SAME 32-byte id from authenticated inputs — the
804
+ // cid-ORDERED ids, both proposal nonces, both FRESH bundle fingerprints. Domain-
805
+ // separated; any input change (re-offer / re-published AD) => a new epoch, so a
806
+ // stale commit can never validate against a refreshed agreement. Callers MUST pass
807
+ // the inputs in cid order (lo < hi) so both sides agree regardless of who proposed.
808
+ fn mig_epoch (lo: global_id, hi: global_id, n_lo: bin, n_hi: bin, f_lo: bin, f_hi: bin) -> bin
809
+ {
810
+ return _hash_code_to_binary (_value_id (
811
+ $proto -> "ours/e2e-migration/v1",
812
+ $a -> lo, $b -> hi, $na -> n_lo, $nb -> n_hi, $fa -> f_lo, $fb -> f_hi )).
813
+ }
814
+
815
+ // FRESH identity bundle (§5.9-4): the migration legs must carry the CURRENT
816
+ // signed AD, so they build via produce_my_address_document (rebuild + re-sign,
817
+ // embedding e2e::my_public_bundle) rather than the CACHED get_my_address_document
818
+ // (which can pre-date the live account fallback). Same shape as
819
+ // my_identity_bundle_fields; only the AD source differs.
820
+ fn my_identity_bundle_fields_fresh (_) -> ($ad -> address_document_types::t_address_document, $cert -> bin+, $root_profile -> bin+, $cp_binding -> bin+)
580
821
  {
581
822
  my_cert_blob is bin+ = NIL.
582
823
  my_rp_blob is bin+ = NIL.
@@ -587,7 +828,220 @@ library a2a_messaging loads libraries
587
828
  my_rp_blob -> (_write root_profile?).
588
829
  if root_cp_binding != NIL { my_rpb_blob -> (_write root_cp_binding?). }
589
830
  }
590
- return ($ad -> address_document::get_my_address_document(), $cert -> my_cert_blob, $root_profile -> my_rp_blob, $cp_binding -> my_rpb_blob).
831
+ return ($ad -> address_document::produce_my_address_document(), $cert -> my_cert_blob, $root_profile -> my_rp_blob, $cp_binding -> my_rpb_blob).
832
+ }
833
+
834
+ // Build + persist + send an OFFER (spec §5.4). Snapshot the fresh public bundle
835
+ // into the FSM entry FIRST, then build the wire targ FROM the snapshot (decoded),
836
+ // so first-send and every retransmit share ONE construction path and are
837
+ // byte-identical (the epoch depends on the snapshot's fp under a fixed nonce).
838
+ // INV-4: only public signed material (AD/cert/root_profile/cp_binding) is snapshotted,
839
+ // never a session pickle. Caller emits _save_state alongside these actions (atomic
840
+ // persist-with-send). Rides the legacy encrypted_channel (peer must be an established
841
+ // contact); the migration-control carve-out (phase D) keeps this send legal even when
842
+ // app-data route is refused.
843
+ fn mig_offer_actions (peer: global_id) -> transaction::action::type[]
844
+ {
845
+ b = my_identity_bundle_fields_fresh NIL.
846
+ lb = _write ( $ad -> (b $ad), $cert -> (b $cert),
847
+ $root_profile -> (b $root_profile), $cp_binding -> (b $cp_binding) ).
848
+ fp = e2e_bundle_fp (b $ad).
849
+ n = _hash_code_to_binary (_value_id (_new_id "ours e2e migration")).
850
+ now = (current_transaction_info::get_transaction_time())?.
851
+ contact_migration peer -> ( $phase -> "offered", $initiator -> (mig_initiator peer),
852
+ $local_nonce -> n, $peer_nonce -> NIL, $epoch -> NIL, $session_id -> NIL,
853
+ $local_bundle -> lb, $local_fp -> fp, $attempts -> 1, $updated -> now ).
854
+ s = _read_or_abort lb.
855
+ return [ encrypted_channel::send_encrypted_tx peer (
856
+ $name -> e2e_migrate_offer_tx,
857
+ $targ -> ( $ad -> (s $ad), $cert -> (s $cert), $root_profile -> (s $root_profile),
858
+ $cp_binding -> (s $cp_binding), $nonce -> n, $peer_nonce -> NIL,
859
+ $pv -> a2a_versions::wire_version,
860
+ $caps -> (a2a_capabilities::self_cap_ids NIL) ) ) ].
861
+ }
862
+
863
+ // §5.4 TRIGGER (liveness): on inbound stamped traffic from a peer we now know is 0.9-capable
864
+ // (its caps advertise cap_e2e_migrate, OR its learned pv>=9) and for which NO migration exists
865
+ // yet, emit OUR offer. ANY side offers on first evidence — NOT conditioned on mig_initiator
866
+ // (election is resolved in the handlers; a higher-cid offer functions as a solicitation that
867
+ // makes the elected lower-cid side emit the authoritative offer). Fail-closed (§1.5): if we
868
+ // don't advertise the cap, or the peer isn't known-0.9, emit nothing — an old peer never gets
869
+ // an offer. Returns [] (NO state write) when the trigger doesn't fire; the CALLER emits
870
+ // _save_state alongside the returned offer (mig_offer_actions persists `offered`).
871
+ // The trigger GATE (pure predicate — testable in isolation; THIS is the criterion-1 boundary:
872
+ // an old peer must NEVER satisfy it). TRUE iff: no migration yet ∧ WE advertise cap_e2e_migrate
873
+ // ∧ the peer is known-0.9 (its caps advertise cap_e2e_migrate, OR its learned pv>=9). Any gate
874
+ // fails → FALSE (no offer). Fail-closed (§1.5).
875
+ fn mig_should_trigger (cid: global_id) -> bool
876
+ {
877
+ if (contact_migration cid) != NIL { return FALSE. } // already in-flight / done
878
+ if (contact_e2e_epoch cid) != NIL { return FALSE. } // already epoch-pinned (migrated) — never re-offer; defense-in-depth vs any future contact_migration-clearing path (MR2)
879
+ if (contact_born_dr cid) == TRUE { return FALSE. } // born-on-DR (fresh v2 contact): already on the ratchet — migration is reserved STRICTLY for pre-existing legacy sessions
880
+ if (a2a_capabilities::self_advertises a2a_capabilities::cap_e2e_migrate) != TRUE { return FALSE. }
881
+ peer_capable is bool = FALSE.
882
+ caps = contact_caps cid.
883
+ if caps != NIL { sc caps? -- ( -> c) { if c == a2a_capabilities::cap_e2e_migrate { peer_capable -> TRUE. } } }
884
+ pv = contact_pv cid.
885
+ if peer_capable != TRUE && (pv == NIL || pv? < 9) { return FALSE. } // not known-0.9
886
+ return TRUE.
887
+ }
888
+
889
+ fn mig_trigger_actions (cid: global_id) -> transaction::action::type[]
890
+ {
891
+ if (mig_should_trigger cid) != TRUE { return []. }
892
+ return mig_offer_actions cid.
893
+ }
894
+
895
+ // §5.4 PROACTIVE reconciler — the receive-INDEPENDENT counterpart of mig_trigger_actions: offer to
896
+ // EVERY contact that passes mig_should_trigger (already-known e2e peers with no migration yet). This
897
+ // is the core of the missing-trigger-path fix: an already-e2e-pinned pair (caps learned at invite,
898
+ // ZERO plaintext app traffic) never hits the plaintext receive trigger, so it must be offered
899
+ // proactively. Reused by advertise_migrate (runtime cap-enable) and sweep_e2e_migrations (the
900
+ // default-cap-boot / GC reconciler). Fail-closed + idempotent BY CONSTRUCTION — mig_should_trigger
901
+ // gates on self-advertise ∧ peer-known-0.9 ∧ contact_migration==NIL ∧ contact_e2e_epoch==NIL, so it
902
+ // is inert pre-cap and never re-offers an in-flight/migrated pair. The CALLER emits _save_state
903
+ // (mig_offer_actions persists each `offered` snapshot). One send action per newly-offered contact.
904
+ fn mig_offer_eligible_actions (_) -> transaction::action::type[]
905
+ {
906
+ acts is transaction::action::type[] = [].
907
+ sc contacts -- (cid -> c) ?? (mig_should_trigger cid) { sc mig_offer_actions cid -- ( -> a) { acts (_count acts|) -> a. } }
908
+ return acts.
909
+ }
910
+
911
+ // §5.6 flush: drain mig_deferred[cid] FIFO and emit each queued app message for E2E delivery
912
+ // (the daemon sends over the now-active migrated session — core is routing-authority only).
913
+ // The CALLER MUST have set the epoch pin FIRST (else a re-injected send routes "migrating" and
914
+ // re-queues). Clears the queue; an empty queue yields no actions; per-contact order preserved.
915
+ fn flush_mig_deferred_actions (cid: global_id) -> transaction::action::type[]
916
+ {
917
+ out is transaction::action::type[] = [].
918
+ q = mig_deferred cid.
919
+ if q == NIL || (_count q?|) == 0 { return out. }
920
+ sc q? -- ( -> m)
921
+ {
922
+ out (_count out|) -> _notify_agent ( $event -> $migration_deferred_flush, $cid -> cid,
923
+ $wire_id -> (m $wire_id), $text -> (m $text), $reply_to -> (m $reply_to), $route -> $e2e ).
924
+ }
925
+ delete mig_deferred cid.
926
+ return out.
927
+ }
928
+
929
+ // ---- core 0.5.0 versioning helpers ---------------------------------------
930
+ // Passive version learning (SPEC §3): record the peer's wire dialect (and
931
+ // its advertised capability ids, when it piggybacked any) off an inbound
932
+ // that carried version evidence. Guarded writes — state only mutates when
933
+ // the learned value actually changes, so handlers that do not _save_state
934
+ // are not left with silently divergent persistence.
935
+ fn learn_contact_version (cid: global_id, pv: int, caps: str[]) -> nil
936
+ {
937
+ prev = contact_pv cid.
938
+ if prev == NIL || prev? != pv { contact_pv cid -> pv. }
939
+ if (_count caps|) != 0 { contact_caps cid -> caps. note_e2e_seen cid caps. }
940
+ }
941
+
942
+ // Owner Addition B: the inviter-facing, render-ready message for a version-
943
+ // incompatible invite second phase. Context-specific wording layered over
944
+ // the registry's generic version_error_t (which rides beside it verbatim).
945
+ fn invite_version_error_message (err: a2a_versions::version_error_t) -> str
946
+ {
947
+ if (err $code) == "peer_version_unsupported"
948
+ {
949
+ return "An invite you created was accepted by a peer running an unsupported (too old) protocol version (v" + (_str (err $peer_version)) + "; minimum supported is v" + (_str (err $min_supported)) + "). The contact was not added — ask them to update their client, then they can redeem the same invite again.".
950
+ }
951
+ return "An invite you created was accepted by a peer whose payload matches no supported protocol shape. The contact was not added — ask them to update their client, then they can redeem the same invite again.".
952
+ }
953
+
954
+ // ---- core 0.7.0 receipts (delivery + read confirmations) -----------------
955
+ // Gate (BOTH kinds, one capability pair; polarity is deliberately the
956
+ // OPPOSITE of CAP-1): emit iff THIS node advertises core.receipts.emit
957
+ // (user policy, manifest-captured) AND the peer POSITIVELY advertises
958
+ // core.receipts.receive in learned contact_caps. Absent/unknown caps =>
959
+ // nothing is sent — emitting to a client that cannot parse receipts is the
960
+ // incident class (undeliverable inbound). REG-6: never authz.
961
+ // Does this caps list mention ANY receipts id (i.e. the peer's build is
962
+ // receipts-aware and its advertisement is an EXPLICIT opinion)?
963
+ fn caps_receipts_opinion (caps: str[]) -> bool
964
+ {
965
+ sc caps -- ( -> c)
966
+ {
967
+ if c == a2a_capabilities::cap_receipts_receive { return TRUE. }
968
+ if c == a2a_capabilities::cap_receipts_emit { return TRUE. }
969
+ }
970
+ return FALSE.
971
+ }
972
+ fn caps_contains (caps: str[], cap: str) -> bool
973
+ {
974
+ sc caps -- ( -> c) { if c == cap { return TRUE. } }
975
+ return FALSE.
976
+ }
977
+
978
+ // HYBRID GATE (stale-caps self-heal): capability ids are exchanged only on
979
+ // invite/restore bundle legs, so a contact paired PRE-receipts keeps its
980
+ // old caps forever unless re-paired — which froze receipts off for every
981
+ // existing contact after the 0.7 update (owner-reported single-tick bug).
982
+ // Rule: if the peer's learned caps express ANY receipts opinion, follow
983
+ // them STRICTLY (preserves explicit emit/receive toggles); if they are
984
+ // silent on receipts, imply `receive` from the peer's learned dialect
985
+ // pv >= 7 — pv IS re-learned from every stamped ordinary message (ongoing
986
+ // learning), and a pv>=7 peer is KNOWN to parse receive_receipt (the rcp
987
+ // surface registered in 0.7). Old peers (pv < 7 / unknown) stay silent.
988
+ // REG-6 holds: this shapes traffic, never authz.
989
+ fn receipt_gate (peer: global_id) -> bool
990
+ {
991
+ if a2a_capabilities::self_advertises a2a_capabilities::cap_receipts_emit != TRUE { return FALSE. }
992
+ caps = contact_caps peer.
993
+ if caps != NIL && caps_receipts_opinion (caps?)
994
+ {
995
+ return caps_contains (caps?) a2a_capabilities::cap_receipts_receive.
996
+ }
997
+ pv = contact_pv peer.
998
+ return pv != NIL && pv? >= 7.
999
+ }
1000
+
1001
+ // Build the receipt send (fire-and-forget over the established encrypted
1002
+ // channel; receipts always FOLLOW message traffic, so the channel exists).
1003
+ // Returns [] when gated off or nothing to confirm — callers append blindly.
1004
+ fn receipt_actions (peer: global_id, kind: str, wire_ids: str[]) -> transaction::action::type[]
1005
+ {
1006
+ if (_count wire_ids|) == 0 { return []. }
1007
+ if receipt_gate peer != TRUE { return []. }
1008
+ return [
1009
+ encrypted_channel::send_encrypted_tx peer (
1010
+ $name -> receive_receipt_tx,
1011
+ $targ -> (
1012
+ $kind -> kind,
1013
+ $wire_ids -> wire_ids,
1014
+ $date -> (current_transaction_info::get_transaction_time())?,
1015
+ $pv -> a2a_versions::wire_version
1016
+ )
1017
+ )
1018
+ ].
1019
+ }
1020
+
1021
+ // READ receipts ride the consumer's get/mark-read path: mufl readonly trns
1022
+ // cannot emit sends, so the consumer's (mutating) unread->read MARK is the
1023
+ // read event — it appends these actions for the ids it JUST transitioned,
1024
+ // which makes emission exact-once for free (no transition, no receipt).
1025
+ fn read_receipt_actions (sender_id: global_id, wire_ids: str[]) -> transaction::action::type[]
1026
+ {
1027
+ return receipt_actions sender_id "read" wire_ids.
1028
+ }
1029
+
1030
+ // Sender-side expectation, DERIVED from learned caps (no wire traffic):
1031
+ // "expected" iff the peer positively advertises the emit capability, else
1032
+ // "unknown" — absence of a receipt is NEVER a failure state.
1033
+ // Same hybrid as the gate: explicit caps opinion wins; otherwise a
1034
+ // pv>=7 peer is expected to emit (its build does by default).
1035
+ fn receipt_expectation (cid: global_id) -> str
1036
+ {
1037
+ caps = contact_caps cid.
1038
+ if caps != NIL && caps_receipts_opinion (caps?)
1039
+ {
1040
+ return (caps_contains (caps?) a2a_capabilities::cap_receipts_emit ?? "expected" ; "unknown").
1041
+ }
1042
+ pv = contact_pv cid.
1043
+ if pv != NIL && pv? >= 7 { return "expected". }
1044
+ return "unknown".
591
1045
  }
592
1046
 
593
1047
  // Verify a received identity bundle against the authenticated sender: D8
@@ -648,7 +1102,8 @@ library a2a_messaging loads libraries
648
1102
  $c -> (my_ad $identity $container_id),
649
1103
  $n -> my_name,
650
1104
  $k -> (kp $public_key),
651
- $v -> scheme
1105
+ $v -> scheme,
1106
+ $iv -> invite_current_version
652
1107
  ).
653
1108
  return ($blob -> (_write invite), $invite_id -> invite_id).
654
1109
  }
@@ -702,13 +1157,22 @@ library a2a_messaging loads libraries
702
1157
 
703
1158
  // My identity bundle: my AD plus, if I am a delegated role, my chain so the
704
1159
  // inviter learns my root linkage symmetrically. All inside the box.
705
- b = my_identity_bundle_fields NIL.
1160
+ // A NIL invite version ($iv) means the inviter predates the invite-version
1161
+ // field (an old node) — down-level my AD to v1 so it accepts my leg-1 bundle.
1162
+ peer_is_v1 = ((inv $iv) == NIL).
1163
+ b = my_identity_bundle_fields peer_is_v1.
1164
+ // The literal sir_payload_v5_t shape: 0.5.0 stamps its wire dialect +
1165
+ // capability ids (SPEC §3/§4). Pre-0.5 inviters ignore both (unknown
1166
+ // fields — shipped, proven behavior).
706
1167
  payload = _write (
707
1168
  $ad -> (b $ad),
708
1169
  $cert -> (b $cert),
709
1170
  $root_profile -> (b $root_profile),
710
1171
  $cp_binding -> (b $cp_binding),
711
- $invite_id -> invite_id
1172
+ $invite_id -> invite_id,
1173
+ $name -> my_name,
1174
+ $pv -> a2a_versions::wire_version,
1175
+ $caps -> (a2a_capabilities::self_cap_ids NIL)
712
1176
  ).
713
1177
  data = _crypto_encrypt_message (kpr $secret_key) eph_pub_inviter payload.
714
1178
 
@@ -727,7 +1191,8 @@ library a2a_messaging loads libraries
727
1191
  $invite_id -> invite_id,
728
1192
  $epk -> (kpr $public_key),
729
1193
  $v -> scheme,
730
- $data -> data
1194
+ $data -> data,
1195
+ $pv -> a2a_versions::wire_version
731
1196
  )
732
1197
  ),
733
1198
  _return_data (
@@ -763,7 +1228,7 @@ library a2a_messaging loads libraries
763
1228
  return [
764
1229
  transaction::action::send target (
765
1230
  $name -> request_contact_restore_tx,
766
- $targ -> ($rid -> rid, $epk -> (kp $public_key), $v -> scheme)
1231
+ $targ -> ($rid -> rid, $epk -> (kp $public_key), $v -> scheme, $pv -> a2a_versions::wire_version)
767
1232
  )
768
1233
  ].
769
1234
  }
@@ -799,11 +1264,57 @@ library a2a_messaging loads libraries
799
1264
  return transaction::success actions.
800
1265
  }
801
1266
 
1267
+ // Phase D §5.6 — APP-DATA traffic barrier. Consult the route BEFORE the box send
1268
+ // (core is the single routing authority; the daemon obeys the verdict for its e2e
1269
+ // app-send path). Every non-legacy verdict is DATA, never an abort, never a silent box.
1270
+ route = e2e_route target_id.
1271
+ if route == "migrating"
1272
+ { // initiator commit window: QUEUE in mig_deferred (distinct from the restore
1273
+ // deferred_msgs), preserving per-contact order; flushed E2E on active. Bounded.
1274
+ mq is deferred_msg_t[] = [].
1275
+ mcur = mig_deferred target_id.
1276
+ if mcur != NIL { mq -> mcur?. }
1277
+ abort "Migration queue for this contact is full (" + (_str deferred_msgs_cap) + ") — commit window still open." when (_count mq|) >= deferred_msgs_cap.
1278
+ mq (_count mq|) -> ($text -> text, $wire_id -> wire_id, $reply_to -> reply_to, $date -> sent_date).
1279
+ mig_deferred target_id -> mq.
1280
+ return transaction::success [
1281
+ _return_data ($sent_to -> target_id, $wire_id -> wire_id, $deferred -> TRUE, $migrating -> TRUE, $queued -> (_count mq|)),
1282
+ _save_state NIL ].
1283
+ }
1284
+ if route == "downgrade_refused"
1285
+ { // epoch-pinned but no current v2 bundle: fail CLOSED (never box a migrated peer).
1286
+ // Recovery (re-offer over the carve-out) is driven by the migration sweep.
1287
+ return transaction::success [ _return_data ($sent_to -> target_id, $wire_id -> wire_id, $downgrade_refused -> TRUE, $code -> $e2e_downgrade_refused) ].
1288
+ }
1289
+ if route == "e2e" && (e2e_pinned target_id || (contact_e2e_epoch target_id) != NIL)
1290
+ { // KNOWN-E2E peer (epoch-pinned): CORE DELIVERS over the MIGRATED session (Option B —
1291
+ // the thin daemon has no transport, and a bare e2e envelope can't be action::send-ed).
1292
+ // encrypt_to advances m_sessions[cid] (the migrated session); the e2e ciphertext rides
1293
+ // a DISTINCT box (receive_e2e_message_tx) so the wire separates it from legacy plaintext.
1294
+ // A FRESH v2 contact (never pinned) falls through to the legacy box below (unchanged).
1295
+ epb = ((((peer_ads target_id)?) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
1296
+ einner = _write ( $text -> text, $wire_id -> wire_id, $reply_to -> reply_to, $pv -> a2a_versions::wire_version ).
1297
+ eenv = e2e::encrypt_to target_id einner epb.
1298
+ eacts is transaction::action::type[] = [
1299
+ encrypted_channel::send_encrypted_tx target_id (
1300
+ $name -> receive_e2e_message_tx,
1301
+ $targ -> ( $e2e_envelope -> (eenv $e2e_envelope), $emsignature -> (eenv $emsignature) ) ) ].
1302
+ sc on_message_sent ($target_id -> target_id, $text -> text, $date -> sent_date, $wire_id -> wire_id, $reply_to -> reply_to) -- ( -> a) { eacts (_count eacts|) -> a. }
1303
+ sc monitor_copy_actions "out" target_id sent_date text -- ( -> a) { eacts (_count eacts|) -> a. }
1304
+ // §4 observability: source $session_id from the ACTUAL envelope (NOT a re-read of
1305
+ // active_session_id — that would make the #1867 "session_id==pin" assertion CIRCULAR;
1306
+ // the real envelope id proves the app traversed the migrated session).
1307
+ eacts (_count eacts|) -> _notify_agent ( $event -> $e2e_app_send, $cid -> target_id, $session_id -> ((eenv $e2e_envelope) $session_id), $olm_type -> ((eenv $e2e_envelope) $olm_type), $wire_id -> wire_id ).
1308
+ eacts (_count eacts|) -> _return_data ($sent_to -> target_id, $wire_id -> wire_id, $route -> $e2e).
1309
+ eacts (_count eacts|) -> _save_state NIL.
1310
+ return transaction::success eacts.
1311
+ }
1312
+ // route == "legacy" (or a fresh-v2 "e2e", box legacy-allowed) -> unchanged box send below.
802
1313
  return encrypted_channel::execute_transaction target_id (fn (_) -> transaction::results::type {
803
1314
  actions is transaction::action::type[] = [
804
1315
  encrypted_channel::send_encrypted_tx target_id (
805
1316
  $name -> receive_message_tx,
806
- $targ -> ($text -> text, $wire_id -> wire_id, $reply_to -> reply_to)
1317
+ $targ -> ($text -> text, $wire_id -> wire_id, $reply_to -> reply_to, $pv -> a2a_versions::wire_version)
807
1318
  )
808
1319
  ].
809
1320
  sc on_message_sent ($target_id -> target_id, $text -> text, $date -> sent_date, $wire_id -> wire_id, $reply_to -> reply_to) -- ( -> a)
@@ -849,11 +1360,36 @@ library a2a_messaging loads libraries
849
1360
  mime_s is str = "".
850
1361
  if mime != NIL { mime_s -> mime safe str. }
851
1362
 
1363
+ // Phase D §5.6 — app-data barrier. Files NEVER queue (bulk binary); a non-legacy
1364
+ // route is a typed result telling the caller to retry (migrating) or that box is
1365
+ // refused (downgrade_refused) / to use e2e (daemon path). Never a silent box.
1366
+ froute = e2e_route target_id.
1367
+ if froute == "migrating"
1368
+ { return transaction::success [ _return_data ($sent_to -> target_id, $wire_id -> wire_id, $migrating -> TRUE, $code -> $e2e_migrating) ]. }
1369
+ if froute == "downgrade_refused"
1370
+ { return transaction::success [ _return_data ($sent_to -> target_id, $wire_id -> wire_id, $downgrade_refused -> TRUE, $code -> $e2e_downgrade_refused) ]. }
1371
+ if froute == "e2e" && (e2e_pinned target_id || (contact_e2e_epoch target_id) != NIL)
1372
+ { // CORE delivers the file over the MIGRATED session (Option B), boxed under a distinct name.
1373
+ fepb = ((((peer_ads target_id)?) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
1374
+ finner = _write ( $filename -> filename, $mime -> mime_s, $data -> data, $wire_id -> wire_id, $reply_to -> reply_to, $pv -> a2a_versions::wire_version ).
1375
+ fenv = e2e::encrypt_to target_id finner fepb.
1376
+ feacts is transaction::action::type[] = [
1377
+ encrypted_channel::send_encrypted_tx target_id (
1378
+ $name -> receive_e2e_file_tx,
1379
+ $targ -> ( $e2e_envelope -> (fenv $e2e_envelope), $emsignature -> (fenv $emsignature) ) ) ].
1380
+ 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) { feacts (_count feacts|) -> a. }
1381
+ sc monitor_copy_actions "out" target_id sent_date (file_monitor_summary filename mime_s data) -- ( -> a) { feacts (_count feacts|) -> a. }
1382
+ feacts (_count feacts|) -> _notify_agent ( $event -> $e2e_app_send, $cid -> target_id, $session_id -> ((fenv $e2e_envelope) $session_id), $olm_type -> ((fenv $e2e_envelope) $olm_type), $wire_id -> wire_id ).
1383
+ feacts (_count feacts|) -> _return_data ($sent_to -> target_id, $wire_id -> wire_id, $route -> $e2e).
1384
+ feacts (_count feacts|) -> _save_state NIL.
1385
+ return transaction::success feacts.
1386
+ }
1387
+ // route == "legacy" (or a fresh-v2 "e2e", box legacy-allowed) -> unchanged box send below.
852
1388
  return encrypted_channel::execute_transaction target_id (fn (_) -> transaction::results::type {
853
1389
  actions is transaction::action::type[] = [
854
1390
  encrypted_channel::send_encrypted_tx target_id (
855
1391
  $name -> receive_file_tx,
856
- $targ -> ($filename -> filename, $mime -> mime_s, $data -> data, $wire_id -> wire_id, $reply_to -> reply_to)
1392
+ $targ -> ($filename -> filename, $mime -> mime_s, $data -> data, $wire_id -> wire_id, $reply_to -> reply_to, $pv -> a2a_versions::wire_version)
857
1393
  )
858
1394
  ].
859
1395
  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)
@@ -1203,7 +1739,7 @@ library a2a_messaging loads libraries
1203
1739
  return transaction::success [
1204
1740
  encrypted_channel::send_encrypted_tx cp_cid (
1205
1741
  $name -> enroll_delegated_node_tx,
1206
- $targ -> ($child_ad -> child_ad, $delegation_cert -> cert_blob, $root_profile -> rp_blob)
1742
+ $targ -> ($child_ad -> child_ad, $delegation_cert -> cert_blob, $root_profile -> rp_blob, $pv -> a2a_versions::wire_version)
1207
1743
  ),
1208
1744
  _return_data ($enroll_relayed -> (_str cp_cid), $child -> (_str (child_ad $identity $container_id)))
1209
1745
  ].
@@ -1237,11 +1773,11 @@ library a2a_messaging loads libraries
1237
1773
  return [
1238
1774
  encrypted_channel::send_encrypted_tx a_id (
1239
1775
  $name -> ingest_connect_descriptor_tx,
1240
- $targ -> ($peer_ad -> ad_b, $peer_name -> name_b)
1776
+ $targ -> ($peer_ad -> ad_b, $peer_name -> name_b, $pv -> a2a_versions::wire_version)
1241
1777
  ),
1242
1778
  encrypted_channel::send_encrypted_tx b_id (
1243
1779
  $name -> ingest_connect_descriptor_tx,
1244
- $targ -> ($peer_ad -> ad_a, $peer_name -> name_a)
1780
+ $targ -> ($peer_ad -> ad_a, $peer_name -> name_a, $pv -> a2a_versions::wire_version)
1245
1781
  )
1246
1782
  ].
1247
1783
  }
@@ -1390,6 +1926,28 @@ library a2a_messaging loads libraries
1390
1926
  encrypted_channel::check_encrypted_or_abort().
1391
1927
 
1392
1928
  sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1929
+
1930
+ // --- 0.5.0 registry gate (acc) — BEFORE any strict read of the args.
1931
+ // The legacy redeem sibling of the sir gate: a version-incompatible
1932
+ // payload surfaces to the inviter as error-as-data (Addition A/B),
1933
+ // never an abort; the invite is NOT consumed.
1934
+ nr = a2a_versions::try_narrow_acc args.
1935
+ if (nr $ok) != TRUE
1936
+ {
1937
+ err = (nr $err)?.
1938
+ return transaction::success [
1939
+ _notify_agent (
1940
+ $event -> $protocol_error,
1941
+ $context -> $invite_redeem,
1942
+ $message -> invite_version_error_message err,
1943
+ $error -> err,
1944
+ $invite_id -> (args $invite_id),
1945
+ $peer_cid -> sender_id
1946
+ )
1947
+ ].
1948
+ }
1949
+ narrowed is a2a_versions::acc_args_t = (nr $payload)?.
1950
+
1393
1951
  invite_id = (args $invite_id) safe global_id.
1394
1952
  joiner_ad = (args $joiner_ad) safe address_document_types::t_address_document.
1395
1953
 
@@ -1416,7 +1974,10 @@ library a2a_messaging loads libraries
1416
1974
  contact_name is str = (invite_rec?) $assigned.
1417
1975
  if contact_name == ""
1418
1976
  {
1419
- joiner_self = (args $joiner_name) safe str.
1977
+ // REGISTRY DISPATCH replaces the strict $joiner_name read (the
1978
+ // sir incident's hygiene sibling): v3 returns the sent name; v2
1979
+ // has no such field and falls back to the sender cid.
1980
+ joiner_self = a2a_versions::acc_joiner_name narrowed.
1420
1981
  contact_name -> (joiner_self == "" ?? (_str sender_id) ; joiner_self).
1421
1982
  }
1422
1983
 
@@ -1442,6 +2003,9 @@ library a2a_messaging loads libraries
1442
2003
  }
1443
2004
 
1444
2005
  contacts sender_id -> ($name -> contact_name, $container_id -> sender_id).
2006
+ // Passive version learning: this legacy surface never carries $pv or
2007
+ // $caps — record the shape-inferred dialect (2 or 3).
2008
+ learn_contact_version sender_id (a2a_versions::acc_version_of args) [].
1445
2009
  // Remember the joiner's address document for upgrade-time re-registration.
1446
2010
  peer_ads sender_id -> joiner_ad.
1447
2011
  if joiner_root != NIL
@@ -1486,15 +2050,57 @@ library a2a_messaging loads libraries
1486
2050
  // box-open: aborts on tamper / wrong key BEFORE anything is consumed.
1487
2051
  payload = _read_or_abort (_crypto_decrypt_message eph_priv? epk_r ct).
1488
2052
 
2053
+ // --- 0.5.0 registry gate (BEFORE any strict read of the payload) ---
2054
+ // Dispatch on the peer's wire version and exact-cast to the registered
2055
+ // type (REG-4). A below-floor or unrecognized payload is the owner's
2056
+ // Addition A/B case: return the ERROR AS DATA to the INVITER via a
2057
+ // $protocol_error notify — transaction::success, NO abort, NO state
2058
+ // consumed (the invite stays redeemable: the peer can update and
2059
+ // redeem this same invite again). Crypto/tamper failures above and
2060
+ // identity-verification failures below remain HARD aborts by design.
2061
+ nr = a2a_versions::try_narrow_sir payload.
2062
+ if (nr $ok) != TRUE
2063
+ {
2064
+ err = (nr $err)?.
2065
+ return transaction::success [
2066
+ _notify_agent (
2067
+ $event -> $protocol_error,
2068
+ $context -> $invite_redeem,
2069
+ $message -> invite_version_error_message err,
2070
+ $error -> err,
2071
+ $invite_id -> invite_id,
2072
+ $peer_cid -> sender_id
2073
+ )
2074
+ ].
2075
+ }
2076
+ // `narrowed` is union-typed: backward compat is visible in this
2077
+ // binding's type; per-version reads go through the registry accessors.
2078
+ narrowed is a2a_versions::sir_payload_t = (nr $payload)?.
2079
+
2080
+ // Identity verification takes the RAW payload: narrow() rebuilds the
2081
+ // record to the registered fields, and verify must keep seeing exactly
2082
+ // what was sent (also future-proof for fields newer than we know).
1489
2083
  // D8 cid-bind + PoP self-sig, then the optional delegation chain — an
1490
2084
  // invalid chain or forged/inconsistent AD aborts before any write.
1491
2085
  vb = verify_identity_bundle payload sender_id.
1492
2086
 
1493
2087
  // --- all gates passed: register + single-use consume (INV-5) ---
1494
2088
  contact_name is str = (rec?) $assigned.
1495
- if contact_name == "" { contact_name -> (_str sender_id). }
2089
+ if contact_name == ""
2090
+ {
2091
+ // REGISTRY DISPATCH replaces the 0.3.0 strict read that caused the
2092
+ // incident ((payload $name) safe str on a NIL): the v3/v5 branches
2093
+ // return the sent $name; the v2 branch returns "" (no such field
2094
+ // in sir_payload_v2_t) and we fall back to the sender cid.
2095
+ joiner_name is str = a2a_versions::sir_joiner_name narrowed.
2096
+ contact_name -> (joiner_name == "" ?? (_str sender_id) ; joiner_name).
2097
+ }
1496
2098
  contacts sender_id -> ($name -> contact_name, $container_id -> sender_id).
2099
+ // Passive version learning (SPEC §3): dialect + piggybacked caps.
2100
+ learn_contact_version sender_id (a2a_versions::sir_version_of payload) (a2a_versions::sir_caps narrowed).
1497
2101
  peer_ads sender_id -> (vb $ad).
2102
+ // Born-on-DR iff the peer presented a v2 (bundle-carrying) AD at first contact.
2103
+ if (peer_has_e2e_bundle sender_id) { contact_born_dr sender_id -> TRUE. }
1498
2104
  if (vb $root) != NIL { contact_roots sender_id -> (vb $root)?. }
1499
2105
  if (vb $pin_binding) != NIL { contact_cp_bindings ((vb $pin_binding_root)?) -> (vb $pin_binding)?. }
1500
2106
  delete pending_invites invite_id.
@@ -1508,14 +2114,23 @@ library a2a_messaging loads libraries
1508
2114
  // inviter ephemeral; the responder opens it with the ephemeral private key it
1509
2115
  // kept. encrypted_channel resumes for all post-contact traffic, both sides
1510
2116
  // being registered after leg 3.
1511
- b = my_identity_bundle_fields NIL.
2117
+ // The responder's just-verified AD tells me its version directly: a v1 AD
2118
+ // ($version==1, no $e2e_bundle) is an old peer — down-level my leg-3 AD to v1
2119
+ // so it accepts my bundle. (leg 1 read the invite version blind; here I have
2120
+ // the real AD, so I key off it.)
2121
+ peer_is_v1 = (((vb $ad) $version) == 1).
2122
+ b = my_identity_bundle_fields peer_is_v1.
1512
2123
  kpi = _crypto_construct_encryption_keypair (rec? $scheme).
2124
+ // The literal cin_payload_v5_t shape ($pv/$caps; this surface never
2125
+ // carried $name). 0.2.0 responders ignore the additions.
1513
2126
  leg3_payload = _write (
1514
2127
  $ad -> (b $ad),
1515
2128
  $cert -> (b $cert),
1516
2129
  $root_profile -> (b $root_profile),
1517
2130
  $cp_binding -> (b $cp_binding),
1518
- $invite_id -> invite_id
2131
+ $invite_id -> invite_id,
2132
+ $pv -> a2a_versions::wire_version,
2133
+ $caps -> (a2a_capabilities::self_cap_ids NIL)
1519
2134
  ).
1520
2135
  leg3_data = _crypto_encrypt_message (kpi $secret_key) epk_r leg3_payload.
1521
2136
  return transaction::success [
@@ -1525,7 +2140,8 @@ library a2a_messaging loads libraries
1525
2140
  $invite_id -> invite_id,
1526
2141
  $epk -> (kpi $public_key),
1527
2142
  $v -> (rec? $scheme),
1528
- $data -> leg3_data
2143
+ $data -> leg3_data,
2144
+ $pv -> a2a_versions::wire_version
1529
2145
  )
1530
2146
  ),
1531
2147
  _notify_agent ($event -> $contact_accepted, $name -> contact_name, $container_id -> sender_id),
@@ -1558,6 +2174,27 @@ library a2a_messaging loads libraries
1558
2174
  // box-open with the kept responder ephemeral private key (aborts on tamper).
1559
2175
  payload = _read_or_abort (_crypto_decrypt_message eph_priv_r? epk_i ct).
1560
2176
 
2177
+ // --- 0.5.0 registry gate (cin) — error-as-data, never an abort ------
2178
+ // A version-incompatible completion surfaces to MY client as a
2179
+ // $protocol_error notify; the pending redemption stays (transient,
2180
+ // GC'd with the stores) so a corrected completion can still land.
2181
+ nr = a2a_versions::try_narrow_cin payload.
2182
+ if (nr $ok) != TRUE
2183
+ {
2184
+ err = (nr $err)?.
2185
+ return transaction::success [
2186
+ _notify_agent (
2187
+ $event -> $protocol_error,
2188
+ $context -> $invite_complete,
2189
+ $message -> ("An invite you redeemed was completed by an inviter running an unsupported protocol version. The contact was not added — ask them to update their client. (" + (err $message) + ")"),
2190
+ $error -> err,
2191
+ $invite_id -> invite_id,
2192
+ $peer_cid -> sender_id
2193
+ )
2194
+ ].
2195
+ }
2196
+ narrowed is a2a_versions::cin_payload_t = (nr $payload)?.
2197
+
1561
2198
  // D8 cid-bind + PoP self-sig, then the optional delegation chain — an
1562
2199
  // invalid chain or forged/inconsistent AD aborts before any write.
1563
2200
  vb = verify_identity_bundle payload sender_id.
@@ -1568,7 +2205,10 @@ library a2a_messaging loads libraries
1568
2205
  if contact_name == "" { contact_name -> (pend?) $inviter_name. }
1569
2206
  if contact_name == "" { contact_name -> (_str sender_id). }
1570
2207
  contacts sender_id -> ($name -> contact_name, $container_id -> sender_id).
2208
+ learn_contact_version sender_id (a2a_versions::cin_version_of payload) (a2a_versions::cin_caps narrowed).
1571
2209
  peer_ads sender_id -> (vb $ad).
2210
+ // Born-on-DR iff the peer presented a v2 (bundle-carrying) AD at first contact.
2211
+ if (peer_has_e2e_bundle sender_id) { contact_born_dr sender_id -> TRUE. }
1572
2212
  if (vb $root) != NIL { contact_roots sender_id -> (vb $root)?. }
1573
2213
  if (vb $pin_binding) != NIL { contact_cp_bindings ((vb $pin_binding_root)?) -> (vb $pin_binding)?. }
1574
2214
  delete pending_redemptions invite_id.
@@ -1627,15 +2267,17 @@ library a2a_messaging loads libraries
1627
2267
  pending_restore_reply_keys sender_id -> (kpr $secret_key).
1628
2268
 
1629
2269
  b = my_identity_bundle_fields NIL.
2270
+ // rst_payload_v5_t shape ($pv/$caps piggyback, SPEC §3/§4).
1630
2271
  payload = _write (
1631
2272
  $ad -> (b $ad), $cert -> (b $cert), $root_profile -> (b $root_profile),
1632
- $cp_binding -> (b $cp_binding), $rid -> rid
2273
+ $cp_binding -> (b $cp_binding), $rid -> rid,
2274
+ $pv -> a2a_versions::wire_version, $caps -> (a2a_capabilities::self_cap_ids NIL)
1633
2275
  ).
1634
2276
  data = _crypto_encrypt_message (kpr $secret_key) epk_requester payload.
1635
2277
  return transaction::success [
1636
2278
  transaction::action::send sender_id (
1637
2279
  $name -> submit_restore_response_tx,
1638
- $targ -> ($rid -> rid, $epk -> (kpr $public_key), $v -> scheme, $data -> data)
2280
+ $targ -> ($rid -> rid, $epk -> (kpr $public_key), $v -> scheme, $data -> data, $pv -> a2a_versions::wire_version)
1639
2281
  ),
1640
2282
  _save_state NIL
1641
2283
  ].
@@ -1671,10 +2313,32 @@ library a2a_messaging loads libraries
1671
2313
  scheme = (args $v) safe int.
1672
2314
  ct = (args $data) safe crypto_message.
1673
2315
  payload = _read_or_abort (_crypto_decrypt_message eph_priv? epk_r ct).
2316
+
2317
+ // --- 0.5.0 registry gate (rst) — error-as-data, never an abort ------
2318
+ // The degraded contact stays degraded (request not consumed: the boot
2319
+ // sweep re-attempts, and a corrected reply can still land).
2320
+ nr = a2a_versions::try_narrow_rst payload.
2321
+ if (nr $ok) != TRUE
2322
+ {
2323
+ err = (nr $err)?.
2324
+ return transaction::success [
2325
+ _notify_agent (
2326
+ $event -> $protocol_error,
2327
+ $context -> $contact_restore,
2328
+ $message -> ("A contact could not be restored: the peer runs an unsupported protocol version. Ask them to update their client. (" + (err $message) + ")"),
2329
+ $error -> err,
2330
+ $peer_cid -> sender_id
2331
+ )
2332
+ ].
2333
+ }
2334
+ narrowed is a2a_versions::rst_payload_t = (nr $payload)?.
2335
+
2336
+ // Post-gate the $rid domain is checked, so this strict read cannot abort.
1674
2337
  abort "Restore payload correlation mismatch." when ((payload $rid) safe global_id) != rid.
1675
2338
  vb = verify_identity_bundle payload sender_id.
1676
2339
 
1677
2340
  // --- all gates passed: (re)install the peer's keys + single-use consume ---
2341
+ learn_contact_version sender_id (a2a_versions::rst_version_of payload) (a2a_versions::rst_caps narrowed).
1678
2342
  peer_ads sender_id -> (vb $ad).
1679
2343
  if (vb $root) != NIL { contact_roots sender_id -> (vb $root)?. }
1680
2344
  if (vb $pin_binding) != NIL { contact_cp_bindings ((vb $pin_binding_root)?) -> (vb $pin_binding)?. }
@@ -1683,16 +2347,18 @@ library a2a_messaging loads libraries
1683
2347
 
1684
2348
  b = my_identity_bundle_fields NIL.
1685
2349
  kp2 = _crypto_construct_encryption_keypair scheme.
2350
+ // rst_payload_v5_t shape ($pv/$caps piggyback, SPEC §3/§4).
1686
2351
  leg2_payload = _write (
1687
2352
  $ad -> (b $ad), $cert -> (b $cert), $root_profile -> (b $root_profile),
1688
- $cp_binding -> (b $cp_binding), $rid -> rid
2353
+ $cp_binding -> (b $cp_binding), $rid -> rid,
2354
+ $pv -> a2a_versions::wire_version, $caps -> (a2a_capabilities::self_cap_ids NIL)
1689
2355
  ).
1690
2356
  leg2_data = _crypto_encrypt_message (kp2 $secret_key) epk_r leg2_payload.
1691
2357
  contact_name = ((contacts sender_id)?) $name.
1692
2358
  return transaction::success [
1693
2359
  transaction::action::send sender_id (
1694
2360
  $name -> complete_restore_tx,
1695
- $targ -> ($rid -> rid, $epk -> (kp2 $public_key), $v -> scheme, $data -> leg2_data)
2361
+ $targ -> ($rid -> rid, $epk -> (kp2 $public_key), $v -> scheme, $data -> leg2_data, $pv -> a2a_versions::wire_version)
1696
2362
  ),
1697
2363
  _notify_agent ($event -> $contact_restored, $name -> contact_name, $container_id -> sender_id),
1698
2364
  _save_state NIL
@@ -1726,10 +2392,30 @@ library a2a_messaging loads libraries
1726
2392
  epk_i = (args $epk) safe publickey_encrypt.
1727
2393
  ct = (args $data) safe crypto_message.
1728
2394
  payload = _read_or_abort (_crypto_decrypt_message eph_priv? epk_i ct).
2395
+
2396
+ // --- 0.5.0 registry gate (rst) — error-as-data, never an abort ------
2397
+ nr = a2a_versions::try_narrow_rst payload.
2398
+ if (nr $ok) != TRUE
2399
+ {
2400
+ err = (nr $err)?.
2401
+ return transaction::success [
2402
+ _notify_agent (
2403
+ $event -> $protocol_error,
2404
+ $context -> $contact_restore,
2405
+ $message -> ("A contact could not complete a key restore: the peer runs an unsupported protocol version. Ask them to update their client. (" + (err $message) + ")"),
2406
+ $error -> err,
2407
+ $peer_cid -> sender_id
2408
+ )
2409
+ ].
2410
+ }
2411
+ narrowed is a2a_versions::rst_payload_t = (nr $payload)?.
2412
+
2413
+ // Post-gate the $rid domain is checked, so this strict read cannot abort.
1729
2414
  abort "Restore payload correlation mismatch." when ((payload $rid) safe global_id) != rid.
1730
2415
  vb = verify_identity_bundle payload sender_id.
1731
2416
 
1732
2417
  // --- all gates passed: replace + single-use consume ---
2418
+ learn_contact_version sender_id (a2a_versions::rst_version_of payload) (a2a_versions::rst_caps narrowed).
1733
2419
  peer_ads sender_id -> (vb $ad).
1734
2420
  if (vb $root) != NIL { contact_roots sender_id -> (vb $root)?. }
1735
2421
  if (vb $pin_binding) != NIL { contact_cp_bindings ((vb $pin_binding_root)?) -> (vb $pin_binding)?. }
@@ -1832,7 +2518,7 @@ library a2a_messaging loads libraries
1832
2518
  {
1833
2519
  actions (_count actions|) -> encrypted_channel::send_encrypted_tx target_id (
1834
2520
  $name -> receive_message_tx,
1835
- $targ -> ($text -> (m $text), $wire_id -> (m $wire_id), $reply_to -> (m $reply_to))
2521
+ $targ -> ($text -> (m $text), $wire_id -> (m $wire_id), $reply_to -> (m $reply_to), $pv -> a2a_versions::wire_version)
1836
2522
  ).
1837
2523
  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
2524
  {
@@ -1874,6 +2560,14 @@ library a2a_messaging loads libraries
1874
2560
  reply_to is a2a_protocol::reply_ref_t+ = NIL.
1875
2561
  if (args $reply_to) != NIL { reply_to -> (args $reply_to) safe a2a_protocol::reply_ref_t. }
1876
2562
 
2563
+ // §5.7 RECEIVE-SIDE DOWNGRADE REFUSAL (MigrationReview — the receive-direction
2564
+ // confidentiality property). A legacy PLAINTEXT app message from an EPOCH-PINNED (migrated)
2565
+ // contact is a downgrade attempt: a migrated peer's app data MUST arrive over the e2e box
2566
+ // (receive_e2e_message). DROP it (never deliver to the app, no receipt) + a typed notify;
2567
+ // the migration sweep re-heals the session if the peer genuinely regressed. Pins UNTOUCHED.
2568
+ if (contact_e2e_epoch sender_id) != NIL
2569
+ { return transaction::success [ _notify_agent ($event -> $downgrade_refused, $cid -> sender_id, $wire_id -> wire_id) ]. }
2570
+
1877
2571
  sender = contacts sender_id.
1878
2572
  sender_name is str+ = NIL.
1879
2573
  if sender != NIL
@@ -1881,11 +2575,22 @@ library a2a_messaging loads libraries
1881
2575
  sender_name -> sender? $name.
1882
2576
  }
1883
2577
 
2578
+ // Passive version learning: only a STAMPED $pv is evidence (an
2579
+ // unstamped message says just "pre-0.5", which must not overwrite the
2580
+ // more precise dialect the invite/restore legs shape-inferred).
2581
+ pv_seen = a2a_versions::peer_pv args.
2582
+ if pv_seen != 0 { learn_contact_version sender_id pv_seen []. }
2583
+
1884
2584
  // The app hook owns storage; it may abort (unknown sender rejected) — in
1885
2585
  // which case nothing is delivered and no copy is emitted. When it accepts,
1886
2586
  // we append the FORCED inbound monitoring copy as core code (after the hook,
1887
2587
  // self-gating on monitoring_proxy) so the app cannot suppress it.
1888
2588
  actions is transaction::action::type[] = [].
2589
+ // NOTE (core 0.9.0): the §5.5 implicit-confirm evidence RELOCATED to handle_receive_e2e_
2590
+ // message — under Option B a responder's post-active app arrives on the DISTINCT e2e box,
2591
+ // not here. This legacy plaintext handler no longer promotes; an epoch-pinned sender is
2592
+ // already refused above (downgrade), and a still-migrating pair's plaintext is ordinary
2593
+ // pre-migration traffic.
1889
2594
  sc on_message_received (
1890
2595
  $sender_id -> sender_id,
1891
2596
  $sender_name -> sender_name,
@@ -1901,6 +2606,25 @@ library a2a_messaging loads libraries
1901
2606
  {
1902
2607
  actions (_count actions|) -> a.
1903
2608
  }
2609
+ // core 0.7.0: DELIVERED receipt, emitted atomically with acceptance
2610
+ // (the hook above may abort = message rejected = no receipt; from here
2611
+ // the message IS stored). Fire-and-forget; gated on positive caps;
2612
+ // pre-wire_id senders have no handle (and no cap) — nothing emitted.
2613
+ if wire_id != ""
2614
+ {
2615
+ sc receipt_actions sender_id "delivered" [wire_id] -- ( -> a)
2616
+ {
2617
+ actions (_count actions|) -> a.
2618
+ }
2619
+ }
2620
+ // §5.4 trigger: liveness offer on first 0.9 evidence from this peer (fires once — then
2621
+ // contact_migration is set and mig_trigger_actions returns []). _save_state persists it.
2622
+ trig is transaction::action::type[] = mig_trigger_actions sender_id.
2623
+ if (_count trig|) > 0
2624
+ {
2625
+ sc trig -- ( -> a) { actions (_count actions|) -> a. }
2626
+ actions (_count actions|) -> _save_state NIL.
2627
+ }
1904
2628
  return transaction::success actions.
1905
2629
  }
1906
2630
 
@@ -1929,6 +2653,11 @@ library a2a_messaging loads libraries
1929
2653
  reply_to is a2a_protocol::reply_ref_t+ = NIL.
1930
2654
  if (args $reply_to) != NIL { reply_to -> (args $reply_to) safe a2a_protocol::reply_ref_t. }
1931
2655
 
2656
+ // §5.7 RECEIVE-SIDE DOWNGRADE REFUSAL (file analogue): a legacy plaintext file from an
2657
+ // epoch-PINNED contact is a downgrade attempt — drop + typed notify, never delivered.
2658
+ if (contact_e2e_epoch sender_id) != NIL
2659
+ { return transaction::success [ _notify_agent ($event -> $downgrade_refused, $cid -> sender_id, $wire_id -> wire_id) ]. }
2660
+
1932
2661
  sender = contacts sender_id.
1933
2662
  sender_name is str+ = NIL.
1934
2663
  if sender != NIL
@@ -1936,6 +2665,10 @@ library a2a_messaging loads libraries
1936
2665
  sender_name -> sender? $name.
1937
2666
  }
1938
2667
 
2668
+ // Passive version learning (see handle_receive_message).
2669
+ pv_seen = a2a_versions::peer_pv args.
2670
+ if pv_seen != 0 { learn_contact_version sender_id pv_seen []. }
2671
+
1939
2672
  actions is transaction::action::type[] = [].
1940
2673
  sc on_file_received (
1941
2674
  $sender_id -> sender_id,
@@ -1954,6 +2687,14 @@ library a2a_messaging loads libraries
1954
2687
  {
1955
2688
  actions (_count actions|) -> a.
1956
2689
  }
2690
+ // core 0.7.0: DELIVERED receipt (files share the wire_id namespace).
2691
+ if wire_id != ""
2692
+ {
2693
+ sc receipt_actions sender_id "delivered" [wire_id] -- ( -> a)
2694
+ {
2695
+ actions (_count actions|) -> a.
2696
+ }
2697
+ }
1957
2698
  return transaction::success actions.
1958
2699
  }
1959
2700
 
@@ -1962,6 +2703,862 @@ library a2a_messaging loads libraries
1962
2703
  return handle_receive_file args.
1963
2704
  }
1964
2705
 
2706
+ // Shared helpers for the two app-e2e RECEIVE handlers (message + file). FACTORED so the
2707
+ // meta-heavy record literals — the $e2e_app_recv notify, the implicit-confirm contact_migration
2708
+ // write + $migration_active notify — are type-reduced ONCE, not inlined in both handlers: the
2709
+ // full daemon packet compiles the migration surface near the per-unit meta-fuel ceiling, and the
2710
+ // duplicated inlines pushed it over (see the transaction/AD any-typing fixes). Behavior is
2711
+ // byte-identical to the inlined form.
2712
+ // A rejected inbound (no-downgrade GATE0 / accept-gate / decode !ok): $e2e_app_recv $ok=FALSE,
2713
+ // never delivered. $session_id is the inbound envelope's (NIL for a malformed GATE0 envelope).
2714
+ fn mig_e2e_reject (sender_id: global_id, env_sid: bin+) -> transaction::results::type
2715
+ {
2716
+ return transaction::success [ _notify_agent ($event -> $e2e_app_recv, $cid -> sender_id, $session_id -> env_sid, $ok -> FALSE, $wire_id -> "") ].
2717
+ }
2718
+ // Shared ACCEPT-gate + do_ic computation for the two app-e2e RECEIVE handlers. Returns
2719
+ // ($accept, $do_ic). accept = e2e_pinned/seen OR committed-initiator-with-staged-match. do_ic
2720
+ // (§5.5 must-fix-C) is DECOUPLED — a box-only committed initiator (staged==committed session, NO
2721
+ // live session, NOT yet epoch-pinned) even when seen, so implicit-confirm stays reachable in
2722
+ // production (a real migrating pair advertises cap_e2e ⇒ seen by `committed`).
2723
+ fn mig_e2e_accept (sender_id: global_id) -> (any)
2724
+ {
2725
+ st = contact_migration sender_id.
2726
+ committed_match is bool = FALSE.
2727
+ do_ic is bool = FALSE.
2728
+ if st != NIL && ((st?) $phase) == "committed" && ((st?) $initiator) == TRUE
2729
+ {
2730
+ staged_sid = e2e::staged_session_id sender_id.
2731
+ if staged_sid != NIL && ((st?) $session_id) != NIL && staged_sid == ((st?) $session_id)
2732
+ {
2733
+ committed_match -> TRUE.
2734
+ if (e2e::active_session_id sender_id) == NIL && (contact_e2e_epoch sender_id) == NIL { do_ic -> TRUE. }
2735
+ }
2736
+ }
2737
+ return ($accept -> (committed_match || (e2e_pinned sender_id)), $do_ic -> do_ic).
2738
+ }
2739
+ // §5.5 must-fix-C IMPLICIT-CONFIRM promotion (box-only committed initiator → active): commit_
2740
+ // rotation (SOLE promotion) + BOTH pins + active + EXTENDED $migration_active + flush, returned
2741
+ // as actions to append BEFORE the deliver hook so the whole thing rides the app hook's tx (an
2742
+ // abort rolls promotion + pins + flush back and the FSM stays `committed`).
2743
+ fn mig_e2e_promote_actions (sender_id: global_id, st: mig_state_t) -> transaction::action::type[]
2744
+ {
2745
+ e2e::commit_rotation sender_id.
2746
+ ic_fin = e2e::active_session_id sender_id.
2747
+ ic_ep = (st $epoch)?.
2748
+ contact_e2e_epoch sender_id -> ( $epoch -> ic_ep, $session_id -> (ic_fin?) ).
2749
+ contact_e2e_seen sender_id -> TRUE.
2750
+ ic_now = (current_transaction_info::get_transaction_time())?.
2751
+ contact_migration sender_id -> ( $phase -> "active", $initiator -> TRUE,
2752
+ $local_nonce -> (st $local_nonce), $peer_nonce -> (st $peer_nonce), $epoch -> ic_ep, $session_id -> (ic_fin?),
2753
+ $local_bundle -> (st $local_bundle), $local_fp -> (st $local_fp), $attempts -> (st $attempts), $updated -> ic_now ).
2754
+ acts is transaction::action::type[] = [ _notify_agent ($event -> $migration_active, $cid -> sender_id, $role -> $initiator, $epoch -> ic_ep, $session_id -> (ic_fin?)) ].
2755
+ sc flush_mig_deferred_actions sender_id -- ( -> a) { acts (_count acts|) -> a. }
2756
+ return acts.
2757
+ }
2758
+ // Delivery tail shared by both handlers: DELIVERED receipt (gated on a wire_id) + the §4
2759
+ // $e2e_app_recv notify (session_id from the ACTUAL inbound envelope, non-circular #1867 proof) +
2760
+ // _save_state (the e2e decode advanced the ratchet — persist unconditionally on the accept path).
2761
+ fn mig_e2e_deliver_tail (sender_id: global_id, wire_id: str, env_sid: bin+) -> transaction::action::type[]
2762
+ {
2763
+ acts is transaction::action::type[] = [].
2764
+ if wire_id != ""
2765
+ { sc receipt_actions sender_id "delivered" [wire_id] -- ( -> a) { acts (_count acts|) -> a. } }
2766
+ acts (_count acts|) -> _notify_agent ($event -> $e2e_app_recv, $cid -> sender_id, $session_id -> env_sid, $ok -> TRUE, $wire_id -> wire_id).
2767
+ acts (_count acts|) -> _save_state NIL.
2768
+ return acts.
2769
+ }
2770
+
2771
+ // ── core 0.9.0 boxed APP-E2E RECEIVE (Option B, spec §5.6/§4). App data over a MIGRATED
2772
+ // session rides a DISTINCT box (receive_e2e_message_tx) carrying the e2e_signed_message as
2773
+ // $targ. THIS handler drives the same audited decode the commit/confirm handlers use
2774
+ // (e2e::decode_migration_envelope: S2 wire-pv, S1 emsig over $from/$to/$envelope bound to the
2775
+ // box sender + me, then decrypt+commit on the migrated session), delivers the plaintext to the
2776
+ // app hook, and — for the §5.5 box-only committed-initiator window — folds in the IMPLICIT
2777
+ // CONFIRM (relocated here from the legacy handler). SECURITY invariants (MigrationReview #27):
2778
+ // • no-downgrade: a missing/garbage e2e envelope FAILS closed (never a legacy/plaintext read);
2779
+ // • ACCEPT-gate: deliver ONLY from an epoch-PINNED contact OR a committed-initiator whose
2780
+ // staged rotation IS the committed session (an unpinned peer never reaches the decrypt);
2781
+ // • authenticated decode: $from == box sender, forged emsig/wire ABORTS inside the decode;
2782
+ // • no plaintext leak: the decrypted body is delivered ONLY through on_message_received;
2783
+ // • must-fix-C: implicit-confirm promotion + pins + flush ride the SAME tx as the app hook —
2784
+ // if the hook ABORTS, they all roll back and the FSM stays `committed`.
2785
+ // §4 observability: $e2e_app_recv $session_id is sourced from the ACTUAL inbound envelope (NOT
2786
+ // a re-read of active_session_id — that would make the #1867 "session_id == pin" check circular).
2787
+ fn handle_receive_e2e_message (args: any) -> transaction::results::type
2788
+ {
2789
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
2790
+ encrypted_channel::check_encrypted_or_abort().
2791
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
2792
+ msg_date = (current_transaction_info::get_transaction_time())?.
2793
+
2794
+ // GATE 0 — carrier shape (no-downgrade: fail CLOSED on a missing/garbage envelope).
2795
+ env is e2e::t_e2e_envelope+ = (args $e2e_envelope) safe e2e::t_e2e_envelope.
2796
+ emsig is crypto_signature+ = (args $emsignature) safe crypto_signature.
2797
+ if env == NIL || emsig == NIL { return mig_e2e_reject sender_id NIL. }
2798
+ env_sid = (env? $session_id).
2799
+
2800
+ // GATE 1 — ACCEPT gate. The SEND side boxes app as receive_e2e_message_tx whenever the route
2801
+ // is "e2e" AND the peer is (seen || epoch-pinned) — EVERY e2e-capable pair, not just migrated
2802
+ // ones (an already-E2E pre-migration pair rides the e2e box too). ACCEPT from any e2e_pinned/
2803
+ // seen contact OR a committed INITIATOR whose STAGED rotation is the committed session (the
2804
+ // responder's post-active app arriving BEFORE our explicit confirm). Any other state → reject
2805
+ // as data, NEVER decode (no session mutation from a non-e2e peer). BROADER than the §5.7
2806
+ // downgrade-refusal (epoch-only): a seen-not-epoch peer's LEGACY plaintext is still accepted.
2807
+ // do_ic (§5.5 must-fix-C IMPLICIT CONFIRM) is computed on its OWN merits (see mig_e2e_accept),
2808
+ // DECOUPLED from the accept branch — else it would be UNREACHABLE in production (a real
2809
+ // migrating pair is `seen` by `committed`).
2810
+ g = mig_e2e_accept sender_id.
2811
+ if (g $accept) != TRUE { return mig_e2e_reject sender_id env_sid. }
2812
+ do_ic is bool = (g $do_ic).
2813
+
2814
+ // GATE 1.5 — the box sender's VERIFIED AD is required to authenticate the envelope.
2815
+ pad = peer_ads sender_id.
2816
+ if pad == NIL { return mig_e2e_reject sender_id env_sid. }
2817
+
2818
+ // GATE 2 — handler-driven AUTHENTICATED decode (shared audited path). For a pinned/active
2819
+ // contact mig_pending is FALSE → decrypt_and_commit advances m_sessions[cid] (the migrated
2820
+ // session). For the do_ic box-only committed initiator, the responder's post-active
2821
+ // olm_type=1 rides the STAGED slot (m_sessions still NIL until commit_rotation in the
2822
+ // promote helper). A !ok is OLM-level (tampered/replay) — forged emsig/wire already ABORTED
2823
+ // inside decode_migration_envelope. Reject-as-data, never delivered.
2824
+ r = e2e::decode_migration_envelope sender_id (_get_container_id()) (pad?) (env?) (emsig?).
2825
+ if (r $ok) != TRUE { return mig_e2e_reject sender_id env_sid. }
2826
+ // Decrypted inner app body (mirrors send_message's einner _write shape).
2827
+ iv = key_storage::read_external ((r $plaintext)?).
2828
+ text = (iv $text) safe str.
2829
+ wire_id is str = "".
2830
+ if (iv $wire_id) != NIL { wire_id -> (iv $wire_id) safe str. }
2831
+ reply_to is a2a_protocol::reply_ref_t+ = NIL.
2832
+ if (iv $reply_to) != NIL { reply_to -> (iv $reply_to) safe a2a_protocol::reply_ref_t. }
2833
+
2834
+ actions is transaction::action::type[] = [].
2835
+ // do_ic: promote BEFORE deliver, SAME tx (must-fix-C rollback — see mig_e2e_promote_actions).
2836
+ if do_ic { sc mig_e2e_promote_actions sender_id ((contact_migration sender_id)?) -- ( -> a) { actions (_count actions|) -> a. } }
2837
+
2838
+ sender = contacts sender_id.
2839
+ sender_name is str+ = NIL.
2840
+ if sender != NIL { sender_name -> sender? $name. }
2841
+ // Deliver plaintext through the app hook (the ONLY exit for the decrypted body). It may ABORT
2842
+ // (unknown sender / rejected) — then nothing is delivered, the do_ic promotion rolls back, and
2843
+ // no receipt/notify is emitted (the tx is atomic).
2844
+ sc on_message_received (
2845
+ $sender_id -> sender_id,
2846
+ $sender_name -> sender_name,
2847
+ $text -> text,
2848
+ $date -> msg_date,
2849
+ $wire_id -> wire_id,
2850
+ $reply_to -> reply_to
2851
+ ) -- ( -> a) { actions (_count actions|) -> a. }
2852
+ sc monitor_copy_actions "in" sender_id msg_date text -- ( -> a) { actions (_count actions|) -> a. }
2853
+ sc mig_e2e_deliver_tail sender_id wire_id env_sid -- ( -> a) { actions (_count actions|) -> a. }
2854
+ // §5.4 trigger (the PRODUCTION-GAP fix): an already-e2e pair receives app data HERE (it never
2855
+ // plaintext-receives), so mirror the plaintext-handler liveness offer. Fires once — then
2856
+ // contact_migration!=NIL (+ the epoch pin) gate it. Reads STORED contact_caps/pv (no re-learn).
2857
+ // do_ic (committed) and the trigger are mutually exclusive (do_ic ⇒ contact_migration!=NIL ⇒
2858
+ // mig_should_trigger FALSE), so this never interacts with the implicit-confirm promotion above.
2859
+ trig is transaction::action::type[] = mig_trigger_actions sender_id.
2860
+ if (_count trig|) > 0
2861
+ {
2862
+ sc trig -- ( -> a) { actions (_count actions|) -> a. }
2863
+ actions (_count actions|) -> _save_state NIL.
2864
+ }
2865
+ return transaction::success actions.
2866
+ }
2867
+
2868
+ trn receive_e2e_message args: any
2869
+ {
2870
+ return handle_receive_e2e_message args.
2871
+ }
2872
+
2873
+ // File analogue of handle_receive_e2e_message — same decode/accept-gate/implicit-confirm/
2874
+ // downgrade discipline; delivers to on_file_received. Files ride the migrated session identically.
2875
+ fn handle_receive_e2e_file (args: any) -> transaction::results::type
2876
+ {
2877
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
2878
+ encrypted_channel::check_encrypted_or_abort().
2879
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
2880
+ file_date = (current_transaction_info::get_transaction_time())?.
2881
+
2882
+ // GATE 0 — carrier shape (no-downgrade).
2883
+ env is e2e::t_e2e_envelope+ = (args $e2e_envelope) safe e2e::t_e2e_envelope.
2884
+ emsig is crypto_signature+ = (args $emsignature) safe crypto_signature.
2885
+ if env == NIL || emsig == NIL { return mig_e2e_reject sender_id NIL. }
2886
+ env_sid = (env? $session_id).
2887
+
2888
+ // GATE 1 — ACCEPT gate + do_ic (shared with the message handler; do_ic decoupled).
2889
+ g = mig_e2e_accept sender_id.
2890
+ if (g $accept) != TRUE { return mig_e2e_reject sender_id env_sid. }
2891
+ do_ic is bool = (g $do_ic).
2892
+
2893
+ pad = peer_ads sender_id.
2894
+ if pad == NIL { return mig_e2e_reject sender_id env_sid. }
2895
+
2896
+ // GATE 2 — authenticated decode.
2897
+ r = e2e::decode_migration_envelope sender_id (_get_container_id()) (pad?) (env?) (emsig?).
2898
+ if (r $ok) != TRUE { return mig_e2e_reject sender_id env_sid. }
2899
+ // Decrypted inner file body (mirrors send_file's finner _write shape).
2900
+ iv = key_storage::read_external ((r $plaintext)?).
2901
+ filename = (iv $filename) safe str.
2902
+ data = (iv $data) safe bin.
2903
+ mime is str = "".
2904
+ if (iv $mime) != NIL { mime -> (iv $mime) safe str. }
2905
+ wire_id is str = "".
2906
+ if (iv $wire_id) != NIL { wire_id -> (iv $wire_id) safe str. }
2907
+ reply_to is a2a_protocol::reply_ref_t+ = NIL.
2908
+ if (iv $reply_to) != NIL { reply_to -> (iv $reply_to) safe a2a_protocol::reply_ref_t. }
2909
+
2910
+ actions is transaction::action::type[] = [].
2911
+ if do_ic { sc mig_e2e_promote_actions sender_id ((contact_migration sender_id)?) -- ( -> a) { actions (_count actions|) -> a. } }
2912
+
2913
+ sender = contacts sender_id.
2914
+ sender_name is str+ = NIL.
2915
+ if sender != NIL { sender_name -> sender? $name. }
2916
+ sc on_file_received (
2917
+ $sender_id -> sender_id,
2918
+ $sender_name -> sender_name,
2919
+ $filename -> filename,
2920
+ $mime -> mime,
2921
+ $data -> data,
2922
+ $date -> file_date,
2923
+ $wire_id -> wire_id,
2924
+ $reply_to -> reply_to
2925
+ ) -- ( -> a) { actions (_count actions|) -> a. }
2926
+ sc monitor_copy_actions "in" sender_id file_date (file_monitor_summary filename mime data) -- ( -> a) { actions (_count actions|) -> a. }
2927
+ sc mig_e2e_deliver_tail sender_id wire_id env_sid -- ( -> a) { actions (_count actions|) -> a. }
2928
+ // §5.4 trigger (the PRODUCTION-GAP fix, _file analogue of the message handler): an already-e2e
2929
+ // pair receiving a FILE over e2e must also auto-offer. Fires once; contact_migration!=NIL (+ epoch
2930
+ // pin) gate it; do_ic and the trigger stay mutually exclusive (see handle_receive_e2e_message).
2931
+ trig is transaction::action::type[] = mig_trigger_actions sender_id.
2932
+ if (_count trig|) > 0
2933
+ {
2934
+ sc trig -- ( -> a) { actions (_count actions|) -> a. }
2935
+ actions (_count actions|) -> _save_state NIL.
2936
+ }
2937
+ return transaction::success actions.
2938
+ }
2939
+
2940
+ trn receive_e2e_file args: any
2941
+ {
2942
+ return handle_receive_e2e_file args.
2943
+ }
2944
+
2945
+ // core 0.7.0: receipt ingest — a peer confirms delivery/read of messages I
2946
+ // sent. TOLERANT AND NEVER LOAD-BEARING: content problems are ignored
2947
+ // (success no-op) — an unknown $kind is a future receipt kind (forward
2948
+ // compat), an unparseable payload is dropped, unknown wire_ids are the
2949
+ // hook's business (messages GC). Only channel/origin violations abort.
2950
+ // NO receipt is ever emitted for a receipt (terminal surface, no recursion).
2951
+ fn handle_receive_receipt (args: any) -> transaction::results::type
2952
+ {
2953
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
2954
+ encrypted_channel::check_encrypted_or_abort().
2955
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
2956
+
2957
+ // Unknown senders: silent success (best-effort surface, no probe oracle).
2958
+ if (contacts sender_id) == NIL { return transaction::success []. }
2959
+ // Registry classification (rcp, M1 abort-free): bad shape => ignore.
2960
+ if a2a_versions::rcp_shape_ok args != TRUE { return transaction::success []. }
2961
+ kind = (args $kind) safe str.
2962
+ if kind != "delivered" && kind != "read" { return transaction::success []. }
2963
+
2964
+ // Tolerant per-element wire_id extraction (mistyped entries skipped).
2965
+ ids is str[] = [].
2966
+ sc (args $wire_ids) -- ( -> w)
2967
+ {
2968
+ if w != NIL && (_typeof w) == "STRING" { ids (_count ids|) -> (w safe str). }
2969
+ }
2970
+ if (_count ids|) == 0 { return transaction::success []. }
2971
+
2972
+ rdate is time+ = NIL.
2973
+ if (args $date) != NIL && (_typeof (args $date)) == "TIME" { rdate -> (args $date) safe time. }
2974
+
2975
+ pv_seen = a2a_versions::peer_pv args.
2976
+ if pv_seen != 0 { learn_contact_version sender_id pv_seen []. }
2977
+
2978
+ actions is transaction::action::type[] = [].
2979
+ sc on_receipt_received (
2980
+ $sender_id -> sender_id,
2981
+ $kind -> kind,
2982
+ $wire_ids -> ids,
2983
+ $date -> rdate
2984
+ ) -- ( -> a)
2985
+ {
2986
+ actions (_count actions|) -> a.
2987
+ }
2988
+ return transaction::success actions.
2989
+ }
2990
+
2991
+ trn receive_receipt args: any
2992
+ {
2993
+ return handle_receive_receipt args.
2994
+ }
2995
+
2996
+ // ---- core 0.9.0 E2E-migration handlers (spec §5.4) -----------------------
2997
+ // STRICT GATE LADDER, error-as-data: narrow -> verify_identity_bundle (forgery
2998
+ // ABORTS by design) -> bundle-presence -> election-collapse/solicitation ->
2999
+ // nonce/epoch -> WRITES LAST. No abort is reachable from a well-formed-but-wrong
3000
+ // payload; only cryptographic/identity forgery aborts (verify_identity_bundle).
3001
+ // Both legs ride the legacy encrypted_channel (origin::external + check_encrypted).
3002
+ fn handle_e2e_migrate_offer (args: any) -> transaction::results::type
3003
+ {
3004
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
3005
+ encrypted_channel::check_encrypted_or_abort().
3006
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
3007
+ // GATE 1 — narrow (error-as-data).
3008
+ nr = a2a_versions::try_narrow_mgb args.
3009
+ if (nr $ok) != TRUE
3010
+ { return transaction::success [ _notify_agent ($event -> $protocol_error, $context -> $e2e_migrate_offer, $message -> (((nr $err)?) $message), $error -> (nr $err)?, $peer_cid -> sender_id) ]. }
3011
+ p = (nr $payload)?.
3012
+ // GATE 2 — verify identity bundle (cid-bind + PoP + optional chain). FORGERY
3013
+ // ABORTS here (by design); also refreshes peer_ads via process_address_document.
3014
+ vb = verify_identity_bundle (p as any) sender_id.
3015
+ // GATE 3 — bundle presence: the peer claims migration, so its verified AD MUST
3016
+ // carry an $e2e_bundle; otherwise a typed refusal (error-as-data, no state write).
3017
+ if (((vb $ad) as any) $identity $e2e_bundle) == NIL
3018
+ { return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $peer_offered_without_e2e_bundle) ]. }
3019
+ // This offer/ack exchange IS the missing caps/AD refresh — learn the piggyback AND install the
3020
+ // refreshed AD. Storing peer_ads here is REQUIRED for a pre-existing legacy contact whose stored
3021
+ // AD is still v1 (no $e2e_bundle): the epoch/decode below reads the peer bundle off peer_ads, so
3022
+ // without this refresh a legacy upgrade would fail the bundle cast. Idempotent for an already-v2 peer.
3023
+ pv_seen = a2a_versions::peer_pv args.
3024
+ learn_contact_version sender_id ((pv_seen != 0 ?? pv_seen ; 9)) (((p $caps) == NIL ?? [] ; (p $caps)?)).
3025
+ peer_ads sender_id -> (vb $ad).
3026
+ // GATE 4 — election collapse / solicitation. If the offer came from the HIGHER
3027
+ // cid (mig_initiator sender_id TRUE => I am the elected LOWER-cid initiator), it
3028
+ // is a SOLICITATION: keep the AD/caps refresh above, supersede any of my own
3029
+ // offered state, and (re)emit MY authoritative offer — do NOT ack.
3030
+ if (mig_initiator sender_id) == TRUE
3031
+ {
3032
+ // EXHAUSTIVE-PHASE NO-OP (MigrationReview): a stale/late higher-cid solicitation must NOT
3033
+ // restart a migration that already progressed past negotiation. At committed I hold the
3034
+ // agreed epoch; at active the epoch PIN is set. Re-emitting `offered` here would diverge
3035
+ // contact_migration from the pin. Mirror the ACK-path's committed/active early-return
3036
+ // (only a genuinely new nonce/epoch AFTER active drives §5.6 re-rotation, handled elsewhere).
3037
+ sol_prev = contact_migration sender_id.
3038
+ if sol_prev != NIL && (((sol_prev?) $phase) == "committed" || ((sol_prev?) $phase) == "active")
3039
+ { return transaction::success []. }
3040
+ solicit is transaction::action::type[] = mig_offer_actions sender_id.
3041
+ solicit (_count solicit|) -> _save_state NIL.
3042
+ return transaction::success solicit.
3043
+ }
3044
+ // Otherwise the offer came from the LOWER (elected) cid: proceed to ACK,
3045
+ // abandoning any competing proposal of mine (deterministic collapse).
3046
+ offer_nonce = (p $nonce) safe bin.
3047
+ // §5.4-5 IDEMPOTENCY / retransmit reproducibility: a REDELIVERED offer (SAME nonce —
3048
+ // broker dup or the initiator's sweep retransmit) must re-send the STORED ack
3049
+ // byte-identically from the snapshot — NEVER recompute a fresh nonce/epoch, which
3050
+ // would diverge from the epoch the initiator already holds from the first ack. First
3051
+ // verify my snapshot fp still matches my LIVE produce-path bundle; on mismatch (my
3052
+ // bundle rotated since acknowledging) supersede with a fresh nonce/epoch instead of
3053
+ // re-sending a stale ack under the same nonce.
3054
+ prev = contact_migration sender_id.
3055
+ // §5.6 / exhaustive phase handling: a redelivered offer AFTER the migration already
3056
+ // progressed to committed/active is an idempotent NO-OP — never restart the FSM. Only a
3057
+ // genuinely new agreement after `active` (a NEW nonce/epoch, epoch-pinned) triggers §5.6
3058
+ // re-rotation recovery (phase D/E); a stale same-nonce redeliver here is a late duplicate.
3059
+ if prev != NIL && (((prev?) $phase) == "committed" || ((prev?) $phase) == "active")
3060
+ { return transaction::success []. }
3061
+ if prev != NIL && ((prev?) $phase) == "acknowledged" && ((prev?) $peer_nonce) != NIL && ((prev?) $peer_nonce) == offer_nonce
3062
+ {
3063
+ live_fp = e2e_bundle_fp (address_document::produce_my_address_document()).
3064
+ if ((prev?) $local_fp) != NIL && ((prev?) $local_bundle) != NIL && live_fp == ((prev?) $local_fp)?
3065
+ {
3066
+ // Byte-identical re-send from the snapshot — NO state write, NO _save_state.
3067
+ rs = _read_or_abort (((prev?) $local_bundle)?).
3068
+ return transaction::success [
3069
+ encrypted_channel::send_encrypted_tx sender_id (
3070
+ $name -> e2e_migrate_ack_tx,
3071
+ $targ -> ( $ad -> (rs $ad), $cert -> (rs $cert), $root_profile -> (rs $root_profile),
3072
+ $cp_binding -> (rs $cp_binding), $nonce -> ((prev?) $local_nonce), $peer_nonce -> offer_nonce,
3073
+ $pv -> a2a_versions::wire_version, $caps -> (a2a_capabilities::self_cap_ids NIL) ) ) ].
3074
+ }
3075
+ // else: my bundle rotated since acknowledging — fall through to supersede below.
3076
+ }
3077
+ // GATE 5 — nonce/epoch (first offer, a NEW nonce that supersedes, or supersession after
3078
+ // an fp mismatch). Snapshot my fresh bundle, compute the shared epoch.
3079
+ b = my_identity_bundle_fields_fresh NIL.
3080
+ lb = _write ( $ad -> (b $ad), $cert -> (b $cert), $root_profile -> (b $root_profile), $cp_binding -> (b $cp_binding) ).
3081
+ my_fp = e2e_bundle_fp (b $ad).
3082
+ peer_fp = e2e_bundle_fp (vb $ad).
3083
+ my_n = _hash_code_to_binary (_value_id (_new_id "ours e2e migration")).
3084
+ now = (current_transaction_info::get_transaction_time())?.
3085
+ // cid-ordered: sender (elected initiator) is the LOWER cid; I am the HIGHER.
3086
+ epoch = mig_epoch sender_id (_get_container_id()) offer_nonce my_n peer_fp my_fp.
3087
+ // WRITES LAST — persist acknowledged WITH my snapshot, in the SAME tx as the ack send.
3088
+ contact_migration sender_id -> ( $phase -> "acknowledged", $initiator -> FALSE,
3089
+ $local_nonce -> my_n, $peer_nonce -> offer_nonce, $epoch -> epoch, $session_id -> NIL,
3090
+ $local_bundle -> lb, $local_fp -> my_fp, $attempts -> 1, $updated -> now ).
3091
+ s = _read_or_abort lb.
3092
+ return transaction::success [
3093
+ encrypted_channel::send_encrypted_tx sender_id (
3094
+ $name -> e2e_migrate_ack_tx,
3095
+ $targ -> ( $ad -> (s $ad), $cert -> (s $cert), $root_profile -> (s $root_profile),
3096
+ $cp_binding -> (s $cp_binding), $nonce -> my_n, $peer_nonce -> offer_nonce,
3097
+ $pv -> a2a_versions::wire_version, $caps -> (a2a_capabilities::self_cap_ids NIL) ) ),
3098
+ _notify_agent ($event -> $migration_started, $cid -> sender_id, $role -> $responder),
3099
+ _save_state NIL ].
3100
+ }
3101
+ trn e2e_migrate_offer args: any { return handle_e2e_migrate_offer args. }
3102
+
3103
+ // core 0.10 (B1): RE-ADVERTISE handler. A contact that has upgraded to v2 pushes its fresh
3104
+ // AD (with $e2e_bundle + the caps piggyback) to me. This is a STATELESS refresh — unlike a
3105
+ // migration offer it creates NO FSM state, so a still-v1 peer that never sends one is never
3106
+ // left with a stalled `offered` entry that would permanently block a later genuine upgrade. I
3107
+ // verify + ingest the AD (refreshes peer_ads + learns caps/pv), then nudge the migration
3108
+ // trigger: if this is a still-legacy contact I now know is v2 (and it carries a bundle),
3109
+ // mig_trigger_actions elects the initiator and emits the authoritative offer, and the existing
3110
+ // offer/ack/commit/confirm FSM upgrades the pre-existing legacy session to the double ratchet.
3111
+ // A born-DR / epoch-pinned / in-flight contact is a no-op (mig_should_trigger returns FALSE).
3112
+ fn handle_readvertise_ad (args: any) -> transaction::results::type
3113
+ {
3114
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
3115
+ encrypted_channel::check_encrypted_or_abort().
3116
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
3117
+ // Only known contacts; an unknown sender is a silent no-op (no state, no leak).
3118
+ if (contacts sender_id) == NIL { return transaction::success []. }
3119
+ // Verify + ingest the refreshed AD (cid-bind + PoP; forgery aborts). Caller writes peer_ads.
3120
+ vb = verify_identity_bundle (args as any) sender_id.
3121
+ peer_ads sender_id -> (vb $ad).
3122
+ // Learn the peer's version + caps piggyback so it becomes known-0.9 (the mig_should_trigger gate).
3123
+ pv_seen = a2a_versions::peer_pv args.
3124
+ caps_in is str[] = ((args $caps) == NIL ?? [] ; ((args $caps) safe (str[]))).
3125
+ learn_contact_version sender_id ((pv_seen != 0 ?? pv_seen ; 9)) caps_in.
3126
+ // Nudge the trigger only when the refreshed AD actually carries a v2 bundle (a real
3127
+ // upgrade). mig_trigger_actions internally gates on mig_should_trigger (skips born-DR /
3128
+ // epoch-pinned / in-flight / not-known-0.9), so this is a safe no-op otherwise.
3129
+ actions is transaction::action::type[] = [].
3130
+ if (peer_has_e2e_bundle sender_id)
3131
+ {
3132
+ trig is transaction::action::type[] = mig_trigger_actions sender_id.
3133
+ sc trig -- ( -> a) { actions (_count actions|) -> a. }
3134
+ }
3135
+ actions (_count actions|) -> _save_state NIL.
3136
+ return transaction::success actions.
3137
+ }
3138
+ trn readvertise_ad args: any { return handle_readvertise_ad args. }
3139
+
3140
+ // ACK handler (initiator). Gates: narrow -> FSM phase==offered ∧ ack echoes my nonce
3141
+ // -> verify bundle (forgery aborts) -> bundle-presence -> compute the SAME epoch ->
3142
+ // WRITES LAST. NOTE: the §5.5 COMMIT continuation (stage_outbound_rotation + send
3143
+ // commit, same tx) is the NEXT increment; this cut reaches `acknowledged` with a
3144
+ // converged epoch on both sides.
3145
+ fn handle_e2e_migrate_ack (args: any) -> transaction::results::type
3146
+ {
3147
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
3148
+ encrypted_channel::check_encrypted_or_abort().
3149
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
3150
+ // GATE 1 — narrow.
3151
+ nr = a2a_versions::try_narrow_mgb args.
3152
+ if (nr $ok) != TRUE
3153
+ { return transaction::success [ _notify_agent ($event -> $protocol_error, $context -> $e2e_migrate_ack, $message -> (((nr $err)?) $message), $error -> (nr $err)?, $peer_cid -> sender_id) ]. }
3154
+ p = (nr $payload)?.
3155
+ // GATE 2 — FSM phase==offered ∧ the ack echoes MY offer nonce (else stale/foreign, drop as data).
3156
+ st = contact_migration sender_id.
3157
+ if st == NIL || ((st?) $phase) != "offered" { return transaction::success []. }
3158
+ my_local_nonce = (st?) $local_nonce.
3159
+ ack_peer_nonce = (p $peer_nonce).
3160
+ if ack_peer_nonce == NIL || ack_peer_nonce != my_local_nonce { return transaction::success []. }
3161
+ // GATE 3 — verify bundle (forgery aborts; peer_ads refresh) + bundle presence.
3162
+ vb = verify_identity_bundle (p as any) sender_id.
3163
+ if (((vb $ad) as any) $identity $e2e_bundle) == NIL
3164
+ { return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $peer_acked_without_e2e_bundle) ]. }
3165
+ pv_seen = a2a_versions::peer_pv args.
3166
+ learn_contact_version sender_id ((pv_seen != 0 ?? pv_seen ; 9)) (((p $caps) == NIL ?? [] ; (p $caps)?)).
3167
+ // Install the ack's refreshed AD (REQUIRED for a legacy contact whose stored AD is still v1):
3168
+ // GATE 4 below reads the peer $e2e_bundle off peer_ads, which must now be the v2 AD.
3169
+ peer_ads sender_id -> (vb $ad).
3170
+ // GATE 4 — compute the SAME epoch (I am the elected initiator = LOWER cid).
3171
+ ack_nonce = (p $nonce) safe bin.
3172
+ my_fp = ((st?) $local_fp)?. // my offer snapshot fp (same bundle -> same fp)
3173
+ peer_fp = e2e_bundle_fp (vb $ad).
3174
+ now = (current_transaction_info::get_transaction_time())?.
3175
+ epoch = mig_epoch (_get_container_id()) sender_id my_local_nonce ack_nonce my_fp peer_fp.
3176
+ // §5.5 COMMIT (same tx, atomic — cross-lib rollback proven, plan B gate 5): stage a
3177
+ // FRESH outbound session to the peer's ACKED bundle, encrypt the commit body on it
3178
+ // (PRE_KEY), persist committed, send. The commit is END-TO-END bound — epoch +
3179
+ // session_id ride INSIDE the fresh session's ciphertext (a relay cannot re-target,
3180
+ // replay across pairs, or splice epochs; the outer $emsignature binds $from/$to).
3181
+ pb = (((vb $ad) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
3182
+ sid = e2e::stage_outbound_rotation sender_id pb.
3183
+ commit_body = _write ( $name -> e2e_migrate_commit_tx,
3184
+ $targ -> ( $epoch -> epoch, $session_id -> sid, $pv -> a2a_versions::wire_version ) ).
3185
+ env = e2e::encrypt_staged sender_id commit_body.
3186
+ // WRITES LAST — persist committed(session_id) atomically with the commit send.
3187
+ contact_migration sender_id -> ( $phase -> "committed", $initiator -> TRUE,
3188
+ $local_nonce -> my_local_nonce, $peer_nonce -> ack_nonce, $epoch -> epoch, $session_id -> sid,
3189
+ $local_bundle -> ((st?) $local_bundle), $local_fp -> my_fp, $attempts -> ((st?) $attempts), $updated -> now ).
3190
+ // BOXED transport (B): the SDK wire schema has no e2e_signed_message transaction variant
3191
+ // yet (a coordinated plan-F SDK-bundle regen), so the staged-session Olm ciphertext rides
3192
+ // as $targ INSIDE the legacy encrypted_channel box; the responder handler drives the e2e
3193
+ // decode. The box is PURE TRANSPORT — epoch + session_id stay INSIDE the Olm ciphertext,
3194
+ // the $emsignature still binds $from/$to/$envelope (verified handler-side, decode_migration_envelope).
3195
+ return transaction::success [
3196
+ encrypted_channel::send_encrypted_tx sender_id (
3197
+ $name -> e2e_migrate_commit_tx,
3198
+ $targ -> ( $e2e_envelope -> (env $e2e_envelope), $emsignature -> (env $emsignature) ) ),
3199
+ _notify_agent ($event -> $migration_started, $cid -> sender_id, $role -> $initiator),
3200
+ _save_state NIL ].
3201
+ }
3202
+ trn e2e_migrate_ack args: any { return handle_e2e_migrate_ack args. }
3203
+
3204
+ // A redelivered migration COMMIT after we already promoted to active (§5.5 lost-confirm: the
3205
+ // initiator's sweep re-sends its commit because our confirm was lost). Evidence rule: re-send
3206
+ // the confirm ONLY when we are genuinely active for this cid on the PINNED session (the epoch
3207
+ // pin's $session_id == the live active session) — proof we already completed THIS rotation.
3208
+ // NO decode (never risk self-healing the live session at active), NO inner re-dispatch, NO
3209
+ // state change; a stale/foreign replay drops silently.
3210
+ fn mig_handle_replayed_commit (sender_id: global_id) -> transaction::results::type
3211
+ {
3212
+ st = contact_migration sender_id.
3213
+ if st == NIL || ((st?) $phase) != "active" { return transaction::success []. }
3214
+ pin = contact_e2e_epoch sender_id.
3215
+ active_sid = e2e::active_session_id sender_id.
3216
+ if pin == NIL || active_sid == NIL || ((pin?) $session_id) != active_sid { return transaction::success []. }
3217
+ confirm_body = _write ( $name -> e2e_migrate_confirm_tx, $targ -> ( $epoch -> ((pin?) $epoch), $pv -> a2a_versions::wire_version ) ).
3218
+ cpb = ((((peer_ads sender_id)?) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
3219
+ cenv = e2e::encrypt_to sender_id confirm_body cpb.
3220
+ return transaction::success [
3221
+ encrypted_channel::send_encrypted_tx sender_id (
3222
+ $name -> e2e_migrate_confirm_tx,
3223
+ $targ -> ( $e2e_envelope -> (cenv $e2e_envelope), $emsignature -> (cenv $emsignature) ) ) ].
3224
+ }
3225
+
3226
+ // COMMIT handler (responder). Under B the commit rides a NAMED box carrying the staged-session
3227
+ // Olm ciphertext as $targ = {$e2e_envelope, $emsignature}; the __t_wrapper decode-seam is NOT
3228
+ // invoked, so THIS handler drives the e2e decode (via the shared, audited e2e::decode_migration_
3229
+ // envelope — S1/S2 verify bound to the box sender + me, then decrypt+STAGE on the fresh session).
3230
+ // Gate ALL before any write: phase==acknowledged; carrier shape; S1/S2 + decrypt; narrow(mgc) of
3231
+ // the DECRYPTED inner body; inner $epoch==stored epoch; inner $session_id==the CARRIER session
3232
+ // (staged if staged, else the just-installed active). ANY mismatch: discard the staged rotation,
3233
+ // typed reject, REMAIN acknowledged (sweep re-drives). A dup at active -> idempotent re-confirm.
3234
+ // Success: promote atomically in ONE tx — commit_rotation + BOTH pins + active + send confirm.
3235
+ fn handle_e2e_migrate_commit (args: any) -> transaction::results::type
3236
+ {
3237
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
3238
+ encrypted_channel::check_encrypted_or_abort().
3239
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
3240
+ st = contact_migration sender_id.
3241
+ if st == NIL { return transaction::success []. }
3242
+ ph = ((st?) $phase).
3243
+ // A commit arriving after we went active (peer lost our confirm): idempotent re-confirm on
3244
+ // the pinned active session — NO decode. Any other non-acknowledged phase drops as data.
3245
+ if ph == "active" { return mig_handle_replayed_commit sender_id. }
3246
+ if ph != "acknowledged" { return transaction::success []. }
3247
+ // GATE 0 — carrier shape (no-downgrade: a missing/garbage e2e envelope FAILS closed; the
3248
+ // box is never treated as a legacy/plaintext commit).
3249
+ env is e2e::t_e2e_envelope+ = (args $e2e_envelope) safe e2e::t_e2e_envelope.
3250
+ emsig is crypto_signature+ = (args $emsignature) safe crypto_signature.
3251
+ if env == NIL || emsig == NIL
3252
+ { return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $commit_malformed_envelope) ]. }
3253
+ // GATE 1 — need the box sender's VERIFIED AD (refreshed at offer/ack) to authenticate the
3254
+ // envelope: sign key + e2e identity key are read from THIS cid's AD (tight $from binding).
3255
+ pad = peer_ads sender_id.
3256
+ if pad == NIL
3257
+ { return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $commit_no_peer_ad) ]. }
3258
+ // GATE 2 — handler-driven e2e decode (ALL crypto in e2e.mm). At acknowledged mig_pending is
3259
+ // TRUE, so the decode-seam STAGES onto a fresh session (the live session is untouched).
3260
+ r = e2e::decode_migration_envelope sender_id (_get_container_id()) (pad?) (env?) (emsig?).
3261
+ if (r $ok) != TRUE
3262
+ { // OLM-LEVEL failure only — tampered ciphertext / session_mismatch / no_session /
3263
+ // replay-at-acknowledged → !ok reject-as-data. (emsig/wire FORGERY already ABORTED
3264
+ // inside decode_migration_envelope, §1.1 — it never reaches here.) Drop the staged
3265
+ // rotation, REMAIN acknowledged (never fall back to legacy). The sweep re-drives.
3266
+ e2e::discard_rotation sender_id.
3267
+ return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $commit_decrypt_failed), _save_state NIL ].
3268
+ }
3269
+ // GATE 3 — narrow the DECRYPTED inner commit body (used ONLY for gating, never emitted).
3270
+ inner = (key_storage::read_external ((r $plaintext)?)) safe transaction::unsigned_message.
3271
+ if inner == NIL
3272
+ { e2e::discard_rotation sender_id.
3273
+ return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $commit_inner_malformed), _save_state NIL ]. }
3274
+ nr = a2a_versions::try_narrow_mgc ((inner?) $targ).
3275
+ if (nr $ok) != TRUE
3276
+ { e2e::discard_rotation sender_id.
3277
+ return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $commit_inner_malformed), _save_state NIL ]. }
3278
+ p = (nr $payload)?.
3279
+ stored_epoch = ((st?) $epoch)?.
3280
+ staged_sid = e2e::staged_session_id sender_id.
3281
+ active_sid = e2e::active_session_id sender_id.
3282
+ carrier_sid = (staged_sid != NIL ?? staged_sid ; active_sid). // where the commit landed
3283
+ inner_sid = (p $session_id).
3284
+ if (p $epoch) != stored_epoch || inner_sid == NIL || carrier_sid == NIL || inner_sid != carrier_sid
3285
+ {
3286
+ e2e::discard_rotation sender_id.
3287
+ return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $commit_epoch_or_session_mismatch), _save_state NIL ].
3288
+ }
3289
+ // SUCCESS — one atomic tx. commit_rotation is the SOLE promotion point (promotes a
3290
+ // staged rotation; a no-op when the fresh session was already installed directly).
3291
+ e2e::commit_rotation sender_id.
3292
+ final_sid = e2e::active_session_id sender_id. // the now-active fresh session (== carrier)
3293
+ contact_e2e_epoch sender_id -> ( $epoch -> stored_epoch, $session_id -> (final_sid?) ).
3294
+ contact_e2e_seen sender_id -> TRUE.
3295
+ now = (current_transaction_info::get_transaction_time())?.
3296
+ contact_migration sender_id -> ( $phase -> "active", $initiator -> FALSE,
3297
+ $local_nonce -> ((st?) $local_nonce), $peer_nonce -> ((st?) $peer_nonce), $epoch -> stored_epoch, $session_id -> (final_sid?),
3298
+ $local_bundle -> ((st?) $local_bundle), $local_fp -> ((st?) $local_fp), $attempts -> ((st?) $attempts), $updated -> now ).
3299
+ // Confirm rides the NEW (now-active) session — encrypt_to targets m_sessions[sender] —
3300
+ // BOXED (same wire-schema constraint). The initiator decodes it on its staged slot.
3301
+ confirm_body = _write ( $name -> e2e_migrate_confirm_tx, $targ -> ( $epoch -> stored_epoch, $pv -> a2a_versions::wire_version ) ).
3302
+ cpb = ((((peer_ads sender_id)?) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
3303
+ cenv = e2e::encrypt_to sender_id confirm_body cpb.
3304
+ return transaction::success [
3305
+ encrypted_channel::send_encrypted_tx sender_id (
3306
+ $name -> e2e_migrate_confirm_tx,
3307
+ $targ -> ( $e2e_envelope -> (cenv $e2e_envelope), $emsignature -> (cenv $emsignature) ) ),
3308
+ _notify_agent ($event -> $migration_active, $cid -> sender_id, $role -> $responder, $epoch -> stored_epoch, $session_id -> (final_sid?)),
3309
+ _save_state NIL ].
3310
+ }
3311
+ trn e2e_migrate_commit args: any { return handle_e2e_migrate_commit args. }
3312
+
3313
+ // CONFIRM handler (initiator). Under B the confirm rides a NAMED box carrying the responder's
3314
+ // olm_type=1 ciphertext (encrypted on its now-active session) as $targ; THIS handler drives the
3315
+ // decode via e2e::decode_migration_envelope, which decrypts on the initiator's STAGED slot (not
3316
+ // yet promoted). Gate: phase==committed; carrier shape; S1/S2 + decrypt; narrow(mgc); inner
3317
+ // $epoch matches. Success: promote atomically — commit_rotation + BOTH pins + active
3318
+ // (+ flush mig_deferred over the new e2e path — that flush is wired in phase D).
3319
+ fn handle_e2e_migrate_confirm (args: any) -> transaction::results::type
3320
+ {
3321
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
3322
+ encrypted_channel::check_encrypted_or_abort().
3323
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
3324
+ st = contact_migration sender_id.
3325
+ if st == NIL { return transaction::success []. }
3326
+ ph = ((st?) $phase).
3327
+ if ph == "active" { return transaction::success []. } // dup confirm after promotion: no-op
3328
+ if ph != "committed" { return transaction::success []. }
3329
+ // GATE 0 — carrier shape (no-downgrade).
3330
+ env is e2e::t_e2e_envelope+ = (args $e2e_envelope) safe e2e::t_e2e_envelope.
3331
+ emsig is crypto_signature+ = (args $emsignature) safe crypto_signature.
3332
+ if env == NIL || emsig == NIL
3333
+ { return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $confirm_malformed_envelope) ]. }
3334
+ pad = peer_ads sender_id.
3335
+ if pad == NIL
3336
+ { return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $confirm_no_peer_ad) ]. }
3337
+ // GATE 1 — handler-driven decode: olm_type=1 on the STAGED slot (initiator reads confirm
3338
+ // pre-promotion). A tampered/foreign confirm fails closed; the staged slot is untouched.
3339
+ r = e2e::decode_migration_envelope sender_id (_get_container_id()) (pad?) (env?) (emsig?).
3340
+ if (r $ok) != TRUE
3341
+ { return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $confirm_decrypt_failed) ]. }
3342
+ // GATE 2 — narrow the DECRYPTED inner confirm body + epoch match (used ONLY for gating).
3343
+ inner = (key_storage::read_external ((r $plaintext)?)) safe transaction::unsigned_message.
3344
+ if inner == NIL
3345
+ { return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $confirm_inner_malformed) ]. }
3346
+ nr = a2a_versions::try_narrow_mgc ((inner?) $targ).
3347
+ if (nr $ok) != TRUE
3348
+ { return transaction::success [ _notify_agent ($event -> $migration_rejected, $cid -> sender_id, $reason -> $confirm_inner_malformed) ]. }
3349
+ p = (nr $payload)?.
3350
+ stored_epoch = ((st?) $epoch)?.
3351
+ if (p $epoch) != stored_epoch { return transaction::success []. } // stale/foreign confirm, drop
3352
+ // SUCCESS — promote atomically. commit_rotation promotes the initiator's staged session.
3353
+ e2e::commit_rotation sender_id.
3354
+ final_sid = e2e::active_session_id sender_id.
3355
+ contact_e2e_epoch sender_id -> ( $epoch -> stored_epoch, $session_id -> (final_sid?) ).
3356
+ contact_e2e_seen sender_id -> TRUE.
3357
+ now = (current_transaction_info::get_transaction_time())?.
3358
+ contact_migration sender_id -> ( $phase -> "active", $initiator -> TRUE,
3359
+ $local_nonce -> ((st?) $local_nonce), $peer_nonce -> ((st?) $peer_nonce), $epoch -> stored_epoch, $session_id -> (final_sid?),
3360
+ $local_bundle -> ((st?) $local_bundle), $local_fp -> ((st?) $local_fp), $attempts -> ((st?) $attempts), $updated -> now ).
3361
+ // §5.6 FLUSH-ON-ACTIVE — PINS-BEFORE-FLUSH: the epoch pin above is now set, so a re-injected
3362
+ // app send routes "e2e" (not "migrating") and won't re-queue. Drain mig_deferred[cid] FIFO
3363
+ // over e2e (the daemon delivers on the migrated session) — preserves per-contact order.
3364
+ acts is transaction::action::type[] = [ _notify_agent ($event -> $migration_active, $cid -> sender_id, $role -> $initiator, $epoch -> stored_epoch, $session_id -> (final_sid?)) ].
3365
+ sc flush_mig_deferred_actions sender_id -- ( -> a) { acts (_count acts|) -> a. }
3366
+ acts (_count acts|) -> _save_state NIL.
3367
+ return transaction::success acts.
3368
+ }
3369
+ trn e2e_migrate_confirm args: any { return handle_e2e_migrate_confirm args. }
3370
+
3371
+ // Host-fired flush (boot/GC cadence + on the $migration_active notify): drain a contact's
3372
+ // mig_deferred over e2e. Idempotent; a contact NOT yet epoch-pinned (still migrating) is a
3373
+ // no-op ($not_active) — never flush before the pin (would re-queue).
3374
+ trn flush_mig_deferred _:($contact -> contact_ref: str)
3375
+ {
3376
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
3377
+ target_id = resolve_contact contact_ref.
3378
+ q = mig_deferred target_id.
3379
+ if q == NIL || (_count q?|) == 0 { return transaction::success [ _return_data ($flushed -> 0) ]. }
3380
+ if (contact_e2e_epoch target_id) == NIL { return transaction::success [ _return_data ($flushed -> 0, $not_active -> TRUE) ]. }
3381
+ n = _count q?|.
3382
+ acts is transaction::action::type[] = flush_mig_deferred_actions target_id.
3383
+ acts (_count acts|) -> _return_data ($flushed -> n, $route -> $e2e).
3384
+ acts (_count acts|) -> _save_state NIL.
3385
+ return transaction::success acts.
3386
+ }
3387
+
3388
+ // Enable the migration capability at RUNTIME (mid-session), no restart. Appends cap_e2e_migrate to
3389
+ // self_caps; the next outbound message's self_cap_ids piggyback carries it, the peer re-learns, and
3390
+ // its mig_should_trigger fires — so an ALREADY-established e2e session is preserved and the migration
3391
+ // ROTATES that live session (a restart would re-key the Olm ratchet and lose the pre-migration
3392
+ // session — see the OWNER-TEST-GUIDE staged flow). A genuine production capability (turn on migration
3393
+ // without a restart), not only a test hook. cap_e2e_migrate is $advertise-class (no control-verb
3394
+ // handler), so add_self_cap is safe here (init's declared-implies-implemented guard is for $supported).
3395
+ trn advertise_migrate _
3396
+ {
3397
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
3398
+ was is bool = a2a_capabilities::self_advertises a2a_capabilities::cap_e2e_migrate.
3399
+ a2a_capabilities::add_self_cap a2a_capabilities::cap_e2e_migrate.
3400
+ // Now that the cap is LIVE, proactively offer to every already-known eligible e2e contact — a
3401
+ // runtime cap-enable must start the SAME migrations a default-cap boot would, else an already-e2e
3402
+ // pair with no inbound traffic would never migrate (mig_should_trigger keeps it fail-closed +
3403
+ // idempotent). This is what turns the OWNER-TEST-GUIDE staged-advertise flow into a real trigger.
3404
+ elig is transaction::action::type[] = mig_offer_eligible_actions NIL.
3405
+ acts is transaction::action::type[] = [ _return_data (
3406
+ $was_advertising -> was,
3407
+ $advertising -> (a2a_capabilities::self_advertises a2a_capabilities::cap_e2e_migrate),
3408
+ $offers_initiated -> (_count elig|) ) ].
3409
+ sc elig -- ( -> a) { acts (_count acts|) -> a. }
3410
+ acts (_count acts|) -> _save_state NIL.
3411
+ return transaction::success acts.
3412
+ }
3413
+
3414
+ // ---- §5.6 recovery sweep (host boot/GC cadence, mirrors restore_degraded_contacts) --------
3415
+ // Re-drive a stalled migration by RETRANSMITTING the persisted phase's leg. offer/ack rebuild
3416
+ // BYTE-IDENTICALLY from the $local_bundle snapshot (§5.4-5 — same nonce, so the peer's already-
3417
+ // computed epoch stays valid); commit re-encrypts on the SURVIVING staged session. Pure builders
3418
+ // (no state write) — the sweep trn bumps $attempts + persists.
3419
+ fn mig_resend_offer_actions (cid: global_id, st: mig_state_t) -> transaction::action::type[]
3420
+ {
3421
+ if (st $local_bundle) == NIL { return []. }
3422
+ s = _read_or_abort ((st $local_bundle)?).
3423
+ return [ encrypted_channel::send_encrypted_tx cid (
3424
+ $name -> e2e_migrate_offer_tx,
3425
+ $targ -> ( $ad -> (s $ad), $cert -> (s $cert), $root_profile -> (s $root_profile),
3426
+ $cp_binding -> (s $cp_binding), $nonce -> (st $local_nonce), $peer_nonce -> NIL,
3427
+ $pv -> a2a_versions::wire_version, $caps -> (a2a_capabilities::self_cap_ids NIL) ) ) ].
3428
+ }
3429
+ fn mig_resend_ack_actions (cid: global_id, st: mig_state_t) -> transaction::action::type[]
3430
+ {
3431
+ if (st $local_bundle) == NIL || (st $peer_nonce) == NIL { return []. }
3432
+ s = _read_or_abort ((st $local_bundle)?).
3433
+ return [ encrypted_channel::send_encrypted_tx cid (
3434
+ $name -> e2e_migrate_ack_tx,
3435
+ $targ -> ( $ad -> (s $ad), $cert -> (s $cert), $root_profile -> (s $root_profile),
3436
+ $cp_binding -> (s $cp_binding), $nonce -> (st $local_nonce), $peer_nonce -> ((st $peer_nonce)?),
3437
+ $pv -> a2a_versions::wire_version, $caps -> (a2a_capabilities::self_cap_ids NIL) ) ) ].
3438
+ }
3439
+ // Commit re-drive: re-encrypt on the SURVIVING staged session (still PRE_KEY; the responder's
3440
+ // session_matches collapses the duplicate). NIL when the staged session is GONE (crash / m_staged
3441
+ // lost, e.g. post-import) → UNRESUMABLE; the caller abandons + supersedes (fresh offer/epoch).
3442
+ fn mig_resend_commit_actions (cid: global_id, st: mig_state_t) -> transaction::action::type[]+
3443
+ {
3444
+ sid = e2e::staged_session_id cid.
3445
+ if sid == NIL { return NIL. }
3446
+ commit_body = _write ( $name -> e2e_migrate_commit_tx,
3447
+ $targ -> ( $epoch -> ((st $epoch)?), $session_id -> sid, $pv -> a2a_versions::wire_version ) ).
3448
+ env = e2e::encrypt_staged cid commit_body.
3449
+ return [ encrypted_channel::send_encrypted_tx cid (
3450
+ $name -> e2e_migrate_commit_tx,
3451
+ $targ -> ( $e2e_envelope -> (env $e2e_envelope), $emsignature -> (env $emsignature) ) ) ].
3452
+ }
3453
+
3454
+ // Host-fired sweep (boot + GC cadence): re-drive every non-terminal migration. $attempts capped
3455
+ // at mig_max_attempts → $migration_stalled notify (state KEPT — legacy still flows offered/ack,
3456
+ // committed keeps queueing; NOTHING silently downgrades). A committed entry whose staged session
3457
+ // was lost is abandoned + superseded (fresh offer). Idempotent; re-fires on the host cadence.
3458
+ // core 0.10 (B1): boot/upgrade RE-ADVERTISE. The daemon calls this at startup (see the DAEMON
3459
+ // CONTRACT). It pushes my fresh v2 AD (+ caps piggyback) to every PRE-EXISTING LEGACY contact —
3460
+ // one that is NOT epoch-pinned, NOT born-DR, and has NO migration in flight — over the legacy
3461
+ // encrypted_channel. A v2 peer ingests it (handle_readvertise_ad) and offers back; a still-v1
3462
+ // peer does not understand the tx and ignores it, leaving NO state that could block a future
3463
+ // upgrade. STATELESS (no _save_state): it only sends, changing no local state, so it is idempotent
3464
+ // and safe to call on every boot. A still-legacy contact becomes migration-eligible only after
3465
+ // this re-advertise round-trips, so no separate production boot sweep is needed.
3466
+ trn readvertise_on_upgrade _
3467
+ {
3468
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
3469
+ b = my_identity_bundle_fields_fresh NIL.
3470
+ actions is transaction::action::type[] = [].
3471
+ n is int = 0.
3472
+ sc contacts -- (cid -> ) ?? ((contact_e2e_epoch cid) == NIL && (contact_born_dr cid) != TRUE && (contact_migration cid) == NIL)
3473
+ {
3474
+ actions (_count actions|) -> encrypted_channel::send_encrypted_tx cid (
3475
+ $name -> readvertise_ad_tx,
3476
+ $targ -> ( $ad -> (b $ad), $cert -> (b $cert), $root_profile -> (b $root_profile),
3477
+ $cp_binding -> (b $cp_binding),
3478
+ $pv -> a2a_versions::wire_version,
3479
+ $caps -> (a2a_capabilities::self_cap_ids NIL) ) ).
3480
+ n -> n + 1.
3481
+ }
3482
+ actions (_count actions|) -> _return_data ($readvertised -> n).
3483
+ return transaction::success actions.
3484
+ }
3485
+
3486
+ trn sweep_e2e_migrations _
3487
+ {
3488
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
3489
+ actions is transaction::action::type[] = [].
3490
+ redriven is int = 0. stalled is int = 0. superseded is int = 0.
3491
+ now = (current_transaction_info::get_transaction_time())?.
3492
+ sc contact_migration -- (cid -> st) ?? (((st) $phase) == "offered" || ((st) $phase) == "acknowledged" || ((st) $phase) == "committed")
3493
+ {
3494
+ att is int = (st $attempts).
3495
+ ph = (st $phase).
3496
+ // §5.6 LIVENESS BACKSTOP: a COMMITTED initiator must never PERMANENTLY stall (that would
3497
+ // strand its mig_deferred app data forever — the peer-rekey / responder-full-regen case,
3498
+ // where our staged commit can never decode on the peer's rotated identity). At the attempts
3499
+ // cap it SUPERSEDES (fresh offer/epoch) instead of only notifying, releasing the barrier and
3500
+ // re-attempting onto the peer's current bundle (the fresh ack re-freezes the epoch on it). It
3501
+ // was NEVER epoch-pinned, so re-offering — legacy flows at `offered` — is NOT a downgrade.
3502
+ // offered/acknowledged still terminate at $migration_stalled (legacy already flows there).
3503
+ if att >= mig_max_attempts && ph != "committed"
3504
+ {
3505
+ actions (_count actions|) -> _notify_agent ($event -> $migration_stalled, $cid -> cid, $phase -> ph, $attempts -> att).
3506
+ stalled -> stalled + 1.
3507
+ }
3508
+ else
3509
+ {
3510
+ do_supersede is bool = FALSE.
3511
+ leg is transaction::action::type[] = [].
3512
+ if ph == "offered"
3513
+ {
3514
+ // §5.4-5 ROTATION DETECTOR: if my published bundle rotated since this snapshot, a
3515
+ // byte-identical resend would carry a STALE fp under the SAME nonce (breaking epoch
3516
+ // equality with the responder's already-acked bundle) → SUPERSEDE (fresh nonce/epoch)
3517
+ // instead of resending. Unchanged fp → byte-identical retransmit (idempotent).
3518
+ live_fp = e2e_bundle_fp (address_document::produce_my_address_document()).
3519
+ if (st $local_fp) != NIL && ((st $local_fp)?) != live_fp { do_supersede -> TRUE. }
3520
+ else { leg -> mig_resend_offer_actions cid st. }
3521
+ }
3522
+ elif ph == "acknowledged" { leg -> mig_resend_ack_actions cid st. }
3523
+ else
3524
+ {
3525
+ // committed: staged session lost (rc==NIL, unresumable) OR the attempts-cap liveness
3526
+ // backstop above → SUPERSEDE (fresh offer/epoch); otherwise re-encrypt on the
3527
+ // surviving staged session and re-send (the responder's session_matches collapses it).
3528
+ rc = mig_resend_commit_actions cid st.
3529
+ if rc == NIL || att >= mig_max_attempts { do_supersede -> TRUE. } else { leg -> rc?. }
3530
+ }
3531
+ if do_supersede
3532
+ {
3533
+ sc mig_offer_actions cid -- ( -> a) { actions (_count actions|) -> a. } // fresh offer/epoch
3534
+ superseded -> superseded + 1.
3535
+ }
3536
+ else
3537
+ {
3538
+ sc leg -- ( -> a) { actions (_count actions|) -> a. }
3539
+ contact_migration cid -> ( $phase -> (st $phase), $initiator -> (st $initiator),
3540
+ $local_nonce -> (st $local_nonce), $peer_nonce -> (st $peer_nonce), $epoch -> (st $epoch),
3541
+ $session_id -> (st $session_id), $local_bundle -> (st $local_bundle), $local_fp -> (st $local_fp),
3542
+ $attempts -> (att + 1), $updated -> now ).
3543
+ redriven -> redriven + 1.
3544
+ }
3545
+ }
3546
+ }
3547
+ // §5.4 INITIATE (MR2-ruled): beyond re-driving in-flight migrations, the sweep is the
3548
+ // eventually-consistent reconciler — it proactively OFFERS to every eligible contact with no
3549
+ // migration yet (mig_should_trigger: contact_migration==NIL ∧ epoch==NIL ∧ self-advertises ∧
3550
+ // peer-known-0.9). This is the ONLY path that covers the post-version-bump default-cap boot with
3551
+ // pre-existing e2e contacts and NO inbound traffic (advertise_migrate isn't called at boot, and
3552
+ // the receive triggers need inbound traffic). Inert pre-cap (self-advertise gate); an already-
3553
+ // migrated pair is never re-offered (never-cleared contact_migration + the epoch-pin guard).
3554
+ elig is transaction::action::type[] = mig_offer_eligible_actions NIL.
3555
+ initiated is int = (_count elig|).
3556
+ sc elig -- ( -> a) { actions (_count actions|) -> a. }
3557
+ actions (_count actions|) -> _return_data ($redriven -> redriven, $stalled -> stalled, $superseded -> superseded, $initiated -> initiated).
3558
+ if (redriven + superseded + initiated) > 0 { actions (_count actions|) -> _save_state NIL. }
3559
+ return transaction::success actions.
3560
+ }
3561
+
1965
3562
  // ---- upgrade: state export / import helpers ------------------------------
1966
3563
  // NOT transactions: each app's export_state/import_state trn composes these
1967
3564
  // with its own app-side fields (inbox / chat history / local book). Field
@@ -1978,6 +3575,7 @@ library a2a_messaging loads libraries
1978
3575
  $my_bio -> my_bio,
1979
3576
  $my_persona -> my_persona,
1980
3577
  $delegation_cert -> delegation_cert,
3578
+ $delegation_cert_v1 -> delegation_cert_v1,
1981
3579
  $root_ad -> root_ad,
1982
3580
  $root_profile -> root_profile,
1983
3581
  $root_cp_binding -> root_cp_binding,
@@ -1988,7 +3586,17 @@ library a2a_messaging loads libraries
1988
3586
  $monitoring_proxy -> monitoring_proxy,
1989
3587
  $app_config -> app_config,
1990
3588
  $format_version -> core_format_version,
1991
- $deferred_msgs -> deferred_msgs
3589
+ $deferred_msgs -> deferred_msgs,
3590
+ $contact_pv -> contact_pv,
3591
+ $contact_caps -> contact_caps,
3592
+ $contact_e2e_seen -> contact_e2e_seen,
3593
+ $contact_born_dr -> contact_born_dr,
3594
+ // core 0.9.0 migration FSM metadata — additive, all keyed by cid. Only
3595
+ // PUBLIC FSM/epoch/queue metadata travels; the staged/active Olm session
3596
+ // pickles stay packet-local in the adapt e2e library (INV-4 / spec §5.1).
3597
+ $contact_migration -> contact_migration,
3598
+ $contact_e2e_epoch -> contact_e2e_epoch,
3599
+ $mig_deferred -> mig_deferred
1992
3600
  ).
1993
3601
  }
1994
3602
 
@@ -2046,6 +3654,13 @@ library a2a_messaging loads libraries
2046
3654
  {
2047
3655
  delegation_cert -> (data $delegation_cert) safe a2a_protocol::delegation_cert_t.
2048
3656
  }
3657
+ // Additive (absent in pre-fix exports → stays NIL; the host re-mints it on
3658
+ // the next set_delegation, so an un-upgraded role degrades to omitting the
3659
+ // chain on down-level rather than aborting the peer).
3660
+ if (data $delegation_cert_v1) != NIL
3661
+ {
3662
+ delegation_cert_v1 -> (data $delegation_cert_v1) safe a2a_protocol::delegation_cert_t.
3663
+ }
2049
3664
  if (data $root_ad) != NIL
2050
3665
  {
2051
3666
  root_ad -> (data $root_ad) safe address_document_types::t_address_document.
@@ -2091,6 +3706,43 @@ library a2a_messaging loads libraries
2091
3706
  {
2092
3707
  deferred_msgs -> (data $deferred_msgs) safe (global_id ->> deferred_msg_t[]).
2093
3708
  }
3709
+ // core 0.5.0: learned peer dialects/caps (absent from pre-0.5 exports
3710
+ // → defaults stay empty; re-learned passively from inbound traffic).
3711
+ if (data $contact_pv) != NIL
3712
+ {
3713
+ contact_pv -> (data $contact_pv) safe (global_id ->> int).
3714
+ }
3715
+ if (data $contact_caps) != NIL
3716
+ {
3717
+ contact_caps -> (data $contact_caps) safe (global_id ->> str[]).
3718
+ }
3719
+ // core 0.8.0: E2E anti-downgrade pin (absent from pre-0.8 exports →
3720
+ // stays empty; re-learned positively from inbound core.e2e evidence).
3721
+ if (data $contact_e2e_seen) != NIL
3722
+ {
3723
+ contact_e2e_seen -> (data $contact_e2e_seen) safe (global_id ->> bool).
3724
+ }
3725
+ if (data $contact_born_dr) != NIL
3726
+ {
3727
+ contact_born_dr -> (data $contact_born_dr) safe (global_id ->> bool).
3728
+ }
3729
+ // core 0.9.0: migration FSM metadata (absent from pre-0.9 exports → all
3730
+ // three stay empty = legacy, spec §5.1). Guarded exactly like the pins.
3731
+ // The adapt staged/active session pickles are packet-local and gone after
3732
+ // an export/import; a non-active FSM entry is re-driven by the host sweep,
3733
+ // an `active` entry with a lost session takes the recovery path (phases C-E).
3734
+ if (data $contact_migration) != NIL
3735
+ {
3736
+ contact_migration -> (data $contact_migration) safe (global_id ->> mig_state_t).
3737
+ }
3738
+ if (data $contact_e2e_epoch) != NIL
3739
+ {
3740
+ contact_e2e_epoch -> (data $contact_e2e_epoch) safe (global_id ->> e2e_epoch_t).
3741
+ }
3742
+ if (data $mig_deferred) != NIL
3743
+ {
3744
+ mig_deferred -> (data $mig_deferred) safe (global_id ->> deferred_msg_t[]).
3745
+ }
2094
3746
 
2095
3747
  // Re-register every peer's keys so encrypted channels keep working after
2096
3748
  // the upgrade — no handshake needed (my own keys are unchanged, and the