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

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.
package/dist/connector.js CHANGED
@@ -26062,6 +26062,13 @@ function deliveryTarget(chatId, threadId, lastChat) {
26062
26062
  }
26063
26063
 
26064
26064
  // src/connector.ts
26065
+ var PKG_VERSION = (() => {
26066
+ try {
26067
+ return JSON.parse(fs3.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
26068
+ } catch {
26069
+ return "unknown";
26070
+ }
26071
+ })();
26065
26072
  var CONFIG = loadConfig();
26066
26073
  var STATE_DIR = CONFIG.stateDir;
26067
26074
  var TG_NET = {
@@ -26119,15 +26126,30 @@ function exportSigningSecret(pkt) {
26119
26126
  }
26120
26127
  function saveState(pkt, dir) {
26121
26128
  try {
26122
- const bytes = withScope((lt) => Buffer.from(pkt.readonlyTx("::actor::export_state", lt).Serialize()));
26123
- fs3.mkdirSync(dir, { recursive: true });
26124
- const tmp = `${dataPath(dir)}.tmp`;
26125
- fs3.writeFileSync(tmp, bytes);
26126
- fs3.renameSync(tmp, dataPath(dir));
26129
+ saveStateFailClosed(pkt, dir);
26127
26130
  } catch (err) {
26128
26131
  log(`[${pkt.name}] failed to save state:`, String(err));
26129
26132
  }
26130
26133
  }
26134
+ function saveStateFailClosed(pkt, dir) {
26135
+ const bytes = withScope((lt) => Buffer.from(pkt.readonlyTx("::actor::export_state", lt).Serialize()));
26136
+ fs3.mkdirSync(dir, { recursive: true });
26137
+ const tmp = `${dataPath(dir)}.tmp`;
26138
+ const fd = fs3.openSync(tmp, "w", 384);
26139
+ try {
26140
+ fs3.writeFileSync(fd, bytes);
26141
+ fs3.fsyncSync(fd);
26142
+ } finally {
26143
+ fs3.closeSync(fd);
26144
+ }
26145
+ fs3.renameSync(tmp, dataPath(dir));
26146
+ const dirFd = fs3.openSync(dir, "r");
26147
+ try {
26148
+ fs3.fsyncSync(dirFd);
26149
+ } finally {
26150
+ fs3.closeSync(dirFd);
26151
+ }
26152
+ }
26131
26153
  function renderDeferredQueues(av) {
26132
26154
  const out = [];
26133
26155
  const arr = av.Reduce("queues");
@@ -26486,7 +26508,7 @@ function activateRoute(conn) {
26486
26508
  wireHandlers(
26487
26509
  pkt,
26488
26510
  {
26489
- onSaveState: () => saveState(pkt, dir),
26511
+ onSaveState: () => saveStateFailClosed(pkt, dir),
26490
26512
  onNotify: (event, payload) => {
26491
26513
  if (event === "message_received") {
26492
26514
  process.nextTick(() => void forwardToTelegram(conn));
@@ -26645,6 +26667,16 @@ async function restoreConnection(name) {
26645
26667
  const conflict = registerRoute(conn);
26646
26668
  if (conflict) log(`[${name}] route conflict on restore: ${conflict} \u2014 left unrouted`);
26647
26669
  if (hasSavedState(dir)) {
26670
+ const preCopy = `${dataPath(dir)}.pre-${PKG_VERSION}`;
26671
+ if (!fs3.existsSync(preCopy)) {
26672
+ try {
26673
+ fs3.copyFileSync(dataPath(dir), preCopy);
26674
+ fs3.chmodSync(preCopy, 384);
26675
+ log(`[${name}] pre-migration blob retained as ${preCopy.split("/").pop()}`);
26676
+ } catch (err) {
26677
+ log(`[${name}] pre-migration retention failed (continuing):`, String(err));
26678
+ }
26679
+ }
26648
26680
  try {
26649
26681
  const buf = fs3.readFileSync(dataPath(dir));
26650
26682
  await withScopeAsync(async (lt) => {
@@ -104,6 +104,14 @@ library a2a_capabilities loads libraries
104
104
  // continues untouched (so the receipts-style id PAIR is not needed here).
105
105
  cap_e2e_migrate = "core.e2e.migrate".
106
106
 
107
+ // core 0.11 — e2e session self-heal (a2a_messaging e2e_rekey_request + unacked
108
+ // redrive). PROTOCOL-surface id with NO control verbs, $advertise-carried:
109
+ // "on a decode failure you may send me e2e_rekey_request and I serve a gated
110
+ // re-key". Gates the REQUESTER's send (a peer that never advertises it gets
111
+ // the readvertise_ad fallback instead — a pre-0.11 daemon must never receive
112
+ // an unknown control tx); never authz (REG-6).
113
+ cap_e2e_rekey = "core.e2e.rekey".
114
+
107
115
  // ---- secret-field sentinels (config dialect, core.configuration) ------
108
116
  // A secret field's VALUE is never echoed in plaintext: reads carry one of
109
117
  // these sentinels, and writes interpret them. "$needs_reentry" is the
@@ -88,6 +88,14 @@ library a2a_messaging loads libraries
88
88
  // separates e2e-carrying box from legacy box (an attacker cannot confuse them).
89
89
  receive_e2e_message_tx = "::a2a_messaging::receive_e2e_message".
90
90
  receive_e2e_file_tx = "::a2a_messaging::receive_e2e_file".
91
+ // core 0.11 (session self-heal): authenticated re-key request. Sent by the side whose
92
+ // e2e DECODE failed (no_session / session_mismatch / tampered from an accepted contact —
93
+ // the TRUE-loss signature: since persist-primary a normal restart RESUMES its sessions,
94
+ // so this fires only when the persisted state was lost/rejected and the account was
95
+ // re-minted, making my old advertised bundle stale) so the peer refreshes my AD and
96
+ // the elected initiator re-establishes a fresh born-DR session, then redrives unacked.
97
+ // A pre-0.11 peer does not understand the tx and ignores it (readvertise precedent).
98
+ e2e_rekey_request_tx = "::a2a_messaging::e2e_rekey_request".
91
99
 
92
100
  // Version stamp of the portable export blob (see import_core_state for the
93
101
  // migration contract). Bump ONLY on a breaking blob-shape change, together
@@ -109,6 +117,52 @@ library a2a_messaging loads libraries
109
117
  // $migration_stalled notify and KEEPS the FSM state — legacy still flows in
110
118
  // offered/acknowledged; committed keeps queueing — nothing silently downgrades.
111
119
  mig_max_attempts = 30.
120
+ // core 0.11 (session self-heal): give up re-sending an e2e_rekey_request for the SAME
121
+ // dead session after this many decode failures (strictly per (cid, failed session_id);
122
+ // cleared on the first successful decode from that cid). Low on purpose: one request
123
+ // usually heals; the cap only bounds a lost-request retry, never a per-message storm.
124
+ rekey_max_attempts = 3.
125
+ // Per-contact cap on unacknowledged (no delivered-receipt yet) e2e sends retained for
126
+ // redrive after a re-key (mirrors deferred_msgs_cap; oldest dropped first, never abort).
127
+ unacked_cap = 50.
128
+ // Age before the periodic sweep re-sends a stuck unacked message (no delivered
129
+ // receipt). Covers a PRE-fix peer that silently rejected our sends and cannot ask
130
+ // us to re-key (it heals once our boot-readvertise refreshed its copy of our AD),
131
+ // and a lost receipt. Repeats are harmless: the receiver's delivered_wire dedup
132
+ // re-acks without re-depositing, and the re-ack clears our buffer.
133
+ redrive_min_age_seconds = 120.
134
+ // Review #12 + ship-review major-4: per-sweep budgets — one txn re-driving 50×N
135
+ // contacts (or emitting one expiry notify per contact across thousands) could hit
136
+ // fuel/action limits and lose the WHOLE sweep, cyclically. A contact's queue is
137
+ // capped at unacked_cap (50) < the crypto budget, so every contact is individually
138
+ // processable; overflow defers the remainder to the (exported) cursor.
139
+ // The crypto budget is DELIBERATELY denominated in CRYPTO OPERATIONS (each entry =
140
+ // one e2e::encrypt_to = 1 ratchet encryption + 1 signature GENERATION; this path
141
+ // performs zero sig-verifies), NOT in fuel: the fuel model undercounts fixed
142
+ // crypto costs (cross-fleet finding), so a fuel number would be a weaker guard.
143
+ // The action budget bounds emitted SEND/RET actions INCLUDING the per-contact
144
+ // expiry notifies of the purge phase.
145
+ redrive_sweep_max_entries = 100.
146
+ redrive_sweep_max_actions = 250.
147
+ // Data-at-rest bounds for the retained plaintext (review: a peer withholding
148
+ // receipts must not pin our plaintext forever): total per-contact byte budget
149
+ // (oldest dropped first; an entry alone above the budget is never retained),
150
+ // and a hard TTL — the periodic sweep purges expired entries.
151
+ unacked_max_bytes = 8388608.
152
+ unacked_ttl_seconds = 172800.
153
+ // Per-ENTRY byte ceiling for retained FILES ("f") — a large file body would bloat
154
+ // the exported blob (data-at-rest) and one entry could evict the whole message
155
+ // window. An oversized file is simply not retained (not auto-redriven; surfaced
156
+ // by the send notify as usual — the app owns re-sending it after a heal).
157
+ unacked_file_entry_max_bytes = 2097152.
158
+ // Responder-side re-key throttle: minimum seconds between session rotations
159
+ // served to one cid (see handle_e2e_rekey_request — requester-side rate-limit
160
+ // alone does not bound a misbehaving authenticated contact).
161
+ rekey_min_interval_seconds = 30.
162
+ // Review #9: the rekey_served attempts cap used to be PERMANENT (until restart) —
163
+ // a peer that legitimately needed >5 rotations over a long uptime was stalled
164
+ // forever. Entries older than this window are treated as expired: a fresh budget.
165
+ rekey_served_reset_seconds = 3600.
112
166
 
113
167
  // 6-digit bind ceremony limits (code is generated host-side — MUFL has no
114
168
  // random source — and handed to set_proxy_pending).
@@ -218,6 +272,66 @@ library a2a_messaging loads libraries
218
272
  // Sends queued during the initiator's commit window; flushed E2E on `active`.
219
273
  // Reuses deferred_msg_t; bounded by deferred_msgs_cap (same overflow abort).
220
274
  mig_deferred is (global_id ->> deferred_msg_t[]) = (,).
275
+
276
+ // ---- core 0.11: e2e session self-heal (restart desync recovery) --------
277
+ // Re-key request rate-limit ledger, keyed by cid. Strictly per (cid, failed
278
+ // session_id): a broker backlog of N messages on one dead session produces at
279
+ // most rekey_max_attempts requests, and a NEW dead session gets a fresh budget.
280
+ // Cleared on the first successful decode from the cid (the pair healed).
281
+ // NOT exported: worst case after a restart is one duplicate request (idempotent).
282
+ metadef rekey_state_t: ($session_id -> bin, $attempts -> int, $updated -> time).
283
+ rekey_pending is (global_id ->> rekey_state_t) = (,).
284
+ // Unacknowledged e2e app sends (no delivered/read receipt yet), keyed by cid —
285
+ // the redrive source that turns "session healed" into "the message still reached
286
+ // the receiver's inbox". Holds the serialized INNER app body ($text/$wire_id/...):
287
+ // the SAME plaintext class the exported inbox already persists at rest, never key
288
+ // material (INV-4 untouched — no session pickle here). Bounded (unacked_cap,
289
+ // oldest-first drop); entries clear on delivered/read receipt; EXPORTED so a
290
+ // sender-side restart (offline-pair case) does not lose undelivered messages.
291
+ // $kind: "m" (message, redriven as receive_e2e_message_tx) | "f" (file,
292
+ // redriven as receive_e2e_file_tx) — files silently lost on restart are the
293
+ // owner's primary case too, so BOTH app payload kinds retain (review fix).
294
+ metadef unacked_entry_t: ($kind -> str, $wire_id -> str, $inner -> bin, $date -> time).
295
+ unacked_e2e is (global_id ->> unacked_entry_t[]) = (,).
296
+ // Responder-side re-key ledger, keyed STRICTLY by cid (review: never key the
297
+ // budget by attacker-controlled fields like the claimed session id). $attempts
298
+ // caps total served rotations between successful decodes from that cid (the
299
+ // ledger clears when the pair provably healed); $updated drives the cooldown.
300
+ // Transient, not exported — worst case after restart is one extra rotation.
301
+ metadef rekey_served_t: ($attempts -> int, $updated -> time).
302
+ rekey_served is (global_id ->> rekey_served_t) = (,).
303
+ rekey_served_max = 5.
304
+ // Review #9: responder-side AD-response cooldown — its OWN ledger. The old check
305
+ // read rekey_served, which only maybe_init_rekey writes, so the NON-initiator
306
+ // responder had no cooldown: every authenticated rekey_request minted a fresh
307
+ // signed AD + save. Transient (not exported): worst case after restart is one
308
+ // extra readvertise.
309
+ ad_response_last is (global_id ->> time) = (,).
310
+ // Review #12 + ship-review major-4: resume point for the budgeted sweep, covering
311
+ // BOTH phases (TTL purge and redrive). EXPORTED: a deployment that only ever runs
312
+ // boot sweeps (short-lived daemons) would otherwise re-scan the same prefix every
313
+ // boot and starve the tail forever. A sweep-txn failure rolls the cursor back with
314
+ // everything else, so a retried sweep resumes from the last COMMITTED position.
315
+ redrive_sweep_cursor is global_id+ = NIL.
316
+ // Recently DELIVERED inbound wire_ids per contact — the receive-side dedup for the
317
+ // at-least-once redrive: a re-delivered wire_id re-acks (delivered receipt, so the
318
+ // sender's buffer clears) but never re-deposits into the inbox. EXPORTED (tiny):
319
+ // the inbox it guards is persisted too, so the guard must survive the same restarts.
320
+ // Retention is AGE-ONLY (finding H + ship-review major-3): an entry lives exactly
321
+ // as long as the SENDER can still redrive it (unacked_ttl_seconds). There is
322
+ // deliberately NO count-based eviction inside that window — any count cap could be
323
+ // pushed past by heavy (still authenticated) traffic while one receipt was lost,
324
+ // and the late redrive would re-deposit a duplicate. The storage bound is the
325
+ // AUTHENTICATED per-contact inbound rate over the 2-day window (each entry is one
326
+ // wire_id string + a date; only accepted contacts reach delivered_note).
327
+ metadef delivered_entry_t: ($w -> str, $d -> time).
328
+ delivered_wire is (global_id ->> delivered_entry_t[]) = (,).
329
+ // Storage CEILING (not a dedup window): an authenticated flooder must not grow
330
+ // delivered_wire without bound over the 2-day window (memory-DoS). Reaching it is
331
+ // a GUARANTEE-LOSS event — the oldest in-TTL entry is dropped AND the loss is
332
+ // SURFACED ($dedup_degraded notify), never a silent eviction. ~16k entries ≈ low
333
+ // single-digit MB per pathological contact.
334
+ delivered_wire_hard_cap = 16384.
221
335
  // Peer address documents, captured when a contact is established. Self-
222
336
  // signed, code-independent, and seed-stable: import_core_state replays
223
337
  // them through address_document::process_address_document so encrypted
@@ -284,6 +398,15 @@ library a2a_messaging loads libraries
284
398
 
285
399
  hidden
286
400
  {
401
+ // core 0.11 persist hardening (finding C redo): the $e2e_sessions blob from the
402
+ // boot import is PARKED here UNVALIDATED and UNASSIGNED — validation happens in
403
+ // the dedicated commit_e2e_restore transaction, where a corrupt pickle's hard
404
+ // BAD_PICKLE error fails that txn alone (atomic rollback, nothing assigned) and
405
+ // the host observes an identity-scoped failure. Transient boot state: NOT
406
+ // exported (the source blob is still on disk; a crash between import and commit
407
+ // simply re-stages on the next boot).
408
+ e2e_restore_staged is ( $v -> int, $account -> bin+, $sessions -> (global_id ->> bin)+ )+ = NIL.
409
+
287
410
  // ---- monitoring + config gate state (NON-app-writable) -----------
288
411
  // Hidden so only this library mutates it (the "app can't override"
289
412
  // guarantee). A pending 6-digit bind, and the verified control plane that
@@ -831,6 +954,278 @@ library a2a_messaging loads libraries
831
954
  return ($ad -> address_document::produce_my_address_document(), $cert -> my_cert_blob, $root_profile -> my_rp_blob, $cp_binding -> my_rpb_blob).
832
955
  }
833
956
 
957
+ // core 0.11 self-heal TRIGGER (receive side of a failed decode). A decode failure with
958
+ // one of the desync codes from an ACCEPTED e2e contact means the pair's session views
959
+ // diverged. Since persist-primary a clean restart RESUMES the live sessions, so this is
960
+ // the TRUE-loss path (state lost/rejected → account re-minted, sessions gone): the peer
961
+ // sends olm_type=1 on a session I no longer hold, or its fresh pre-key carries an ik my
962
+ // stored peer_ads predates. The message itself is undecryptable forever — recovery =
963
+ // tell the peer, authenticated, to re-key AND to refresh my AD (my re-minted account
964
+ // makes my previously advertised e2e_bundle stale). Rate-limited per (cid, session_id).
965
+ fn rekey_desync_code (code: str) -> bool
966
+ {
967
+ return code == "no_session" || code == "session_mismatch" || code == "tampered".
968
+ }
969
+ // Retain an outbound e2e app send until its delivered/read receipt (redrive source).
970
+ // Bounded three ways, never an abort: entry count (unacked_cap, oldest first),
971
+ // per-contact bytes (unacked_max_bytes — an entry alone above the budget is not
972
+ // retained at all), and age (unacked_ttl_seconds, purged by the periodic sweep).
973
+ // Typed retention result (review #7): the caller must SURFACE what the redrive
974
+ // guarantee actually covers. $retained FALSE = this send exceeded its byte budget
975
+ // and will NOT auto-resend on a lost session; $evicted = wire_ids of OLDER sends
976
+ // shed to admit this one (their at-least-once guarantee just ended) — never a
977
+ // silent drop.
978
+ fn unacked_note (cid: global_id, kind: str, wire_id: str, inner: bin, date: time)
979
+ -> ( $retained -> bool, $evicted -> str[] )
980
+ {
981
+ new_len = _binlen inner.
982
+ entry_cap is int = unacked_max_bytes.
983
+ if kind == "f" { entry_cap -> unacked_file_entry_max_bytes. }
984
+ if new_len > entry_cap { return ( $retained -> FALSE, $evicted -> [] ). }
985
+ evicted is str[] = [].
986
+ q0 = unacked_e2e cid.
987
+ kept is unacked_entry_t[] = [].
988
+ if q0 != NIL
989
+ {
990
+ // Totals INCLUDING the new entry, then shed oldest-first until both
991
+ // budgets (count, bytes) hold; copy the surviving suffix in order.
992
+ total is int = new_len.
993
+ cnt is int = 1.
994
+ sc q0? -- ( -> ent) { total -> total + (_binlen (ent $inner)). cnt -> cnt + 1. }
995
+ drop is int = 0.
996
+ sc q0? -- ( -> ent)
997
+ {
998
+ if cnt > unacked_cap || total > unacked_max_bytes
999
+ {
1000
+ total -> total - (_binlen (ent $inner)).
1001
+ cnt -> cnt - 1.
1002
+ drop -> drop + 1.
1003
+ evicted (_count evicted|) -> (ent $wire_id).
1004
+ }
1005
+ }
1006
+ i is int = 0.
1007
+ sc q0? -- ( -> ent) { if i >= drop { kept (_count kept|) -> ent. } i -> i + 1. }
1008
+ }
1009
+ kept (_count kept|) -> ($kind -> kind, $wire_id -> wire_id, $inner -> inner, $date -> date).
1010
+ unacked_e2e cid -> kept.
1011
+ return ( $retained -> TRUE, $evicted -> evicted ).
1012
+ }
1013
+ // Receive-side dedup store (see delivered_wire above): membership probe + bounded note.
1014
+ fn wire_seen (cid: global_id, wire_id: str) -> bool
1015
+ {
1016
+ q = delivered_wire cid.
1017
+ if q == NIL { return FALSE. }
1018
+ hit is bool = FALSE.
1019
+ sc q? -- ( -> e) { if (e $w) == wire_id { hit -> TRUE. } }
1020
+ return hit.
1021
+ }
1022
+ // AGE-ONLY retention (ship-review major-3): an entry is evicted only past
1023
+ // unacked_ttl_seconds — no count-based eviction inside the sender's redrive
1024
+ // window. The hard storage ceiling above is the sole exception; crossing it
1025
+ // returns the dropped wire_id so the CALLER surfaces the guarantee loss.
1026
+ fn delivered_note (cid: global_id, wire_id: str) -> ( $dropped -> str+ )
1027
+ {
1028
+ dropped is str+ = NIL.
1029
+ if wire_id != ""
1030
+ {
1031
+ now = (current_transaction_info::get_transaction_time())?.
1032
+ q0 = delivered_wire cid.
1033
+ aged is delivered_entry_t[] = [].
1034
+ if q0 != NIL
1035
+ {
1036
+ sc q0? -- ( -> e)
1037
+ { if (_substract_seconds now (e $d)) <= unacked_ttl_seconds { aged (_count aged|) -> e. } }
1038
+ }
1039
+ q is delivered_entry_t[] = [].
1040
+ skip is int = 0.
1041
+ if (_count aged|) >= delivered_wire_hard_cap
1042
+ {
1043
+ skip -> 1.
1044
+ sc aged -- ( -> e) { if dropped == NIL { dropped -> (e $w). } }
1045
+ }
1046
+ i is int = 0.
1047
+ sc aged -- ( -> e) { if i >= skip { q (_count q|) -> e. } i -> i + 1. }
1048
+ q (_count q|) -> ($w -> wire_id, $d -> now).
1049
+ delivered_wire cid -> q.
1050
+ }
1051
+ return ( $dropped -> dropped ).
1052
+ }
1053
+ // Drop the entries a delivered/read receipt covers. Returns TRUE when anything cleared.
1054
+ fn unacked_clear (cid: global_id, ids: str[]) -> bool
1055
+ {
1056
+ q0 = unacked_e2e cid.
1057
+ if q0 == NIL { return FALSE. }
1058
+ q is unacked_entry_t[] = [].
1059
+ dropped is bool = FALSE.
1060
+ sc q0? -- ( -> ent)
1061
+ {
1062
+ hit is bool = FALSE.
1063
+ sc ids -- ( -> w) { if w == (ent $wire_id) { hit -> TRUE. } }
1064
+ if hit { dropped -> TRUE. } else { q (_count q|) -> ent. }
1065
+ }
1066
+ if dropped != TRUE { return FALSE. }
1067
+ if (_count q|) == 0 { delete unacked_e2e cid. } else { unacked_e2e cid -> q. }
1068
+ return TRUE.
1069
+ }
1070
+ // Re-send every retained unacked message to cid, re-encrypted on the CURRENT session
1071
+ // (encrypt_to lazily establishes a fresh born-DR pre-key when none is live). Entries
1072
+ // STAY in the buffer — they clear on the delivered receipt (at-least-once; receivers
1073
+ // key receipts/dedup by wire_id). No-op without a usable peer bundle.
1074
+ // Does this peer advertise the self-heal cap (Leg-5 compat gate)? A pre-0.11 peer never
1075
+ // receives the unknown e2e_rekey_request tx — it gets a readvertise_ad instead.
1076
+ fn peer_supports_rekey (cid: global_id) -> bool
1077
+ {
1078
+ pcaps = contact_caps cid.
1079
+ if pcaps == NIL { return FALSE. }
1080
+ hit is bool = FALSE.
1081
+ sc pcaps? -- ( -> c) { if c == a2a_capabilities::cap_e2e_rekey { hit -> TRUE. } }
1082
+ return hit.
1083
+ }
1084
+ fn redrive_unacked_actions (cid: global_id) -> transaction::action::type[]
1085
+ {
1086
+ // Cap-gate (finding F): the at-least-once redrive REQUIRES receive-side
1087
+ // wire_id dedup, which only a 0.11 (cap_e2e_rekey) peer has. Replaying into
1088
+ // a pre-0.11 peer would deposit duplicates it cannot recognize. Its heal
1089
+ // path stays the readvertise + next-real-send establish (pre-existing).
1090
+ if (peer_supports_rekey cid) != TRUE { return []. }
1091
+ q = unacked_e2e cid.
1092
+ if q == NIL || (_count (q?)|) == 0 { return []. }
1093
+ pad = peer_ads cid.
1094
+ if pad == NIL { return []. }
1095
+ epb = (((pad?) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
1096
+ if epb == NIL { return []. }
1097
+ acts is transaction::action::type[] = [].
1098
+ sc q? -- ( -> ent)
1099
+ {
1100
+ eenv = e2e::encrypt_to cid (ent $inner) epb.
1101
+ acts (_count acts|) -> encrypted_channel::send_encrypted_tx cid (
1102
+ $name -> ((ent $kind) == "f" ?? receive_e2e_file_tx ; receive_e2e_message_tx),
1103
+ $targ -> ( $e2e_envelope -> (eenv $e2e_envelope), $emsignature -> (eenv $emsignature) ) ).
1104
+ acts (_count acts|) -> _notify_agent ( $event -> $e2e_app_send, $cid -> cid,
1105
+ $session_id -> ((eenv $e2e_envelope) $session_id), $olm_type -> ((eenv $e2e_envelope) $olm_type),
1106
+ $wire_id -> (ent $wire_id), $redriven -> TRUE ).
1107
+ }
1108
+ return acts.
1109
+ }
1110
+ // A CONTENTLESS e2e pre-key ("rekey ping"): the initiator sends it to BOOTSTRAP the shared
1111
+ // session when it has minted a fresh outbound but has no buffered app data to carry the
1112
+ // pre-key. The peer's decode establishes the session (and its session-replace redrives its
1113
+ // own buffer); the $rekey_ping marker suppresses any inbox deposit. Requires a live/just-
1114
+ // minted session (caller mints first); no-op without a peer bundle.
1115
+ fn rekey_ping_actions (cid: global_id) -> transaction::action::type[]
1116
+ {
1117
+ // Cap-gate (finding F): a pre-0.11 peer does not understand the $rekey_ping
1118
+ // marker — its receive path would treat the contentless bootstrap as an app
1119
+ // message. Only cap-advertising peers get pings.
1120
+ if (peer_supports_rekey cid) != TRUE { return []. }
1121
+ pad = peer_ads cid.
1122
+ if pad == NIL { return []. }
1123
+ epb = (((pad?) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
1124
+ if epb == NIL { return []. }
1125
+ pinner = _write ( $rekey_ping -> TRUE, $pv -> a2a_versions::wire_version ).
1126
+ eenv = e2e::encrypt_to cid pinner epb.
1127
+ return [ encrypted_channel::send_encrypted_tx cid (
1128
+ $name -> receive_e2e_message_tx,
1129
+ $targ -> ( $e2e_envelope -> (eenv $e2e_envelope), $emsignature -> (eenv $emsignature) ) ),
1130
+ _notify_agent ( $event -> $e2e_app_send, $cid -> cid, $rekey_ping -> TRUE,
1131
+ $session_id -> ((eenv $e2e_envelope) $session_id), $olm_type -> ((eenv $e2e_envelope) $olm_type) ) ].
1132
+ }
1133
+ // SIGNAL the peer to (re-)establish: carry my FRESH AD so it can authenticate my pre-keys,
1134
+ // and — if it speaks the cap — ask it to re-key. fsid is ADVISORY ($failed_session_id, NIL
1135
+ // for a proactive send-side nudge). Rate-limited per cid (attempts within a window) so a
1136
+ // decode-fail storm or a spammer cannot amplify. Sends exactly ONE control message. Does
1137
+ // NOT mint or redrive — the caller decides that by role (only the initiator mints).
1138
+ fn rekey_signal_actions (cid: global_id, fsid: bin+) -> transaction::action::type[]
1139
+ {
1140
+ now = (current_transaction_info::get_transaction_time())?.
1141
+ st = rekey_pending cid.
1142
+ att is int = 1.
1143
+ if st != NIL && (_substract_seconds now ((st?) $updated)) < rekey_min_interval_seconds
1144
+ {
1145
+ if ((st?) $attempts) >= rekey_max_attempts { return []. }
1146
+ att -> ((st?) $attempts) + 1.
1147
+ }
1148
+ rekey_pending cid -> ($session_id -> fsid, $attempts -> att, $updated -> now).
1149
+ b = my_identity_bundle_fields_fresh NIL.
1150
+ supports = peer_supports_rekey cid.
1151
+ acts is transaction::action::type[] = [].
1152
+ if supports
1153
+ {
1154
+ acts (_count acts|) -> encrypted_channel::send_encrypted_tx cid (
1155
+ $name -> e2e_rekey_request_tx,
1156
+ $targ -> ( $ad -> (b $ad), $cert -> (b $cert), $root_profile -> (b $root_profile),
1157
+ $cp_binding -> (b $cp_binding),
1158
+ $pv -> a2a_versions::wire_version,
1159
+ $caps -> (a2a_capabilities::self_cap_ids NIL),
1160
+ $failed_session_id -> fsid ) ).
1161
+ }
1162
+ else
1163
+ {
1164
+ acts (_count acts|) -> encrypted_channel::send_encrypted_tx cid (
1165
+ $name -> readvertise_ad_tx,
1166
+ $targ -> ( $ad -> (b $ad), $cert -> (b $cert), $root_profile -> (b $root_profile),
1167
+ $cp_binding -> (b $cp_binding),
1168
+ $pv -> a2a_versions::wire_version,
1169
+ $caps -> (a2a_capabilities::self_cap_ids NIL) ) ).
1170
+ }
1171
+ acts (_count acts|) -> _notify_agent ($event -> $e2e_rekey, $cid -> cid, $role -> $requester, $session_id -> fsid, $attempts -> att, $peer_supports -> supports).
1172
+ return acts.
1173
+ }
1174
+ // INITIATOR-ONLY re-establishment: mint ONE fresh outbound session (the sole new session
1175
+ // the pair converges on) and drive a pre-key to the peer — redriving buffered sends, or a
1176
+ // contentless ping if there is nothing to carry. Returns [] (mints nothing) unless I am the
1177
+ // elected initiator (lower cid), the cid-keyed budget allows it, the advisory fsid is not
1178
+ // stale, and no migration is in flight (the FSM owns re-key then). The NON-initiator never
1179
+ // calls through here — it signals and waits for THIS side's pre-key.
1180
+ fn maybe_init_rekey (cid: global_id, fsid: bin+) -> transaction::action::type[]
1181
+ {
1182
+ // Review #5: the whole self-heal replay/bootstrap is cap-gated, not just the
1183
+ // rekey_request leg — a pre-0.11 peer has no delivered_wire dedup (replay
1184
+ // would deposit duplicates) and no $rekey_ping handling (the contentless
1185
+ // bootstrap would surface as a broken app message). Its heal path remains
1186
+ // readvertise + the next real outbound establishing a fresh session.
1187
+ if (peer_supports_rekey cid) != TRUE { return []. }
1188
+ if (mig_initiator cid) != TRUE { return []. }
1189
+ if (peer_has_e2e_bundle cid) != TRUE { return []. }
1190
+ st = contact_migration cid.
1191
+ if st != NIL
1192
+ {
1193
+ ph = (st?) $phase.
1194
+ if ph == "offered" || ph == "acknowledged" || ph == "committed" { return []. }
1195
+ }
1196
+ now = (current_transaction_info::get_transaction_time())?.
1197
+ active is bin+ = e2e::active_session_id cid.
1198
+ if fsid != NIL && active != NIL && (active?) != (fsid?) { return []. } // stale request — I already rotated
1199
+ served is rekey_served_t+ = rekey_served cid.
1200
+ // Review #9: an aged ledger entry grants a fresh budget instead of a
1201
+ // permanent (until-restart) stall at the attempts cap.
1202
+ if served != NIL && (_substract_seconds now ((served?) $updated)) >= rekey_served_reset_seconds
1203
+ {
1204
+ delete rekey_served cid.
1205
+ served -> NIL.
1206
+ }
1207
+ if served != NIL
1208
+ {
1209
+ if ((served?) $attempts) >= rekey_served_max { return []. }
1210
+ if (_substract_seconds now ((served?) $updated)) < rekey_min_interval_seconds { return []. }
1211
+ }
1212
+ epb = ((((peer_ads cid)?) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
1213
+ if epb == NIL { return []. }
1214
+ att is int = 1.
1215
+ if served != NIL { att -> ((served?) $attempts) + 1. }
1216
+ rekey_served cid -> ($attempts -> att, $updated -> now).
1217
+ // Discard any orphaned staged slot (occupied outside an in-flight migration) so the
1218
+ // fresh rotation is the SOLE promotion; then mint the new outbound session.
1219
+ if (e2e::staged_session_id cid) != NIL { e2e::discard_rotation cid. }
1220
+ e2e::stage_outbound_rotation cid (epb?).
1221
+ e2e::commit_rotation cid.
1222
+ acts is transaction::action::type[] = [].
1223
+ sc redrive_unacked_actions cid -- ( -> a) { acts (_count acts|) -> a. }
1224
+ if (_count acts|) == 0 { sc rekey_ping_actions cid -- ( -> a) { acts (_count acts|) -> a. } }
1225
+ acts (_count acts|) -> _notify_agent ($event -> $e2e_rekey, $cid -> cid, $role -> $initiator, $session_id -> (e2e::active_session_id cid), $attempts -> att).
1226
+ return acts.
1227
+ }
1228
+
834
1229
  // Build + persist + send an OFFER (spec §5.4). Snapshot the fresh public bundle
835
1230
  // into the FSM entry FIRST, then build the wire targ FROM the snapshot (decoded),
836
1231
  // so first-send and every retransmit share ONE construction path and are
@@ -1295,6 +1690,9 @@ library a2a_messaging loads libraries
1295
1690
  epb = ((((peer_ads target_id)?) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
1296
1691
  einner = _write ( $text -> text, $wire_id -> wire_id, $reply_to -> reply_to, $pv -> a2a_versions::wire_version ).
1297
1692
  eenv = e2e::encrypt_to target_id einner epb.
1693
+ // core 0.11 self-heal: retain until the delivered receipt — the redrive source
1694
+ // if the peer restarted and this send lands on a dead session (silent-drop fix).
1695
+ m_res = unacked_note target_id "m" wire_id einner sent_date.
1298
1696
  eacts is transaction::action::type[] = [
1299
1697
  encrypted_channel::send_encrypted_tx target_id (
1300
1698
  $name -> receive_e2e_message_tx,
@@ -1304,8 +1702,8 @@ library a2a_messaging loads libraries
1304
1702
  // §4 observability: source $session_id from the ACTUAL envelope (NOT a re-read of
1305
1703
  // active_session_id — that would make the #1867 "session_id==pin" assertion CIRCULAR;
1306
1704
  // 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).
1705
+ 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, $retained -> (m_res $retained), $evicted -> (m_res $evicted) ).
1706
+ eacts (_count eacts|) -> _return_data ($sent_to -> target_id, $wire_id -> wire_id, $route -> $e2e, $retained -> (m_res $retained)).
1309
1707
  eacts (_count eacts|) -> _save_state NIL.
1310
1708
  return transaction::success eacts.
1311
1709
  }
@@ -1373,14 +1771,19 @@ library a2a_messaging loads libraries
1373
1771
  fepb = ((((peer_ads target_id)?) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
1374
1772
  finner = _write ( $filename -> filename, $mime -> mime_s, $data -> data, $wire_id -> wire_id, $reply_to -> reply_to, $pv -> a2a_versions::wire_version ).
1375
1773
  fenv = e2e::encrypt_to target_id finner fepb.
1774
+ // core 0.11 self-heal: files retain for redrive exactly like messages (review
1775
+ // fix — a restarted receiver silently losing FILES is the owner's primary case).
1776
+ // finding J: an oversized file (> unacked_file_entry_max_bytes) is NOT retained —
1777
+ // that MUST be surfaced, not silently reported as a plain success.
1778
+ f_res = unacked_note target_id "f" wire_id finner sent_date.
1376
1779
  feacts is transaction::action::type[] = [
1377
1780
  encrypted_channel::send_encrypted_tx target_id (
1378
1781
  $name -> receive_e2e_file_tx,
1379
1782
  $targ -> ( $e2e_envelope -> (fenv $e2e_envelope), $emsignature -> (fenv $emsignature) ) ) ].
1380
1783
  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
1784
  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).
1785
+ 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, $retained -> (f_res $retained), $evicted -> (f_res $evicted) ).
1786
+ feacts (_count feacts|) -> _return_data ($sent_to -> target_id, $wire_id -> wire_id, $route -> $e2e, $retained -> (f_res $retained)).
1384
1787
  feacts (_count feacts|) -> _save_state NIL.
1385
1788
  return transaction::success feacts.
1386
1789
  }
@@ -1432,6 +1835,13 @@ library a2a_messaging loads libraries
1432
1835
  // every export and, on a later RE-ADD of the same peer, the boot/GC sweep
1433
1836
  // would silently deliver the stale queued messages.
1434
1837
  if (deferred_msgs target_id) != NIL { delete deferred_msgs target_id. }
1838
+ // core 0.11 self-heal stores (review fix): unacked_e2e is EXPORTED plaintext —
1839
+ // removal must erase it (delete semantics), and a later re-add of the same cid
1840
+ // must never redrive removed-era messages or dedup against stale wire_ids.
1841
+ if (unacked_e2e target_id) != NIL { delete unacked_e2e target_id. }
1842
+ if (delivered_wire target_id) != NIL { delete delivered_wire target_id. }
1843
+ if (rekey_pending target_id) != NIL { delete rekey_pending target_id. }
1844
+ if (rekey_served target_id) != NIL { delete rekey_served target_id. }
1435
1845
  if (pending_restores target_id) != NIL { delete pending_restores target_id. }
1436
1846
  if (pending_restore_keys target_id) != NIL { delete pending_restore_keys target_id. }
1437
1847
  if (pending_restore_replies target_id) != NIL { delete pending_restore_replies target_id. }
@@ -2711,9 +3121,16 @@ library a2a_messaging loads libraries
2711
3121
  // byte-identical to the inlined form.
2712
3122
  // A rejected inbound (no-downgrade GATE0 / accept-gate / decode !ok): $e2e_app_recv $ok=FALSE,
2713
3123
  // 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
3124
+ // core 0.11: $code names WHY (additive notify field — observability, never silent):
3125
+ // "malformed" (GATE0) | "gate" (accept gate) | "no_peer_ad" (GATE1.5) |
3126
+ // the typed e2e decode code ("no_session" | "session_mismatch" | "tampered" | ...).
3127
+ fn mig_e2e_reject_actions (sender_id: global_id, env_sid: bin+, code: str) -> transaction::action::type[]
3128
+ {
3129
+ return [ _notify_agent ($event -> $e2e_app_recv, $cid -> sender_id, $session_id -> env_sid, $ok -> FALSE, $wire_id -> "", $code -> code) ].
3130
+ }
3131
+ fn mig_e2e_reject (sender_id: global_id, env_sid: bin+, code: str) -> transaction::results::type
2715
3132
  {
2716
- return transaction::success [ _notify_agent ($event -> $e2e_app_recv, $cid -> sender_id, $session_id -> env_sid, $ok -> FALSE, $wire_id -> "") ].
3133
+ return transaction::success (mig_e2e_reject_actions sender_id env_sid code).
2717
3134
  }
2718
3135
  // Shared ACCEPT-gate + do_ic computation for the two app-e2e RECEIVE handlers. Returns
2719
3136
  // ($accept, $do_ic). accept = e2e_pinned/seen OR committed-initiator-with-staged-match. do_ic
@@ -2761,6 +3178,18 @@ library a2a_messaging loads libraries
2761
3178
  fn mig_e2e_deliver_tail (sender_id: global_id, wire_id: str, env_sid: bin+) -> transaction::action::type[]
2762
3179
  {
2763
3180
  acts is transaction::action::type[] = [].
3181
+ // core 0.11 self-heal: a successful decode from this cid means the pair converged —
3182
+ // reset BOTH re-key budgets (requester + responder ledgers) so a FUTURE genuine
3183
+ // desync gets a fresh one.
3184
+ if (rekey_pending sender_id) != NIL { delete rekey_pending sender_id. }
3185
+ if (rekey_served sender_id) != NIL { delete rekey_served sender_id. }
3186
+ // Record the delivery for the at-least-once redrive dedup (no-op on ""). Rides the
3187
+ // same tx as the deposit, so guard and inbox commit or roll back together.
3188
+ // Ship-review major-3: crossing the storage ceiling drops the oldest in-TTL
3189
+ // entry — a real dedup-guarantee loss, surfaced, never silent.
3190
+ dn = delivered_note sender_id wire_id.
3191
+ if (dn $dropped) != NIL
3192
+ { acts (_count acts|) -> _notify_agent ($event -> $dedup_degraded, $cid -> sender_id, $dropped_wire_id -> ((dn $dropped)?)). }
2764
3193
  if wire_id != ""
2765
3194
  { sc receipt_actions sender_id "delivered" [wire_id] -- ( -> a) { acts (_count acts|) -> a. } }
2766
3195
  acts (_count acts|) -> _notify_agent ($event -> $e2e_app_recv, $cid -> sender_id, $session_id -> env_sid, $ok -> TRUE, $wire_id -> wire_id).
@@ -2794,7 +3223,7 @@ library a2a_messaging loads libraries
2794
3223
  // GATE 0 — carrier shape (no-downgrade: fail CLOSED on a missing/garbage envelope).
2795
3224
  env is e2e::t_e2e_envelope+ = (args $e2e_envelope) safe e2e::t_e2e_envelope.
2796
3225
  emsig is crypto_signature+ = (args $emsignature) safe crypto_signature.
2797
- if env == NIL || emsig == NIL { return mig_e2e_reject sender_id NIL. }
3226
+ if env == NIL || emsig == NIL { return mig_e2e_reject sender_id NIL "malformed". }
2798
3227
  env_sid = (env? $session_id).
2799
3228
 
2800
3229
  // GATE 1 — ACCEPT gate. The SEND side boxes app as receive_e2e_message_tx whenever the route
@@ -2808,12 +3237,12 @@ library a2a_messaging loads libraries
2808
3237
  // DECOUPLED from the accept branch — else it would be UNREACHABLE in production (a real
2809
3238
  // migrating pair is `seen` by `committed`).
2810
3239
  g = mig_e2e_accept sender_id.
2811
- if (g $accept) != TRUE { return mig_e2e_reject sender_id env_sid. }
3240
+ if (g $accept) != TRUE { return mig_e2e_reject sender_id env_sid "gate". }
2812
3241
  do_ic is bool = (g $do_ic).
2813
3242
 
2814
3243
  // GATE 1.5 — the box sender's VERIFIED AD is required to authenticate the envelope.
2815
3244
  pad = peer_ads sender_id.
2816
- if pad == NIL { return mig_e2e_reject sender_id env_sid. }
3245
+ if pad == NIL { return mig_e2e_reject sender_id env_sid "no_peer_ad". }
2817
3246
 
2818
3247
  // GATE 2 — handler-driven AUTHENTICATED decode (shared audited path). For a pinned/active
2819
3248
  // contact mig_pending is FALSE → decrypt_and_commit advances m_sessions[cid] (the migrated
@@ -2821,16 +3250,75 @@ library a2a_messaging loads libraries
2821
3250
  // olm_type=1 rides the STAGED slot (m_sessions still NIL until commit_rotation in the
2822
3251
  // promote helper). A !ok is OLM-level (tampered/replay) — forged emsig/wire already ABORTED
2823
3252
  // inside decode_migration_envelope. Reject-as-data, never delivered.
3253
+ pre_sid is bin+ = e2e::active_session_id sender_id.
2824
3254
  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. }
3255
+ if (r $ok) != TRUE
3256
+ {
3257
+ // core 0.11 self-heal: surface the typed code, and on a desync signature
3258
+ // (no_session / session_mismatch / tampered) fire the rate-limited re-key
3259
+ // request back to the sender — the message is undecryptable forever, but the
3260
+ // pair re-keys and the sender's unacked redrive re-delivers it (no silent drop).
3261
+ code is str = "internal".
3262
+ if (r $error) != NIL { code -> ((r $error)?) $code. }
3263
+ racts is transaction::action::type[] = mig_e2e_reject_actions sender_id env_sid code.
3264
+ if rekey_desync_code code
3265
+ {
3266
+ // Signal the peer (carry my fresh AD; ask for re-key if it speaks the cap),
3267
+ // then — only if I am the elected initiator — mint the fresh session myself.
3268
+ sc rekey_signal_actions sender_id env_sid -- ( -> a) { racts (_count racts|) -> a. }
3269
+ sc maybe_init_rekey sender_id env_sid -- ( -> a) { racts (_count racts|) -> a. }
3270
+ racts (_count racts|) -> _save_state NIL.
3271
+ }
3272
+ return transaction::success racts.
3273
+ }
2826
3274
  // Decrypted inner app body (mirrors send_message's einner _write shape).
2827
3275
  iv = key_storage::read_external ((r $plaintext)?).
3276
+ // core 0.11 self-heal: a rekey PING (contentless bootstrap pre-key) — the decode above
3277
+ // established/replaced our session; redrive our buffer onto it and deliver NOTHING to
3278
+ // the inbox. Heals the pair without an app message.
3279
+ if (iv $rekey_ping) == TRUE
3280
+ {
3281
+ pacts is transaction::action::type[] = [].
3282
+ if (rekey_pending sender_id) != NIL { delete rekey_pending sender_id. }
3283
+ if (rekey_served sender_id) != NIL { delete rekey_served sender_id. }
3284
+ sc redrive_unacked_actions sender_id -- ( -> a) { pacts (_count pacts|) -> a. }
3285
+ pacts (_count pacts|) -> _notify_agent ($event -> $e2e_rekey, $cid -> sender_id, $role -> $healed, $session_id -> env_sid).
3286
+ pacts (_count pacts|) -> _save_state NIL.
3287
+ return transaction::success pacts.
3288
+ }
2828
3289
  text = (iv $text) safe str.
2829
3290
  wire_id is str = "".
2830
3291
  if (iv $wire_id) != NIL { wire_id -> (iv $wire_id) safe str. }
2831
3292
  reply_to is a2a_protocol::reply_ref_t+ = NIL.
2832
3293
  if (iv $reply_to) != NIL { reply_to -> (iv $reply_to) safe a2a_protocol::reply_ref_t. }
2833
3294
 
3295
+ // core 0.11 self-heal: at-least-once redrive dedup. An already-delivered wire_id
3296
+ // RE-ACKS (so the sender's unacked buffer clears even when the first receipt was
3297
+ // lost) but never re-deposits into the inbox. The decode above ADVANCED the
3298
+ // ratchet — persist it (the _save_state below), or a restart would desync again.
3299
+ if wire_id != "" && (wire_seen sender_id wire_id)
3300
+ {
3301
+ dacts is transaction::action::type[] = [].
3302
+ // Review #10: a duplicate can be the FIRST proof of the migrated session —
3303
+ // the implicit-confirm promotion must not be skipped or committed stalls.
3304
+ if do_ic { sc mig_e2e_promote_actions sender_id ((contact_migration sender_id)?) -- ( -> a) { dacts (_count dacts|) -> a. } }
3305
+ sc receipt_actions sender_id "delivered" [wire_id] -- ( -> a) { dacts (_count dacts|) -> a. }
3306
+ // Convergence must not be skipped on the duplicate path (finding I): the
3307
+ // decode above was a REAL successful decode — reset both re-key budgets
3308
+ // (a future genuine desync needs a fresh one), and if it was a pre-key
3309
+ // that REPLACED our live session (the peer restarted and is redriving),
3310
+ // re-encrypt our own retained sends onto the fresh session NOW — the
3311
+ // duplicate is often the FIRST inbound after the peer's recovery.
3312
+ if (rekey_pending sender_id) != NIL { delete rekey_pending sender_id. }
3313
+ if (rekey_served sender_id) != NIL { delete rekey_served sender_id. }
3314
+ dup_post_sid is bin+ = e2e::active_session_id sender_id.
3315
+ if pre_sid != NIL && dup_post_sid != NIL && (pre_sid?) != (dup_post_sid?)
3316
+ { sc redrive_unacked_actions sender_id -- ( -> a) { dacts (_count dacts|) -> a. } }
3317
+ dacts (_count dacts|) -> _notify_agent ($event -> $e2e_app_recv, $cid -> sender_id, $session_id -> env_sid, $ok -> TRUE, $wire_id -> wire_id, $duplicate -> TRUE).
3318
+ dacts (_count dacts|) -> _save_state NIL.
3319
+ return transaction::success dacts.
3320
+ }
3321
+
2834
3322
  actions is transaction::action::type[] = [].
2835
3323
  // do_ic: promote BEFORE deliver, SAME tx (must-fix-C rollback — see mig_e2e_promote_actions).
2836
3324
  if do_ic { sc mig_e2e_promote_actions sender_id ((contact_migration sender_id)?) -- ( -> a) { actions (_count actions|) -> a. } }
@@ -2850,6 +3338,13 @@ library a2a_messaging loads libraries
2850
3338
  $reply_to -> reply_to
2851
3339
  ) -- ( -> a) { actions (_count actions|) -> a. }
2852
3340
  sc monitor_copy_actions "in" sender_id msg_date text -- ( -> a) { actions (_count actions|) -> a. }
3341
+ // core 0.11 self-heal: the decode REPLACED our live session (the peer's fresh pre-key
3342
+ // after ITS restart — the 0.8.0 establish path swapped m_sessions[cid]). Any sends we
3343
+ // retained re-encrypt on the fresh session NOW, so the pair converges without waiting
3344
+ // for a rekey round-trip.
3345
+ post_sid is bin+ = e2e::active_session_id sender_id.
3346
+ if pre_sid != NIL && post_sid != NIL && (pre_sid?) != (post_sid?)
3347
+ { sc redrive_unacked_actions sender_id -- ( -> a) { actions (_count actions|) -> a. } }
2853
3348
  sc mig_e2e_deliver_tail sender_id wire_id env_sid -- ( -> a) { actions (_count actions|) -> a. }
2854
3349
  // §5.4 trigger (the PRODUCTION-GAP fix): an already-e2e pair receives app data HERE (it never
2855
3350
  // plaintext-receives), so mirror the plaintext-handler liveness offer. Fires once — then
@@ -2882,20 +3377,34 @@ library a2a_messaging loads libraries
2882
3377
  // GATE 0 — carrier shape (no-downgrade).
2883
3378
  env is e2e::t_e2e_envelope+ = (args $e2e_envelope) safe e2e::t_e2e_envelope.
2884
3379
  emsig is crypto_signature+ = (args $emsignature) safe crypto_signature.
2885
- if env == NIL || emsig == NIL { return mig_e2e_reject sender_id NIL. }
3380
+ if env == NIL || emsig == NIL { return mig_e2e_reject sender_id NIL "malformed". }
2886
3381
  env_sid = (env? $session_id).
2887
3382
 
2888
3383
  // GATE 1 — ACCEPT gate + do_ic (shared with the message handler; do_ic decoupled).
2889
3384
  g = mig_e2e_accept sender_id.
2890
- if (g $accept) != TRUE { return mig_e2e_reject sender_id env_sid. }
3385
+ if (g $accept) != TRUE { return mig_e2e_reject sender_id env_sid "gate". }
2891
3386
  do_ic is bool = (g $do_ic).
2892
3387
 
2893
3388
  pad = peer_ads sender_id.
2894
- if pad == NIL { return mig_e2e_reject sender_id env_sid. }
3389
+ if pad == NIL { return mig_e2e_reject sender_id env_sid "no_peer_ad". }
2895
3390
 
2896
3391
  // GATE 2 — authenticated decode.
3392
+ pre_sid is bin+ = e2e::active_session_id sender_id.
2897
3393
  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. }
3394
+ if (r $ok) != TRUE
3395
+ {
3396
+ // core 0.11 self-heal (file analogue — same desync trigger as the message handler).
3397
+ code is str = "internal".
3398
+ if (r $error) != NIL { code -> ((r $error)?) $code. }
3399
+ racts is transaction::action::type[] = mig_e2e_reject_actions sender_id env_sid code.
3400
+ if rekey_desync_code code
3401
+ {
3402
+ sc rekey_signal_actions sender_id env_sid -- ( -> a) { racts (_count racts|) -> a. }
3403
+ sc maybe_init_rekey sender_id env_sid -- ( -> a) { racts (_count racts|) -> a. }
3404
+ racts (_count racts|) -> _save_state NIL.
3405
+ }
3406
+ return transaction::success racts.
3407
+ }
2899
3408
  // Decrypted inner file body (mirrors send_file's finner _write shape).
2900
3409
  iv = key_storage::read_external ((r $plaintext)?).
2901
3410
  filename = (iv $filename) safe str.
@@ -2907,6 +3416,27 @@ library a2a_messaging loads libraries
2907
3416
  reply_to is a2a_protocol::reply_ref_t+ = NIL.
2908
3417
  if (iv $reply_to) != NIL { reply_to -> (iv $reply_to) safe a2a_protocol::reply_ref_t. }
2909
3418
 
3419
+ // At-least-once redrive dedup for FILES (finding E) — mirrors the message
3420
+ // handler: a re-delivered wire_id RE-ACKS (the sender's buffer clears even
3421
+ // when the first receipt was lost) but never re-deposits the file. Includes
3422
+ // the same convergence as the message path (finding I): budget resets + the
3423
+ // session-replace redrive. Without this a file redrive deposited a duplicate.
3424
+ if wire_id != "" && (wire_seen sender_id wire_id)
3425
+ {
3426
+ fdacts is transaction::action::type[] = [].
3427
+ // Review #10: same implicit-confirm promotion as the message dup path.
3428
+ if do_ic { sc mig_e2e_promote_actions sender_id ((contact_migration sender_id)?) -- ( -> a) { fdacts (_count fdacts|) -> a. } }
3429
+ sc receipt_actions sender_id "delivered" [wire_id] -- ( -> a) { fdacts (_count fdacts|) -> a. }
3430
+ if (rekey_pending sender_id) != NIL { delete rekey_pending sender_id. }
3431
+ if (rekey_served sender_id) != NIL { delete rekey_served sender_id. }
3432
+ fdup_post_sid is bin+ = e2e::active_session_id sender_id.
3433
+ if pre_sid != NIL && fdup_post_sid != NIL && (pre_sid?) != (fdup_post_sid?)
3434
+ { sc redrive_unacked_actions sender_id -- ( -> a) { fdacts (_count fdacts|) -> a. } }
3435
+ fdacts (_count fdacts|) -> _notify_agent ($event -> $e2e_app_recv, $cid -> sender_id, $session_id -> env_sid, $ok -> TRUE, $wire_id -> wire_id, $duplicate -> TRUE, $file -> TRUE).
3436
+ fdacts (_count fdacts|) -> _save_state NIL.
3437
+ return transaction::success fdacts.
3438
+ }
3439
+
2910
3440
  actions is transaction::action::type[] = [].
2911
3441
  if do_ic { sc mig_e2e_promote_actions sender_id ((contact_migration sender_id)?) -- ( -> a) { actions (_count actions|) -> a. } }
2912
3442
 
@@ -2924,6 +3454,10 @@ library a2a_messaging loads libraries
2924
3454
  $reply_to -> reply_to
2925
3455
  ) -- ( -> a) { actions (_count actions|) -> a. }
2926
3456
  sc monitor_copy_actions "in" sender_id file_date (file_monitor_summary filename mime data) -- ( -> a) { actions (_count actions|) -> a. }
3457
+ // core 0.11 self-heal: session replaced by the peer's fresh pre-key → redrive unacked.
3458
+ post_sid is bin+ = e2e::active_session_id sender_id.
3459
+ if pre_sid != NIL && post_sid != NIL && (pre_sid?) != (post_sid?)
3460
+ { sc redrive_unacked_actions sender_id -- ( -> a) { actions (_count actions|) -> a. } }
2927
3461
  sc mig_e2e_deliver_tail sender_id wire_id env_sid -- ( -> a) { actions (_count actions|) -> a. }
2928
3462
  // §5.4 trigger (the PRODUCTION-GAP fix, _file analogue of the message handler): an already-e2e
2929
3463
  // pair receiving a FILE over e2e must also auto-offer. Fires once; contact_migration!=NIL (+ epoch
@@ -2985,6 +3519,13 @@ library a2a_messaging loads libraries
2985
3519
  {
2986
3520
  actions (_count actions|) -> a.
2987
3521
  }
3522
+ // core 0.11 self-heal: a delivered/read receipt retires the redrive retention for
3523
+ // these wire_ids. Persist the shrink — otherwise a restart resurrects acked entries
3524
+ // and a later redrive would duplicate them.
3525
+ if unacked_clear sender_id ids
3526
+ {
3527
+ actions (_count actions|) -> _save_state NIL.
3528
+ }
2988
3529
  return transaction::success actions.
2989
3530
  }
2990
3531
 
@@ -3118,6 +3659,13 @@ library a2a_messaging loads libraries
3118
3659
  if (contacts sender_id) == NIL { return transaction::success []. }
3119
3660
  // Verify + ingest the refreshed AD (cid-bind + PoP; forgery aborts). Caller writes peer_ads.
3120
3661
  vb = verify_identity_bundle (args as any) sender_id.
3662
+ // F187 anti-downgrade (core 0.11): a KNOWN-e2e contact never legitimately refreshes
3663
+ // to a bundle-less (v1, down-levelled) AD — accepting one would overwrite the v2
3664
+ // peer_ads entry and brick the pair into downgrade_refused (state poisoning by an
3665
+ // authenticated-but-misbehaving peer). Validate BEFORE the write; ignore otherwise.
3666
+ ra_bundle = (((vb $ad) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
3667
+ if (e2e_pinned sender_id || (contact_e2e_epoch sender_id) != NIL) && ra_bundle == NIL
3668
+ { return transaction::success []. }
3121
3669
  peer_ads sender_id -> (vb $ad).
3122
3670
  // Learn the peer's version + caps piggyback so it becomes known-0.9 (the mig_should_trigger gate).
3123
3671
  pv_seen = a2a_versions::peer_pv args.
@@ -3137,6 +3685,103 @@ library a2a_messaging loads libraries
3137
3685
  }
3138
3686
  trn readvertise_ad args: any { return handle_readvertise_ad args. }
3139
3687
 
3688
+ // core 0.11 (session self-heal): the peer's DECODE of my e2e traffic failed with a desync
3689
+ // code — it cannot read my current session (typically: it restarted and lost its sessions,
3690
+ // so my olm_type=1 traffic is undecryptable for it, and/or my stored copy of its AD
3691
+ // predates its re-minted account, so its fresh pre-keys fail MY authenticated decode).
3692
+ // The request carries the peer's FRESH identity bundle: verify (forgery aborts — same
3693
+ // verify_identity_bundle trust as readvertise, which already overwrites peer_ads),
3694
+ // refresh peer_ads, then REPLACE my dead outbound session with a fresh born-DR one via
3695
+ // the SOLE promotion APIs (stage_outbound_rotation + commit_rotation — never a raw write)
3696
+ // and redrive my retained unacked sends on it (re-encrypted; the dropped originals are
3697
+ // undecryptable forever, re-delivery is the only path to the peer's inbox). Answer with
3698
+ // MY fresh AD (readvertise back) so a MUTUALLY-stale pair (both restarted) converges in
3699
+ // one exchange: both peer_ads fresh → all surviving traffic is fresh pre-keys → the
3700
+ // 0.8.0 establish path accepts them. No epoch/pin state is touched (no downgrade
3701
+ // surface). Replay/spam is bounded RESPONDER-side (see the gating below): a rotation
3702
+ // is served only for MY CURRENT session id and at most once per cooldown window —
3703
+ // a replayed or repeated request degrades to the idempotent peer_ads refresh. The
3704
+ // requester side is additionally rate-limited per (cid, session_id). A migration
3705
+ // genuinely in flight owns its staged slot — never clobbered here; the sweep
3706
+ // supersedes it.
3707
+ fn handle_e2e_rekey_request (args: any) -> transaction::results::type
3708
+ {
3709
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
3710
+ encrypted_channel::check_encrypted_or_abort().
3711
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
3712
+ // Only known contacts; an unknown sender is a silent no-op (no state, no leak).
3713
+ if (contacts sender_id) == NIL { return transaction::success []. }
3714
+ // Verify the refreshed AD (cid-bind + PoP; forgery aborts) — but VALIDATE BEFORE
3715
+ // ANY WRITE (F187 anti-downgrade/poisoning): a known-e2e contact's refresh MUST
3716
+ // carry an e2e_bundle. A bundle-less (v1, down-levelled) AD from an authenticated
3717
+ // -but-misbehaving peer would otherwise overwrite the known-v2 peer_ads entry and
3718
+ // brick the pair into downgrade_refused until the next genuine readvertise.
3719
+ vb = verify_identity_bundle (args as any) sender_id.
3720
+ vb_bundle = (((vb $ad) as any) $identity $e2e_bundle) safe address_document_types::t_e2e_bundle.
3721
+ if (e2e_pinned sender_id || (contact_e2e_epoch sender_id) != NIL) && vb_bundle == NIL
3722
+ { return transaction::success [ _notify_agent ($event -> $e2e_rekey, $cid -> sender_id, $role -> $responder, $rejected -> $bundle_less) ]. }
3723
+ peer_ads sender_id -> (vb $ad).
3724
+ pv_seen = a2a_versions::peer_pv args.
3725
+ caps_in is str[] = ((args $caps) == NIL ?? [] ; ((args $caps) safe (str[]))).
3726
+ learn_contact_version sender_id ((pv_seen != 0 ?? pv_seen ; 9)) caps_in.
3727
+ actions is transaction::action::type[] = [].
3728
+ fsid is bin+ = (args $failed_session_id) safe bin.
3729
+ now = (current_transaction_info::get_transaction_time())?.
3730
+ // CONVERGENCE LEG (Dev-1 residual LOW): readvertise my fresh AD BACK — this is how the
3731
+ // requester refreshes ITS stored copy of MY bundle when I (not it) re-minted my account.
3732
+ // It must NOT hide behind the rotation gate (a throttled/non-initiator request would then
3733
+ // starve the one-side-restarted case).
3734
+ // Review #9: the cooldown now has its OWN ledger (ad_response_last) — the old check read
3735
+ // rekey_served, which only maybe_init_rekey writes, so a NON-initiator responder had NO
3736
+ // cooldown at all: every authenticated request minted a fresh signed AD + save.
3737
+ prev_resp = ad_response_last sender_id.
3738
+ cool_ok is bool = prev_resp == NIL || (_substract_seconds now (prev_resp?)) >= rekey_min_interval_seconds.
3739
+ if cool_ok
3740
+ {
3741
+ ad_response_last sender_id -> now.
3742
+ b = my_identity_bundle_fields_fresh NIL.
3743
+ actions (_count actions|) -> encrypted_channel::send_encrypted_tx sender_id (
3744
+ $name -> readvertise_ad_tx,
3745
+ $targ -> ( $ad -> (b $ad), $cert -> (b $cert), $root_profile -> (b $root_profile),
3746
+ $cp_binding -> (b $cp_binding),
3747
+ $pv -> a2a_versions::wire_version,
3748
+ $caps -> (a2a_capabilities::self_cap_ids NIL) ) ).
3749
+ }
3750
+ // SINGLE-INITIATOR re-establishment: mint the fresh session ONLY if I am the elected
3751
+ // initiator (maybe_init_rekey enforces role + cid-keyed budget + advisory-sid + no
3752
+ // in-flight migration). As the NON-initiator I only refreshed peer_ads + readvertised
3753
+ // back; the initiator (the requester, here) mints on ITS side and its pre-key
3754
+ // establishes the shared session on mine. Exactly one minter ⇒ no glare.
3755
+ sc maybe_init_rekey sender_id fsid -- ( -> a) { actions (_count actions|) -> a. }
3756
+ // TRUE-loss liveness, higher-cid side (review #6 — NO MINT, no glare). When the
3757
+ // REQUESTER is the elected initiator (I am NOT), it lost its state: it has
3758
+ // nothing to redrive and nothing re-triggers its own mint — my readvertise
3759
+ // above only refreshes its copy of my bundle, and my own sweep waits up to a
3760
+ // GC period. fsid == my ACTIVE session id proves the request is about my
3761
+ // CURRENT session (not stale/replayed). Re-drive my buffer (or send a
3762
+ // cap-gated ping) on the EXISTING session NOW: the requester cannot decode
3763
+ // those (it lost the session), each failed decode fires its reject path —
3764
+ // rekey_signal + maybe_init_rekey — and by then it holds my fresh AD from the
3765
+ // readvertise above, so THE INITIATOR mints, exactly one minter, no glare.
3766
+ // Bounded by the same ad_response cooldown as the readvertise (cool_ok).
3767
+ if cool_ok && (mig_initiator sender_id) != TRUE && (contact_migration sender_id) == NIL
3768
+ {
3769
+ g_active is bin+ = e2e::active_session_id sender_id.
3770
+ if fsid != NIL && g_active != NIL && (g_active?) == (fsid?)
3771
+ {
3772
+ pre_cnt is int = (_count actions|).
3773
+ sc redrive_unacked_actions sender_id -- ( -> a) { actions (_count actions|) -> a. }
3774
+ if (_count actions|) == pre_cnt
3775
+ { sc rekey_ping_actions sender_id -- ( -> a) { actions (_count actions|) -> a. } }
3776
+ if (_count actions|) > pre_cnt
3777
+ { actions (_count actions|) -> _notify_agent ($event -> $e2e_rekey, $cid -> sender_id, $role -> $responder_retrigger, $session_id -> fsid). }
3778
+ }
3779
+ }
3780
+ actions (_count actions|) -> _save_state NIL.
3781
+ return transaction::success actions.
3782
+ }
3783
+ trn e2e_rekey_request args: any { return handle_e2e_rekey_request args. }
3784
+
3140
3785
  // ACK handler (initiator). Gates: narrow -> FSM phase==offered ∧ ack echoes my nonce
3141
3786
  // -> verify bundle (forgery aborts) -> bundle-presence -> compute the SAME epoch ->
3142
3787
  // WRITES LAST. NOTE: the §5.5 COMMIT continuation (stage_outbound_rotation + send
@@ -3483,6 +4128,173 @@ library a2a_messaging loads libraries
3483
4128
  return transaction::success actions.
3484
4129
  }
3485
4130
 
4131
+ // Coherence probe (finding #3 evidence): the ik_curve of MY CURRENT account's
4132
+ // public bundle. Host compares it against the transport IPD's advertised bundle
4133
+ // post-restore. Readonly; account() only mutates when NO account exists — never
4134
+ // the case on this call path (ctor mints one before any host-driven restore).
4135
+ trn readonly e2e_self_fp _
4136
+ {
4137
+ return ( $ik -> ((e2e::my_public_bundle NIL) $ik_curve) ).
4138
+ }
4139
+
4140
+ // Finding C redo — the VALIDATION transaction. Runs alone (host-driven, boot,
4141
+ // pre-exposure): validates + assigns the staged $e2e_sessions blob. A corrupt
4142
+ // pickle raises the engine's HARD BAD_PICKLE inside e2e::import_sessions, which
4143
+ // fails THIS txn atomically — nothing assigned, staging untouched — and the host
4144
+ // observes the failure (unambiguous: nothing but validation runs here) and calls
4145
+ // reject_e2e_restore. Success persists the restored sessions with the txn.
4146
+ trn commit_e2e_restore _
4147
+ {
4148
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
4149
+ if e2e_restore_staged == NIL
4150
+ { return transaction::success [ _return_data ($status -> $none) ]. }
4151
+ n = e2e::import_sessions (e2e_restore_staged?).
4152
+ e2e_restore_staged -> NIL.
4153
+ return transaction::success [ _return_data ($status -> $ok, $sessions -> n), _save_state NIL ].
4154
+ }
4155
+
4156
+ // Finding C redo — the REJECT leg: discard the corrupt staged blob (the live e2e
4157
+ // state is untouched — the ctor-minted fresh account stays, the self-heal fallback
4158
+ // re-establishes) and surface the rejection. Host calls this after observing a
4159
+ // commit_e2e_restore failure; the _save_state persists the now-clean export so the
4160
+ // corrupt pickles never come back on the next boot.
4161
+ trn reject_e2e_restore _
4162
+ {
4163
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
4164
+ e2e_restore_staged -> NIL.
4165
+ return transaction::success [
4166
+ _notify_agent ($event -> $e2e_restore_rejected),
4167
+ _return_data ($status -> $rejected),
4168
+ _save_state NIL ].
4169
+ }
4170
+
4171
+ // core 0.11 (session self-heal, boot leg): push my FRESH AD to every E2E-CAPABLE contact —
4172
+ // the complement of readvertise_on_upgrade's legacy-only set. Since persist-primary a
4173
+ // clean restart RESUMES the account+sessions and this push is a cheap refresh; it is
4174
+ // LOAD-BEARING on the fallback path (persisted state lost/rejected → the account was
4175
+ // re-minted, so the e2e_bundle every peer holds for me is stale; until a peer refreshes
4176
+ // it, my fresh pre-keys fail its authenticated decode (session_mismatch) while its
4177
+ // olm_type=1 traffic to me is undecryptable (no_session) — the two-sided black hole).
4178
+ // This stateless push re-arms the 0.8.0 pre-key-replace self-heal. A pre-0.10 peer
4179
+ // ignores the tx (readvertise precedent). The daemon calls this on EVERY boot, alongside
4180
+ // readvertise_on_upgrade and sweep_e2e_migrations (DAEMON CONTRACT).
4181
+ trn readvertise_e2e_recovery _
4182
+ {
4183
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
4184
+ b = my_identity_bundle_fields_fresh NIL.
4185
+ actions is transaction::action::type[] = [].
4186
+ n is int = 0.
4187
+ sc contacts -- (cid -> ) ?? ((contact_e2e_epoch cid) != NIL || (contact_born_dr cid) == TRUE || (e2e_pinned cid) || (contact_migration cid) != NIL)
4188
+ {
4189
+ actions (_count actions|) -> encrypted_channel::send_encrypted_tx cid (
4190
+ $name -> readvertise_ad_tx,
4191
+ $targ -> ( $ad -> (b $ad), $cert -> (b $cert), $root_profile -> (b $root_profile),
4192
+ $cp_binding -> (b $cp_binding),
4193
+ $pv -> a2a_versions::wire_version,
4194
+ $caps -> (a2a_capabilities::self_cap_ids NIL) ) ).
4195
+ n -> n + 1.
4196
+ }
4197
+ actions (_count actions|) -> _return_data ($readvertised -> n).
4198
+ return transaction::success actions.
4199
+ }
4200
+
4201
+ // core 0.11 (session self-heal, retry leg): re-send unacked e2e messages stuck without
4202
+ // a delivered receipt for redrive_min_age_seconds+ (see the const above). Host calls
4203
+ // this on the boot/GC cadence next to readvertise_e2e_recovery. Mutates session state
4204
+ // (encrypt_to advances the ratchet) → _save_state when anything was redriven.
4205
+ trn redrive_unacked_sweep _
4206
+ {
4207
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
4208
+ now = (current_transaction_info::get_transaction_time())?.
4209
+ actions is transaction::action::type[] = [].
4210
+ // Separate counters (finding K / review #15): a TTL purge is NOT a redrive,
4211
+ // and a deferred contact is neither — the log must say what actually happened.
4212
+ purged is int = 0.
4213
+ redriven is int = 0.
4214
+ deferred is int = 0.
4215
+ // Ship-review major-4: ONE bounded, resumable pass over BOTH phases. Per
4216
+ // contact: (1) TTL purge — entries past unacked_ttl_seconds drop for good
4217
+ // (a peer withholding receipts cannot pin plaintext forever) with ONE
4218
+ // $e2e_delivery_expired RET per affected contact (review #7: explicit, never
4219
+ // silent) — then (2) the aged redrive. Budgets bound the WHOLE txn: crypto
4220
+ // ops (ratchet encryptions — this path performs zero sig-verifies, so the op
4221
+ // count is exact, not a fuel proxy) and emitted actions (SEND/RET including
4222
+ // the expiry notifies). A contact whose worst case would overflow either
4223
+ // budget is deferred; the EXPORTED cursor resumes there next sweep, and a
4224
+ // sweep-txn abort rolls the cursor back so a retry covers the same segment.
4225
+ crypto_budget is int = redrive_sweep_max_entries.
4226
+ // Ship-review round-2 minor: reserve the fixed 2-action tail (_save_state +
4227
+ // _return_data) up front so the emitted total NEVER exceeds
4228
+ // redrive_sweep_max_actions — the no-save case uses only 1 of the 2 (the
4229
+ // _return_data), which is slack, not overflow.
4230
+ action_budget is int = redrive_sweep_max_actions - 2.
4231
+ resume_after is global_id+ = redrive_sweep_cursor.
4232
+ past_cursor is bool = (resume_after == NIL).
4233
+ last_done is global_id+ = NIL.
4234
+ exhausted is bool = FALSE.
4235
+ expired is global_id[] = [].
4236
+ sc unacked_e2e -- (cid -> q) ?? (_count q|) > 0
4237
+ {
4238
+ if past_cursor != TRUE
4239
+ {
4240
+ deferred -> deferred + 1.
4241
+ if cid == (resume_after?) { past_cursor -> TRUE. }
4242
+ }
4243
+ else
4244
+ {
4245
+ // worst case for this contact: 1 expiry RET + (1 crypto op + 2 actions)
4246
+ // per redriven entry
4247
+ if exhausted || (_count q|) > crypto_budget || action_budget < ((_count q|) * 2 + 1)
4248
+ {
4249
+ exhausted -> TRUE.
4250
+ deferred -> deferred + 1.
4251
+ }
4252
+ else
4253
+ {
4254
+ live is unacked_entry_t[] = [].
4255
+ gone is str[] = [].
4256
+ sc q -- ( -> ent)
4257
+ {
4258
+ if (_substract_seconds now (ent $date)) <= unacked_ttl_seconds { live (_count live|) -> ent. }
4259
+ else { gone (_count gone|) -> (ent $wire_id). }
4260
+ }
4261
+ if (_count gone|) > 0
4262
+ {
4263
+ actions (_count actions|) -> _notify_agent ($event -> $e2e_delivery_expired, $cid -> cid, $wire_ids -> gone).
4264
+ action_budget -> action_budget - 1.
4265
+ if (_count live|) == 0 { expired (_count expired|) -> cid. } else { unacked_e2e cid -> live. }
4266
+ purged -> purged + 1.
4267
+ }
4268
+ if (_count live|) > 0
4269
+ {
4270
+ oldest is time+ = NIL.
4271
+ sc live -- ( -> ent) { if oldest == NIL { oldest -> (ent $date). } }
4272
+ if oldest != NIL && (_substract_seconds now (oldest?)) > redrive_min_age_seconds
4273
+ {
4274
+ pre_cnt is int = (_count actions|).
4275
+ sc redrive_unacked_actions cid -- ( -> a) { actions (_count actions|) -> a. }
4276
+ // Count only contacts something was actually re-sent for (the
4277
+ // cap-gate or a missing bundle can make the redrive a no-op).
4278
+ if (_count actions|) > pre_cnt
4279
+ {
4280
+ redriven -> redriven + 1.
4281
+ crypto_budget -> crypto_budget - (_count live|).
4282
+ action_budget -> action_budget - ((_count actions|) - pre_cnt).
4283
+ }
4284
+ }
4285
+ }
4286
+ last_done -> cid.
4287
+ }
4288
+ }
4289
+ }
4290
+ sc expired -- ( -> cid) { delete unacked_e2e cid. }
4291
+ if past_cursor != TRUE { redrive_sweep_cursor -> NIL. }
4292
+ else { if exhausted { redrive_sweep_cursor -> last_done. } else { redrive_sweep_cursor -> NIL. } }
4293
+ if purged > 0 || redriven > 0 || exhausted { actions (_count actions|) -> _save_state NIL. }
4294
+ actions (_count actions|) -> _return_data ($redriven_contacts -> redriven, $purged_contacts -> purged, $deferred_contacts -> deferred).
4295
+ return transaction::success actions.
4296
+ }
4297
+
3486
4298
  trn sweep_e2e_migrations _
3487
4299
  {
3488
4300
  current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
@@ -3596,7 +4408,26 @@ library a2a_messaging loads libraries
3596
4408
  // pickles stay packet-local in the adapt e2e library (INV-4 / spec §5.1).
3597
4409
  $contact_migration -> contact_migration,
3598
4410
  $contact_e2e_epoch -> contact_e2e_epoch,
3599
- $mig_deferred -> mig_deferred
4411
+ $mig_deferred -> mig_deferred,
4412
+ // core 0.11 Signal-model restart survival: the pickle_key-SEALED Olm account +
4413
+ // LIVE per-peer session pickles (opaque bin). m_staged is deliberately NOT
4414
+ // exported — a restart mid-migration drops the transient staged session and the
4415
+ // migration sweep supersedes it (review #16: this comment previously claimed
4416
+ // staged was persisted). Persisting account+live lets a restart RESUME the exact
4417
+ // ratchet instead of re-minting a fresh account (the desync root cause) —
4418
+ // self-heal then only runs on TRUE loss (reinstall/corruption). state_data.bin
4419
+ // is LOCAL-ONLY, so this stays off any peer/broker; the sealed bytes carry no raw
4420
+ // secretkey type. NOTE: if state_data.bin is ever repurposed as a CROSS-NODE portable
4421
+ // blob, move this to a local sidecar (the material is local-secrecy class).
4422
+ $e2e_sessions -> (e2e::export_sessions NIL),
4423
+ // core 0.11 self-heal: unacked e2e sends (additive; app payload class, NO key
4424
+ // material — INV-4 holds). rekey_pending is deliberately NOT exported (transient
4425
+ // rate-limit ledger; a restart at worst re-sends one idempotent request).
4426
+ $unacked_e2e -> unacked_e2e,
4427
+ $delivered_wire -> delivered_wire,
4428
+ // Ship-review major-4: the sweep resume cursor survives restarts, else a
4429
+ // boot-sweep-only lifecycle re-scans the same prefix forever (tail starves).
4430
+ $redrive_cursor -> redrive_sweep_cursor
3600
4431
  ).
3601
4432
  }
3602
4433
 
@@ -3728,9 +4559,10 @@ library a2a_messaging loads libraries
3728
4559
  }
3729
4560
  // core 0.9.0: migration FSM metadata (absent from pre-0.9 exports → all
3730
4561
  // 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).
4562
+ // Since persist-primary the ACTIVE session pickles ride $e2e_sessions and
4563
+ // survive export/import (validated commit); only the transient STAGED pickle
4564
+ // is gone after a restart — a non-active FSM entry is re-driven by the host
4565
+ // sweep, a committed-with-lost-staged rotation is superseded by it (§5.6).
3734
4566
  if (data $contact_migration) != NIL
3735
4567
  {
3736
4568
  contact_migration -> (data $contact_migration) safe (global_id ->> mig_state_t).
@@ -3743,6 +4575,59 @@ library a2a_messaging loads libraries
3743
4575
  {
3744
4576
  mig_deferred -> (data $mig_deferred) safe (global_id ->> deferred_msg_t[]).
3745
4577
  }
4578
+ // core 0.11 self-heal: unacked e2e sends (absent from pre-0.11 exports → empty).
4579
+ if (data $unacked_e2e) != NIL
4580
+ {
4581
+ unacked_e2e -> (data $unacked_e2e) safe (global_id ->> unacked_entry_t[]).
4582
+ }
4583
+ if (data $delivered_wire) != NIL
4584
+ {
4585
+ // Current shape first; a pre-H blob carried bare wire_id strings — migrate
4586
+ // them with the import time as the delivery date (they age out on the same
4587
+ // TTL clock from now, which can only RETAIN LONGER, never dedup less).
4588
+ dwn = (data $delivered_wire) safe (global_id ->> delivered_entry_t[]).
4589
+ if dwn != NIL { delivered_wire -> dwn?. }
4590
+ else
4591
+ {
4592
+ dwo = (data $delivered_wire) safe (global_id ->> str[]).
4593
+ if dwo != NIL
4594
+ {
4595
+ mnow = (current_transaction_info::get_transaction_time())?.
4596
+ sc dwo? -- (mcid -> ws)
4597
+ {
4598
+ mq is delivered_entry_t[] = [].
4599
+ sc ws -- ( -> w) { mq (_count mq|) -> ($w -> w, $d -> mnow). }
4600
+ delivered_wire mcid -> mq.
4601
+ }
4602
+ }
4603
+ }
4604
+ }
4605
+ // core 0.11 Signal-model restart survival: the SEALED Olm account + LIVE session
4606
+ // pickles (no staged — see export). A pre-0.11 blob lacks the field → safe-cast
4607
+ // NIL → no restore → a fresh account is lazily minted and the self-heal fallback
4608
+ // re-establishes (clean degrade). A STRUCTURALLY corrupt field safe-casts to NIL
4609
+ // (same fallback); content-corrupt sealed bytes are caught later by the validated
4610
+ // commit (finding C redo below).
4611
+ // GUARD (pre-#137-blob fix): `safe` does NOT turn an ABSENT field into a
4612
+ // clean NIL for record targets — meta.mm's record checker aborts on any
4613
+ // non-dictionary input ("SAFE cast to record failed"), with no NIL
4614
+ // branch even for nullable targets (verified identically on 0.10.10 and
4615
+ // 0.10.12; see meta.mm record-path). Without this pre-check the WHOLE
4616
+ // import failed for every pre-#137 blob. Same explicit `!= NIL` guard as
4617
+ // $redrive_cursor below (the ship-review-major-4 pattern).
4618
+ es is ( $v -> int, $account -> bin+, $sessions -> (global_id ->> bin)+ )+ = NIL.
4619
+ if (data $e2e_sessions) != NIL
4620
+ {
4621
+ es -> (data $e2e_sessions) safe ( $v -> int, $account -> bin+, $sessions -> (global_id ->> bin)+ ).
4622
+ }
4623
+ // Finding C redo: do NOT validate or assign here — a corrupt pickle raises a
4624
+ // HARD engine error that would fail the whole boot import (contacts and inbox
4625
+ // included). Park the blob; the host drives commit_e2e_restore next (still
4626
+ // pre-exposure), where a validation failure is isolated + atomic.
4627
+ if es != NIL { e2e_restore_staged -> es. }
4628
+ // Ship-review major-4: restore the sweep resume cursor (absent in older blobs).
4629
+ if (data $redrive_cursor) != NIL
4630
+ { redrive_sweep_cursor -> (data $redrive_cursor) safe global_id. }
3746
4631
 
3747
4632
  // Re-register every peer's keys so encrypted channels keep working after
3748
4633
  // the upgrade — no handshake needed (my own keys are unchanged, and the
@@ -86,6 +86,21 @@ async function main() {
86
86
  ok(T(g2('epoch_absent')), 'pre-0.9 blob import: contact_e2e_epoch stays empty');
87
87
  ok(T(g2('deferred_absent')), 'pre-0.9 blob import: mig_deferred stays empty');
88
88
 
89
+ // ---- A3: PRE-0.11 / v0 blob (no format_version, no e2e_sessions) ----------
90
+ // The #137 migration gap: replay-after-restore was covered, the OLD-blob
91
+ // upgrade path was not. Without the $e2e_sessions NIL-guard this import
92
+ // raises "SAFE cast to record failed" (meta.mm record-path aborts on NIL —
93
+ // verified identical on 0.10.10 and 0.10.12) and the WHOLE import fails.
94
+ console.log('=== mig: pre-0.11 v0 blob import → succeeds, sessions degrade clean ===');
95
+ try {
96
+ const r3 = await mutate(A, '::actor::qa_mig_import_pre_dr', {});
97
+ const g3 = (k) => r3.Reduce(k).Visualize();
98
+ ok(g3('imported_name') === 'pre-dr', `v0 blob import succeeds and carries my_name (got ${g3('imported_name')})`);
99
+ ok(T(g3('format_stamped')), 're-export is format-stamped after v0 import');
100
+ } catch (err) {
101
+ ok(false, `v0 blob import RAISED (the #137 e2e_sessions guard gap): ${String(err).split('\n')[0]}`);
102
+ }
103
+
89
104
  console.log('=== mig: rotate-once (two peers stage a fresh session, commit, converge) ===');
90
105
  const B = await mkNode('mig-gate-B', 'B'); await sleep(800);
91
106
  const aCid = A.cid, bCid = B.cid;
@@ -127,6 +127,24 @@ application actor loads libraries
127
127
  ) ].
128
128
  }
129
129
 
130
+ trn qa_mig_import_pre_dr _
131
+ {
132
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
133
+ // A faithful PRE-0.11 / pre-stamp (v0) blob: the original-schema required
134
+ // fields only — NO $format_version (absent stamp == version 0 per the
135
+ // migration contract) and, critically, NO $e2e_sessions. This is what
136
+ // every deployed consumer's state_data.bin looks like before the DR
137
+ // upgrade. Import must SUCCEED (the #137 gap: the unguarded
138
+ // $e2e_sessions record-cast raised "SAFE cast to record failed" on this
139
+ // exact shape, failing the whole import — contacts included).
140
+ a2a_messaging::import_core_state ( $my_name -> "pre-dr", $contacts -> (,), $peer_ads -> (,) ).
141
+ exp = a2a_messaging::export_core_state NIL.
142
+ return transaction::success [ _return_data (
143
+ $imported_name -> (exp $my_name),
144
+ $format_stamped -> ((exp $format_version) != NIL)
145
+ ) ].
146
+ }
147
+
130
148
  // ---- Phase-B staged-rotation exercise (adapt e2e §5.5) ----------------
131
149
  // Thin qa wrappers over the adapt e2e facade so a two-node driver can drive
132
150
  // establish -> stage -> commit and assert the rotate-once property. The driver
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ours.network/tg-connector",
3
- "version": "0.1.8-nightly.2",
3
+ "version": "0.1.8-nightly.4",
4
4
  "description": "Bridge Telegram bots to ours proxy nodes — one ADAPT wrapper hosting N messenger packets, each connecting one Telegram bot to one ours node. Run `ours-tg-connector add_new_connection`.",
5
5
  "type": "module",
6
6
  "license": "FSL-1.1-Apache-2.0",
@@ -35,12 +35,12 @@
35
35
  "test": "for f in tests/*.test.mjs; do echo \"# $f\"; node_modules/.bin/tsx \"$f\" || exit 1; done"
36
36
  },
37
37
  "dependencies": {
38
- "@adapt-toolkit/sdk": "0.10.8",
39
- "@adapt-toolkit/sdk-native": "0.10.8",
38
+ "@adapt-toolkit/sdk": "0.10.12",
39
+ "@adapt-toolkit/sdk-native": "0.10.12",
40
40
  "undici": "^7.28.0"
41
41
  },
42
42
  "devDependencies": {
43
- "@adapt-toolkit/mufl": "0.10.8",
43
+ "@adapt-toolkit/mufl": "0.10.12",
44
44
  "@types/node": "^20.14.0",
45
45
  "esbuild": "^0.24.2",
46
46
  "tsx": "^4.19.0",