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

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
@@ -26677,12 +26677,14 @@ async function restoreConnection(name) {
26677
26677
  log(`[${name}] pre-migration retention failed (continuing):`, String(err));
26678
26678
  }
26679
26679
  }
26680
+ let imported = false;
26680
26681
  try {
26681
26682
  const buf = fs3.readFileSync(dataPath(dir));
26682
26683
  await withScopeAsync(async (lt) => {
26683
26684
  const adaptData = pkt.pw.packet.ParseValue(new Uint8Array(buf)).Attach(lt);
26684
26685
  await pkt.mutatingTx("::actor::import_state", adaptData, lt);
26685
26686
  });
26687
+ imported = true;
26686
26688
  } catch (err) {
26687
26689
  log(`[${name}] FAILED TO IMPORT SAVED STATE \u2014 continuing with the reseeded identity; surviving contacts (if the blob was partially migrated) self-heal via contact restore:`, String(err));
26688
26690
  try {
@@ -26691,6 +26693,26 @@ async function restoreConnection(name) {
26691
26693
  } catch {
26692
26694
  }
26693
26695
  }
26696
+ if (imported) {
26697
+ try {
26698
+ const st = await withScopeAsync(async (lt) => {
26699
+ const r = await pkt.mutatingTx("::a2a_messaging::commit_e2e_restore", {}, lt);
26700
+ const status = r.Reduce("status").Visualize();
26701
+ const sessions = r.Reduce("sessions").IsNil() ? "0" : r.Reduce("sessions").Visualize();
26702
+ return { status: String(status), sessions: String(sessions) };
26703
+ });
26704
+ log(`[${name}] e2e restore commit: status=${st.status} sessions=${st.sessions}`);
26705
+ } catch (err) {
26706
+ log(`[${name}] E2E RESTORE REJECTED \u2014 staged session blob failed pickle validation; discarding it, fresh account + self-heal fallback take over: ${String(err).slice(0, 260)}`);
26707
+ try {
26708
+ await withScopeAsync(async (lt) => {
26709
+ await pkt.mutatingTx("::a2a_messaging::reject_e2e_restore", {}, lt);
26710
+ });
26711
+ } catch (err2) {
26712
+ log(`[${name}] reject_e2e_restore failed (staging is transient; continuing):`, String(err2));
26713
+ }
26714
+ }
26715
+ }
26694
26716
  }
26695
26717
  const key = isCatchAll(cfg.chatId) ? "any chat" : chatKey(cfg.chatId, cfg.threadId || void 0);
26696
26718
  log(`[${name}] restored (bot ${botLabel(bot)}, ${key}${cfg.peerCid ? `, peer ${cfg.peerCid}` : ", awaiting proxy"})`);
@@ -1402,34 +1402,35 @@ application actor loads libraries
1402
1402
  // The packet-level snapshot is NOT used for upgrades: it is bound to the unit
1403
1403
  // code hash, so a new .muflo cannot load an old snapshot. This data blob is.
1404
1404
  //
1405
- // The blob stays FLAT with the historical field names — the core fields come
1406
- // from a2a_messaging::export_core_state / import_core_state, the app fields
1407
- // are composed in here — so a PRE-migration export imports unchanged.
1405
+ // Core (contact / profile / hierarchy / DR-session) state is carried WHOLE under
1406
+ // $core: export_core_state owns its OWN field set, so any field the shared core
1407
+ // adds — most importantly $e2e_sessions (the DR ratchet pickles that a manual
1408
+ // per-field projection silently DROPPED, losing messages across a reload) — rides
1409
+ // forward automatically, and the core's monitoring keys never collide with the
1410
+ // APP-level monitoring keys we still own below (they share both names AND shapes).
1411
+ // The blob stays code-independent; import_state migrates the pre-namespacing FLAT
1412
+ // shape forward (see there). Mirrors ours-mcp's actor exactly.
1408
1413
 
1409
1414
  trn readonly export_state _
1410
1415
  {
1411
- core_state = a2a_messaging::export_core_state NIL.
1412
1416
  return (
1413
1417
  $app_format_version -> 1,
1414
- $my_name -> core_state $my_name,
1415
- $contacts -> core_state $contacts,
1416
- $pending_invites -> core_state $pending_invites,
1418
+ $core -> a2a_messaging::export_core_state NIL,
1419
+ // ---- app-owned state (route inbox + files + local book + monitoring) ----
1417
1420
  $inbox -> inbox,
1418
1421
  $next_msg_seq -> next_msg_seq,
1419
1422
  $file_inbox -> file_inbox,
1420
1423
  $next_file_seq -> next_file_seq,
1421
- $peer_ads -> core_state $peer_ads,
1422
1424
  $registrar_ad -> registrar_ad,
1423
1425
  $local_auto_accept -> local_auto_accept,
1424
1426
  // Nonces are exported so a restart does not reopen the replay window
1425
1427
  // for still-fresh credentials; stale ones are purged lazily anyway.
1426
1428
  $seen_nonces -> seen_nonces,
1427
1429
  $pending_introductions -> pending_introductions,
1428
- $my_bio -> core_state $my_bio,
1429
- $delegation_cert -> core_state $delegation_cert,
1430
- $root_ad -> core_state $root_ad,
1431
- $root_profile -> core_state $root_profile,
1432
- $contact_roots -> core_state $contact_roots,
1430
+ // App-level (role->root) monitoring — a DISTINCT mechanism from core's
1431
+ // forced monitoring. Stays app-owned and top-level; it must NEVER be fed
1432
+ // into import_core_state (that would arm core's hidden monitoring_proxy,
1433
+ // which the app cannot disarm). See import_state's legacy branch.
1433
1434
  $monitoring_enabled -> monitoring_enabled,
1434
1435
  $monitoring_inbox -> monitoring_inbox,
1435
1436
  $proxy_pending -> proxy_pending,
@@ -1449,11 +1450,36 @@ application actor loads libraries
1449
1450
  if (data $app_format_version) != NIL { app_fmt -> (data $app_format_version) safe int. }
1450
1451
  abort "App state blob format_version " + (_str app_fmt) + " is newer than this code (supports up to 1) — upgrade ours-tg-connector before importing." when app_fmt > 1.
1451
1452
 
1452
- // Core fields (contacts/profile/hierarchy) — validated and restored by
1453
- // the shared library, which also replays every peer's address document
1454
- // through process_address_document so encrypted channels keep working
1455
- // after the upgrade with no re-handshake.
1456
- a2a_messaging::import_core_state data.
1453
+ // Core fields (contacts/profile/hierarchy/DR-sessions) — validated and restored
1454
+ // by the shared library, which also replays every peer's address document
1455
+ // through process_address_document so encrypted channels keep working after the
1456
+ // upgrade with no re-handshake, and parks $e2e_sessions for the staged commit
1457
+ // below. The current export namespaces core under $core, so the core owns its
1458
+ // own field set and its monitoring keys never collide with the app's. A
1459
+ // PRE-namespacing FLAT blob carries the core fields at the top level — migrate it
1460
+ // by feeding import_core_state ONLY the genuine shared fields. We deliberately
1461
+ // OMIT proxy_pending / monitoring_proxy on the legacy path: in a flat blob those
1462
+ // keys hold the APP-level monitoring state (same names AND shapes as core's), and
1463
+ // feeding them to import_core_state would arm core's hidden forced-monitoring
1464
+ // proxy — which the app can NEVER disarm. Mirrors ours-mcp's actor exactly.
1465
+ if (data $core) != NIL
1466
+ {
1467
+ a2a_messaging::import_core_state (data $core).
1468
+ }
1469
+ else
1470
+ {
1471
+ a2a_messaging::import_core_state (
1472
+ $my_name -> data $my_name,
1473
+ $contacts -> data $contacts,
1474
+ $pending_invites -> data $pending_invites,
1475
+ $peer_ads -> data $peer_ads,
1476
+ $my_bio -> data $my_bio,
1477
+ $delegation_cert -> data $delegation_cert,
1478
+ $root_ad -> data $root_ad,
1479
+ $root_profile -> data $root_profile,
1480
+ $contact_roots -> data $contact_roots
1481
+ ).
1482
+ }
1457
1483
 
1458
1484
  // The inbox + next_msg_seq are the only parts the message-lifecycle changes
1459
1485
  // touched. A pre-lifecycle blob has no $next_msg_seq and inbox entries with
@@ -200,6 +200,13 @@ library a2a_capabilities loads libraries
200
200
  // an app never wires capabilities, and the piggyback must degrade to
201
201
  // "advertises nothing" there, never abort an invite/restore leg.
202
202
  self_caps is str[] = [].
203
+ // Part C: transport routes stay in this low-level capability namespace,
204
+ // while the messaging layer owns contact state, encryption checks, retry,
205
+ // and migration subscription. Optional for backwards-compatible actors.
206
+ on_advertise is (any -> transaction::results::type) =
207
+ fn (_: any) -> transaction::results::type { return transaction::success []. }.
208
+ on_advertise_ack is (any -> transaction::results::type) =
209
+ fn (_: any) -> transaction::results::type { return transaction::success []. }.
203
210
  }
204
211
 
205
212
  // FAIL-FAST: $supported is the static list of capability ids this app
@@ -221,13 +228,17 @@ library a2a_capabilities loads libraries
221
228
  // handlers (e.g. core.receipts.*). $supported keeps its declared-implies-
222
229
  // implemented handler guard; $advertise is for ids that gate peer
223
230
  // traffic shaping only and never route through dispatch.
224
- $advertise -> advertise_list: str[]+
231
+ $advertise -> advertise_list: str[]+,
232
+ $on_advertise -> advertise_cb: (any -> transaction::results::type)+,
233
+ $on_advertise_ack -> advertise_ack_cb: (any -> transaction::results::type)+
225
234
  ))
226
235
  {
227
236
  describe -> describe_cb.
228
237
  handlers -> handler_map.
229
238
  on_unknown -> fallback.
230
239
  if authorizer_cb != NIL { authorizer -> authorizer_cb. }
240
+ if advertise_cb != NIL { on_advertise -> advertise_cb?. }
241
+ if advertise_ack_cb != NIL { on_advertise_ack -> advertise_ack_cb?. }
231
242
  merged is str[] = [].
232
243
  sc supported_caps -- ( -> cap) { merged (_count merged|) -> cap. }
233
244
  if advertise_list != NIL
@@ -273,6 +284,11 @@ library a2a_capabilities loads libraries
273
284
  if (self_advertises cap) != TRUE { self_caps (_count self_caps|) -> cap. }
274
285
  }
275
286
 
287
+ // Thin, callback-routed wire transactions. a2a_capabilities intentionally
288
+ // owns no contact or retry state; consumers register the orchestration hooks.
289
+ trn advertise args: any { return on_advertise args. }
290
+ trn advertise_ack args: any { return on_advertise_ack args. }
291
+
276
292
  // ---- manifest helpers -------------------------------------------------
277
293
  fn has_capability (_:($manifest -> m: app_manifest_t, $cap -> cap: str)) -> bool
278
294
  {
@@ -83,6 +83,8 @@ library a2a_messaging loads libraries
83
83
  // core 0.10 (B1): stateless AD re-advertise pushed to pre-existing legacy contacts on
84
84
  // upgrade, so an idle legacy pair learns both sides are now v2 and the migration FSM fires.
85
85
  readvertise_ad_tx = "::a2a_messaging::readvertise_ad".
86
+ capability_advertise_tx = "::a2a_capabilities::advertise".
87
+ capability_advertise_ack_tx = "::a2a_capabilities::advertise_ack".
86
88
  // core 0.9.0 boxed APP-E2E (Option B): app data over the MIGRATED session rides these named
87
89
  // boxes ($targ = the e2e_signed_message). DISTINCT from legacy receive_message_tx so the wire
88
90
  // separates e2e-carrying box from legacy box (an attacker cannot confuse them).
@@ -188,6 +190,9 @@ library a2a_messaging loads libraries
188
190
  // guarded on import (pre-0.5 exports import unchanged).
189
191
  contact_pv is (global_id ->> int) = (,).
190
192
  contact_caps is (global_id ->> str[]) = (,).
193
+ // ACK-confirmed capability fingerprint per contact. A missing/stale entry
194
+ // is retried by reconcile_advertise; only the encrypted ACK advances it.
195
+ contact_advertised_caps is (global_id ->> str) = (,).
191
196
  // core 0.8.0: monotonic E2E anti-downgrade pin (SPEC §4). Positive-evidence,
192
197
  // set TRUE the first time a peer advertises core.e2e and NEVER cleared — it
193
198
  // CANNOT be derived from contact_caps (which is last-seen-wins, so a later
@@ -427,6 +432,14 @@ library a2a_messaging loads libraries
427
432
  // can order/dedup. No opt-in flag — push is gated only on monitoring_proxy.
428
433
  roster_push_seq is int = 0.
429
434
 
435
+ // core 0.12 (2b auto-advertise): the wire_version + a fingerprint of my self cap-id
436
+ // set captured at the LAST reconcile_advertise. Persisted so a post-upgrade boot
437
+ // NOTICES a version/cap change and re-advertises to legacy peers exactly once — the
438
+ // core owns the trigger, so the app stops orchestrating readvertise_on_upgrade.
439
+ // 0/"" = never reconciled (⇒ the first reconcile after any boot advertises).
440
+ advertised_pv is int = 0.
441
+ advertised_caps is str = "".
442
+
430
443
  // core 3.0: per-outstanding-invite ephemeral PRIVATE keys, keyed by invite id.
431
444
  // hidden ⇒ only this library mutates it AND it is structurally invisible to the
432
445
  // export record builder, but `hidden` governs VISIBILITY, not persistence — it
@@ -491,6 +504,10 @@ library a2a_messaging loads libraries
491
504
  // (peer, wire_id) on unknown < sent < delivered < read — duplicates
492
505
  // and out-of-order arrivals collapse to no-ops.
493
506
  on_receipt_received is (any -> transaction::action::type[]) = fn (_: any) -> transaction::action::type[] { return []. }
507
+ // Optional core middleware at the successful message-send choke point.
508
+ // Integration modules install it without coupling messaging to them.
509
+ // Default no-op preserves every existing consumer.
510
+ post_send_middleware is (any -> transaction::action::type[]) = fn (_: any) -> transaction::action::type[] { return []. }
494
511
  }
495
512
 
496
513
  init = fn (_:(
@@ -526,6 +543,13 @@ library a2a_messaging loads libraries
526
543
  }).
527
544
  }
528
545
 
546
+ // Separate from init so an integration importing a2a_messaging can install
547
+ // after the consumer has wired its ordinary storage hooks.
548
+ fn set_post_send_middleware (cb: (any -> transaction::action::type[])) -> nil
549
+ {
550
+ post_send_middleware -> cb.
551
+ }
552
+
529
553
  // ---- shared action builders -------------------------------------------
530
554
  // Signal the host to persist the packet. Only emitted at the end of a
531
555
  // complete procedure — intermediate states (e.g. channel handshake) are
@@ -1698,6 +1722,7 @@ library a2a_messaging loads libraries
1698
1722
  $name -> receive_e2e_message_tx,
1699
1723
  $targ -> ( $e2e_envelope -> (eenv $e2e_envelope), $emsignature -> (eenv $emsignature) ) ) ].
1700
1724
  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. }
1725
+ sc post_send_middleware ($target_id -> target_id, $text -> text, $date -> sent_date, $wire_id -> wire_id, $reply_to -> reply_to) -- ( -> a) { eacts (_count eacts|) -> a. }
1701
1726
  sc monitor_copy_actions "out" target_id sent_date text -- ( -> a) { eacts (_count eacts|) -> a. }
1702
1727
  // §4 observability: source $session_id from the ACTUAL envelope (NOT a re-read of
1703
1728
  // active_session_id — that would make the #1867 "session_id==pin" assertion CIRCULAR;
@@ -1719,6 +1744,10 @@ library a2a_messaging loads libraries
1719
1744
  {
1720
1745
  actions (_count actions|) -> a.
1721
1746
  }
1747
+ sc post_send_middleware ($target_id -> target_id, $text -> text, $date -> sent_date, $wire_id -> wire_id, $reply_to -> reply_to) -- ( -> a)
1748
+ {
1749
+ actions (_count actions|) -> a.
1750
+ }
1722
1751
  // FORCED: emit the outbound monitoring copy as core code, after the app
1723
1752
  // hook, so the app cannot suppress it (self-gates on monitoring_proxy).
1724
1753
  sc monitor_copy_actions "out" target_id sent_date text -- ( -> a)
@@ -1830,6 +1859,9 @@ library a2a_messaging loads libraries
1830
1859
  delete contacts target_id.
1831
1860
  if peer_ads target_id != NIL { delete peer_ads target_id. }
1832
1861
  if contact_roots target_id != NIL { delete contact_roots target_id. }
1862
+ if contact_pv target_id != NIL { delete contact_pv target_id. }
1863
+ if contact_caps target_id != NIL { delete contact_caps target_id. }
1864
+ if contact_advertised_caps target_id != NIL { delete contact_advertised_caps target_id. }
1833
1865
 
1834
1866
  // Contact-restore stores too: an orphaned deferred queue would persist in
1835
1867
  // every export and, on a later RE-ADD of the same peer, the boot/GC sweep
@@ -2288,10 +2320,20 @@ library a2a_messaging loads libraries
2288
2320
  // can never be silently overwritten with a different keyset).
2289
2321
  address_document::process_address_document peer_ad TRUE.
2290
2322
 
2291
- // Idempotent re-introduction: if peer_cid is already a contact, just refresh the
2292
- // stored AD and keep the existing name — never clobber it or re-notify as new.
2323
+ peer_name is str = "".
2324
+ if (args $peer_name) != NIL { peer_name -> (args $peer_name) safe str. }
2325
+
2326
+ // Idempotent re-introduction: refresh the stored AD. A contact created from a
2327
+ // nameless/legacy introduction may still be labelled by its CID; in that one
2328
+ // case adopt the now-available peer label. Any better name (including an
2329
+ // explicit invite alias) remains authoritative and is never overwritten.
2293
2330
  if (contacts peer_cid) != NIL
2294
2331
  {
2332
+ existing = (contacts peer_cid)?.
2333
+ if peer_name != "" && (existing $name) == (_str peer_cid)
2334
+ {
2335
+ contacts peer_cid -> ($name -> peer_name, $container_id -> peer_cid).
2336
+ }
2295
2337
  peer_ads peer_cid -> peer_ad.
2296
2338
  return transaction::success [
2297
2339
  _notify_agent ($event -> $reintroduced, $container_id -> peer_cid, $by_cp -> sender_id),
@@ -2300,8 +2342,6 @@ library a2a_messaging loads libraries
2300
2342
  }
2301
2343
 
2302
2344
  // New contact: register under the CP-supplied display name (cid as last resort).
2303
- peer_name is str = "".
2304
- if (args $peer_name) != NIL { peer_name -> (args $peer_name) safe str. }
2305
2345
  contact_label is str = (peer_name == "" ?? (_str peer_cid) ; peer_name).
2306
2346
  contacts peer_cid -> ($name -> contact_label, $container_id -> peer_cid).
2307
2347
  peer_ads peer_cid -> peer_ad.
@@ -2934,6 +2974,10 @@ library a2a_messaging loads libraries
2934
2974
  {
2935
2975
  actions (_count actions|) -> a.
2936
2976
  }
2977
+ sc post_send_middleware ($target_id -> target_id, $text -> (m $text), $date -> (m $date), $wire_id -> (m $wire_id), $reply_to -> (m $reply_to)) -- ( -> a)
2978
+ {
2979
+ actions (_count actions|) -> a.
2980
+ }
2937
2981
  sc monitor_copy_actions "out" target_id (m $date) (m $text) -- ( -> a)
2938
2982
  {
2939
2983
  actions (_count actions|) -> a.
@@ -4198,6 +4242,127 @@ library a2a_messaging loads libraries
4198
4242
  return transaction::success actions.
4199
4243
  }
4200
4244
 
4245
+ // core 0.12 (2b): comma-joined fingerprint of my advertised cap-id set. self_cap_ids is
4246
+ // captured at init in a stable order (supported ∪ advertise, then any runtime
4247
+ // add_self_cap APPENDS), so this string changes iff my advertised caps change — the cheap
4248
+ // change-detector reconcile_advertise gates the legacy upgrade push on.
4249
+ fn caps_fingerprint (_) -> str
4250
+ {
4251
+ s is str = "".
4252
+ sc (a2a_capabilities::self_cap_ids NIL) -- ( -> c) { s -> (s + c) + ",". }
4253
+ return s.
4254
+ }
4255
+
4256
+ fn fingerprint_caps (caps: str[]) -> str
4257
+ {
4258
+ s is str = "".
4259
+ sc caps -- ( -> c) { s -> (s + c) + ",". }
4260
+ return s.
4261
+ }
4262
+
4263
+ // Generic capability snapshot receiver. Exact replacement is intentional:
4264
+ // removals must propagate. The E2E pin remains monotonic, so an advertised
4265
+ // removal cannot reopen plaintext routing. Duplicate snapshots still ACK,
4266
+ // which repairs a lost ACK without duplicating delta-side effects.
4267
+ fn handle_capability_advertise (args: any) -> transaction::results::type
4268
+ {
4269
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
4270
+ encrypted_channel::check_encrypted_or_abort().
4271
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
4272
+ if (contacts sender_id) == NIL { return transaction::success []. }
4273
+ caps is str[] = ((args $caps) safe (str[])).
4274
+ fp = (args $fingerprint) safe str.
4275
+ abort "Capability advertisement fingerprint mismatch." when fp != fingerprint_caps caps.
4276
+ pv = (args $pv) safe int.
4277
+ prev = contact_caps sender_id.
4278
+ prev_fp is str = "".
4279
+ if prev != NIL { prev_fp -> fingerprint_caps prev?. }
4280
+ contact_caps sender_id -> caps.
4281
+ contact_pv sender_id -> pv.
4282
+ note_e2e_seen sender_id caps.
4283
+ actions is transaction::action::type[] = [
4284
+ encrypted_channel::send_encrypted_tx sender_id (
4285
+ $name -> capability_advertise_ack_tx,
4286
+ $targ -> ($fingerprint -> fp)
4287
+ )
4288
+ ].
4289
+ if prev_fp != fp
4290
+ {
4291
+ actions (_count actions|) -> _notify_agent (
4292
+ $event -> $peer_capabilities_changed, $cid -> sender_id,
4293
+ $previous_fingerprint -> prev_fp, $fingerprint -> fp, $caps -> caps
4294
+ ).
4295
+ // DR migration is a subscriber/special-case of the generic delta:
4296
+ // all eligibility, election, born-DR and epoch gates remain inside
4297
+ // the existing trigger unchanged.
4298
+ sc mig_trigger_actions sender_id -- ( -> a) { actions (_count actions|) -> a. }
4299
+ }
4300
+ actions (_count actions|) -> _save_state NIL.
4301
+ return transaction::success actions.
4302
+ }
4303
+
4304
+ fn handle_capability_advertise_ack (args: any) -> transaction::results::type
4305
+ {
4306
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
4307
+ encrypted_channel::check_encrypted_or_abort().
4308
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
4309
+ if (contacts sender_id) == NIL { return transaction::success []. }
4310
+ fp = (args $fingerprint) safe str.
4311
+ // A stale/replayed ACK cannot suppress a newer capability snapshot.
4312
+ if fp != caps_fingerprint NIL { return transaction::success []. }
4313
+ contact_advertised_caps sender_id -> fp.
4314
+ return transaction::success [ _save_state NIL ].
4315
+ }
4316
+
4317
+ // Part C: the SINGLE generic capability re-advertise entrypoint. The app declares
4318
+ // capabilities once at init and calls this on boot/GC. A persisted global fingerprint
4319
+ // detects code-defined changes; a persisted per-contact ACK ledger prevents repeat sends
4320
+ // while retrying offline/lost-ACK contacts. On a global change, the legacy full-AD push
4321
+ // remains a migration bootstrap subscriber/special-case. E2E account/session recovery is
4322
+ // intentionally still the separate readvertise_e2e_recovery daemon sweep.
4323
+ trn reconcile_advertise _
4324
+ {
4325
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
4326
+ cur_pv = a2a_versions::wire_version.
4327
+ cur_fp = caps_fingerprint NIL.
4328
+ changed is bool = (advertised_pv != cur_pv) || (cur_fp != advertised_caps).
4329
+ actions is transaction::action::type[] = [].
4330
+ cap_n is int = 0.
4331
+ legacy_n is int = 0.
4332
+ // Per-contact ACK ledger: retry missing/stale peers on the next cadence,
4333
+ // but never re-spam a peer that confirmed this exact capability set.
4334
+ sc contacts -- (cid -> ) ?? ((contact_advertised_caps cid) != cur_fp)
4335
+ {
4336
+ actions (_count actions|) -> encrypted_channel::send_encrypted_tx cid (
4337
+ $name -> capability_advertise_tx,
4338
+ $targ -> ($pv -> cur_pv, $caps -> (a2a_capabilities::self_cap_ids NIL), $fingerprint -> cur_fp) ).
4339
+ cap_n -> cap_n + 1.
4340
+ }
4341
+ // ON CHANGE ONLY: the legacy upgrade push to pre-existing legacy contacts.
4342
+ if changed
4343
+ {
4344
+ b = my_identity_bundle_fields_fresh NIL.
4345
+ sc contacts -- (cid -> ) ?? ((contact_e2e_epoch cid) == NIL && (contact_born_dr cid) != TRUE && (contact_migration cid) == NIL)
4346
+ {
4347
+ actions (_count actions|) -> encrypted_channel::send_encrypted_tx cid (
4348
+ $name -> readvertise_ad_tx,
4349
+ $targ -> ( $ad -> (b $ad), $cert -> (b $cert), $root_profile -> (b $root_profile),
4350
+ $cp_binding -> (b $cp_binding),
4351
+ $pv -> a2a_versions::wire_version,
4352
+ $caps -> (a2a_capabilities::self_cap_ids NIL) ) ).
4353
+ legacy_n -> legacy_n + 1.
4354
+ }
4355
+ }
4356
+ advertised_pv -> cur_pv.
4357
+ advertised_caps -> cur_fp.
4358
+ actions (_count actions|) -> _return_data (
4359
+ $changed -> changed, $capability_advertised -> cap_n,
4360
+ $e2e_readvertised -> 0, $legacy_readvertised -> legacy_n
4361
+ ).
4362
+ actions (_count actions|) -> _save_state NIL.
4363
+ return transaction::success actions.
4364
+ }
4365
+
4201
4366
  // core 0.11 (session self-heal, retry leg): re-send unacked e2e messages stuck without
4202
4367
  // a delivered receipt for redrive_min_age_seconds+ (see the const above). Host calls
4203
4368
  // this on the boot/GC cadence next to readvertise_e2e_recovery. Mutates session state
@@ -4401,6 +4566,7 @@ library a2a_messaging loads libraries
4401
4566
  $deferred_msgs -> deferred_msgs,
4402
4567
  $contact_pv -> contact_pv,
4403
4568
  $contact_caps -> contact_caps,
4569
+ $contact_advertised_caps -> contact_advertised_caps,
4404
4570
  $contact_e2e_seen -> contact_e2e_seen,
4405
4571
  $contact_born_dr -> contact_born_dr,
4406
4572
  // core 0.9.0 migration FSM metadata — additive, all keyed by cid. Only
@@ -4427,7 +4593,11 @@ library a2a_messaging loads libraries
4427
4593
  $delivered_wire -> delivered_wire,
4428
4594
  // Ship-review major-4: the sweep resume cursor survives restarts, else a
4429
4595
  // boot-sweep-only lifecycle re-scans the same prefix forever (tail starves).
4430
- $redrive_cursor -> redrive_sweep_cursor
4596
+ $redrive_cursor -> redrive_sweep_cursor,
4597
+ // core 0.12 (2b): the pv + cap-set fingerprint of my last self-advertise
4598
+ // reconcile, so a post-upgrade boot detects the change and re-advertises once.
4599
+ $advertised_pv -> advertised_pv,
4600
+ $advertised_caps -> advertised_caps
4431
4601
  ).
4432
4602
  }
4433
4603
 
@@ -4628,6 +4798,13 @@ library a2a_messaging loads libraries
4628
4798
  // Ship-review major-4: restore the sweep resume cursor (absent in older blobs).
4629
4799
  if (data $redrive_cursor) != NIL
4630
4800
  { redrive_sweep_cursor -> (data $redrive_cursor) safe global_id. }
4801
+ // core 0.12 (2b): restore the last-advertised pv + cap fingerprint (absent in older
4802
+ // blobs → stays 0/"" → the first reconcile_advertise after upgrade sees a change and
4803
+ // re-advertises, which is exactly the desired post-upgrade behavior).
4804
+ if (data $advertised_pv) != NIL { advertised_pv -> (data $advertised_pv) safe int. }
4805
+ if (data $advertised_caps) != NIL { advertised_caps -> (data $advertised_caps) safe str. }
4806
+ if (data $contact_advertised_caps) != NIL
4807
+ { contact_advertised_caps -> (data $contact_advertised_caps) safe (global_id ->> str). }
4631
4808
 
4632
4809
  // Re-register every peer's keys so encrypted channels keep working after
4633
4810
  // the upgrade — no handshake needed (my own keys are unchanged, and the
@@ -0,0 +1,144 @@
1
+ // Core-owned notification integration for ordinary message sends.
2
+ //
3
+ // Recipients hand each sender a scoped notify_address_t over their established
4
+ // encrypted channel. This library owns those opaque handouts, persists them,
5
+ // and installs the optional a2a_messaging successful-send middleware. Missing
6
+ // or deleted handouts are no-ops; notification delivery is fire-and-forget.
7
+ library a2a_notification_integration loads libraries
8
+ current_transaction_info,
9
+ encrypted_channel,
10
+ a2a_messaging,
11
+ a2a_notifications
12
+ uses transactions
13
+ {
14
+ receive_notify_address_tx = "::a2a_notification_integration::receive_notify_address".
15
+
16
+ // Peer cid -> validated serialized notify_address_t. Opaque serialized
17
+ // storage composes cleanly beside a2a_messaging::export_core_state.
18
+ received_notify_addresses is (global_id ->> bin) = (,).
19
+
20
+ metadef integration_state_t: (
21
+ $version -> int,
22
+ $received_notify_addresses -> (global_id ->> bin)
23
+ ).
24
+
25
+ fn _save_state (_) = (transaction::action::return_data ($kind -> $save_state)).
26
+
27
+ // Relationship binding is checked at the handout boundary. The service
28
+ // later validates the token against its signed live exact-token store; the
29
+ // current protocol intentionally requires no sender<->service contact.
30
+ fn validate_address_for (recipient: global_id, blob: bin) -> a2a_notifications::notify_address_t
31
+ {
32
+ addr = a2a_notifications::decode_notify_address blob.
33
+ abort "Notify address token recipient does not match its sender." when (addr $token $c $recipient_cid) != recipient.
34
+ abort "Notify address token is not scoped to this sender." when (addr $token $c $scope) != _str (_get_container_id()).
35
+ return addr.
36
+ }
37
+
38
+ // Ordinary consumers are notification clients, not notification services.
39
+ // Install safe no-op service/UI callbacks here so they only need to init
40
+ // this integration. A service host may call a2a_notifications::init after
41
+ // this function to replace the defaults with durable/WebPush hooks.
42
+ init = fn (_:($_read_or_abort -> read: (bin->any)))
43
+ {
44
+ a2a_notifications::init (
45
+ $_read_or_abort -> read,
46
+ $on_notification_posted -> fn (_: any) -> transaction::action::type[] { return []. },
47
+ $on_notifications_marked_read -> fn (_: any) -> transaction::action::type[] { return []. },
48
+ $on_unregistered -> fn (_: any) -> transaction::action::type[] { return []. },
49
+ $on_notify_registration -> fn (_: any) -> transaction::action::type[] { return []. }
50
+ ).
51
+ a2a_messaging::set_post_send_middleware (fn (arg: any) -> transaction::action::type[]
52
+ {
53
+ target_id = (arg $target_id) safe global_id.
54
+ address = received_notify_addresses target_id.
55
+ if address == NIL { return []. }
56
+
57
+ wire_id = (arg $wire_id) safe str.
58
+ // Built only from stringified global ids and wire ids, whose hex
59
+ // alphabets require no JSON escaping.
60
+ payload = "{\"v\":1,\"kind\":\"message\",\"sender\":\"" +
61
+ (_str (_get_container_id())) + "\",\"wire_id\":\"" + wire_id + "\"}".
62
+ return [ a2a_notifications::notification_send_action address? payload wire_id ].
63
+ }).
64
+ }
65
+
66
+ fn handle_receive_notify_address (args: any) -> transaction::results::type
67
+ {
68
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
69
+ encrypted_channel::check_encrypted_or_abort ().
70
+ from = current_transaction_info::get_external_envelope_or_abort() $from.
71
+
72
+ if (args $address) == NIL
73
+ {
74
+ if (received_notify_addresses from) != NIL { delete received_notify_addresses from. }
75
+ return transaction::success [ _save_state NIL ].
76
+ }
77
+
78
+ blob = (args $address) safe bin.
79
+ validate_address_for from blob.
80
+ received_notify_addresses from -> blob.
81
+ return transaction::success [ _save_state NIL ].
82
+ }
83
+
84
+ trn receive_notify_address args: any
85
+ {
86
+ return handle_receive_notify_address args.
87
+ }
88
+
89
+ // Recipient-side distribution: build the sender-scoped handout from the
90
+ // notification client mirror and deliver it over the existing encrypted
91
+ // contact channel. Consumers retain only UI policy, not protocol state.
92
+ trn send_notify_address _:($service -> service_ref: str, $contact -> contact_ref: str)
93
+ {
94
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
95
+ target_id = a2a_messaging::resolve_contact contact_ref.
96
+ blob = a2a_notifications::build_notify_address service_ref contact_ref.
97
+ return encrypted_channel::execute_transaction target_id (fn (_) -> transaction::results::type {
98
+ return transaction::success [
99
+ encrypted_channel::send_encrypted_tx target_id (
100
+ $name -> receive_notify_address_tx,
101
+ $targ -> ($address -> blob)
102
+ ),
103
+ transaction::action::return_data ($kind -> $data, $payload -> ($sent_to -> target_id)),
104
+ _save_state NIL
105
+ ].
106
+ }).
107
+ }
108
+
109
+ // NIL is the wire-level mute/removal signal and intentionally leaves the
110
+ // ordinary messaging relationship untouched.
111
+ trn delete_notify_address _:($contact -> contact_ref: str)
112
+ {
113
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
114
+ target_id = a2a_messaging::resolve_contact contact_ref.
115
+ return encrypted_channel::execute_transaction target_id (fn (_) -> transaction::results::type {
116
+ return transaction::success [
117
+ encrypted_channel::send_encrypted_tx target_id (
118
+ $name -> receive_notify_address_tx,
119
+ $targ -> ($address -> NIL)
120
+ ),
121
+ transaction::action::return_data ($kind -> $data, $payload -> ($sent_to -> target_id)),
122
+ _save_state NIL
123
+ ].
124
+ }).
125
+ }
126
+
127
+ fn export_state (_) -> integration_state_t
128
+ {
129
+ return (
130
+ $version -> 1,
131
+ $received_notify_addresses -> received_notify_addresses
132
+ ).
133
+ }
134
+
135
+ fn import_state (data: any) -> nil
136
+ {
137
+ abort "Unsupported notification integration state version." when ((data $version) safe int) != 1.
138
+ imported = (data $received_notify_addresses) safe (global_id ->> bin).
139
+ // Validate now so a corrupt local snapshot cannot turn a later accepted
140
+ // send_message into a middleware parse abort.
141
+ sc imported -- (peer -> blob) { validate_address_for peer blob. }
142
+ received_notify_addresses -> imported.
143
+ }
144
+ }