actr-hyper 0.3.1

Hyper — Actor platform infrastructure: sandbox, transport, scheduler, WASM engine, signing, AIS bootstrap, persistence & crypto primitives
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
//! Node runtime inner — holds all running-state fields for an attached node.
//!
//! This module is the internal implementation backing the public
//! `Node<Attached>` / `Node<Registered>` typestate chain defined in
//! `crate::lib`. The struct itself is crate-private; consumers interact with
//! it indirectly through `Node<S>` → `ActrRef` transitions.

use crate::actr_ref::{ActrRef, ActrRefShared};
use crate::ais_client::AisClient;
use crate::context::{BootstrapContextBuilder, RuntimeContext};
use crate::inbound::{DataStreamRegistry, MediaFrameRegistry};
use crate::lifecycle::dedup::{DEDUP_TTL, DedupOutcome, DedupState, DedupWaiter};
use crate::outbound::Gate;
use crate::transport::HostTransport;
use crate::wire::webrtc::SignalingClient;
#[cfg(feature = "opentelemetry")]
use crate::wire::webrtc::trace::{inject_span_context_to_rpc, set_parent_from_rpc_envelope};
use actr_framework::Bytes;
use actr_protocol::prost::Message as ProstMessage;
use actr_protocol::{
    AIdCredential, ActorResult, ActrError, ActrId, PayloadType, RegisterAuthMode, RegisterRequest,
    RpcEnvelope, TurnCredential, register_response,
};
use actr_runtime::check_acl_permission;
use actr_runtime_mailbox::{DeadLetterQueue, Mailbox};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{Mutex, RwLock};
use tokio_util::sync::CancellationToken;
#[cfg(feature = "opentelemetry")]
use tracing::Instrument as _;

/// Internal running-state of an attached node.
///
/// Holds every field required to run a workload after `Hyper::attach` has
/// bound a package. Kept private to the crate: external callers use the
/// public `Node<S>` wrappers in `crate::lib` and the `ActrRef` handle
/// returned by `Node::start`.
pub(crate) struct Inner {
    /// Runtime configuration
    pub(crate) config: actr_config::RuntimeConfig,

    /// SQLite persistent mailbox
    pub(crate) mailbox: Arc<dyn Mailbox>,

    /// Dead Letter Queue for poison messages
    pub(crate) dlq: Arc<dyn DeadLetterQueue>,

    /// In-process gate for `Dest::Shell` / `Dest::Local` calls.
    ///
    /// Created in `build()` together with `shell_to_workload` so the inproc
    /// lane is usable as soon as the node exists, even before registration.
    pub(crate) inproc_gate: Gate,

    /// Cross-process gate for `Dest::Actor(_)` calls.
    ///
    /// `None` until `start()` finishes WebRTC / PeerGate initialization. Any
    /// outbound call issued before that point returns `Internal("PeerGate
    /// not initialized yet")` — see `RuntimeContext::select_gate`.
    pub(crate) outproc_gate: Option<Gate>,

    /// DataStream callback registry shared between the inbound WebRTC / WS
    /// gates (which dispatch into it) and `RuntimeContext`
    /// (register_stream / send_data_stream).
    pub(crate) data_stream_registry: Arc<DataStreamRegistry>,

    /// MediaTrack callback registry shared between WebRTC media tracks and
    /// `RuntimeContext` (register_media_track / send_media_sample).
    pub(crate) media_frame_registry: Arc<MediaFrameRegistry>,

    /// Signaling client
    pub(crate) signaling_client: Arc<dyn SignalingClient>,

    /// Actor ID (obtained after startup)
    pub(crate) actor_id: Option<ActrId>,

    /// Actor Credential (obtained after startup, used for subsequent authentication messages)
    pub(crate) credential_state: Option<CredentialState>,

    /// WebRTC coordinator (created after startup)
    pub(crate) webrtc_coordinator: Option<Arc<crate::wire::webrtc::WebRtcCoordinator>>,

    /// WebRTC Gate (created after startup)
    pub(crate) webrtc_gate: Option<Arc<crate::wire::webrtc::gate::WebRtcGate>>,

    /// WebSocket Gate (direct-connect mode inbound, optional)
    pub(crate) websocket_gate: Option<Arc<crate::wire::websocket::WebSocketGate>>,

    /// Shell → Workload transport (REQUEST direction)
    ///
    /// Workload receives REQUEST from Shell (zero serialization, direct RpcEnvelope passing)
    pub(crate) shell_to_workload: Option<Arc<HostTransport>>,

    /// Workload → Shell transport (RESPONSE direction)
    ///
    /// Workload sends RESPONSE to Shell (separate pending_requests from Shell's)
    pub(crate) workload_to_shell: Option<Arc<HostTransport>>,

    /// Shutdown token for graceful shutdown
    pub(crate) shutdown_token: CancellationToken,

    /// Packaged manifest.lock.toml content loaded at startup for fingerprint lookups.
    ///
    /// Wrapped in `Arc` so per-request `RuntimeContext` clones only bump a refcount
    /// instead of deep-cloning the dependency vector.
    pub(crate) actr_lock: Option<Arc<actr_config::lock::LockFile>>,
    /// Network event receiver (from NetworkEventHandle)
    pub(crate) network_event_rx:
        Option<tokio::sync::mpsc::Receiver<crate::lifecycle::network_event::NetworkEvent>>,

    /// Network event result sender (to NetworkEventHandle)
    pub(crate) network_event_result_tx:
        Option<tokio::sync::mpsc::Sender<crate::lifecycle::network_event::NetworkEventResult>>,

    /// Network event debounce configuration
    pub(crate) network_event_debounce_config:
        Option<crate::lifecycle::network_event::DebounceConfig>,

    /// Request deduplication state (15 s TTL response cache, prevents double-processing on retry)
    pub(crate) dedup_state: Arc<Mutex<DedupState>>,

    /// Verified package manifest for package-backed nodes.
    #[allow(dead_code)]
    pub(crate) package_manifest: Option<actr_pack::PackageManifest>,

    /// Pre-issued registration credential injected by the Hyper layer during
    /// the `Attached → Registered` state transition. `start()` uses it directly
    /// instead of re-registering with the signaling server.
    pub(crate) preregistered_credential: Option<actr_protocol::register_response::RegisterOk>,

    /// Shared WebSocket direct-connect address map populated by discovery
    ///
    /// Shared with `DefaultWireBuilder` so discovered ws:// URLs can be reused
    /// directly instead of relying on a static url_template
    /// The map is keyed by `ActrId`.
    pub(crate) discovered_ws_addresses:
        Arc<tokio::sync::RwLock<std::collections::HashMap<ActrId, String>>>,

    /// Runtime workload (WASM, dynclib, etc.)
    ///
    /// `handle_incoming` dispatches through this workload.
    ///
    /// The `Mutex` serializes dispatch into a single guest actor instance:
    /// `WasmWorkload::handle` and `DynClibWorkload::handle` both take
    /// `&mut self` because the underlying Wasmtime `Store` / native guest
    /// ABI is single-threaded, so concurrent dispatch through the same
    /// instance would be unsound. Lifecycle hooks also take this lock because
    /// package-backed WASM / dynclib workloads expose them on the same guest
    /// instance; transport and other observation hooks reach linked workloads
    /// through `hook_observer` without holding this lock.
    pub(crate) workload_dispatch: Arc<Mutex<crate::workload::Workload>>,

    /// Optional shell-side observer that receives linked-workload transport /
    /// credential / mailbox hook invocations.
    ///
    /// `None` means "no observer installed"; the built-in tracing defaults
    /// still fire from the event-source wiring sites. When `Some`, hook
    /// invocations are dispatched through `lifecycle::hooks::spawn_hook`
    /// so panics in observer code cannot unwind into the event source.
    #[allow(dead_code)]
    pub(crate) hook_observer: Option<crate::lifecycle::hooks::WorkloadHookObserverRef>,

    /// Queue-length threshold at which the mailbox backpressure
    /// watchdog fires the framework `on_mailbox_backpressure` hook.
    ///
    /// Resolved from [`HyperConfig`] at node construction time so the
    /// runtime loop does not need to hold a reference back to `HyperConfig`.
    pub(crate) mailbox_backpressure_threshold: usize,

    /// Lead time before credential expiry at which the framework fires
    /// the `on_credential_expiring` hook. Resolved from [`HyperConfig`]
    /// at node construction time.
    #[allow(dead_code)]
    pub(crate) credential_expiry_warning: Duration,
}

/// Credential state for shared access between tasks
#[derive(Clone)]
pub struct CredentialState {
    inner: Arc<RwLock<CredentialStateInner>>,
}

#[derive(Clone)]
struct CredentialStateInner {
    credential: AIdCredential,
    expires_at: Option<prost_types::Timestamp>,
    /// HMAC time-limited TURN credential, updated together with credential on registration/renewal
    turn_credential: Option<TurnCredential>,
}

impl CredentialState {
    /// Create a new CredentialState with TURN credential
    pub fn new(
        credential: AIdCredential,
        expires_at: Option<prost_types::Timestamp>,
        turn_credential: Option<TurnCredential>,
    ) -> Self {
        Self {
            inner: Arc::new(RwLock::new(CredentialStateInner {
                credential,
                expires_at,
                turn_credential,
            })),
        }
    }

    pub async fn credential(&self) -> AIdCredential {
        self.inner.read().await.credential.clone()
    }

    pub async fn expires_at(&self) -> Option<prost_types::Timestamp> {
        self.inner.read().await.expires_at
    }

    /// Get TURN credential (HMAC time-limited credential)
    pub async fn turn_credential(&self) -> Option<TurnCredential> {
        self.inner.read().await.turn_credential.clone()
    }

    /// Update credential and TURN credential
    ///
    /// Called on credential renewal; only overwrites the old TURN credential when the new one is not empty
    pub(crate) async fn update(
        &self,
        credential: AIdCredential,
        expires_at: Option<prost_types::Timestamp>,
        turn_credential: Option<TurnCredential>,
    ) {
        let mut guard = self.inner.write().await;
        guard.credential = credential;
        guard.expires_at = expires_at;
        if turn_credential.is_some() {
            guard.turn_credential = turn_credential;
        }
    }
}

/// Host operation executor - routes guest outbound calls through RuntimeContext
///
/// Called by the workload dispatch path in `handle_incoming`.
async fn host_operation_handler(
    ctx: crate::context::RuntimeContext,
    workload_dispatch: Arc<Mutex<crate::workload::Workload>>,
    pending: crate::workload::HostOperation,
) -> crate::workload::HostOperationResult {
    use crate::workload::{HostOperation, HostOperationResult, decode_dest};
    use actr_framework::guest::dynclib_abi::code as abi_code;
    use actr_framework::{Context as _, Dest};
    use actr_protocol::{DataStream, PayloadType};

    /// Map `ActrError` to ABI error code, preserving semantics for guest-side discrimination
    fn actr_error_to_code(err: &ActrError) -> i32 {
        match err {
            ActrError::DecodeFailure(_) | ActrError::InvalidArgument(_) => abi_code::PROTOCOL_ERROR,
            _ => abi_code::GENERIC_ERROR,
        }
    }

    match pending {
        HostOperation::CallRaw(req) => {
            match ctx
                .call_raw(
                    &Dest::Actor(req.target),
                    req.route_key,
                    PayloadType::RpcReliable,
                    bytes::Bytes::from(req.payload),
                    30_000,
                )
                .await
            {
                Ok(resp) => HostOperationResult::Bytes(resp.to_vec()),
                Err(e) => {
                    tracing::error!("call_raw routing failed: {e:?}");
                    HostOperationResult::Error(actr_error_to_code(&e))
                }
            }
        }

        HostOperation::Call(req) => {
            let dest = match decode_dest(&req.dest) {
                Some(d) => d,
                None => {
                    tracing::error!(route_key = req.route_key, "call: dest decode failed");
                    return HostOperationResult::Error(abi_code::PROTOCOL_ERROR);
                }
            };
            match ctx
                .call_raw(
                    &dest,
                    req.route_key,
                    PayloadType::RpcReliable,
                    bytes::Bytes::from(req.payload),
                    30_000,
                )
                .await
            {
                Ok(resp) => HostOperationResult::Bytes(resp.to_vec()),
                Err(e) => {
                    tracing::error!("call routing failed: {e:?}");
                    HostOperationResult::Error(actr_error_to_code(&e))
                }
            }
        }

        HostOperation::Tell(req) => {
            let dest = match decode_dest(&req.dest) {
                Some(d) => d,
                None => {
                    tracing::error!(route_key = req.route_key, "tell: dest decode failed");
                    return HostOperationResult::Error(abi_code::PROTOCOL_ERROR);
                }
            };
            match ctx
                .tell_raw(
                    &dest,
                    req.route_key,
                    PayloadType::RpcReliable,
                    bytes::Bytes::from(req.payload),
                )
                .await
            {
                Ok(()) => HostOperationResult::Done,
                Err(e) => {
                    tracing::error!("tell routing failed: {e:?}");
                    HostOperationResult::Error(actr_error_to_code(&e))
                }
            }
        }

        HostOperation::Discover(req) => {
            match ctx.discover_route_candidate(&req.target_type).await {
                Ok(id) => HostOperationResult::Bytes(id.encode_to_vec()),
                Err(e) => {
                    tracing::error!("discover failed: {e:?}");
                    HostOperationResult::Error(actr_error_to_code(&e))
                }
            }
        }

        HostOperation::RegisterStream(req) => {
            let stream_id = req.stream_id;
            let callback_ctx = ctx.clone();
            let callback_workload_dispatch = workload_dispatch.clone();
            match ctx
                .register_stream(stream_id, move |chunk: DataStream, sender| {
                    let ctx_for_executor = callback_ctx.clone();
                    let workload_dispatch = callback_workload_dispatch.clone();
                    Box::pin(async move {
                        let invocation = crate::workload::InvocationContext {
                            self_id: actr_framework::Context::self_id(&ctx_for_executor).clone(),
                            caller_id: Some(sender.clone()),
                            request_id: format!(
                                "data-stream:{}:{}",
                                chunk.stream_id, chunk.sequence
                            ),
                        };
                        let call_executor: crate::workload::HostAbiFn =
                            std::sync::Arc::new(move |pending| {
                                let ctx = ctx_for_executor.clone();
                                Box::pin(async move {
                                    stream_callback_host_operation_handler(ctx, pending).await
                                })
                            });
                        let mut guard = workload_dispatch.lock().await;
                        guard
                            .dispatch_data_stream(chunk, sender, invocation, &call_executor)
                            .await
                    })
                })
                .await
            {
                Ok(()) => HostOperationResult::Done,
                Err(e) => {
                    tracing::error!("register_stream failed: {e:?}");
                    HostOperationResult::Error(actr_error_to_code(&e))
                }
            }
        }

        HostOperation::UnregisterStream(req) => match ctx.unregister_stream(&req.stream_id).await {
            Ok(()) => HostOperationResult::Done,
            Err(e) => {
                tracing::error!("unregister_stream failed: {e:?}");
                HostOperationResult::Error(actr_error_to_code(&e))
            }
        },

        HostOperation::SendDataStream(req) => {
            let dest = match decode_dest(&req.dest) {
                Some(d) => d,
                None => {
                    tracing::error!("send_data_stream: dest decode failed");
                    return HostOperationResult::Error(abi_code::PROTOCOL_ERROR);
                }
            };
            let payload_type = match PayloadType::try_from(req.payload_type) {
                Ok(PayloadType::StreamReliable | PayloadType::StreamLatencyFirst) => {
                    PayloadType::try_from(req.payload_type).expect("checked payload type")
                }
                Ok(other) => {
                    tracing::error!(?other, "send_data_stream: invalid stream payload type");
                    return HostOperationResult::Error(abi_code::PROTOCOL_ERROR);
                }
                Err(_) => {
                    tracing::error!(
                        payload_type = req.payload_type,
                        "send_data_stream: unknown payload type"
                    );
                    return HostOperationResult::Error(abi_code::PROTOCOL_ERROR);
                }
            };
            match ctx.send_data_stream(&dest, req.chunk, payload_type).await {
                Ok(()) => HostOperationResult::Done,
                Err(e) => {
                    tracing::error!("send_data_stream failed: {e:?}");
                    HostOperationResult::Error(actr_error_to_code(&e))
                }
            }
        }
    }
}

fn lifecycle_invocation(
    actor_id: &ActrId,
    request_id: &'static str,
) -> crate::workload::InvocationContext {
    crate::workload::InvocationContext {
        self_id: actor_id.clone(),
        caller_id: None,
        request_id: request_id.to_string(),
    }
}

pub(crate) fn lifecycle_host_abi(
    ctx: crate::context::RuntimeContext,
    workload_dispatch: Arc<Mutex<crate::workload::Workload>>,
) -> crate::workload::HostAbiFn {
    std::sync::Arc::new(move |pending| {
        let ctx = ctx.clone();
        let workload_dispatch = workload_dispatch.clone();
        Box::pin(async move { host_operation_handler(ctx, workload_dispatch, pending).await })
    })
}

async fn stream_callback_host_operation_handler(
    ctx: crate::context::RuntimeContext,
    pending: crate::workload::HostOperation,
) -> crate::workload::HostOperationResult {
    use crate::workload::{HostOperation, HostOperationResult, decode_dest};
    use actr_framework::guest::dynclib_abi::code as abi_code;
    use actr_framework::{Context as _, Dest};
    use actr_protocol::PayloadType;

    fn actr_error_to_code(err: &ActrError) -> i32 {
        match err {
            ActrError::DecodeFailure(_) | ActrError::InvalidArgument(_) => abi_code::PROTOCOL_ERROR,
            _ => abi_code::GENERIC_ERROR,
        }
    }

    match pending {
        HostOperation::CallRaw(req) => {
            match ctx
                .call_raw(
                    &Dest::Actor(req.target),
                    req.route_key,
                    PayloadType::RpcReliable,
                    bytes::Bytes::from(req.payload),
                    30_000,
                )
                .await
            {
                Ok(resp) => HostOperationResult::Bytes(resp.to_vec()),
                Err(e) => HostOperationResult::Error(actr_error_to_code(&e)),
            }
        }
        HostOperation::Call(req) => {
            let dest = match decode_dest(&req.dest) {
                Some(d) => d,
                None => return HostOperationResult::Error(abi_code::PROTOCOL_ERROR),
            };
            match ctx
                .call_raw(
                    &dest,
                    req.route_key,
                    PayloadType::RpcReliable,
                    bytes::Bytes::from(req.payload),
                    30_000,
                )
                .await
            {
                Ok(resp) => HostOperationResult::Bytes(resp.to_vec()),
                Err(e) => HostOperationResult::Error(actr_error_to_code(&e)),
            }
        }
        HostOperation::Tell(req) => {
            let dest = match decode_dest(&req.dest) {
                Some(d) => d,
                None => return HostOperationResult::Error(abi_code::PROTOCOL_ERROR),
            };
            match ctx
                .tell_raw(
                    &dest,
                    req.route_key,
                    PayloadType::RpcReliable,
                    bytes::Bytes::from(req.payload),
                )
                .await
            {
                Ok(()) => HostOperationResult::Done,
                Err(e) => HostOperationResult::Error(actr_error_to_code(&e)),
            }
        }
        HostOperation::Discover(req) => {
            match ctx.discover_route_candidate(&req.target_type).await {
                Ok(id) => HostOperationResult::Bytes(id.encode_to_vec()),
                Err(e) => HostOperationResult::Error(actr_error_to_code(&e)),
            }
        }
        HostOperation::RegisterStream(_) => {
            tracing::error!("register_stream from inside a stream callback is not supported");
            HostOperationResult::Error(abi_code::UNSUPPORTED_OP)
        }
        HostOperation::UnregisterStream(req) => match ctx.unregister_stream(&req.stream_id).await {
            Ok(()) => HostOperationResult::Done,
            Err(e) => HostOperationResult::Error(actr_error_to_code(&e)),
        },
        HostOperation::SendDataStream(req) => {
            let dest = match decode_dest(&req.dest) {
                Some(d) => d,
                None => return HostOperationResult::Error(abi_code::PROTOCOL_ERROR),
            };
            let payload_type = match PayloadType::try_from(req.payload_type) {
                Ok(PayloadType::StreamReliable | PayloadType::StreamLatencyFirst) => {
                    PayloadType::try_from(req.payload_type).expect("checked payload type")
                }
                Ok(_) | Err(_) => return HostOperationResult::Error(abi_code::PROTOCOL_ERROR),
            };
            match ctx.send_data_stream(&dest, req.chunk, payload_type).await {
                Ok(()) => HostOperationResult::Done,
                Err(e) => HostOperationResult::Error(actr_error_to_code(&e)),
            }
        }
    }
}

/// Map ActrError to error code for ErrorResponse
fn protocol_error_to_code(err: &ActrError) -> u32 {
    match err {
        ActrError::Unavailable(_) => 503,            // Service Unavailable
        ActrError::TimedOut => 504,                  // Gateway Timeout
        ActrError::NotFound(_) => 404,               // Not Found
        ActrError::PermissionDenied(_) => 403,       // Forbidden
        ActrError::InvalidArgument(_) => 400,        // Bad Request
        ActrError::UnknownRoute(_) => 404,           // Not Found - route not found
        ActrError::DependencyNotFound { .. } => 400, // Bad Request
        ActrError::DecodeFailure(_) => 400,          // Bad Request - decode failure
        ActrError::NotImplemented(_) => 501,         // Not Implemented
        ActrError::Internal(_) => 500,               // Internal Server Error
    }
}

impl Inner {
    #[allow(dead_code)]
    pub(crate) fn package_manifest(&self) -> Option<&actr_pack::PackageManifest> {
        self.package_manifest.as_ref()
    }

    /// Network event processing loop (background task)
    ///
    /// # Responsibilities
    /// - Receive network events from Channel
    /// - Delegate to NetworkEventProcessor for handling
    /// - Record processing time and send results
    async fn network_event_loop(
        event_rx: tokio::sync::mpsc::Receiver<crate::lifecycle::network_event::NetworkEvent>,
        result_tx: tokio::sync::mpsc::Sender<crate::lifecycle::network_event::NetworkEventResult>,
        event_processor: Arc<dyn crate::lifecycle::network_event::NetworkEventProcessor>,
        shutdown_token: CancellationToken,
    ) {
        crate::lifecycle::network_event::run_network_event_reconciler(
            event_rx,
            result_tx,
            event_processor,
            shutdown_token,
        )
        .await;
    }

    fn duplicate_wait_timeout(timeout_ms: i64) -> Duration {
        if timeout_ms > 0 {
            Duration::from_millis(timeout_ms as u64)
        } else {
            DEDUP_TTL
        }
    }

    async fn wait_for_inflight_duplicate(
        mut waiter: DedupWaiter,
        timeout: Duration,
    ) -> ActorResult<Bytes> {
        let wait_for_result = async {
            loop {
                if let Some(result) = waiter.borrow().clone() {
                    return result;
                }

                if waiter.changed().await.is_err() {
                    if let Some(result) = waiter.borrow().clone() {
                        return result;
                    }
                    return Err(ActrError::Unavailable(
                        "duplicate request result unavailable".to_string(),
                    ));
                }
            }
        };

        match tokio::time::timeout(timeout, wait_for_result).await {
            Ok(result) => result,
            Err(_) => Err(ActrError::Unavailable(format!(
                "duplicate request in-flight timed out after {}ms",
                timeout.as_millis()
            ))),
        }
    }

    /// - Single-hop calls: effectively identical
    /// - Multi-hop calls: trace_id spans all hops, request_id per hop
    #[cfg_attr(
        feature = "opentelemetry",
        tracing::instrument(
            skip_all,
            name = "ActrNode.handle_incoming",
            fields(
                actr_id = %self.actor_id.as_ref().map(|id| id.to_string()).unwrap_or_default(),
                route_key = %envelope.route_key,
                request_id = %envelope.request_id,
            )
        )
    )]
    pub async fn handle_incoming(
        &self,
        envelope: RpcEnvelope,
        caller_id: Option<&ActrId>,
    ) -> ActorResult<Bytes> {
        // Log received message
        if let Some(caller) = caller_id {
            tracing::debug!(
                "📨 Handling incoming message: route_key={}, caller={}, request_id={}",
                envelope.route_key,
                caller,
                envelope.request_id
            );
        } else {
            tracing::debug!(
                "📨 Handling incoming message: route_key={}, request_id={}",
                envelope.route_key,
                envelope.request_id
            );
        }

        // 0. Get actor_id early for ACL check
        let actor_id = self.actor_id.as_ref().ok_or_else(|| {
            ActrError::Internal(
                "Actor ID not set - node must be started before handling messages".to_string(),
            )
        })?;

        // 0.1. ACL Permission Check (before processing message)
        let acl_allowed = check_acl_permission(caller_id, actor_id, self.config.acl.as_ref())
            .map_err(|err_msg| ActrError::Internal(format!("ACL check failed: {}", err_msg)))?;

        if !acl_allowed {
            tracing::warn!(
                severity = 5,
                error_category = "acl_denied",
                request_id = %envelope.request_id,
                route_key = %envelope.route_key,
                caller = %caller_id
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "<none>".to_string()),
                "🚫 ACL: Permission denied"
            );

            return Err(ActrError::PermissionDenied(format!(
                "ACL denied: {} is not allowed to call {}",
                caller_id
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "<unknown>".to_string()),
                actor_id
            )));
        }

        // 0.2. Deduplication: return cached response for retried request_ids
        let outcome = {
            self.dedup_state
                .lock()
                .await
                .check_or_mark(&envelope.request_id)
        };
        match outcome {
            DedupOutcome::Fresh => {} // proceed normally
            DedupOutcome::InFlight(waiter) => {
                tracing::debug!(
                    request_id = %envelope.request_id,
                    route_key = %envelope.route_key,
                    "duplicate request in-flight; waiting for original result"
                );
                return Self::wait_for_inflight_duplicate(
                    waiter,
                    Self::duplicate_wait_timeout(envelope.timeout_ms),
                )
                .await;
            }
            DedupOutcome::Duplicate(cached) => {
                tracing::debug!(
                    request_id = %envelope.request_id,
                    route_key = %envelope.route_key,
                    "♻️ returning cached response for duplicate request_id"
                );
                return cached;
            }
        }

        // 1. Create Context with caller_id from transport layer
        let credential_state = self.credential_state.clone().ok_or_else(|| {
            ActrError::Internal(
                "Credential not set - node must be started before handling messages".to_string(),
            )
        })?;
        let ctx = self.make_runtime_context(
            actor_id,
            caller_id, // caller_id from transport layer (MessageRecord.from)
            &envelope.request_id,
            &credential_state.credential().await,
        );

        // 2. Dispatch
        let dispatch_ctx = crate::workload::InvocationContext {
            self_id: actor_id.clone(),
            caller_id: caller_id.cloned(),
            request_id: envelope.request_id.clone(),
        };
        let ctx_for_executor = ctx.clone();
        let workload_for_executor = self.workload_dispatch.clone();
        let call_executor: crate::workload::HostAbiFn = std::sync::Arc::new(move |pending| {
            let ctx = ctx_for_executor.clone();
            let workload_dispatch = workload_for_executor.clone();
            Box::pin(async move { host_operation_handler(ctx, workload_dispatch, pending).await })
        });

        let mut guard = self.workload_dispatch.lock().await;
        let result = guard
            .dispatch_envelope(envelope.clone(), ctx.clone(), dispatch_ctx, &call_executor)
            .await
            .map_err(|e| ActrError::Internal(format!("workload dispatch failed: {e:?}")));

        match &result {
            Ok(_) => tracing::debug!(
                request_id = %envelope.request_id,
                route_key = %envelope.route_key,
                "✅ Message handled successfully"
            ),
            Err(e) => tracing::error!(
                severity = 6,
                error_category = "handler_error",
                request_id = %envelope.request_id,
                route_key = %envelope.route_key,
                "❌ Message handling failed: {:?}", e
            ),
        }

        // 3. Store completed result in dedup cache before returning
        self.dedup_state
            .lock()
            .await
            .complete(&envelope.request_id, result.clone());

        result
    }

    /// Build a new `Inner` from config and runtime workload.
    ///
    /// This is the internal constructor behind the public node builders and
    /// Hyper package attach helpers.
    pub(crate) async fn build(
        config: actr_config::RuntimeConfig,
        workload: crate::workload::Workload,
        package_manifest: Option<actr_pack::PackageManifest>,
        packaged_lock: Option<actr_config::lock::LockFile>,
        mailbox_backpressure_threshold: usize,
        credential_expiry_warning: Duration,
    ) -> ActorResult<Self> {
        use crate::outbound::{Gate, HostGate};
        use crate::wire::webrtc::{ReconnectConfig, SignalingConfig, WebSocketSignalingClient};

        tracing::info!("🚀 Initializing ActrNode");

        // Initialize Mailbox
        let mailbox_path = config
            .mailbox_path
            .as_ref()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_else(|| ":memory:".to_string());

        tracing::info!("📂 Mailbox database path: {}", mailbox_path);

        let mailbox: Arc<dyn actr_runtime_mailbox::Mailbox> = Arc::new(
            actr_runtime_mailbox::SqliteMailbox::new(&mailbox_path)
                .await
                .map_err(|e| {
                    actr_protocol::ActrError::Unavailable(format!("Mailbox init failed: {e}"))
                })?,
        );

        // Initialize Dead Letter Queue
        let dlq_path = if mailbox_path == ":memory:" {
            ":memory:".to_string()
        } else {
            format!("{mailbox_path}.dlq")
        };

        let dlq: Arc<dyn actr_runtime_mailbox::DeadLetterQueue> = Arc::new(
            actr_runtime_mailbox::SqliteDeadLetterQueue::new_standalone(&dlq_path)
                .await
                .map_err(|e| {
                    actr_protocol::ActrError::Unavailable(format!("DLQ init failed: {e}"))
                })?,
        );
        tracing::info!("✅ Dead Letter Queue initialized");

        // Initialize signaling client
        let webrtc_role = if config.webrtc.advanced.prefer_answerer() {
            Some("answer".to_string())
        } else {
            None
        };

        let signaling_config = SignalingConfig {
            server_url: config.signaling_url.clone(),
            connection_timeout: 30,
            heartbeat_interval: 30,
            reconnect_config: ReconnectConfig::default(),
            auth_config: None,
            webrtc_role,
        };

        let client = Arc::new(WebSocketSignalingClient::new(signaling_config));
        client.start_reconnect_manager();
        let signaling_client: Arc<dyn crate::wire::webrtc::SignalingClient> = client;

        // Initialize inproc infrastructure (Shell ↔ Guest)
        let shell_to_workload = Arc::new(HostTransport::new());
        let workload_to_shell = Arc::new(HostTransport::new());
        let inproc_gate = Gate::Host(Arc::new(HostGate::new(shell_to_workload.clone())));

        let data_stream_registry = Arc::new(DataStreamRegistry::new());
        let media_frame_registry = Arc::new(MediaFrameRegistry::new());

        tracing::info!("✅ Inproc infrastructure initialized (bidirectional Shell ↔ Guest)");

        let actr_lock = if let Some(lock) = packaged_lock {
            tracing::info!(
                "📋 Loaded packaged manifest.lock.toml with {} dependencies",
                lock.dependencies.len()
            );
            Some(Arc::new(lock))
        } else {
            tracing::warn!(
                "⚠️ manifest.lock.toml not found in package. Continuing without dependency fingerprints."
            );
            None
        };

        tracing::info!("✅ ActrNode initialized");

        Ok(Self {
            config,
            mailbox,
            dlq,
            inproc_gate,
            outproc_gate: None, // Populated in start() once WebRTC / PeerGate is ready.
            data_stream_registry,
            media_frame_registry,
            signaling_client,
            actor_id: None,
            credential_state: None,
            webrtc_coordinator: None,
            webrtc_gate: None,
            websocket_gate: None,
            shell_to_workload: Some(shell_to_workload),
            workload_to_shell: Some(workload_to_shell),
            shutdown_token: CancellationToken::new(),
            actr_lock,
            network_event_rx: None,
            network_event_result_tx: None,
            network_event_debounce_config: None,
            dedup_state: Arc::new(Mutex::new(DedupState::new())),
            package_manifest,
            preregistered_credential: None,
            discovered_ws_addresses: Arc::new(tokio::sync::RwLock::new(
                std::collections::HashMap::new(),
            )),
            workload_dispatch: Arc::new(Mutex::new(workload)),
            hook_observer: None,
            mailbox_backpressure_threshold,
            credential_expiry_warning,
        })
    }

    /// Snapshot the current runtime handles into a `BootstrapContextBuilder`.
    ///
    /// The returned builder is cloned into long-lived hook closures and into
    /// `ActrRefShared` so those paths can materialize bootstrap contexts
    /// without retaining a reference back to `Inner`. The snapshot freezes
    /// `outproc_gate` and `actr_lock` at call time — callers that want to
    /// observe a later-initialized `outproc_gate` must rebuild.
    pub(crate) fn bootstrap_ctx_builder(&self) -> BootstrapContextBuilder {
        BootstrapContextBuilder::new(
            self.inproc_gate.clone(),
            self.outproc_gate.clone(),
            self.data_stream_registry.clone(),
            self.media_frame_registry.clone(),
            self.signaling_client.clone(),
            self.actr_lock.clone(),
        )
    }

    /// Build a `RuntimeContext` for the per-request dispatch path.
    ///
    /// Unlike `BootstrapContextBuilder::build_bootstrap`, this carries the
    /// envelope's caller identity and request id through into the context.
    pub(crate) fn make_runtime_context(
        &self,
        self_id: &ActrId,
        caller_id: Option<&ActrId>,
        request_id: &str,
        credential: &AIdCredential,
    ) -> RuntimeContext {
        RuntimeContext::new(
            self_id.clone(),
            caller_id.cloned(),
            request_id.to_string(),
            self.inproc_gate.clone(),
            self.outproc_gate.clone(),
            self.data_stream_registry.clone(),
            self.media_frame_registry.clone(),
            self.signaling_client.clone(),
            credential.clone(),
            self.actr_lock.clone(),
        )
    }

    /// Create network event processing infrastructure (called on demand, before `start()`).
    ///
    /// # Parameters
    /// - `debounce_ms`: Debounce window in milliseconds. If 0, no debounce.
    ///
    /// # Panics
    /// Panics if called more than once.
    pub fn create_network_event_handle(
        &mut self,
        debounce_ms: u64,
    ) -> crate::lifecycle::NetworkEventHandle {
        if self.network_event_rx.is_some() {
            panic!("create_network_event_handle() can only be called once");
        }

        let (event_tx, event_rx) = tokio::sync::mpsc::channel(100);
        let (result_tx, result_rx) = tokio::sync::mpsc::channel(100);

        let debounce_config = if debounce_ms > 0 {
            Some(crate::lifecycle::network_event::DebounceConfig {
                window: std::time::Duration::from_millis(debounce_ms),
            })
        } else {
            None
        };

        self.network_event_rx = Some(event_rx);
        self.network_event_result_tx = Some(result_tx);
        self.network_event_debounce_config = debounce_config;

        crate::lifecycle::NetworkEventHandle::new(event_tx, result_rx)
    }

    /// Attach a credential already issued by AIS so that `start()` can skip
    /// the signaling registration step.
    ///
    /// Called by the Hyper layer between `Hyper::register()` and `Hyper::start()`.
    pub fn set_preregistered_credential(&mut self, register_ok: register_response::RegisterOk) {
        tracing::debug!("Pre-registered credential attached; start() will skip AIS registration");
        self.preregistered_credential = Some(register_ok);
    }

    /// Start the system
    pub async fn start(mut self) -> ActorResult<ActrRef> {
        tracing::info!("🚀 Starting ActrNode");
        tracing::info!("Actr Rust version: {}", env!("CARGO_PKG_VERSION"));

        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // 1. Build RegisterRequest
        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // Get ActrType from configuration
        let actr_type = self.config.actr_type().clone();
        tracing::info!("📋 Actor type: {}", actr_type);

        // ServiceSpec is derived by the Hyper layer from the verified package
        // (see `service_spec::calculate_service_spec_from_package`). The raw
        // ActrNode::start() path has no package context and always sends None
        // on its own RegisterRequest; callers that need a spec must go
        // through `Hyper::register()`.
        let service_spec = None;

        // If a WebSocket listen port is configured, build the advertised ws:// address
        // to register with the signaling server so clients can discover it.
        let ws_address = if let Some(port) = self.config.websocket_listen_port {
            let host = self
                .config
                .websocket_advertised_host
                .as_deref()
                .unwrap_or("127.0.0.1");
            Some(format!("ws://{}:{}", host, port))
        } else {
            None
        };

        if let Some(ref addr) = ws_address {
            tracing::info!(
                "📡 Advertising WebSocket address to signaling server: {}",
                addr
            );
        }

        let register_request = RegisterRequest {
            actr_type: actr_type.clone(),
            realm: self.config.realm,
            service_spec,
            acl: self.config.acl.clone(),
            service: None,
            ws_address,
            auth_mode: Some(RegisterAuthMode::Linked as i32),
            ..Default::default()
        };

        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // 1. Obtain registration info (Hyper pre-injected or AIS HTTP)
        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        let register_ok = if let Some(injected) = self.preregistered_credential.take() {
            tracing::info!(
                "Using Hyper pre-injected registration credential; skipping AIS registration"
            );
            injected
        } else {
            let ais_endpoint = &self.config.ais_endpoint;
            tracing::info!(
                ais_endpoint = %ais_endpoint,
                "Registering actor with AIS via HTTP"
            );
            let mut ais = AisClient::new(ais_endpoint);
            if let Some(ref secret) = self.config.realm_secret {
                ais = ais.with_realm_secret(secret);
            }
            let resp = ais
                .register_linked(register_request.clone())
                .await
                .map_err(|e| ActrError::Unavailable(format!("AIS registration failed: {e}")))?;
            match resp.result {
                Some(register_response::Result::Success(ok)) => {
                    tracing::info!("✅ AIS HTTP registration successful");
                    ok
                }
                Some(register_response::Result::Error(error)) => {
                    tracing::error!(
                        severity = 10,
                        error_category = "registration_error",
                        error_code = error.code,
                        "❌ AIS registration failed: code={}, message={}",
                        error.code,
                        error.message
                    );
                    return Err(ActrError::Unavailable(format!(
                        "AIS registration rejected: {} (code: {})",
                        error.message, error.code
                    )));
                }
                None => {
                    tracing::error!(
                        severity = 10,
                        error_category = "registration_error",
                        "❌ AIS registration response missing result"
                    );
                    return Err(ActrError::Unavailable(
                        "Invalid AIS registration response: missing result".to_string(),
                    ));
                }
            }
        };

        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // 3. Set credential on signaling client, then connect signaling WS
        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // The signaling server requires credential params in the WS URL for
        // authentication. We must set actor_id + credential BEFORE connecting
        // so that build_url_with_identity() includes them in the query string.
        let pre_connect_credential_state = {
            let actor_id = register_ok.actr_id.clone();
            let credential_state = CredentialState::new(
                register_ok.credential.clone(),
                register_ok.credential_expires_at,
                Some(register_ok.turn_credential.clone()),
            );
            self.signaling_client.set_actor_id(actor_id).await;
            self.signaling_client
                .set_credential_state(credential_state.clone())
                .await;
            credential_state
        };

        // Install the signaling-side hook callback so that
        // SignalingConnectStart / Connected / Disconnected events flow
        // through the framework tracing defaults and into a
        // user-installed observer. Done BEFORE connect() so the initial
        // attempt produces a SignalingConnectStart event.
        {
            let actor_id = register_ok.actr_id.clone();
            let credential_state = pre_connect_credential_state.clone();
            // Snapshot at this point — outproc_gate is still None here, so
            // signaling-event contexts will carry None for outproc_gate
            // (matching the pre-existing behavior prior to B13 refactor).
            let ctx_builder_snapshot = self.bootstrap_ctx_builder();
            let ctx_builder: crate::lifecycle::hooks::HookContextBuilder = Arc::new(move || {
                let snapshot = ctx_builder_snapshot.clone();
                let actor_id = actor_id.clone();
                let credential_state = credential_state.clone();
                Box::pin(async move {
                    Some(snapshot.build_bootstrap(&actor_id, &credential_state.credential().await))
                })
            });
            let cb = crate::lifecycle::hooks::build_hook_callback(
                self.hook_observer.clone(),
                ctx_builder,
            );
            self.signaling_client.set_hook_callback(cb);
        }

        tracing::info!("📡 Connecting to signaling server (with credential)");
        self.signaling_client
            .connect()
            .await
            .map_err(|e| ActrError::Unavailable(format!("Signaling connect failed: {e}")))?;
        tracing::info!("✅ Connected to signaling server");

        // Collect background task handles so they can be managed by ActrRefShared later.
        let mut task_handles = Vec::new();

        // Node-level hook callback, built inside the registration
        // setup block below and published back out into this wider
        // scope so the mailbox backpressure watchdog can subscribe.
        let node_hook_callback: Option<crate::wire::webrtc::HookCallback>;

        {
            let actor_id = register_ok.actr_id;
            let credential = register_ok.credential;

            tracing::info!("🆔 Assigned ActrId: {}", actor_id);
            tracing::info!("🔐 Received credential (key_id: {})", credential.key_id);
            tracing::info!(
                "💓 Signaling heartbeat interval: {} seconds",
                register_ok.signaling_heartbeat_interval_secs
            );

            // TurnCredential is a required field; should always be present under normal registration.
            tracing::debug!("TurnCredential received, TURN authentication ready");

            if let Some(expires_at) = &register_ok.credential_expires_at {
                tracing::debug!("⏰ Credential expires at: {}s", expires_at.seconds);
            }

            // Store ActrId and credential state
            self.actor_id = Some(actor_id.clone());
            let credential_state = CredentialState::new(
                credential,
                register_ok.credential_expires_at,
                Some(register_ok.turn_credential.clone()),
            );
            self.credential_state = Some(credential_state.clone());

            // Build the node-level lifecycle hook callback once: it is
            // reused for the initial `on_credential_renewed`, handed to
            // the heartbeat task for subsequent credential events, and
            // handed to the mailbox backpressure watchdog for
            // `on_mailbox_backpressure` on rising-edge crossings.
            //
            // The signaling layer already has its own callback installed
            // above — this second callback only carries credential and
            // mailbox-backpressure events, so no overlap with the
            // signaling-event plumbing.
            node_hook_callback =
                {
                    let actor_id_for_hook = actor_id.clone();
                    let credential_state_for_hook = credential_state.clone();
                    // Snapshot at this point — outproc_gate is still None
                    // here; credential / mailbox hook contexts inherit that
                    // and therefore cannot issue Dest::Actor(_) calls (same
                    // behavior as before B13 refactor).
                    let ctx_builder_snapshot = self.bootstrap_ctx_builder();
                    let ctx_builder: crate::lifecycle::hooks::HookContextBuilder =
                        Arc::new(move || {
                            let snapshot = ctx_builder_snapshot.clone();
                            let actor_id = actor_id_for_hook.clone();
                            let credential_state = credential_state_for_hook.clone();
                            Box::pin(async move {
                                Some(snapshot.build_bootstrap(
                                    &actor_id,
                                    &credential_state.credential().await,
                                ))
                            })
                        });
                    Some(crate::lifecycle::hooks::build_hook_callback(
                        self.hook_observer.clone(),
                        ctx_builder,
                    ))
                };

            // Fire `on_credential_renewed` at initial registration: the
            // credential is considered "renewed" from "nothing" to the
            // value just issued by AIS. Subsequent renewals fire the
            // same hook from `lifecycle::heartbeat`.
            if let Some(expires_at) = &register_ok.credential_expires_at {
                let new_expiry = std::time::UNIX_EPOCH
                    + std::time::Duration::from_secs(expires_at.seconds.max(0) as u64);
                if let Some(cb) = node_hook_callback.as_ref() {
                    cb(crate::wire::webrtc::HookEvent::CredentialRenewed { new_expiry }).await;
                } else {
                    tracing::info!(new_expiry = ?new_expiry, "credential renewed");
                }
            }

            // Note: actor_id and credential_state were already set on signaling_client
            // before connect (step 3 above), so reconnect URLs already carry correct auth.

            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            // 1.3. Inproc transports were filled in during `build()`; nothing
            //      to stage here now that ContextFactory has been removed.
            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            tracing::info!("✅ Inproc infrastructure already ready (created in ActrNode::build())");

            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            // 1.5. Create WebRTC infrastructure
            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            tracing::info!("🌐 Initializing WebRTC infrastructure");

            let media_frame_registry = self.media_frame_registry.clone();

            // Create WebRtcCoordinator
            let coordinator = Arc::new(crate::wire::webrtc::WebRtcCoordinator::new(
                actor_id.clone(),
                credential_state.clone(),
                self.signaling_client.clone(),
                self.config.webrtc.clone(),
                media_frame_registry,
            ));

            // Install the WebRTC hook callback — fires
            // WebRtcConnectStart / Connected (with relayed info) /
            // Disconnected HookEvents on every peer state change.
            {
                let actor_id_for_hook = actor_id.clone();
                let credential_state_for_hook = credential_state.clone();
                // Snapshot before outproc_gate is wired up (just below). This
                // preserves the pre-refactor behavior where WebRTC-event
                // hook contexts carry outproc_gate = None.
                let ctx_builder_snapshot = self.bootstrap_ctx_builder();
                let ctx_builder: crate::lifecycle::hooks::HookContextBuilder =
                    Arc::new(move || {
                        let snapshot = ctx_builder_snapshot.clone();
                        let actor_id = actor_id_for_hook.clone();
                        let credential_state = credential_state_for_hook.clone();
                        Box::pin(async move {
                            Some(
                                snapshot.build_bootstrap(
                                    &actor_id,
                                    &credential_state.credential().await,
                                ),
                            )
                        })
                    });
                let cb = crate::lifecycle::hooks::build_hook_callback(
                    self.hook_observer.clone(),
                    ctx_builder,
                );
                coordinator.set_hook_callback(cb);
            }

            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            // 1.6. Create PeerTransport + PeerGate (new architecture)
            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            tracing::info!("🏗️  Creating PeerTransport with WebRTC support");

            // Create DefaultWireBuilder with WebRTC coordinator
            use crate::transport::{DefaultWireBuilder, DefaultWireBuilderConfig};

            // WebSocket channel always enabled: target ws:// address is fully discovered at runtime
            // Direct-connect mode: encode local node ActrId as hex, sent as X-Actr-Node-Id
            let local_id_hex = hex::encode(actor_id.encode_to_vec());
            let wire_builder_config = DefaultWireBuilderConfig {
                local_id_hex,
                enable_webrtc: true,
                enable_websocket: true,
                // Share the discovered_ws_addresses map so that post-discovery calls
                // can use the signaling-provided ws:// URL for this actor node.
                discovered_ws_addresses: self.discovered_ws_addresses.clone(),
                // Pass credential_state so outbound WS handshake carries X-Actr-Credential,
                // enabling peer WebSocketGate to perform Ed25519 signature verification.
                credential_state: Some(credential_state.clone()),
            };
            let wire_builder = Arc::new(DefaultWireBuilder::new(
                Some(coordinator.clone()),
                wire_builder_config,
            ));

            // Create PeerTransport
            use crate::transport::PeerTransport;
            let transport_manager = Arc::new(PeerTransport::new(actor_id.clone(), wire_builder));

            // Create PeerGate with WebRTC coordinator for MediaTrack support
            use crate::outbound::PeerGate;
            let outproc_gate =
                Arc::new(PeerGate::new(transport_manager, Some(coordinator.clone())));
            let outproc_gate_enum = Gate::Peer(outproc_gate.clone());
            tracing::info!("PeerTransport + PeerGate initialized");

            let data_stream_registry = self.data_stream_registry.clone();

            // Create WebRtcGate with shared pending_requests and DataStreamRegistry
            let pending_requests = outproc_gate.get_pending_requests();
            let gate = Arc::new(crate::wire::webrtc::gate::WebRtcGate::new(
                coordinator.clone(),
                pending_requests,
                data_stream_registry.clone(),
            ));
            // Set local_id
            gate.set_local_id(actor_id.clone()).await;
            tracing::info!(
                "✅ WebRtcGate created with shared pending_requests and DataStreamRegistry"
            );

            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            // 1.7. Wire the outproc gate into Inner so subsequent
            //      `make_runtime_context` / `bootstrap_ctx_builder` calls
            //      observe it. All per-request contexts created by
            //      `handle_incoming` go through this field live.
            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            tracing::info!("🔧 Wiring outproc_gate into node");
            self.outproc_gate = Some(outproc_gate_enum);
            tracing::info!("✅ Node runtime gates fully initialized (inproc + outproc)");

            // Save references
            self.webrtc_coordinator = Some(coordinator.clone());
            self.webrtc_gate = Some(gate.clone());
            tracing::info!("✅ WebRTC infrastructure initialized");

            // Fire `on_start` once the runtime context can see the initialized
            // gates, before starting request-accepting/background loops. Its
            // Err/panic aborts Node::start.
            {
                let startup_ctx = self
                    .bootstrap_ctx_builder()
                    .build_bootstrap(&actor_id, &credential_state.credential().await);
                let invocation = lifecycle_invocation(&actor_id, "lifecycle:on_start");
                let call_executor =
                    lifecycle_host_abi(startup_ctx.clone(), self.workload_dispatch.clone());
                let mut workload = self.workload_dispatch.lock().await;
                crate::lifecycle::hooks::call_lifecycle_hook(
                    "on_start",
                    workload.on_start(startup_ctx, invocation, &call_executor),
                )
                .await?;
            }

            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            // 1.7.6. WebSocket Server (direct-connect mode, optional)
            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            if let Some(listen_port) = self.config.websocket_listen_port {
                tracing::info!(
                    "🔌 WebSocket direct-connect mode enabled, binding port {}",
                    listen_port
                );
                use crate::key_cache::AisKeyCache;
                use crate::wire::websocket::gate::WsAuthContext;
                use crate::wire::websocket::{WebSocketGate, WebSocketServer};

                // Build AisKeyCache and seed it with the signing key from the registration response
                let ais_key_cache = AisKeyCache::new();
                if !register_ok.signing_pubkey.is_empty() {
                    match ais_key_cache
                        .seed(register_ok.signing_key_id, &register_ok.signing_pubkey)
                        .await
                    {
                        Ok(()) => tracing::info!(
                            key_id = register_ok.signing_key_id,
                            "🔑 AisKeyCache seeded from RegisterOk"
                        ),
                        Err(e) => tracing::warn!(
                            key_id = register_ok.signing_key_id,
                            error = ?e,
                            "AisKeyCache seed failed; WebSocket will reject all inbound connections"
                        ),
                    }
                } else {
                    tracing::warn!(
                        "RegisterOk missing signing_pubkey; WebSocket credential verification will degrade"
                    );
                }

                let auth_ctx = WsAuthContext {
                    ais_key_cache,
                    actor_id: actor_id.clone(),
                    credential_state: credential_state.clone(),
                    signaling_client: self.signaling_client.clone(),
                };

                match WebSocketServer::bind(listen_port).await {
                    Ok((ws_server, conn_rx)) => {
                        ws_server.start(self.shutdown_token.clone());
                        let ws_gate = Arc::new(WebSocketGate::new(
                            conn_rx,
                            outproc_gate.get_pending_requests(),
                            data_stream_registry.clone(),
                            Some(auth_ctx),
                        ));

                        // Install the WebSocket peer-lifecycle hook.
                        {
                            let actor_id_for_hook = actor_id.clone();
                            let credential_state_for_hook = credential_state.clone();
                            // Snapshot taken after outproc_gate is live: ws
                            // peer-lifecycle hook contexts can issue
                            // Dest::Actor(_) calls.
                            let ctx_builder_snapshot = self.bootstrap_ctx_builder();
                            let ctx_builder: crate::lifecycle::hooks::HookContextBuilder =
                                Arc::new(move || {
                                    let snapshot = ctx_builder_snapshot.clone();
                                    let actor_id = actor_id_for_hook.clone();
                                    let credential_state = credential_state_for_hook.clone();
                                    Box::pin(async move {
                                        Some(snapshot.build_bootstrap(
                                            &actor_id,
                                            &credential_state.credential().await,
                                        ))
                                    })
                                });
                            let cb = crate::lifecycle::hooks::build_hook_callback(
                                self.hook_observer.clone(),
                                ctx_builder,
                            );
                            ws_gate.set_hook_callback(cb);
                        }

                        self.websocket_gate = Some(ws_gate);
                        tracing::info!(
                            "✅ WebSocketServer + WebSocketGate initialized (credential auth enabled)"
                        );
                    }
                    Err(e) => {
                        tracing::error!(
                            "❌ Failed to bind WebSocket server on port {}: {:?}",
                            listen_port,
                            e
                        );
                    }
                }
            }

            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            // 1.7.5. Create shared state for credential management
            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            // Shared credential state initialized above; reused across tasks

            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            // 1.8. Spawn heartbeat task (periodic Ping to signaling server)
            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            {
                let shutdown = self.shutdown_token.clone();
                let client = self.signaling_client.clone();
                let actor_id_for_heartbeat = actor_id.clone();
                let credential_state_for_heartbeat = credential_state.clone();
                let mailbox_for_heartbeat = self.mailbox.clone();
                let register_request_for_heartbeat = register_request.clone();

                // Use interval from registration response, default to 30s
                let heartbeat_interval_secs = register_ok.signaling_heartbeat_interval_secs;
                let heartbeat_interval = if heartbeat_interval_secs > 0 {
                    Duration::from_secs(heartbeat_interval_secs as u64)
                } else {
                    Duration::from_secs(30)
                };
                let ais_endpoint_for_heartbeat = self.config.ais_endpoint.clone();
                let heartbeat_handle = tokio::spawn(crate::lifecycle::heartbeat::heartbeat_task(
                    shutdown,
                    client,
                    actor_id_for_heartbeat,
                    credential_state_for_heartbeat,
                    mailbox_for_heartbeat,
                    heartbeat_interval,
                    register_request_for_heartbeat,
                    ais_endpoint_for_heartbeat,
                    node_hook_callback.clone(),
                ));
                task_handles.push(heartbeat_handle);
            }
            tracing::info!(
                "✅ Heartbeat task started (interval: {}s)",
                register_ok.signaling_heartbeat_interval_secs
            );

            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            // 1.8.5. Spawn network event processing loop
            // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
            if let (Some(event_rx), Some(result_tx)) = (
                self.network_event_rx.take(),
                self.network_event_result_tx.take(),
            ) {
                use crate::lifecycle::network_event::DefaultNetworkEventProcessor;

                // Create DefaultNetworkEventProcessor
                // If debounce config exists, use new_with_debounce
                let event_processor =
                    if let Some(config) = self.network_event_debounce_config.clone() {
                        Arc::new(DefaultNetworkEventProcessor::new_with_debounce(
                            self.signaling_client.clone(),
                            self.webrtc_coordinator.clone(),
                            config,
                        ))
                    } else {
                        Arc::new(DefaultNetworkEventProcessor::new(
                            self.signaling_client.clone(),
                            self.webrtc_coordinator.clone(),
                        ))
                    };

                let shutdown = self.shutdown_token.clone();
                let network_event_handle = tokio::spawn(async move {
                    Self::network_event_loop(event_rx, result_tx, event_processor, shutdown).await;
                });
                task_handles.push(network_event_handle);
                tracing::info!("✅ Network event loop started");
            }

            {
                // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
                // 1.9. Spawn dedicated Unregister task (best-effort, with timeout)
                // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
                //
                // This task:
                // - Waits for shutdown_token to be cancelled (e.g., wait_for_ctrl_c_and_shutdown)
                // - Then sends UnregisterRequest via signaling client with a timeout
                //
                // NOTE: we push its JoinHandle into task_handles so it can be aborted
                // by ActrRefShared::Drop if needed.
                let shutdown = self.shutdown_token.clone();
                let client = self.signaling_client.clone();
                let actor_id_for_unreg = actor_id.clone();
                let credential_state_for_unreg = credential_state.clone();
                let webrtc_coordinator = self.webrtc_coordinator.clone();

                let unregister_handle = tokio::spawn(async move {
                    // Wait for shutdown signal
                    shutdown.cancelled().await;
                    tracing::info!(
                        "📡 Shutdown signal received, sending UnregisterRequest for Actor {}",
                        actor_id_for_unreg
                    );

                    // 1. Close all WebRTC peer connections first (if any)
                    if let Some(coord) = webrtc_coordinator {
                        if let Err(e) = coord.close_all_peers().await {
                            tracing::warn!(
                                "⚠️ Failed to close all WebRTC peers before UnregisterRequest: {}",
                                e
                            );
                        } else {
                            tracing::info!("✅ All WebRTC peers closed before UnregisterRequest");
                        }
                    } else {
                        tracing::debug!(
                            "WebRTC coordinator not found before UnregisterRequest (no WebRTC?)"
                        );
                    }

                    // 2. Then send UnregisterRequest with a timeout (e.g. 5 seconds)
                    let result = tokio::time::timeout(
                        Duration::from_secs(5),
                        client.send_unregister_request(
                            actor_id_for_unreg.clone(),
                            credential_state_for_unreg.credential().await,
                            Some("Graceful shutdown".to_string()),
                        ),
                    )
                    .await;
                    tracing::info!("UnregisterRequest result: {:?}", result);
                    match result {
                        Ok(Ok(_)) => {
                            tracing::info!(
                                "✅ UnregisterRequest sent to signaling server for Actor {}",
                                actor_id_for_unreg
                            );
                        }
                        Ok(Err(e)) => {
                            tracing::warn!(
                                "⚠️ Failed to send UnregisterRequest for Actor {}: {}",
                                actor_id_for_unreg,
                                e
                            );
                        }
                        Err(_) => {
                            tracing::warn!(
                                "⚠️ UnregisterRequest timeout (5s) for Actor {}",
                                actor_id_for_unreg
                            );
                        }
                    }
                });

                task_handles.push(unregister_handle);
            }
        } // end registration setup block

        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // 2. Transport layer initialization (completed via WebRTC infrastructure)
        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        tracing::info!("✅ Transport layer initialized via WebRTC infrastructure");

        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // 3.1 Convert to Arc (before starting background loops)
        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // Clone actor_id before moving self into Arc
        let actor_id = self
            .actor_id
            .as_ref()
            .ok_or_else(|| ActrError::Internal("Actor ID not set".to_string()))?
            .clone();
        // Snapshot now that outproc_gate has been wired above; this builder
        // is shared between on_start / on_stop hooks and the ActrRefShared
        // handle returned to the caller.
        let bootstrap_ctx_builder = self.bootstrap_ctx_builder();
        let credential_state = self
            .credential_state
            .clone()
            .expect("CredentialState must be initialized in start()");
        let shutdown_token = self.shutdown_token.clone();
        let node_ref = Arc::new(self);

        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // 3.2. Register workload-level stop hook.
        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        {
            let node = node_ref.clone();
            let actor_id = actor_id.clone();
            let credential_state = credential_state.clone();
            let shutdown = shutdown_token.clone();
            let on_stop_handle = tokio::spawn(async move {
                shutdown.cancelled().await;
                let stop_ctx = node
                    .bootstrap_ctx_builder()
                    .build_bootstrap(&actor_id, &credential_state.credential().await);
                let invocation = lifecycle_invocation(&actor_id, "lifecycle:on_stop");
                let call_executor =
                    lifecycle_host_abi(stop_ctx.clone(), node.workload_dispatch.clone());
                let mut workload = node.workload_dispatch.lock().await;
                if let Err(e) = crate::lifecycle::hooks::call_lifecycle_hook(
                    "on_stop",
                    workload.on_stop(stop_ctx, invocation, &call_executor),
                )
                .await
                {
                    tracing::warn!(error = %e, "workload on_stop returned Err");
                }
            });
            task_handles.push(on_stop_handle);
        }

        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // 3.5. Start WebRTC background loops
        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        tracing::info!("🚀 Starting WebRTC background loops");

        // Start WebRtcCoordinator signaling loop
        if let Some(coordinator) = &node_ref.webrtc_coordinator {
            coordinator.clone().start().await.map_err(|e| {
                ActrError::Unavailable(format!("WebRtcCoordinator start failed: {e}"))
            })?;
            tracing::info!("✅ WebRtcCoordinator signaling loop started");
        }

        // Start WebRtcGate message receive loop (route to Mailbox)
        if let Some(gate) = &node_ref.webrtc_gate {
            gate.start_receive_loop(node_ref.mailbox.clone())
                .await
                .map_err(|e| {
                    ActrError::Unavailable(format!("WebRtcGate receive loop start failed: {e}"))
                })?;
            tracing::info!("✅ WebRtcGate → Mailbox routing started");
        }

        // Start WebSocketGate message receive loop (route to Mailbox, direct-connect mode)
        if let Some(ws_gate) = &node_ref.websocket_gate {
            ws_gate
                .start_receive_loop(node_ref.mailbox.clone())
                .await
                .map_err(|e| {
                    ActrError::Unavailable(format!("WebSocketGate receive loop start failed: {e}"))
                })?;
            tracing::info!("✅ WebSocketGate → Mailbox routing started");
        }
        tracing::info!("✅ WebRTC background loops started");

        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // 4.6. Start Inproc receive loop (Shell → Guest)
        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        if let Some(shell_to_workload) = &node_ref.shell_to_workload {
            tracing::info!("🔄 Starting Inproc receive loop (Shell → Guest)");
            // Start Guest receive loop (Shell → Guest REQUEST)
            if let Some(workload_to_shell) = &node_ref.workload_to_shell {
                let node = node_ref.clone();
                let request_rx_lane = shell_to_workload
                    .get_lane(PayloadType::RpcReliable, None)
                    .await
                    .map_err(|e| {
                        ActrError::Unavailable(format!("Failed to get guest receive lane: {e}"))
                    })?;
                let response_tx = workload_to_shell.clone();
                let shutdown = shutdown_token.clone();

                let inproc_handle = tokio::spawn(async move {
                    loop {
                        tokio::select! {
                            _ = shutdown.cancelled() => {
                                tracing::info!("📭 Guest receive loop (Shell → Guest) received shutdown signal");
                                break;
                            }
                            envelope_result = request_rx_lane.recv_envelope() => {
                                match envelope_result {
                                    Ok(envelope) => {
                                        let request_id = envelope.request_id.clone();
                                        tracing::debug!("📨 Guest received REQUEST from Shell: request_id={}", request_id);
                                        // Extract and set tracing context from envelope
                                        #[cfg(feature = "opentelemetry")]
                                        let span = {
                                            let actr_id_str = node.actor_id.as_ref().map(|id| id.to_string()).unwrap_or_default();
                                            let span = tracing::info_span!("ActrNode.lane_receive", actr_id = %actr_id_str, request_id = %request_id);
                                            set_parent_from_rpc_envelope(&span, &envelope);
                                            span
                                        };

                                        // Shell calls have no caller_id (local process communication)
                                        let handle_incoming_fut = node.handle_incoming(envelope.clone(), None);
                                        #[cfg(feature = "opentelemetry")]
                                        let handle_incoming_fut = handle_incoming_fut.instrument(span.clone());

                                        match handle_incoming_fut.await {
                                            Ok(response_bytes) => {
                                                // Send RESPONSE back via workload_to_shell
                                                // Keep same route_key (no prefix needed - separate channels!)
                                                #[cfg_attr(not(feature = "opentelemetry"), allow(unused_mut))]
                                                let mut response_envelope = RpcEnvelope {
                                                    route_key: envelope.route_key.clone(),
                                                    payload: Some(response_bytes),
                                                    error: None,
                                                    traceparent: None,
                                                    tracestate: None,
                                                    request_id: request_id.clone(),
                                                    metadata: Vec::new(),
                                                    timeout_ms: 30000,
                                                };
                                                // Inject tracing context
                                                #[cfg(feature = "opentelemetry")]
                                                inject_span_context_to_rpc(&span, &mut response_envelope);

                                                // Send via Guest → Shell channel
                                                let send_response_fut = response_tx.send_message(PayloadType::RpcReliable, None, response_envelope);
                                                #[cfg(feature = "opentelemetry")]
                                                let send_response_fut = send_response_fut.instrument(span.clone());
                                                if let Err(e) = send_response_fut.await {
                                                    tracing::error!(
                                                        severity = 7,
                                                        error_category = "transport_error",
                                                        request_id = %request_id,
                                                        "❌ Failed to send RESPONSE to Shell: {:?}",
                                                        e
                                                    );
                                                }
                                            }
                                            Err(e) => {
                                                tracing::error!(
                                                    severity = 6,
                                                    error_category = "handler_error",
                                                    request_id = %request_id,
                                                    route_key = %envelope.route_key,
                                                    "❌ Guest message handling failed: {:?}",
                                                    e
                                                );

                                                // Send error response (system-level error on envelope)
                                                let error_response = actr_protocol::ErrorResponse {
                                                    code: protocol_error_to_code(&e),
                                                    message: e.to_string(),
                                                };
                                                #[cfg_attr(not(feature = "opentelemetry"), allow(unused_mut))]
                                                let mut error_envelope = RpcEnvelope {
                                                    route_key: envelope.route_key.clone(),
                                                    payload: None,
                                                    error: Some(error_response),
                                                    traceparent: envelope.traceparent.clone(),
                                                    tracestate: envelope.tracestate.clone(),
                                                    request_id: request_id.clone(),
                                                    metadata: Vec::new(),
                                                    timeout_ms: 30000,
                                                };
                                                // Inject tracing context
                                                #[cfg(feature = "opentelemetry")]
                                                inject_span_context_to_rpc(&span, &mut error_envelope);

                                                let send_error_response_fut = response_tx.send_message(PayloadType::RpcReliable, None, error_envelope);
                                                #[cfg(feature = "opentelemetry")]
                                                let send_error_response_fut = send_error_response_fut.instrument(span);
                                                if let Err(send_err) = send_error_response_fut.await {
                                                    tracing::error!(
                                                        severity = 7,
                                                        error_category = "transport_error",
                                                        request_id = %request_id,
                                                        "❌ Failed to send ERROR response to Shell: {:?}",
                                                        send_err
                                                    );
                                                }
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        tracing::error!(
                                            severity = 8,
                                            error_category = "transport_error",
                                            "❌ Failed to receive from Shell → Guest lane: {:?}",
                                            e
                                        );
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    tracing::info!("✅ Guest receive loop (Shell → Guest) terminated gracefully");
                });
                task_handles.push(inproc_handle);
            }
        }
        tracing::info!("✅ Guest receive loop (Shell → Guest REQUEST) started");

        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // 4.7. Start Shell receive loop (Guest → Shell RESPONSE)
        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        tracing::info!("🔄 Starting Shell receive loop (Guest → Shell RESPONSE)");
        if let Some(workload_to_shell) = &node_ref.workload_to_shell {
            // Start Shell receive loop (Guest → Shell RESPONSE)
            if let Some(shell_to_workload) = &node_ref.shell_to_workload {
                let response_rx_lane = workload_to_shell
                    .get_lane(PayloadType::RpcReliable, None)
                    .await
                    .map_err(|e| {
                        ActrError::Unavailable(format!("Failed to get shell receive lane: {e}"))
                    })?;
                let request_mgr = shell_to_workload.clone();
                let shutdown = shutdown_token.clone();

                let shell_receive_handle = tokio::spawn(async move {
                    loop {
                        tokio::select! {
                            _ = shutdown.cancelled() => {
                                tracing::info!("📭 Shell receive loop (Guest → Shell) received shutdown signal");
                                break;
                            }
                            envelope_result = response_rx_lane.recv_envelope() => {
                                match envelope_result {
                                    Ok(envelope) => {
                                        tracing::debug!(
                                            "📨 Shell received RESPONSE from Guest: request_id={}",
                                            envelope.request_id
                                        );

                                        // Check if response is success or error
                                        match (envelope.payload, envelope.error) {
                                            (Some(payload), None) => {
                                                // Success response
                                                if let Err(e) = request_mgr
                                                    .complete_response(&envelope.request_id, payload)
                                                    .await
                                                {
                                                    tracing::warn!(
                                                        severity = 4,
                                                        error_category = "orphan_response",
                                                        request_id = %envelope.request_id,
                                                        "⚠️  No pending request found for response: {:?}",
                                                        e
                                                    );
                                                }
                                            }
                                            (None, Some(error)) => {
                                                // Error response - convert to ActrError and complete with error
                                                let actr_err = ActrError::Unavailable(format!("RPC error {}: {}", error.code, error.message));
                                                if let Err(e) = request_mgr
                                                    .complete_error(&envelope.request_id, actr_err)
                                                    .await
                                                {
                                                    tracing::warn!(
                                                        severity = 4,
                                                        error_category = "orphan_response",
                                                        request_id = %envelope.request_id,
                                                        "⚠️  No pending request found for error response: {:?}",
                                                        e
                                                    );
                                                }
                                            }
                                            _ => {
                                                tracing::error!(
                                                    severity = 7,
                                                    error_category = "protocol_error",
                                                    request_id = %envelope.request_id,
                                                    "❌ Invalid RpcEnvelope: both payload and error are present or both absent"
                                                );
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        tracing::error!(
                                            severity = 8,
                                            error_category = "transport_error",
                                            "❌ Failed to receive from Guest → Shell lane: {:?}",
                                            e
                                        );
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    tracing::info!("✅ Shell receive loop (Guest → Shell) terminated gracefully");
                });
                task_handles.push(shell_receive_handle);
            }
        }
        tracing::info!("✅ Shell receive loop (Guest → Shell RESPONSE) started");

        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // 4.9. Mailbox backpressure watchdog
        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        //
        // Emits the framework `on_mailbox_backpressure` hook once per
        // rising-edge crossing of the configured threshold.
        //
        // Preferred path: a push-based notification from the mailbox
        // backend via [`Mailbox::set_depth_observer`], which runs
        // synchronously on every enqueue and has zero worst-case delay.
        //
        // Fallback path: mailbox backends without depth support (or
        // which can't cheaply compute depth on every enqueue) keep
        // using a 1 Hz poll of [`Mailbox::status`].
        let backpressure_threshold = node_ref.mailbox_backpressure_threshold;
        {
            use std::sync::atomic::{AtomicBool, Ordering};
            let mailbox = node_ref.mailbox.clone();
            let shutdown = shutdown_token.clone();
            let hook_cb = node_hook_callback.clone();
            let triggered = Arc::new(AtomicBool::new(false));

            // Shared rising-edge state + hook-firing closure used by
            // both the push and polling code paths.
            let fire_if_rising = {
                let triggered = triggered.clone();
                let hook_cb = hook_cb.clone();
                Arc::new(move |queue_len: usize| {
                    if queue_len >= backpressure_threshold {
                        if !triggered.swap(true, Ordering::AcqRel) {
                            if let Some(cb) = hook_cb.as_ref() {
                                let cb = cb.clone();
                                tokio::spawn(async move {
                                    cb(crate::wire::webrtc::HookEvent::MailboxBackpressure {
                                        queue_len,
                                        threshold: backpressure_threshold,
                                    })
                                    .await;
                                });
                            } else {
                                tracing::warn!(
                                    queue_len,
                                    threshold = backpressure_threshold,
                                    "mailbox backpressure",
                                );
                            }
                        }
                    } else if triggered.swap(false, Ordering::AcqRel) {
                        tracing::info!(
                            queue_len,
                            threshold = backpressure_threshold,
                            "mailbox backpressure cleared",
                        );
                    }
                })
            };

            // Try the push path first. The observer installs only if
            // the backend supports it; otherwise `installed` is `false`
            // and we fall through to polling.
            struct EnqueueObserver {
                fire: Arc<dyn Fn(usize) + Send + Sync + 'static>,
            }
            impl actr_runtime_mailbox::MailboxDepthObserver for EnqueueObserver {
                fn on_depth_change(&self, queued_messages: usize) {
                    (self.fire)(queued_messages);
                }
            }

            let installed = {
                let observer: Arc<dyn actr_runtime_mailbox::MailboxDepthObserver> =
                    Arc::new(EnqueueObserver {
                        fire: fire_if_rising.clone(),
                    });
                mailbox.set_depth_observer(observer)
            };

            if installed {
                tracing::debug!("mailbox backpressure watchdog: push notifications enabled");
            } else {
                tracing::debug!(
                    "mailbox backpressure watchdog: backend does not support push, falling back to 1 Hz polling"
                );
                let mailbox_for_poll = mailbox.clone();
                let shutdown_for_poll = shutdown.clone();
                let fire_for_poll = fire_if_rising.clone();
                let watchdog_handle = tokio::spawn(async move {
                    let mut ticker = tokio::time::interval(Duration::from_secs(1));
                    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
                    loop {
                        tokio::select! {
                            _ = shutdown_for_poll.cancelled() => {
                                tracing::debug!(
                                    "mailbox backpressure watchdog shutting down"
                                );
                                break;
                            }
                            _ = ticker.tick() => {
                                let status = match mailbox_for_poll.status().await {
                                    Ok(s) => s,
                                    Err(e) => {
                                        tracing::debug!(?e, "mailbox status poll failed");
                                        continue;
                                    }
                                };
                                fire_for_poll(status.queued_messages as usize);
                            }
                        }
                    }
                });
                task_handles.push(watchdog_handle);
            }
        }

        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        // 5. Start Mailbox processing loop (State Path)
        // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        tracing::info!("🔄 Starting Mailbox processing loop (State Path)");
        {
            let node = node_ref.clone();
            let mailbox = node_ref.mailbox.clone();
            let gate = node_ref.webrtc_gate.clone();
            let shutdown = shutdown_token.clone();

            let mailbox_handle = tokio::spawn(async move {
                loop {
                    tokio::select! {
                        // Listen for shutdown signal
                        _ = shutdown.cancelled() => {
                            tracing::info!("📭 Mailbox loop received shutdown signal");
                            break;
                        }
                        // Dequeue messages (by priority)
                        result = mailbox.dequeue() => {
                            match result {
                                Ok(messages) => {
                                    if messages.is_empty() {
                                        // Queue empty, sleep briefly
                                        tokio::time::sleep(Duration::from_millis(10)).await;
                                        continue;
                                    }
                                    tracing::debug!("📬 Mailbox dequeue: {} messages", messages.len());

                                    // Process messages one by one
                                    for msg_record in messages {
                                        // Deserialize RpcEnvelope (Protobuf)
                                        match RpcEnvelope::decode(&msg_record.payload[..]) {
                                            Ok(envelope) => {
                                                let request_id = envelope.request_id.clone();
                                                let queue_latency_ms = (chrono::Utc::now() - msg_record.created_at).num_milliseconds();
                                                tracing::info!(request_id = %request_id, queue_latency_ms = queue_latency_ms, "rpc.mailbox.dequeued");

                                                tracing::debug!("📦 Processing message: request_id={}", request_id);
                                                #[cfg(feature = "opentelemetry")]
                                                let span = {
                                                    let actr_id_str = node.actor_id.as_ref().map(|id| id.to_string()).unwrap_or_default();
                                                    let span = tracing::info_span!("ActrNode.mailbox_receive", actr_id = %actr_id_str, request_id = %request_id, queue_wait_ms = queue_latency_ms);
                                                    set_parent_from_rpc_envelope(&span, &envelope);
                                                    span
                                                };

                                                // Decode caller_id from MessageRecord.from (transport layer)
                                                let caller_id_result = ActrId::decode(&msg_record.from[..]);
                                                let caller_id_ref = caller_id_result.as_ref().ok();

                                                if caller_id_ref.is_none() {
                                                    tracing::warn!(
                                                        request_id = %request_id,
                                                        "⚠️  Failed to decode caller_id from MessageRecord.from"
                                                    );
                                                }

                                                // Call handle_incoming with caller_id from transport layer
                                                let handle_incoming_fut = node.handle_incoming(envelope.clone(), caller_id_ref);
                                                #[cfg(feature = "opentelemetry")]
                                                let handle_incoming_fut = handle_incoming_fut.instrument(span.clone());

                                                match handle_incoming_fut.await {
                                                    Ok(response_bytes) => {
                                                        // Send response (reuse request_id)
                                                        if let Some(ref gate) = gate {
                                                            // Use already decoded caller_id
                                                            match caller_id_result {
                                                                Ok(caller) => {
                                                                    // Construct response RpcEnvelope (reuse request_id!)
                                                                    #[cfg_attr(not(feature = "opentelemetry"), allow(unused_mut))]
                                                                    let mut response_envelope = RpcEnvelope {
                                                                        request_id, // Reuse!
                                                                        route_key: envelope.route_key.clone(),
                                                                        payload: Some(response_bytes),
                                                                        error: None,
                                                                        traceparent: envelope.traceparent.clone(),
                                                                        tracestate: envelope.tracestate.clone(),
                                                                        metadata: Vec::new(), // Response doesn't need extra metadata
                                                                        timeout_ms: 30000,
                                                                    };
                                                                    // Inject tracing context
                                                                    #[cfg(feature = "opentelemetry")]
                                                                    inject_span_context_to_rpc(&span, &mut response_envelope);

                                                                    let send_response_fut = gate.send_response(&caller, response_envelope);
                                                                    #[cfg(feature = "opentelemetry")]
                                                                    let send_response_fut = send_response_fut.instrument(span);
                                                                    if let Err(e) = send_response_fut.await {
                                                                        tracing::error!(
                                                                            severity = 7,
                                                                            error_category = "transport_error",
                                                                            request_id = %envelope.request_id,
                                                                            "❌ Failed to send response: {:?}",
                                                                            e
                                                                        );
                                                                    }
                                                                }
                                                                Err(e) => {
                                                                    tracing::error!(
                                                                        severity = 8,
                                                                        error_category = "protobuf_decode",
                                                                        request_id = %envelope.request_id,
                                                                        "❌ Failed to decode caller_id: {:?}",
                                                                        e
                                                                    );
                                                                }
                                                            }
                                                        }

                                                        // ACK message
                                                        if let Err(e) = mailbox.ack(msg_record.id).await {
                                                            tracing::error!(
                                                                severity = 9,
                                                                error_category = "mailbox_error",
                                                                request_id = %envelope.request_id,
                                                                message_id = %msg_record.id,
                                                                "❌ Mailbox ACK failed: {:?}",
                                                                e
                                                            );
                                                        }
                                                    }
                                                    Err(e) => {
                                                        tracing::error!(
                                                            severity = 6,
                                                            error_category = "handler_error",
                                                            request_id = %envelope.request_id,
                                                            route_key = %envelope.route_key,
                                                            "❌ handle_incoming failed: {:?}", e
                                                        );
                                                        // ACK to avoid infinite retries
                                                        // Application errors are caller's responsibility
                                                        let _ = mailbox.ack(msg_record.id).await;
                                                    }
                                                }
                                            }
                                            Err(e) => {
                                                // Poison message - cannot decode RpcEnvelope
                                                tracing::error!(
                                                    severity = 9,
                                                    error_category = "protobuf_decode",
                                                    message_id = %msg_record.id,
                                                    "❌ Poison message: Failed to deserialize RpcEnvelope: {:?}",
                                                    e
                                                );

                                                // Write to Dead Letter Queue
                                                use actr_runtime_mailbox::DlqRecord;
                                                use chrono::Utc;
                                                use uuid::Uuid;

                                                let dlq_record = DlqRecord {
                                                    id: Uuid::new_v4(),
                                                    original_message_id: Some(msg_record.id.to_string()),
                                                    from: Some(msg_record.from.clone()),
                                                    to: node.actor_id.as_ref().map(|id| {
                                                        let mut buf = Vec::new();
                                                        id.encode(&mut buf).unwrap();
                                                        buf
                                                    }),
                                                    raw_bytes: msg_record.payload.clone(),
                                                    error_message: format!("Protobuf decode failed: {e}"),
                                                    error_category: "protobuf_decode".to_string(),
                                                    trace_id: format!("mailbox-{}", msg_record.id),
                                                    request_id: None,
                                                    created_at: Utc::now(),
                                                    redrive_attempts: 0,
                                                    last_redrive_at: None,
                                                    context: Some(format!(
                                                        r#"{{"source":"mailbox","priority":"{}"}}"#,
                                                        match msg_record.priority {
                                                            actr_runtime_mailbox::MessagePriority::High => "high",
                                                            actr_runtime_mailbox::MessagePriority::Normal => "normal",
                                                        }
                                                    )),
                                                };

                                                if let Err(dlq_err) = node.dlq.enqueue(dlq_record).await {
                                                    tracing::error!(
                                                        severity = 10,
                                                        "❌ CRITICAL: Failed to write poison message to DLQ: {:?}",
                                                        dlq_err
                                                    );
                                                } else {
                                                    tracing::warn!(
                                                        severity = 9,
                                                        "☠️ Poison message moved to DLQ: message_id={}",
                                                        msg_record.id
                                                    );
                                                }

                                                // ACK the poison message to remove from mailbox
                                                let _ = mailbox.ack(msg_record.id).await;
                                            }
                                        }
                                    }
                                }
                                Err(e) => {
                                    tracing::error!(
                                        severity = 9,
                                        error_category = "mailbox_error",
                                        "❌ Mailbox dequeue failed: {:?}", e
                                    );
                                    tokio::time::sleep(Duration::from_secs(1)).await;
                                }
                            }
                        }
                    }
                }
                tracing::info!("✅ Mailbox processing loop terminated gracefully");
            });

            task_handles.push(mailbox_handle);
        }
        tracing::info!("✅ Mailbox processing loop started");
        tracing::info!("✅ ActrNode started successfully");

        {
            let ready_ctx = bootstrap_ctx_builder
                .build_bootstrap(&actor_id, &credential_state.credential().await);
            let invocation = lifecycle_invocation(&actor_id, "lifecycle:on_ready");
            let call_executor =
                lifecycle_host_abi(ready_ctx.clone(), node_ref.workload_dispatch.clone());
            let mut workload = node_ref.workload_dispatch.lock().await;
            if let Err(e) = crate::lifecycle::hooks::call_lifecycle_hook(
                "on_ready",
                workload.on_ready(ready_ctx, invocation, &call_executor),
            )
            .await
            {
                tracing::warn!(error = %e, "workload on_ready returned Err");
            }
        }

        // Create ActrRefShared
        let shared = Arc::new(ActrRefShared {
            actor_id,
            bootstrap_ctx_builder,
            credential_state,
            shutdown_token,
            task_handles: Mutex::new(task_handles),
        });

        // Create ActrRef
        tracing::info!("✅ ActrRef created (Shell → Guest communication handle)");

        Ok(ActrRef { shared })
    }
}