cellos-supervisor 0.5.1

CellOS execution-cell runner — boots cells in Firecracker microVMs or gVisor, enforces narrow typed authority, emits signed CloudEvents.
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
//! [`Supervisor`] — lifecycle orchestration extracted from the composition root.
//!
//! `main.rs` wires the adapters; `Supervisor::run` owns the lifecycle sequence:
//! network_scope → trust_plane_observability (optional) → secrets → started → run → export → destroy → revoke → destroyed.
//!
//! Teardown semantics: `destroy` and `revoke_for_cell` are called unconditionally
//! even when a phase error has already been captured.

use std::collections::HashMap;
use std::sync::Arc;

use anyhow::Context;
use cellos_core::ports::{CellBackend, EventSink, ExportSink, SecretBroker};
use cellos_core::types::SecretDeliveryMode;
use cellos_core::{
    authz_rejected_data_v1, command_completed_data_v1, compliance_summary_data_v1,
    export_completed_data_v2, export_failed_data_v2, identity_materialized_data_v1,
    identity_revoked_data_v1, lifecycle_destroyed_data_v1, lifecycle_started_data_v1,
    observability_fs_touch_export_data_v1, observability_network_enforcement_data_v1,
    observability_network_scope_data_v1, observability_process_spawned_data_v1,
    policy_rejected_data_v1, validate_spec_against_policy, verify_authority_derivation,
    AuthorityDerivationToken, AuthorizationPolicy, CloudEventV1, Correlation, EgressRule,
    ExecutionCellDocument, ExecutionCellSpec, ExportArtifactMetadata, IdentityFailureOperation,
    LifecycleDestroyOutcome, LifecycleTerminalState, PolicyPackSpec, SecretView,
};
#[cfg(target_os = "linux")]
use cellos_core::{observability_container_security_data_v1, observability_network_policy_data_v1};

#[cfg(target_os = "linux")]
use crate::network_policy::read_proc_caps;
use crate::runtime_secret::RuntimeSecretSession;
use crate::supervisor_helpers::{
    argv0_allow_prefixes_error, cloud_event, configured_broker_name, effective_export_target_name,
    identity_resolve_key, logical_export_destination, resolve_export_target_kind,
    runtime_secret_entries_for_doc, runtime_secret_lease_requests_for_doc,
};

pub struct Supervisor {
    pub host: Arc<dyn CellBackend>,
    pub broker: Arc<dyn SecretBroker>,
    /// Primary event sink (JetStream or noop).
    pub event_sink: Arc<dyn EventSink>,
    /// Optional secondary JSONL sink — receives every event after the primary.
    pub jsonl_sink: Option<Arc<dyn EventSink>>,
    pub default_export_sink: Arc<dyn ExportSink>,
    pub named_export_sinks: HashMap<String, Arc<dyn ExportSink>>,
    /// Active policy pack for admission gate enforcement.  When set, every cell
    /// spec is validated before `host.create()` is called; violations produce a
    /// `policy.rejected` CloudEvent and an error return.
    pub policy_pack: Option<PolicyPackSpec>,
    /// T12 RBAC — operator-supplied authorization policy, loaded from
    /// `CELLOS_AUTHZ_POLICY_PATH` at startup. When set, every cell spec is
    /// checked against the policy's `subjects` / `allowedPools` /
    /// `allowedPolicyPacks` lists before `host.create()`; rejection produces a
    /// `cell.authz.v1.rejected` CloudEvent and a startup error. Independent
    /// of the policy-pack admission gate (`policy_pack` above) — both gates
    /// fire in series with their own rule namespaces.
    pub authz_policy: Option<AuthorizationPolicy>,
    /// Operator-supplied role → ED25519 verifying key map, sourced from
    /// `CELLOS_AUTHORITY_KEYS_PATH` and loaded once at startup. Plumbed through
    /// from `build_supervisor` so the `lifecycle.started` event's
    /// `derivationVerified` flag reflects the real cryptographic verification
    /// result (Lane B). Wrapped in `Arc` so cloning per cell run is cheap.
    /// Empty map is the legacy/default behaviour: tokens are present but no
    /// keys are configured → verification fails with `unknown role` →
    /// `derivationVerified: false`.
    pub authority_keys: Arc<HashMap<String, String>>,
    /// SEC-25 Phase 2: operator-supplied trust-keyset signer kid →
    /// `ed25519_dalek::VerifyingKey` map, sourced from
    /// `CELLOS_TRUST_VERIFY_KEYS_PATH` and loaded once at startup. Plumbed
    /// through from `build_supervisor` so the verifier
    /// (`cellos_core::verify_signed_trust_keyset_envelope`) has the keyring it
    /// needs at startup-time keyset establishment AND at any future per-cell
    /// envelope re-verification. Wrapped in `Arc` so cloning per cell run is
    /// cheap. Empty map is the legacy/default behaviour: any envelope
    /// reference under `CELLOS_TRUST_KEYSET_PATH` will surface a
    /// `keyset_verification_failed` event because no signature can verify
    /// against an empty keyring.
    pub trust_verify_keys: Arc<HashMap<String, ed25519_dalek::VerifyingKey>>,
    /// I6 / O6: tracks whether the supervisor was started in PERMISSIVE
    /// universal-token mode AND a universal token was accepted at admission
    /// time (`parentRunId: null`). When `true`, `Supervisor::run` emits a
    /// single `cell.identity.universal_token_accepted_in_permissive_mode`
    /// CloudEvent so the audit trail records the exposure.
    pub universal_token_accepted_in_permissive_mode: bool,
}

// I5 per-event signing has moved out of this lifecycle module and into the
// composition root: see `crate::event_signing::SigningEventSink`, which
// wraps `Arc<dyn EventSink>` and replaces every emit with a transport
// CloudEvent of type `dev.cellos.events.signed_envelope.v1`. The
// supervisor's `emit()` is back to a one-line forward to the configured
// sinks; whether the bytes that hit JetStream / JSONL are signed or not is
// decided in `composition::build_primary_event_sink` and
// `composition::build_jsonl_sink`.
//
// D7 zeroize hardening for the new SigningConfig lives at its current
// home `crate::event_signing::SigningConfig`.

/// SEAM-1 / L2-04 Phase 2b — resolved activation plan for the in-netns
/// DNS proxy. Built by [`Supervisor::build_dns_proxy_activation`] in the
/// async lifecycle path and consumed by `linux_run_cell_command_isolated`
/// in the sync `spawn_blocking` thread that owns the workload child PID.
///
/// Owns clones of all spec-derived state so the plan survives the
/// async/sync boundary without lifetime entanglement.
/// SEC-22 Phase 2 — resolved activation plan for the in-netns SNI-aware
/// L7 proxy. Built by [`Supervisor::build_sni_proxy_activation`] in the
/// async lifecycle path and consumed by `linux_run_cell_command_isolated`
/// once the workload child PID is known.
///
/// Owns clones of all spec-derived state so the plan survives the
/// async/sync boundary without lifetime entanglement (mirrors
/// [`DnsProxyActivation`]).
#[derive(Debug, Clone)]
pub(crate) struct SniProxyActivation {
    #[allow(dead_code)]
    pub cfg: crate::sni_proxy::SniProxyConfig,
    #[allow(dead_code)]
    pub listen_addr: std::net::SocketAddr,
}

#[derive(Debug, Clone)]
pub(crate) struct DnsProxyActivation {
    // The cfg + listen_addr fields are only consumed by the Linux spawn path.
    // On non-Linux the activation is built but never spawned (skip path); the
    // resolver_id is still useful for diagnostic logging on either platform.
    #[allow(dead_code)]
    pub cfg: crate::dns_proxy::DnsProxyConfig,
    #[allow(dead_code)]
    pub listen_addr: std::net::SocketAddr,
    #[allow(dead_code)]
    pub upstream_addr: std::net::SocketAddr,
    pub resolver_id: String,
}

impl Supervisor {
    pub fn new(
        host: Arc<dyn CellBackend>,
        broker: Arc<dyn SecretBroker>,
        event_sink: Arc<dyn EventSink>,
        jsonl_sink: Option<Arc<dyn EventSink>>,
        default_export_sink: Arc<dyn ExportSink>,
        named_export_sinks: HashMap<String, Arc<dyn ExportSink>>,
        authority_keys: Arc<HashMap<String, String>>,
    ) -> Self {
        Self {
            host,
            broker,
            event_sink,
            jsonl_sink,
            default_export_sink,
            named_export_sinks,
            policy_pack: None,
            authz_policy: None,
            authority_keys,
            trust_verify_keys: Arc::new(HashMap::new()),
            universal_token_accepted_in_permissive_mode: false,
        }
    }

    /// T12 RBAC — admission gate that runs *before* the policy-pack gate and
    /// `host.create()`. Returns `Ok(())` when the spec is authorized;
    /// returns `Err` (after emitting a `cell.authz.v1.rejected` CloudEvent)
    /// when it is not.
    ///
    /// Evaluation order (each step short-circuits with its own rejection
    /// reason):
    /// 1. **Subject**: `spec.correlation.tenantId` must be present AND appear
    ///    in `authz_policy.subjects`. Absent tenant id is treated as
    ///    `subject_not_authorized` — the operator opted into the gate, so
    ///    every spec must declare a tenant.
    /// 2. **Pool**: when `allowed_pools` is non-empty, `spec.placement.poolId`
    ///    must be present and in the list. Absent pool is allowed only when
    ///    `allowed_pools` is empty.
    /// 3. **Policy pack**: when `allowed_policy_packs` is non-empty,
    ///    `spec.policy.packId` must be present and in the list.
    pub(crate) async fn enforce_authz_policy(
        &self,
        doc: &ExecutionCellDocument,
        authz_policy: &AuthorizationPolicy,
    ) -> anyhow::Result<()> {
        let spec = &doc.spec;
        let tenant_id = spec
            .correlation
            .as_ref()
            .and_then(|c| c.tenant_id.as_deref());

        // 1. Subject (tenant) check.
        let tenant = match tenant_id {
            Some(t) => t,
            None => {
                let msg = "spec.correlation.tenantId is required when an \
                           AuthorizationPolicy is configured but the spec did not declare one";
                self.emit_authz_rejection(spec, "subject_not_authorized", msg, None, None)
                    .await;
                return Err(anyhow::anyhow!(
                    "cell spec rejected by authorization policy: {msg}"
                ));
            }
        };
        if !authz_policy.subjects.iter().any(|s| s == tenant) {
            let msg =
                format!("tenantId {tenant:?} is not in the authorization policy subjects list");
            self.emit_authz_rejection(spec, "subject_not_authorized", &msg, None, None)
                .await;
            return Err(anyhow::anyhow!(
                "cell spec rejected by authorization policy: {msg}"
            ));
        }

        // 2. Pool check.
        if !authz_policy.allowed_pools.is_empty() {
            let pool_id = spec.placement.as_ref().and_then(|p| p.pool_id.as_deref());
            match pool_id {
                Some(p) if authz_policy.allowed_pools.iter().any(|x| x == p) => { /* allowed */ }
                Some(p) => {
                    let msg =
                        format!("pool {p:?} is not in the authorization policy allowedPools list");
                    self.emit_authz_rejection(spec, "pool_not_allowed", &msg, Some(p), None)
                        .await;
                    return Err(anyhow::anyhow!(
                        "cell spec rejected by authorization policy: {msg}"
                    ));
                }
                None => {
                    let msg = "spec.placement.poolId is required when the authorization \
                               policy declares allowedPools";
                    self.emit_authz_rejection(spec, "pool_not_allowed", msg, None, None)
                        .await;
                    return Err(anyhow::anyhow!(
                        "cell spec rejected by authorization policy: {msg}"
                    ));
                }
            }
        }

        // 3. Policy pack check.
        if !authz_policy.allowed_policy_packs.is_empty() {
            let pack_id = spec.policy.as_ref().and_then(|p| p.pack_id.as_deref());
            match pack_id {
                Some(p) if authz_policy.allowed_policy_packs.iter().any(|x| x == p) => {
                    /* allowed */
                }
                Some(p) => {
                    let msg = format!(
                        "policy pack {p:?} is not in the authorization policy \
                         allowedPolicyPacks list"
                    );
                    self.emit_authz_rejection(spec, "policy_pack_not_allowed", &msg, None, Some(p))
                        .await;
                    return Err(anyhow::anyhow!(
                        "cell spec rejected by authorization policy: {msg}"
                    ));
                }
                None => {
                    let msg = "spec.policy.packId is required when the authorization \
                               policy declares allowedPolicyPacks";
                    self.emit_authz_rejection(spec, "policy_pack_not_allowed", msg, None, None)
                        .await;
                    return Err(anyhow::anyhow!(
                        "cell spec rejected by authorization policy: {msg}"
                    ));
                }
            }
        }

        Ok(())
    }

    /// Best-effort `cell.authz.v1.rejected` event emit. Logs and discards
    /// transport failures — the admission error returned to `run()` is the
    /// authoritative outcome; we never mask it with an emit error.
    async fn emit_authz_rejection(
        &self,
        spec: &ExecutionCellSpec,
        reason: &str,
        message: &str,
        denied_pool_id: Option<&str>,
        denied_policy_pack_id: Option<&str>,
    ) {
        match authz_rejected_data_v1(spec, reason, message, denied_pool_id, denied_policy_pack_id) {
            Ok(data) => {
                let ev = cloud_event("dev.cellos.events.cell.authz.v1.rejected", data);
                if let Err(e) = self.emit(&ev).await {
                    tracing::warn!(
                        target: "cellos.supervisor.rbac",
                        error = %e,
                        "authz.rejected event emit failed"
                    );
                }
            }
            Err(e) => {
                tracing::warn!(
                    target: "cellos.supervisor.rbac",
                    error = %e,
                    "authz.rejected event build failed"
                );
            }
        }
    }

    /// Compute the `(derivationVerified, roleRoot, parentRunId)` triple
    /// emitted on `dev.cellos.events.cell.lifecycle.v1.started`.
    ///
    /// Returns `(None, None, None)` when the spec carries no derivation
    /// token — preserving the original lifecycle.started shape for specs
    /// that don't opt into authority derivation.
    ///
    /// When a token is present, `derivationVerified` is the boolean result
    /// of `verify_authority_derivation` against `self.authority_keys` —
    /// the same cryptographic check `main.rs` runs as a fail-closed gate
    /// before `build_supervisor`. This means the started event reports the
    /// real ED25519 verification result, not a structural-only stub.
    ///
    /// Extracted as a method so the wiring (Supervisor stores the keys → the
    /// started-event path uses them) can be unit-tested without standing up
    /// a full `Supervisor::run` lifecycle.
    pub(crate) fn compute_derivation_verification(
        &self,
        spec: &ExecutionCellSpec,
        token: Option<&AuthorityDerivationToken>,
    ) -> (Option<bool>, Option<String>, Option<String>) {
        match token {
            Some(token) => {
                let verified =
                    verify_authority_derivation(spec, token, self.authority_keys.as_ref()).is_ok();
                let role = token.role_root.0.clone();
                let parent = token.parent_run_id.clone();
                (Some(verified), Some(role), parent)
            }
            None => (None, None, None),
        }
    }

    /// Emit to the primary sink then optionally to the JSONL sink.
    ///
    /// I5 (per-event signing): when the operator opts in via
    /// `CELLOS_EVENT_SIGNING={ed25519|hmac}` plus a kid + key, the wrapping
    /// happens inside `event_sink` / `jsonl_sink` themselves — see
    /// `crate::event_signing::SigningEventSink`, attached in the
    /// composition root. From `Supervisor`'s perspective, an emit is just a
    /// forward to the configured sinks regardless of whether they're
    /// signing.
    pub(crate) async fn emit(&self, event: &CloudEventV1) -> anyhow::Result<()> {
        self.event_sink
            .emit(event)
            .await
            .map_err(|e| anyhow::anyhow!("primary sink emit: {e}"))?;
        if let Some(ref j) = self.jsonl_sink {
            j.emit(event)
                .await
                .map_err(|e| anyhow::anyhow!("jsonl sink emit: {e}"))?;
        }
        Ok(())
    }

    /// Execute the full cell lifecycle for `doc` with the given `run_id`.
    ///
    /// Returns `Ok(())` on success, `Err` if any phase failed.
    /// Teardown (destroy + revoke) is always called regardless of phase errors.
    pub async fn run(
        &self,
        doc: &ExecutionCellDocument,
        run_id: &str,
        spec_hash: Option<&str>,
    ) -> anyhow::Result<()> {
        // ── T12 authorization gate ─────────────────────────────────────────
        // Runs BEFORE the policy-pack gate so an unauthorized subject can
        // never reach pack evaluation, host.create(), or any secret broker
        // call. Independent rule namespace from the policy pack.
        if let Some(ref authz) = self.authz_policy {
            self.enforce_authz_policy(doc, authz).await?;
        }

        // ── policy admission gate ──────────────────────────────────────────
        // Validate before calling host.create(); a rejected cell never gets a VM.
        if let Some(ref pack) = self.policy_pack {
            let violations = validate_spec_against_policy(&doc.spec, pack);
            if !violations.is_empty() {
                let violation_msgs: Vec<String> = violations
                    .iter()
                    .map(|v| format!("{}: {}", v.rule, v.message))
                    .collect();
                // Emit the rejection event (best-effort — don't mask the admission error).
                if let Ok(data) = policy_rejected_data_v1(&doc.spec, &violations) {
                    let ev = cloud_event("dev.cellos.events.cell.policy.v1.rejected", data);
                    if let Err(e) = self.emit(&ev).await {
                        tracing::warn!(error = %e, "policy.rejected event emit failed");
                    }
                }
                return Err(anyhow::anyhow!(
                    "cell spec rejected by policy pack '{}': {}",
                    pack.id,
                    violation_msgs.join("; ")
                ));
            }
        }

        // SEC-16: capture any broker-supplied correlation ID before the host
        // is created. We forward it into the compliance summary CloudEvent
        // when the operator did not set `spec.correlation.correlationId`,
        // so audit pipelines (taudit, etc.) can stitch a CellOS run together
        // with the broker's exec session ID without an operator hint.
        let broker_correlation_id = self.broker.broker_correlation_id();

        let handle = self
            .host
            .create(doc)
            .await
            .map_err(|e| anyhow::anyhow!("cell create: {e}"))?;

        let ttl = doc.spec.lifetime.ttl_seconds;

        tracing::info!(
            cell_id = %handle.cell_id,
            spec_id = %doc.spec.id,
            run_id = %run_id,
            "cell created"
        );

        let mut phase_err: Option<anyhow::Error> = None;
        // L5-15 — shared FlowAccumulator wired between the in-netns nflog
        // listener (which records `Opened` events as the workload exercises
        // 5-tuples) and the homeostasis emit site (which reads
        // `unique_flow_count()` to stamp `exercised_egress_connections`).
        //
        // Created here, before any subprocess spawn, so the listener's
        // `setns(2)` thread receives a clone that's already alive. Only
        // populated when `CELLOS_PER_FLOW_REALTIME=1` (or the legacy
        // `_FIRECRACKER_PER_FLOW_EBPF=1`) is on — when the env gate is off
        // we keep `None` to preserve the E2-06 contract at the emit site.
        let flow_accumulator: Option<
            std::sync::Arc<
                std::sync::Mutex<crate::ebpf_flow::connection_tracking::FlowAccumulator>,
            >,
        > = {
            let realtime_on = std::env::var(crate::per_flow::ENV_PER_FLOW_REALTIME).as_deref()
                == Ok("1")
                || std::env::var(crate::per_flow::ENV_PER_FLOW_EBPF).as_deref() == Ok("1");
            if realtime_on {
                Some(std::sync::Arc::new(std::sync::Mutex::new(
                    crate::ebpf_flow::connection_tracking::FlowAccumulator::new(),
                )))
            } else {
                None
            }
        };
        let mut identity_materialized = false;
        let mut resolved_secrets: Vec<SecretView> = Vec::new();
        // Captured after the command phase; forwarded to the compliance summary event.
        let mut command_exit_code: Option<i32> = None;
        // Tracks whether the in-VM exit bridge produced an authenticated exit
        // code. None = bridge wasn't used (host-side spawn) so the clean/forced
        // distinction is not meaningful for this run. Some(true) = clean
        // (4-byte exit code received). Some(false) = forced (bridge errored;
        // any recorded exit code is synthetic — supervisor likely SIGKILLed
        // the VMM during teardown).
        let mut in_vm_exit_authenticated: Option<bool> = None;
        // P0-5 / G2 — captured from the lifecycle.started CloudEvent envelope
        // so we can populate `provenance.parent` on revoke + export receipt
        // events. `None` until lifecycle.started has been emitted; downstream
        // call sites tolerate absence (no provenance block in that case).
        let mut started_event_id: Option<String> = None;

        // ── network_scope ──────────────────────────────────────────────────
        let egress_rule_count = doc
            .spec
            .authority
            .egress_rules
            .as_ref()
            .map(|v| v.len())
            .unwrap_or(0);
        let has_opaque_network = doc.spec.authority.network.is_some();
        match observability_network_scope_data_v1(
            &doc.spec,
            &handle.cell_id,
            Some(run_id),
            egress_rule_count,
            has_opaque_network,
        )
        .context("build network_scope data")
        {
            Err(e) => phase_err = Some(e),
            Ok(data) => {
                let ev = cloud_event(
                    "dev.cellos.events.cell.observability.v1.network_scope",
                    data,
                );
                if let Err(e) = self.emit(&ev).await {
                    phase_err = Some(e);
                }
            }
        }

        self.maybe_emit_trust_plane_observability(doc, &handle.cell_id, run_id, &mut phase_err)
            .await;

        // SEC-21: host-controlled resolver refresh + drift events. Disabled
        // unless `CELLOS_DNS_AUTHORITY_REFRESH=1`; runs one tick per cell run.
        self.maybe_run_dns_authority_refresh(doc, &handle.cell_id, run_id, &mut phase_err)
            .await;

        // SEC-21 Phase 2: continuous resolver-refresh ticker. Disabled unless
        // BOTH `CELLOS_DNS_AUTHORITY_REFRESH=1` AND
        // `CELLOS_DNS_AUTHORITY_CONTINUOUS=1`. Runs alongside the workload
        // for the lifetime of the cell; teardown is at the end of `run()`
        // before the destroyed event fires.
        let mut continuous_resolver_ticker: Option<
            cellos_supervisor::resolver_refresh::ticker::TickerHandle,
        > = self.maybe_spawn_continuous_resolver_refresh(doc, &handle.cell_id, run_id);

        // SEC-22 Phase 1: L7 hostname-allowlist evaluation + direct-DNS-block
        // observability. Disabled unless `CELLOS_L7_GATE_OBSERVABILITY=1`.
        // Kernel-level direct-DNS containment runs separately in
        // `generate_nft_ruleset` and is not gated by this flag — only the
        // observable signal is.
        self.maybe_emit_l7_gate_observability(doc, &handle.cell_id, run_id, &mut phase_err)
            .await;

        // SEAM-1 / L2-04 Phase 2b: in-netns DNS proxy activation.
        // Disabled unless `CELLOS_DNS_PROXY=1` AND the spec carries a
        // populated `dnsAuthority.hostnameAllowlist` AND at least one
        // `do53-*` resolver with a parseable `host:port` endpoint. The
        // actual `setns(2)` spawn happens later in
        // `linux_run_cell_command_isolated` once the workload child PID
        // is known; this call only resolves the activation predicate +
        // captures the runtime handle so the spawn can run later.
        let dns_proxy_activation = self.build_dns_proxy_activation(doc, &handle.cell_id, run_id);
        let dns_proxy_emitter = if dns_proxy_activation.is_some() {
            #[cfg(target_os = "linux")]
            {
                Some(std::sync::Arc::new(
                    crate::dns_proxy::spawn::EventSinkEmitter::capture_current(
                        self.event_sink.clone(),
                        self.jsonl_sink.clone(),
                    ),
                )
                    as std::sync::Arc<dyn crate::dns_proxy::DnsQueryEmitter>)
            }
            #[cfg(not(target_os = "linux"))]
            {
                tracing::warn!(
                    target: "cellos.supervisor.dns_proxy",
                    cell_id = %handle.cell_id,
                    run_id = %run_id,
                    "SEAM-1 DNS proxy: non-Linux platform — spawn no-op (predicate held but setns unavailable)"
                );
                None
            }
        } else {
            None
        };

        // SEC-22 Phase 2: in-netns SNI-aware proxy activation. Disabled
        // unless `CELLOS_SNI_PROXY=1` AND the spec carries a populated
        // `dnsAuthority.hostnameAllowlist`. Like the DNS proxy, the actual
        // `setns(2)` spawn happens later in `linux_run_cell_command_isolated`
        // once the workload child PID is known; this slot only resolves the
        // activation predicate + captures the runtime handle.
        let sni_proxy_activation = self.build_sni_proxy_activation(doc, &handle.cell_id, run_id);
        let sni_proxy_emitter = if sni_proxy_activation.is_some() {
            #[cfg(target_os = "linux")]
            {
                Some(std::sync::Arc::new(
                    crate::sni_proxy::spawn::EventSinkEmitter::capture_current(
                        self.event_sink.clone(),
                        self.jsonl_sink.clone(),
                    ),
                )
                    as std::sync::Arc<dyn crate::sni_proxy::L7DecisionEmitter>)
            }
            #[cfg(not(target_os = "linux"))]
            {
                tracing::warn!(
                    target: "cellos.supervisor.sni_proxy",
                    cell_id = %handle.cell_id,
                    run_id = %run_id,
                    "SEC-22 Phase 2 SNI proxy: non-Linux platform — spawn no-op (predicate held but setns unavailable)"
                );
                None
            }
        } else {
            None
        };

        // ── secrets ────────────────────────────────────────────────────────
        let secret_delivery = doc
            .spec
            .run
            .as_ref()
            .map(|run| run.secret_delivery.clone())
            .unwrap_or(SecretDeliveryMode::Env);
        let uses_runtime_leased_broker =
            matches!(secret_delivery, SecretDeliveryMode::RuntimeLeasedBroker);

        if uses_runtime_leased_broker {
            if phase_err.is_none() {
                let requests = runtime_secret_lease_requests_for_doc(doc);
                if !requests.is_empty() {
                    match self
                        .broker
                        .prepare_runtime_secret_lease(&handle.cell_id, &requests)
                        .await
                    {
                        Ok(()) => {
                            if let Some(identity) = &doc.spec.identity {
                                match identity_materialized_data_v1(
                                    &doc.spec,
                                    &handle.cell_id,
                                    Some(run_id),
                                    identity,
                                )
                                .context("build identity materialized data")
                                {
                                    Err(e) => phase_err = Some(e),
                                    Ok(data) => {
                                        let ev = cloud_event(
                                            "dev.cellos.events.cell.identity.v1.materialized",
                                            data,
                                        );
                                        if let Err(e) = self.emit(&ev).await {
                                            phase_err = Some(e);
                                        } else {
                                            identity_materialized = true;
                                        }
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            if let Some(identity) = &doc.spec.identity {
                                let err_text = format!(
                                    "runtime leased broker prepare {} -> {}: {e}",
                                    identity_resolve_key(identity),
                                    identity.secret_ref
                                );
                                self.emit_identity_failed_best_effort(
                                    doc,
                                    &handle.cell_id,
                                    run_id,
                                    identity,
                                    IdentityFailureOperation::Materialize,
                                    &err_text,
                                )
                                .await;
                                phase_err = Some(anyhow::anyhow!("{err_text}"));
                            } else {
                                phase_err =
                                    Some(anyhow::anyhow!("runtime leased broker prepare: {e}"));
                            }
                        }
                    }
                }
            }
        } else {
            if phase_err.is_none() {
                if let Some(identity) = &doc.spec.identity {
                    let identity_ttl = identity.ttl_seconds.unwrap_or(ttl);
                    let resolve_key = identity_resolve_key(identity);
                    let broker_name = configured_broker_name();
                    match self
                        .broker
                        .resolve(resolve_key, &handle.cell_id, identity_ttl)
                        .await
                    {
                        Ok(mut view) if view.value.is_empty() => {
                            // Fail-fast: an empty identity credential is a silent runtime
                            // wedge waiting to happen — surface it now with the same
                            // structured error path used for outright resolve failures.
                            tracing::error!(
                                target: "cellos.supervisor.secrets",
                                key = %identity.secret_ref,
                                resolve_key = %resolve_key,
                                broker = %broker_name,
                                "secret unresolvable"
                            );
                            view.key = identity.secret_ref.clone();
                            let err_text = format!(
                                "identity {} unresolvable via {} broker (empty value for {})",
                                identity.secret_ref, broker_name, resolve_key
                            );
                            self.emit_identity_failed_best_effort(
                                doc,
                                &handle.cell_id,
                                run_id,
                                identity,
                                IdentityFailureOperation::Materialize,
                                &err_text,
                            )
                            .await;
                            phase_err = Some(anyhow::anyhow!("{err_text}"));
                        }
                        Ok(mut view) => {
                            // The broker resolves using the provider-specific lookup key
                            // (for GitHub OIDC, the audience), but the workload contract
                            // exposes the credential under the logical in-cell alias.
                            view.key = identity.secret_ref.clone();
                            resolved_secrets.push(view);
                            match identity_materialized_data_v1(
                                &doc.spec,
                                &handle.cell_id,
                                Some(run_id),
                                identity,
                            )
                            .context("build identity materialized data")
                            {
                                Err(e) => phase_err = Some(e),
                                Ok(data) => {
                                    let ev = cloud_event(
                                        "dev.cellos.events.cell.identity.v1.materialized",
                                        data,
                                    );
                                    if let Err(e) = self.emit(&ev).await {
                                        phase_err = Some(e);
                                    } else {
                                        identity_materialized = true;
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            tracing::error!(
                                target: "cellos.supervisor.secrets",
                                key = %identity.secret_ref,
                                resolve_key = %resolve_key,
                                broker = %broker_name,
                                error = %e,
                                "secret unresolvable"
                            );
                            let err_text = format!(
                                "identity {} unresolvable via {} broker: {e}",
                                identity.secret_ref, broker_name
                            );
                            self.emit_identity_failed_best_effort(
                                doc,
                                &handle.cell_id,
                                run_id,
                                identity,
                                IdentityFailureOperation::Materialize,
                                &err_text,
                            )
                            .await;
                            phase_err = Some(anyhow::anyhow!("{err_text}"));
                        }
                    }
                }
            }

            if phase_err.is_none() {
                if let Some(refs) = &doc.spec.authority.secret_refs {
                    let broker_name = configured_broker_name();
                    for key in refs {
                        if doc
                            .spec
                            .identity
                            .as_ref()
                            .is_some_and(|identity| key == &identity.secret_ref)
                        {
                            continue;
                        }
                        match self.broker.resolve(key, &handle.cell_id, ttl).await {
                            Ok(view) => {
                                // Fail-fast on empty resolution: a broker that returns an empty
                                // string for a declared secretRef is indistinguishable from a
                                // missing secret to the workload, and silently injecting "" leads
                                // to subprocesses hanging on resources they can't open (e.g. an
                                // empty $DISPLAY). Treat empty as unresolvable so the cell is
                                // aborted before spawn rather than wedging at runtime.
                                if view.value.is_empty() {
                                    tracing::error!(
                                        target: "cellos.supervisor.secrets",
                                        key = %key,
                                        broker = %broker_name,
                                        "secret unresolvable"
                                    );
                                    phase_err = Some(anyhow::anyhow!(
                                        "secret {key} unresolvable via {broker_name} broker"
                                    ));
                                    break;
                                }
                                resolved_secrets.push(view);
                            }
                            Err(e) => {
                                tracing::error!(
                                    target: "cellos.supervisor.secrets",
                                    key = %key,
                                    broker = %broker_name,
                                    error = %e,
                                    "secret unresolvable"
                                );
                                phase_err = Some(anyhow::anyhow!(
                                    "secret {key} unresolvable via {broker_name} broker: {e}"
                                ));
                                break;
                            }
                        }
                    }
                }
            }
        }

        // ── started ────────────────────────────────────────────────────────
        if phase_err.is_none() {
            // L5-05 / Lane B: surface authority-derivation verification result on
            // the started event so taudit can answer "prove every prod cell
            // derived authority from role X" by querying lifecycle.started
            // events alone.
            //
            // Non-fatal: a failed verification records derivationVerified=false
            // and lets the run proceed — taudit aggregates the boolean across
            // runs to detect drift. The real fail-closed gate runs in `main.rs`
            // before `build_supervisor` and rejects invalid tokens outright.
            //
            // The role-keys map is plumbed in via `Supervisor::authority_keys`
            // (set by `build_supervisor` from `load_authority_keys`), so the
            // `derivationVerified` flag now reflects the actual ED25519
            // signature check rather than a structural-only stub. Specs
            // without a derivation token emit none of the three new fields,
            // preserving the original lifecycle.started shape.
            let (derivation_verified, role_root_str, parent_run_id_str) = self
                .compute_derivation_verification(
                    &doc.spec,
                    doc.spec.authority.authority_derivation.as_ref(),
                );

            match lifecycle_started_data_v1(
                &doc.spec,
                &handle.cell_id,
                Some(run_id),
                derivation_verified,
                role_root_str.as_deref(),
                parent_run_id_str.as_deref(),
                spec_hash,
                handle.kernel_digest_sha256.as_deref(),
                handle.rootfs_digest_sha256.as_deref(),
                handle.firecracker_digest_sha256.as_deref(),
            )
            .context("build lifecycle started data")
            {
                Err(e) => phase_err = Some(e),
                Ok(data) => {
                    let ev = cloud_event("dev.cellos.events.cell.lifecycle.v1.started", data);
                    // P0-5 / G2: record the started envelope's CloudEvent id so
                    // revoke + export receipt events can stamp it as
                    // `provenance.parent`. We capture even if `emit` fails —
                    // the envelope was constructed and the ID identifies the
                    // attempted event. Downstream provenance is best-effort.
                    started_event_id = Some(ev.id.clone());
                    if let Err(e) = self.emit(&ev).await {
                        phase_err = Some(e);
                    }
                }
            }
        }

        // I6 / O6: when admission accepted a universal (parentRunId: null)
        // authority derivation token in PERMISSIVE mode, emit one structured
        // warning event so the audit trail records the exposure. Strict mode
        // (the 1.0 default) rejects universal tokens at admission time and
        // never reaches this path.
        if self.universal_token_accepted_in_permissive_mode {
            self.emit_universal_token_permissive_warning(doc, &handle.cell_id, run_id, spec_hash)
                .await;
        }

        // ── container_security (Linux only) ───────────────────────────────
        // Emit capability bitmasks read from /proc/self/status immediately after
        // lifecycle.started so the audit trail captures the concrete capability
        // set in place when the cell began — rather than "deepce could not
        // determine capabilities because capsh was not installed."
        #[cfg(target_os = "linux")]
        if phase_err.is_none() {
            let caps = read_proc_caps();
            let data = observability_container_security_data_v1(
                &handle.cell_id,
                Some(run_id),
                caps[0].as_deref(),
                caps[1].as_deref(),
                caps[2].as_deref(),
                caps[3].as_deref(),
                caps[4].as_deref(),
            );
            let ev = cloud_event(
                "dev.cellos.events.cell.observability.v1.container_security",
                data,
            );
            if let Err(e) = self.emit(&ev).await {
                tracing::warn!(error = %e, "container_security event emit failed (non-fatal)");
            }
        }

        // ── network_policy (Linux + CLONE_NEWNET) ─────────────────────────
        #[cfg(target_os = "linux")]
        if phase_err.is_none() {
            if let Some(flags) = linux_subprocess_unshare_flags() {
                if flags & libc::CLONE_NEWNET != 0 {
                    let egress_rules = doc.spec.authority.egress_rules.as_deref().unwrap_or(&[]);
                    match observability_network_policy_data_v1(
                        &doc.spec,
                        &handle.cell_id,
                        Some(run_id),
                        "clone_newnet",
                        egress_rules,
                    )
                    .context("build network_policy data")
                    {
                        Err(e) => phase_err = Some(e),
                        Ok(data) => {
                            let ev = cloud_event(
                                "dev.cellos.events.cell.observability.v1.network_policy",
                                data,
                            );
                            if let Err(e) = self.emit(&ev).await {
                                phase_err = Some(e);
                            }
                        }
                    }
                }
            }
        }

        // ── run ────────────────────────────────────────────────────────────
        let egress_rules_for_run: Vec<EgressRule> =
            doc.spec.authority.egress_rules.clone().unwrap_or_default();

        if phase_err.is_none() {
            if let Some(ref run) = doc.spec.run {
                if let Some(msg) = argv0_allow_prefixes_error(&run.argv) {
                    phase_err = Some(anyhow::anyhow!("{msg}"));
                }
            }
        }

        if phase_err.is_none() {
            if let Some(ref run) = doc.spec.run {
                let program = run.argv.first().map(String::as_str).unwrap_or("");
                let argc = run.argv.len();
                match observability_process_spawned_data_v1(
                    &doc.spec,
                    &handle.cell_id,
                    Some(run_id),
                    program,
                    argc,
                )
                .context("build process_spawned data")
                {
                    Err(e) => phase_err = Some(e),
                    Ok(data) => {
                        let ev = cloud_event(
                            "dev.cellos.events.cell.observability.v1.process_spawned",
                            data,
                        );
                        if let Err(e) = self.emit(&ev).await {
                            phase_err = Some(e);
                        }
                    }
                }

                if phase_err.is_none() {
                    let mut runtime_secret_session: Option<RuntimeSecretSession> = None;
                    if run.secret_delivery == SecretDeliveryMode::RuntimeBroker {
                        let entries = runtime_secret_entries_for_doc(doc, &resolved_secrets);
                        match RuntimeSecretSession::start_snapshot(&handle.cell_id, &entries).await
                        {
                            Ok(session) => {
                                runtime_secret_session = Some(session);
                            }
                            Err(e) => {
                                phase_err =
                                    Some(e.context("start runtimeBroker secret delivery session"));
                            }
                        }
                    } else if run.secret_delivery == SecretDeliveryMode::RuntimeLeasedBroker {
                        let requests = runtime_secret_lease_requests_for_doc(doc);
                        match RuntimeSecretSession::start_leased(
                            &handle.cell_id,
                            self.broker.clone(),
                            &requests,
                        )
                        .await
                        {
                            Ok(session) => {
                                runtime_secret_session = Some(session);
                            }
                            Err(e) => {
                                phase_err = Some(
                                    e.context("start runtimeLeasedBroker secret delivery session"),
                                );
                            }
                        }
                    }

                    let (
                        exit_code,
                        duration_ms,
                        spawn_err,
                        net_enforcement_nft,
                        dns_proxy_spawn_err,
                        sni_proxy_spawn_err,
                        per_flow_rows,
                    ) = if phase_err.is_none() {
                        // Check if the backend manages in-VM execution (e.g. Firecracker
                        // + cellos-init vsock bridge). If so, skip the host-side spawn.
                        if let Some(result) = self.host.wait_for_in_vm_exit(&handle.cell_id).await {
                            let code = match result {
                                Ok(c) => {
                                    // Authenticated exit code via vsock bridge —
                                    // terminal_state will be Clean for the
                                    // destroyed event.
                                    in_vm_exit_authenticated = Some(true);
                                    c
                                }
                                Err(e) => {
                                    // Bridge errored before delivering 4 bytes;
                                    // teardown will SIGKILL the VMM and the -1
                                    // recorded here is synthetic. Distinguish
                                    // this in the destroyed event so audit can
                                    // tell "clean exit" from "we gave up".
                                    in_vm_exit_authenticated = Some(false);
                                    phase_err = Some(anyhow::anyhow!("in-VM exit bridge: {e}"));
                                    -1
                                }
                            };
                            // Surface the backend's nft enforcement signal so the
                            // `network_enforcement` CloudEvent is emitted on the
                            // in-VM exit path with parity to the host-subprocess
                            // path. Backends that don't own enforcement leave
                            // this `None` and the event is suppressed (as before).
                            //
                            // scope (FC-38): in-VM exit path does not surface
                            // per-flow rows yet (the supervisor cannot scrape
                            // counters from a Firecracker guest's nft table).
                            // Future work tracks this with eBPF on the host
                            // bridge or guest-side telemetry.
                            (
                                code,
                                0u64,
                                None,
                                handle.nft_rules_applied,
                                None,
                                None,
                                Vec::new(),
                            )
                        } else {
                            crate::command_runner::run_cell_command(
                                run,
                                doc.spec.lifetime.ttl_seconds,
                                &handle,
                                &egress_rules_for_run,
                                doc.spec.authority.dns_authority.as_ref(),
                                &resolved_secrets,
                                runtime_secret_session.as_ref(),
                                dns_proxy_activation.clone(),
                                dns_proxy_emitter.clone(),
                                sni_proxy_activation.clone(),
                                sni_proxy_emitter.clone(),
                                // Per-flow real-time listener
                                // sink + run_id for the in-netns nflog
                                // listener. None when the env gate is off
                                // or self.event_sink isn't set up; the
                                // closure spawn checks the env again
                                // before binding the netlink socket.
                                Some((self.event_sink.clone(), run_id.to_string())),
                                // L5-15 — clone the shared accumulator into
                                // the listener path. The supervisor keeps
                                // its own clone for the homeostasis emit
                                // read below.
                                flow_accumulator.clone(),
                            )
                            .await
                        }
                    } else {
                        (-1, 0, None, None, None, None, Vec::new())
                    };
                    command_exit_code = Some(exit_code);

                    // SEAM-1 / L2-04 Phase 2b: surface any proxy spawn error
                    // as a single `dns_query` event with `reasonCode:
                    // upstream_failure`. Preserves the audit trail W3 designed
                    // for the activation stub — without this, a setns/bind
                    // failure would silently leave the cell unprotected.
                    if let Some(err_text) = dns_proxy_spawn_err {
                        self.emit_dns_proxy_spawn_failure(
                            doc,
                            &handle.cell_id,
                            run_id,
                            dns_proxy_activation
                                .as_ref()
                                .map(|a| a.resolver_id.as_str()),
                            &err_text,
                        )
                        .await;
                    }

                    // SEC-22 Phase 2 spawn-error audit: wired in W9 finalize.
                    // The closure-return tuple was extended to carry
                    // `sni_proxy_spawn_err` (mirroring the dns_proxy_spawn_err
                    // channel just above), and a setns/bind failure on the L7
                    // proxy now surfaces as one `l7_egress_decision` event with
                    // `reasonCode: l7_unknown_protocol` + an `errorText` field
                    // identifying the spawn-side cause. The cell itself is NOT
                    // killed: SEC-22's kernel-level direct-DNS block remains in
                    // place; this proxy is the L7 audit layer on top, not the
                    // only line of defence.
                    if let Some(err_text) = sni_proxy_spawn_err {
                        self.emit_sni_proxy_spawn_failure(doc, &handle.cell_id, run_id, &err_text)
                            .await;
                    }

                    if let Some(session) = runtime_secret_session.take() {
                        session.shutdown().await;
                    }

                    if let Some(nft_rules_applied) = net_enforcement_nft {
                        match observability_network_enforcement_data_v1(
                            &doc.spec,
                            &handle.cell_id,
                            Some(run_id),
                            nft_rules_applied,
                            egress_rules_for_run.len(),
                            exit_code,
                            spawn_err.as_deref(),
                        )
                        .context("build network_enforcement data")
                        {
                            Err(e) => phase_err = Some(e),
                            Ok(data) => {
                                let ev = cloud_event(
                                    "dev.cellos.events.cell.observability.v1.network_enforcement",
                                    data,
                                );
                                if let Err(e) = self.emit(&ev).await {
                                    phase_err = Some(e);
                                }
                            }
                        }
                    }

                    // FC-38 Phase 1: per-rule attribution events emitted from
                    // the post-run nft counter scan. `per_flow_rows` is empty
                    // unless `CELLOS_PER_FLOW_ENFORCEMENT_EVENTS=1` was set
                    // AND nft applied successfully on the isolated path; on
                    // non-Linux supervisor hosts this loop is a no-op (the
                    // Vec is empty). One event per rule whose decision is
                    // `deny` regardless of count, OR whose decision is
                    // `allow` and packet_count > 0 (allow rules with zero
                    // traffic are intentionally skipped — the operator
                    // already saw the rule declared in `network_policy`).
                    if phase_err.is_none() && !per_flow_rows.is_empty() {
                        self.emit_per_flow_decision_events(
                            doc,
                            &handle.cell_id,
                            run_id,
                            &egress_rules_for_run,
                            &per_flow_rows,
                        )
                        .await;
                    }

                    if phase_err.is_none() {
                        match command_completed_data_v1(
                            &doc.spec,
                            &handle.cell_id,
                            Some(run_id),
                            &run.argv,
                            exit_code,
                            duration_ms,
                            spawn_err.as_deref(),
                        )
                        .context("build command completed data")
                        {
                            Err(e) => phase_err = Some(e),
                            Ok(data) => {
                                let ev = cloud_event(
                                    "dev.cellos.events.cell.command.v1.completed",
                                    data,
                                );
                                if let Err(e) = self.emit(&ev).await {
                                    phase_err = Some(e);
                                } else if let Some(msg) = spawn_err {
                                    phase_err = Some(anyhow::anyhow!("command spawn: {msg}"));
                                } else if exit_code != 0 {
                                    phase_err = Some(anyhow::anyhow!(
                                        "command exited with status {exit_code}"
                                    ));
                                }
                            }
                        }
                    }
                }
            }
        }

        // Authority shaping: secret material is no longer needed after the subprocess exits.
        // Drop now so ZeroizeOnDrop wipes the values before the export / destroy phases run.
        drop(resolved_secrets);

        // P0-4 / G1 — build a spec view whose `Correlation.correlation_id` is
        // back-filled from the broker (`broker_correlation_id`) when the
        // operator did not supply one. We compute this once here and reuse it
        // for export + revoke + compliance summary so audit consumers see the
        // same `correlationId` on every event in the teardown phase, not just
        // on `compliance.summary`. Cloning `doc.spec` keeps the merge scoped:
        // it never mutates the inbound document, so a parallel call sharing
        // the same `&ExecutionCellDocument` keeps its own correlation view.
        let teardown_effective_correlation = {
            let mut c = doc.spec.correlation.clone().unwrap_or_default();
            if c.correlation_id.is_none() {
                c.correlation_id = broker_correlation_id.clone();
            }
            if c == Correlation::default() {
                None
            } else {
                Some(c)
            }
        };
        let teardown_spec = if teardown_effective_correlation == doc.spec.correlation {
            // No change — avoid the clone when the operator already supplied
            // a correlation_id (or no broker correlation is available).
            None
        } else {
            let mut s = doc.spec.clone();
            s.correlation = teardown_effective_correlation;
            Some(s)
        };
        let teardown_spec_ref = teardown_spec.as_ref().unwrap_or(&doc.spec);

        // P0-5 / G2 — pre-compute the `provenance.parent` block we stamp on
        // revoke + export receipt events. Walks back to
        // `cell.lifecycle.v1.started`, which is the receiver-side root of
        // the run for taudit's graph build. `None` only when the started
        // event was never emitted (e.g. an early phase_err); downstream call
        // sites tolerate the absence by emitting no `provenance` block,
        // preserving v1/v2 schema backward-compat.
        let teardown_provenance: Option<cellos_core::Provenance> =
            started_event_id.as_ref().map(|id| cellos_core::Provenance {
                parent: id.clone(),
                parent_type: "dev.cellos.events.cell.lifecycle.v1.started".to_string(),
            });

        // ── export ─────────────────────────────────────────────────────────
        if phase_err.is_none() {
            if let Some(ref export) = doc.spec.export {
                if let Some(artifacts) = &export.artifacts {
                    for art in artifacts {
                        match observability_fs_touch_export_data_v1(
                            &doc.spec,
                            &handle.cell_id,
                            Some(run_id),
                            &art.path,
                            &art.name,
                        )
                        .context("build fs_touch data")
                        {
                            Err(e) => {
                                phase_err = Some(e);
                                break;
                            }
                            Ok(data) => {
                                let ev = cloud_event(
                                    "dev.cellos.events.cell.observability.v1.fs_touch",
                                    data,
                                );
                                if let Err(e) = self.emit(&ev).await {
                                    phase_err = Some(e);
                                    break;
                                }
                            }
                        }

                        if phase_err.is_some() {
                            break;
                        }

                        let effective_target_name = effective_export_target_name(doc, art);
                        let sink = effective_target_name
                            .and_then(|name| self.named_export_sinks.get(name))
                            .unwrap_or(&self.default_export_sink);
                        let target_kind = resolve_export_target_kind(doc, art, sink.target_kind());
                        let destination_hint = logical_export_destination(
                            doc,
                            art,
                            sink.destination_hint(&art.name).as_deref(),
                        );
                        let export_metadata = ExportArtifactMetadata {
                            content_type: art.content_type.clone(),
                        };

                        match sink.push(&art.name, &art.path, &export_metadata).await {
                            Ok(mut receipt) => {
                                receipt.target_kind = target_kind.clone();
                                if receipt.target_name.is_none() {
                                    receipt.target_name = effective_target_name.map(str::to_string);
                                }
                                if let Some(destination) =
                                    logical_export_destination(doc, art, Some(&receipt.destination))
                                {
                                    receipt.destination = destination;
                                }

                                // P0-4 / P0-5: stamp broker-merged correlation
                                // (G1) and lifecycle-started provenance (G2)
                                // so taudit can stitch artifact → started →
                                // spec → derivation token without operator
                                // hints. `teardown_spec_ref` falls back to
                                // `&doc.spec` when no merge was needed.
                                match export_completed_data_v2(
                                    teardown_spec_ref,
                                    &handle.cell_id,
                                    Some(run_id),
                                    &art.name,
                                    &receipt,
                                    teardown_provenance.as_ref(),
                                )
                                .context("build export_completed v2 data")
                                {
                                    Err(e) => {
                                        phase_err = Some(e);
                                        break;
                                    }
                                    Ok(data) => {
                                        let ev = cloud_event(
                                            "dev.cellos.events.cell.export.v2.completed",
                                            data,
                                        );
                                        if let Err(e) = self.emit(&ev).await {
                                            phase_err = Some(e);
                                            break;
                                        }
                                    }
                                }
                            }
                            Err(e) => {
                                let err_text = e.to_string();
                                // P0-4 / P0-5: same broker-merged correlation
                                // + lifecycle-started provenance as the
                                // success path so failed receipts route
                                // through the same audit graph as completed.
                                match export_failed_data_v2(
                                    teardown_spec_ref,
                                    &handle.cell_id,
                                    Some(run_id),
                                    &art.name,
                                    target_kind,
                                    effective_target_name,
                                    destination_hint.as_deref(),
                                    &err_text,
                                    teardown_provenance.as_ref(),
                                )
                                .context("build export_failed v2 data")
                                {
                                    Ok(data) => {
                                        let ev = cloud_event(
                                            "dev.cellos.events.cell.export.v2.failed",
                                            data,
                                        );
                                        if let Err(emit_err) = self.emit(&ev).await {
                                            tracing::warn!(
                                                error = %emit_err,
                                                artifact = %art.name,
                                                "export failed event emit failed"
                                            );
                                        }
                                    }
                                    Err(build_err) => {
                                        tracing::warn!(
                                            error = %build_err,
                                            artifact = %art.name,
                                            "export failed event build failed"
                                        );
                                    }
                                }
                                phase_err = Some(anyhow::anyhow!("{err_text}"));
                                break;
                            }
                        }
                    }
                }
            }
        }

        // ── teardown: destroy + revoke (always) ────────────────────────────
        let destroy_r = self.host.destroy(&handle).await;
        let revoke_r = self.broker.revoke_for_cell(&handle.cell_id).await;

        if let Some(identity) = &doc.spec.identity {
            match &revoke_r {
                Ok(()) if identity_materialized => {
                    // P0-4 / P0-5: revoke is the receiver-side end of the
                    // secret-broker round trip — stamp broker-merged
                    // correlation (G1) and lifecycle-started provenance (G2)
                    // so taudit can answer "which run consumed this lease"
                    // by walking provenance.parent back to the started
                    // envelope without operator joins.
                    match identity_revoked_data_v1(
                        teardown_spec_ref,
                        &handle.cell_id,
                        Some(run_id),
                        identity,
                        Some("teardown"),
                        teardown_provenance.as_ref(),
                    )
                    .context("build identity revoked data")
                    {
                        Err(e) => {
                            if phase_err.is_none() {
                                phase_err = Some(e);
                            } else {
                                tracing::warn!(
                                    error = %e,
                                    "identity revoked event build failed (keeping prior phase error)"
                                );
                            }
                        }
                        Ok(data) => {
                            let ev =
                                cloud_event("dev.cellos.events.cell.identity.v1.revoked", data);
                            if let Err(e) = self.emit(&ev).await {
                                if phase_err.is_none() {
                                    phase_err = Some(e);
                                } else {
                                    tracing::warn!(
                                        error = %e,
                                        "identity revoked event emit failed (keeping prior phase error)"
                                    );
                                }
                            }
                        }
                    }
                }
                Err(e) if identity_materialized => {
                    let err_text = format!("identity revoke {}: {e}", identity.secret_ref);
                    self.emit_identity_failed_best_effort(
                        doc,
                        &handle.cell_id,
                        run_id,
                        identity,
                        IdentityFailureOperation::Revoke,
                        &err_text,
                    )
                    .await;
                }
                _ => {}
            }
        }

        if let Err(e) = destroy_r {
            let err = anyhow::anyhow!("cell destroy: {e}");
            if phase_err.is_none() {
                phase_err = Some(err);
            } else {
                tracing::warn!(error = %e, "destroy failed (keeping prior phase error)");
            }
        }
        if let Err(e) = revoke_r {
            let err = anyhow::anyhow!("secret revoke: {e}");
            if phase_err.is_none() {
                phase_err = Some(err);
            } else {
                tracing::warn!(error = %e, "revoke failed (keeping prior phase error)");
            }
        }

        // ── compliance summary ─────────────────────────────────────────────
        // SEC-16 / P0-4 — the broker-supplied correlation ID has already
        // been merged into `teardown_spec_ref` above (G1), so the same
        // correlation surface that revoke + export receipts saw is the one
        // compliance summary publishes. Single source of truth keeps audit
        // consumers from observing inconsistent `correlation.correlationId`
        // across teardown-phase events for the same run.
        match compliance_summary_data_v1(
            teardown_spec_ref,
            &handle.cell_id,
            Some(run_id),
            command_exit_code,
        )
        .context("build compliance summary data")
        {
            Err(e) => {
                if phase_err.is_none() {
                    phase_err = Some(e);
                }
            }
            Ok(data) => {
                let ev = cloud_event("dev.cellos.events.cell.compliance.v1.summary", data);
                if let Err(e) = self.emit(&ev).await {
                    tracing::warn!(error = %e, "compliance summary emit failed (non-fatal)");
                }
            }
        }

        // ── authority homeostasis ──────────────────────────────────────────────────
        // Best-effort, non-fatal — same pattern as compliance.summary.
        // MVP: egress declared count from spec; exercised = proxy via nft signal.
        // Real per-connection count requires eBPF (L5-12 full).
        {
            let declared_egress = doc
                .spec
                .authority
                .egress_rules
                .as_ref()
                .map(|v| v.len() as u32)
                .unwrap_or(0);
            let declared_secrets = doc
                .spec
                .authority
                .secret_refs
                .as_ref()
                .map(|v| v.len() as u32)
                .unwrap_or(0);

            // L5-15: when `CELLOS_PER_FLOW_REALTIME=1` is on, a per-cell flow
            // accumulator (`crate::ebpf_flow::connection_tracking::FlowAccumulator`)
            // counts UNIQUE 5-tuples observed by the kernel-side backend
            // and the count rides into the homeostasis signal as a real
            // `u32`. The accumulator is constructed at the top of `run()`,
            // a clone is handed to the in-netns nflog listener via
            // `linux_run_cell_command_isolated`, and the listener records
            // an `Opened` event per `cellos-flow accept` datagram it
            // decodes. By the time we reach this emit site `child.wait()`
            // has returned and the listener thread has been joined, so
            // the accumulator holds the real count from nflog or eBPF
            // (whichever backend was wired).
            //
            // The env-off branch preserves the E2-06 contract: `None` +
            // the `telemetry_pending_L2-04` diagnostic so consumers can
            // distinguish "operator opted out" from "operator opted in
            // but observed zero flows."
            //
            // The single source of truth for the env gate is
            // `crate::per_flow::build_activation_from_env`, which honours
            // both the legacy `CELLOS_FIRECRACKER_PER_FLOW_EBPF=1` name and
            // the backend-neutral `CELLOS_PER_FLOW_REALTIME=1` alias.
            let (exercised_egress, exercised_egress_reason): (Option<u32>, Option<String>) =
                if let Some(acc) = flow_accumulator.as_ref() {
                    // Real count from nflog or eBPF — whichever backend
                    // fed the accumulator during the run.
                    let count = match acc.lock() {
                        Ok(guard) => guard.unique_flow_count(),
                        Err(poisoned) => poisoned.into_inner().unique_flow_count(),
                    };
                    let count_u32 = if count > u32::MAX as u64 {
                        u32::MAX
                    } else {
                        count as u32
                    };
                    (Some(count_u32), None)
                } else {
                    (None, Some("telemetry_pending_L2-04".to_string()))
                };

            let efficiency = cellos_core::HomeostasisSignal::compute_efficiency(
                declared_egress,
                exercised_egress,
            );
            let spec_hash = cellos_core::canonical_spec_hash(&doc.spec);

            let signal = cellos_core::HomeostasisSignal {
                spec_hash,
                declared_egress_rules: declared_egress,
                exercised_egress_connections: exercised_egress,
                exercised_egress_reason,
                declared_mount_paths: 0,
                accessed_mount_paths: 0,
                declared_secret_count: declared_secrets,
                authority_efficiency: efficiency,
                recommended_removals: vec![],
            };

            match cellos_core::homeostasis_signal_data_v1(
                &doc.spec,
                &handle.cell_id,
                Some(run_id),
                &signal,
            )
            .context("build homeostasis signal data")
            {
                Err(e) => {
                    tracing::warn!(error = %e, "homeostasis signal build failed (non-fatal)");
                }
                Ok(data) => {
                    let ev = cloud_event("dev.cellos.events.cell.authority.v1.homeostasis", data);
                    if let Err(e) = self.emit(&ev).await {
                        tracing::warn!(error = %e, "homeostasis signal emit failed (non-fatal)");
                    }
                }
            }

            // L5-15 enforcement: when real flow telemetry is wired AND the
            // observed unique-connection count exceeds the declared egress-rule
            // count, emit a sibling violation event. This is a security
            // invariant breach — either the spec under-declares (operator
            // action: widen egressRules) or enforcement leaked (operator
            // action: audit nftables / eBPF rule application). We only fire
            // when `exercised_egress` is `Some(_)`; a `None` count means
            // "telemetry pending" (per E2-06) and cannot prove a violation.
            if let Some(exercised_count) = exercised_egress {
                let declared_u64 = declared_egress as u64;
                let exercised_u64 = exercised_count as u64;
                if exercised_u64 > declared_u64 {
                    tracing::warn!(
                        cell_id = %handle.cell_id,
                        declared = declared_u64,
                        exercised = exercised_u64,
                        "homeostasis violation: exercised egress exceeds declared authority"
                    );
                    let violation_data = cellos_core::homeostasis_violation_data_v1(
                        &handle.cell_id,
                        declared_u64,
                        exercised_u64,
                        &signal.spec_hash,
                    );
                    let violation_event = cloud_event(
                        "dev.cellos.events.cell.authority.v1.homeostasis_violation",
                        violation_data,
                    );
                    if let Err(e) = self.emit(&violation_event).await {
                        tracing::warn!(
                            error = %e,
                            "homeostasis violation emit failed (non-fatal)"
                        );
                    }
                }
            }
        }

        // SEC-21 Phase 2: tear down the continuous resolver-refresh ticker
        // before the destroyed event fires. Bounded join: 2s timeout matches
        // the W4 SEAM-1 Phase 2b DNS proxy shutdown pattern.
        if let Some(ticker_handle) = continuous_resolver_ticker.take() {
            ticker_handle
                .shutdown
                .store(true, std::sync::atomic::Ordering::SeqCst);
            match tokio::time::timeout(std::time::Duration::from_secs(2), ticker_handle.task).await
            {
                Ok(Ok(stats)) => {
                    tracing::info!(
                        target: "cellos.supervisor.resolver_refresh.ticker",
                        cell_id = %handle.cell_id,
                        run_id = %run_id,
                        tick_count = stats.tick_count,
                        events_emitted = stats.events_emitted,
                        resolver_errors = stats.resolver_errors,
                        "SEC-21 Phase 2 continuous resolver-refresh ticker exited"
                    );
                }
                Ok(Err(join_err)) => {
                    tracing::warn!(
                        target: "cellos.supervisor.resolver_refresh.ticker",
                        cell_id = %handle.cell_id,
                        run_id = %run_id,
                        error = %join_err,
                        "SEC-21 Phase 2 continuous resolver-refresh ticker panicked"
                    );
                }
                Err(_) => {
                    tracing::warn!(
                        target: "cellos.supervisor.resolver_refresh.ticker",
                        cell_id = %handle.cell_id,
                        run_id = %run_id,
                        "SEC-21 Phase 2 continuous resolver-refresh ticker join timeout (>2s); abandoning"
                    );
                }
            }
        }

        // ── destroyed ──────────────────────────────────────────────────────
        let outcome = if phase_err.is_none() {
            LifecycleDestroyOutcome::Succeeded
        } else {
            LifecycleDestroyOutcome::Failed
        };
        let reason = phase_err.as_ref().map(|e| e.to_string());
        // terminal_state is populated only when the in-VM bridge was actually
        // consulted for this run. Host-side spawn paths emit no terminalState
        // — the clean/forced distinction only describes whether the
        // authenticated vsock exit-code path delivered a result.
        let terminal_state = in_vm_exit_authenticated.map(|authenticated| {
            if authenticated {
                LifecycleTerminalState::Clean
            } else {
                LifecycleTerminalState::Forced
            }
        });
        // F5 (D5 destruction-evidence): pass `None, None` until F1b wires
        // the per-run evidence-bundle aggregator (see
        // `destruction_evidence::DestructionEvidenceAggregator`). Once F1b
        // lands, the supervisor will look up the URN of the bundle for
        // `run_id` and the host backend's `TeardownReport`-derived residue
        // class and pass them here. The function is additive: today's
        // `None, None` produces the byte-identical legacy payload.
        match lifecycle_destroyed_data_v1(
            &doc.spec,
            &handle.cell_id,
            Some(run_id),
            outcome,
            reason.as_deref(),
            terminal_state,
            None,
            None,
        )
        .context("build lifecycle destroyed data")
        {
            Err(e) => {
                if phase_err.is_none() {
                    phase_err = Some(e);
                }
            }
            Ok(data) => {
                let ev = cloud_event("dev.cellos.events.cell.lifecycle.v1.destroyed", data);
                if let Err(e) = self.emit(&ev).await {
                    if phase_err.is_none() {
                        phase_err = Some(e);
                    } else {
                        tracing::warn!(error = %e, "destroyed event emit failed (keeping prior phase error)");
                    }
                }
            }
        }

        if let Some(e) = phase_err {
            return Err(e);
        }

        tracing::info!(cell_id = %handle.cell_id, "lifecycle complete");
        Ok(())
    }
}

// Network-policy helpers moved to `crate::network_policy`:
//   generate_nft_ruleset, pick_resolver_socket_addr,
//   parse_do53_endpoint, parse_udp_resolver_endpoint,
//   apply_nft_in_ns, scan_nft_counters_in_ns, read_proc_caps.

#[cfg(test)]
mod tests {
    // ── Lane B: derivationVerified wiring ─────────────────────────────────
    //
    // Proves the role-keys map plumbed in via `Supervisor::authority_keys`
    // is the one consulted when computing the `derivationVerified` flag on
    // `dev.cellos.events.cell.lifecycle.v1.started`. We exercise the helper
    // directly rather than running the full `Supervisor::run` lifecycle —
    // the inline match block at the started-event call site delegates here,
    // so this is the smallest assertion that proves the wiring is honest.
    mod derivation_verified {
        use super::super::Supervisor;
        use cellos_core::ports::{NoopEventSink, NoopExportSink};
        use cellos_core::spec_validation::authority_derivation_signing_payload;
        use cellos_core::{
            AuthorityBundle, AuthorityCapability, AuthorityDerivationToken, AuthoritySignature,
            EgressRule, ExecutionCellSpec, Lifetime, RoleId,
        };
        use cellos_host_cellos::MemorySecretBroker;
        use cellos_host_stub::StubCellBackend;
        use std::collections::HashMap;
        use std::sync::Arc;

        fn signed_spec_and_token(
            seed: u8,
            tamper_signature: bool,
        ) -> (ExecutionCellSpec, AuthorityDerivationToken, String) {
            use base64::engine::general_purpose::STANDARD;
            use base64::Engine as _;
            use ed25519_dalek::{Signer as _, SigningKey};

            let signing_key = SigningKey::from_bytes(&[seed; 32]);
            let verifying_key_b64 = STANDARD.encode(signing_key.verifying_key().to_bytes());

            let egress = vec![EgressRule {
                host: "api.example.com".into(),
                port: 443,
                protocol: Some("https".into()),
                dns_egress_justification: None,
            }];

            let spec = ExecutionCellSpec {
                id: "lane-b-cell".into(),
                correlation: None,
                ingress: None,
                environment: None,
                placement: None,
                policy: None,
                identity: None,
                run: None,
                authority: AuthorityBundle {
                    egress_rules: Some(egress.clone()),
                    secret_refs: Some(vec!["api-key".into()]),
                    // authority_derivation attached on the caller side
                    ..AuthorityBundle::default()
                },
                lifetime: Lifetime { ttl_seconds: 60 },
                export: None,
                telemetry: None,
            };

            let mut token = AuthorityDerivationToken {
                role_root: RoleId("role-test".into()),
                parent_run_id: Some("run-lane-b".into()),
                derivation_steps: vec![],
                leaf_capability: AuthorityCapability {
                    egress_rules: egress,
                    secret_refs: vec!["api-key".into()],
                },
                grantor_signature: AuthoritySignature {
                    algorithm: "ed25519".into(),
                    bytes: String::new(),
                },
            };
            let payload = authority_derivation_signing_payload(&token).expect("payload encode");
            let signature = signing_key.sign(&payload);
            let mut sig_bytes = signature.to_bytes();
            if tamper_signature {
                sig_bytes[0] ^= 0xFF; // flip a byte to invalidate
            }
            token.grantor_signature.bytes = STANDARD.encode(sig_bytes);

            (spec, token, verifying_key_b64)
        }

        fn supervisor_with_keys(keys: HashMap<String, String>) -> Supervisor {
            Supervisor::new(
                Arc::new(StubCellBackend),
                Arc::new(MemorySecretBroker::new()),
                Arc::new(NoopEventSink),
                None,
                Arc::new(NoopExportSink),
                HashMap::new(),
                Arc::new(keys),
            )
        }

        #[test]
        fn returns_none_triple_when_no_token_attached() {
            let (spec, _token, _vk) = signed_spec_and_token(0xA1, false);
            let sup = supervisor_with_keys(HashMap::new());
            let (verified, role, parent) = sup.compute_derivation_verification(&spec, None);
            assert_eq!(verified, None);
            assert_eq!(role, None);
            assert_eq!(parent, None);
        }

        #[test]
        fn reports_true_when_keys_authorize_valid_signature() {
            let (spec, token, verifying_key_b64) = signed_spec_and_token(0xA2, false);
            let mut keys = HashMap::new();
            keys.insert("role-test".to_string(), verifying_key_b64);
            let sup = supervisor_with_keys(keys);
            let (verified, role, parent) = sup.compute_derivation_verification(&spec, Some(&token));
            assert_eq!(
                verified,
                Some(true),
                "valid signature + matching role key must verify"
            );
            assert_eq!(role.as_deref(), Some("role-test"));
            assert_eq!(parent.as_deref(), Some("run-lane-b"));
        }

        #[test]
        fn reports_false_when_signature_is_tampered() {
            let (spec, token, verifying_key_b64) = signed_spec_and_token(0xA3, true);
            let mut keys = HashMap::new();
            keys.insert("role-test".to_string(), verifying_key_b64);
            let sup = supervisor_with_keys(keys);
            let (verified, role, parent) = sup.compute_derivation_verification(&spec, Some(&token));
            assert_eq!(
                verified,
                Some(false),
                "tampered signature must fail verification"
            );
            // Role + parent are still echoed so taudit can group failures.
            assert_eq!(role.as_deref(), Some("role-test"));
            assert_eq!(parent.as_deref(), Some("run-lane-b"));
        }

        #[test]
        fn reports_false_when_keys_map_is_empty() {
            // Pre-Lane-B behaviour: missing operator keys → unknown role →
            // derivationVerified=false. Locks in the contract that an empty
            // map (e.g. CELLOS_AUTHORITY_KEYS_PATH unset) does NOT silently
            // claim verification succeeded.
            let (spec, token, _vk) = signed_spec_and_token(0xA4, false);
            let sup = supervisor_with_keys(HashMap::new());
            let (verified, _role, _parent) =
                sup.compute_derivation_verification(&spec, Some(&token));
            assert_eq!(verified, Some(false));
        }
    }
}