meerkat-runtime 0.8.7

v9 runtime control-plane for Meerkat agent lifecycle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
//! Wave-c C-6c — consumer side of the `meerkat_mob_seam` composition.
//!
//! Wave-c C-6p landed the producer side: the mob actor converts each
//! emitted `MobMachineEffect::Request*` variant into a typed
//! [`MobSeamEffect`][mse] and routes it through a
//! [`CompositionDispatcher`][cd]. Until this module lands, that
//! dispatcher resolves the typed route but fails with
//! [`DispatchRefusal::UnwiredConsumer`][dr] because no
//! [`ConsumerSurface`][cs] is registered for the `meerkat` target
//! instance.
//!
//! C-6c closes that seam: [`MeerkatConsumerSurface`] is the typed
//! consumer surface. The dispatcher invokes
//! [`ConsumerSurface::apply_routed_input`] with the typed
//! [`InputVariantId`] + projected field bindings declared by the
//! `meerkat_mob_seam` composition schema
//! (`meerkat-machine-schema/src/catalog/compositions.rs::meerkat_mob_seam_composition`).
//! This surface translates each of the four routed variants —
//! `PrepareBindings`, `Ingest`, `Retire`, `Destroy` — into the
//! corresponding `MeerkatMachineInput` and applies it against the
//! session's shared DSL authority.
//!
//! The route bindings declared in the schema are the sole source of
//! truth for field projection shape. If a route binding references a
//! producer field the effect body did not populate, the dispatcher
//! returns [`DispatchRefusal::MissingProducerField`][dr] before this
//! surface is reached, so [`apply_routed_input`][cs_apply] can assume
//! the declared bindings are present.
//!
//! [mse]: meerkat_mob::runtime::composition::MobSeamEffect
//! [cd]: crate::composition::CompositionDispatcher
//! [cs]: crate::composition::ConsumerSurface
//! [cs_apply]: crate::composition::ConsumerSurface::apply_routed_input
//! [dr]: crate::composition::DispatchRefusal

use std::sync::{Arc, OnceLock};

use async_trait::async_trait;
use meerkat_core::types::SessionId;
use meerkat_machine_schema::identity::{
    EffectVariantId, FieldId, InputVariantId, MachineInstanceId,
};

use crate::composition::{
    CompositionSignalDispatcher, FieldValue, ProducerInstance, ProducerSignal, SignalPayload,
};
use crate::composition::{ConsumerSurface, OwnedFieldValue, SignalDispatchOutcome};
use crate::generated::meerkat_mob_seam as seam_facts;
use crate::meerkat_machine::{MeerkatMachine, dsl as mm_dsl};

/// Consumer-side surface for the `meerkat_mob_seam` composition.
///
/// Implements [`ConsumerSurface`] for the `meerkat` target instance. The
/// dispatcher hands the surface one routed input at a time; the surface
/// translates the typed [`InputVariantId`] + projected-field tuple into
/// the matching [`MeerkatMachineInput`][mmi] and applies it against the
/// session's shared DSL authority on the owning [`MeerkatMachine`].
///
/// Session selection: routed effects prefer a projected `session_id`.
/// `Ingest` may arrive without one, so the shared surface resolves its
/// projected `runtime_id` through each registered session's DSL-owned
/// `active_runtime_id`. Zero or multiple matches are refused rather than
/// guessing.
///
/// [mmi]: crate::meerkat_machine::dsl::MeerkatMachineInput
pub struct MeerkatConsumerSurface {
    machine: Arc<MeerkatMachine>,
    /// Optional pinned session id. `None` means the surface infers the
    /// session from the `agent_runtime_id` field of each routed input;
    /// `Some(id)` means every routed input is applied against that
    /// session and the surface refuses variants whose projected
    /// `agent_runtime_id` disagrees.
    pinned_session: Option<SessionId>,
}

/// Producer-side signal source sum for MeerkatMachine lifecycle effects
/// routed through the `meerkat_mob_seam` signal surface.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MeerkatSeamSignal {
    RuntimeBound {
        agent_runtime_id: mm_dsl::AgentRuntimeId,
        fence_token: mm_dsl::FenceToken,
    },
    RuntimeRetired {
        agent_runtime_id: mm_dsl::AgentRuntimeId,
        fence_token: mm_dsl::FenceToken,
    },
    RuntimeDestroyed {
        agent_runtime_id: mm_dsl::AgentRuntimeId,
        fence_token: mm_dsl::FenceToken,
    },
}

impl MeerkatSeamSignal {
    pub fn variant_id(&self) -> EffectVariantId {
        match self {
            Self::RuntimeBound { .. } => seam_facts::effects::meerkat::runtime_bound(),
            Self::RuntimeRetired { .. } => seam_facts::effects::meerkat::runtime_retired(),
            Self::RuntimeDestroyed { .. } => seam_facts::effects::meerkat::runtime_destroyed(),
        }
    }

    pub fn generated_signal_route(&self) -> Option<seam_facts::TypedRoutedSignal> {
        seam_facts::route_to_signal(
            &seam_facts::producers::meerkat_instance_id(),
            &self.variant_id(),
        )
    }

    fn field(&self, id: &FieldId) -> Option<FieldValue<'_>> {
        let (agent_runtime_id, fence_token) = match self {
            Self::RuntimeBound {
                agent_runtime_id,
                fence_token,
            }
            | Self::RuntimeRetired {
                agent_runtime_id,
                fence_token,
            }
            | Self::RuntimeDestroyed {
                agent_runtime_id,
                fence_token,
            } => (agent_runtime_id, fence_token),
        };
        if id == &seam_facts::fields::agent_runtime_id() {
            Some(FieldValue::Str(agent_runtime_id.0.as_str()))
        } else if id == &seam_facts::fields::fence_token() {
            Some(FieldValue::U64(fence_token.0))
        } else {
            None
        }
    }
}

impl ProducerSignal for MeerkatSeamSignal {
    fn variant_id(&self) -> EffectVariantId {
        self.variant_id()
    }

    fn field(&self, id: &FieldId) -> Option<FieldValue<'_>> {
        self.field(id)
    }
}

pub type MeerkatCompositionSignalDispatcher =
    Arc<dyn CompositionSignalDispatcher<Signal = MeerkatSeamSignal>>;

pub fn meerkat_producer_instance() -> ProducerInstance {
    let producer = seam_facts::producers::meerkat();
    ProducerInstance {
        composition: seam_facts::composition_id(),
        instance_id: producer.instance_id,
        machine: producer.machine,
    }
}

pub fn lift_routed_signal(effect: &mm_dsl::MeerkatMachineEffect) -> Option<MeerkatSeamSignal> {
    match effect {
        mm_dsl::MeerkatMachineEffect::RuntimeBound {
            agent_runtime_id,
            fence_token,
        } => Some(MeerkatSeamSignal::RuntimeBound {
            agent_runtime_id: agent_runtime_id.clone(),
            fence_token: *fence_token,
        }),
        mm_dsl::MeerkatMachineEffect::RuntimeRetired {
            agent_runtime_id,
            fence_token,
        } => Some(MeerkatSeamSignal::RuntimeRetired {
            agent_runtime_id: agent_runtime_id.clone(),
            fence_token: *fence_token,
        }),
        mm_dsl::MeerkatMachineEffect::RuntimeDestroyed {
            agent_runtime_id,
            fence_token,
        } => Some(MeerkatSeamSignal::RuntimeDestroyed {
            agent_runtime_id: agent_runtime_id.clone(),
            fence_token: *fence_token,
        }),
        _ => None,
    }
}

pub async fn dispatch_routed_signal(
    dispatcher: &MeerkatCompositionSignalDispatcher,
    signal: MeerkatSeamSignal,
) -> Result<SignalDispatchOutcome, String> {
    let variant = signal.variant_id();
    dispatcher
        .dispatch_signal(
            meerkat_producer_instance(),
            SignalPayload::Emitted {
                variant,
                body: signal,
            },
        )
        .await
        .map_err(|refusal| refusal.to_string())
}

impl std::fmt::Debug for MeerkatConsumerSurface {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MeerkatConsumerSurface")
            .field("pinned_session", &self.pinned_session)
            .finish_non_exhaustive()
    }
}

impl MeerkatConsumerSurface {
    /// Build a consumer surface backed by the given machine. The surface
    /// resolves each routed input's target session from projected fields.
    pub fn new(machine: Arc<MeerkatMachine>) -> Self {
        Self {
            machine,
            pinned_session: None,
        }
    }

    /// Build a consumer surface pinned to `session_id`. All routed
    /// inputs are applied against this session; variants that carry a
    /// `session_id` are additionally checked for agreement and refused on
    /// mismatch.
    pub fn pinned(machine: Arc<MeerkatMachine>, session_id: SessionId) -> Self {
        Self {
            machine,
            pinned_session: Some(session_id),
        }
    }

    async fn resolve_session(
        &self,
        _variant: &InputVariantId,
        projected: &[(FieldId, OwnedFieldValue)],
    ) -> Result<SessionId, String> {
        // Typed session_id is the canonical source (Shape 4 — producer DSL
        // emits `session_id: SessionId` alongside `agent_runtime_id`; see
        // `MobMachineEffect::RequestRuntimeBinding` in
        // `meerkat-machine-schema/src/catalog/dsl/mob_machine.rs:168`).
        let projected_session_id = projected
            .iter()
            .find(|(id, _)| id == &seam_facts::fields::session_id())
            .and_then(|(_, v)| match v {
                OwnedFieldValue::Str(s) => Some(s.clone()),
                _ => None,
            });

        match (&self.pinned_session, projected_session_id) {
            (Some(pinned), Some(sid)) if sid != pinned.to_string() => Err(format!(
                "routed session_id `{sid}` does not match pinned session `{pinned}`"
            )),
            (Some(pinned), _) => Ok(pinned.clone()),
            (None, Some(sid)) => SessionId::parse(&sid)
                .map_err(|e| format!("routed session_id `{sid}` is not a valid UUID: {e}")),
            (None, None) => Err(
                "routed input did not project `session_id` and surface is not pinned \
                 to a session — no session can be resolved"
                    .into(),
            ),
        }
    }
}

#[allow(clippy::panic)]
fn meerkat_instance_id() -> &'static MachineInstanceId {
    static ID: OnceLock<MachineInstanceId> = OnceLock::new();
    ID.get_or_init(seam_facts::producers::meerkat_instance_id)
}

fn project_u64(fields: &[(FieldId, OwnedFieldValue)], field: &FieldId) -> Result<u64, String> {
    fields
        .iter()
        .find(|(id, _)| id == field)
        .ok_or_else(|| format!("missing projected field `{}`", field.as_str()))
        .and_then(|(_, v)| match v {
            OwnedFieldValue::U64(n) => Ok(*n),
            other => Err(format!(
                "projected field `{}` is not U64: {other:?}",
                field.as_str()
            )),
        })
}

fn project_optional_u64(
    fields: &[(FieldId, OwnedFieldValue)],
    field: &FieldId,
) -> Result<Option<u64>, String> {
    match fields.iter().find(|(id, _)| id == field) {
        None => Ok(None),
        Some((_, OwnedFieldValue::U64(n))) => Ok(Some(*n)),
        Some((_, other)) => Err(format!(
            "projected field `{}` is not U64: {other:?}",
            field.as_str()
        )),
    }
}

fn project_str<'a>(
    fields: &'a [(FieldId, OwnedFieldValue)],
    field: &FieldId,
) -> Result<&'a str, String> {
    fields
        .iter()
        .find(|(id, _)| id == field)
        .ok_or_else(|| format!("missing projected field `{}`", field.as_str()))
        .and_then(|(_, v)| match v {
            OwnedFieldValue::Str(s) => Ok(s.as_str()),
            other => Err(format!(
                "projected field `{}` is not Str: {other:?}",
                field.as_str()
            )),
        })
}

fn project_work_origin(
    fields: &[(FieldId, OwnedFieldValue)],
    field: &FieldId,
) -> Result<mm_dsl::WorkOrigin, String> {
    fields
        .iter()
        .find(|(id, _)| id == field)
        .ok_or_else(|| format!("missing projected field `{}`", field.as_str()))
        .and_then(|(_, v)| match v {
            OwnedFieldValue::Opaque(value) => value
                .downcast_ref::<mm_dsl::WorkOrigin>()
                .copied()
                .ok_or_else(|| format!("projected field `{}` is not WorkOrigin", field.as_str())),
            other => Err(format!(
                "projected field `{}` is not WorkOrigin: {other:?}",
                field.as_str()
            )),
        })
}

#[async_trait]
impl ConsumerSurface for MeerkatConsumerSurface {
    fn instance_id(&self) -> &MachineInstanceId {
        meerkat_instance_id()
    }

    async fn apply_routed_input(
        &self,
        variant: InputVariantId,
        projected: Vec<(FieldId, OwnedFieldValue)>,
    ) -> Result<(), crate::composition::ConsumerError> {
        let session_id = self.resolve_session(&variant, &projected).await?;
        let input = if variant == seam_facts::inputs::prepare_bindings() {
            let rt = project_str(&projected, &seam_facts::fields::agent_runtime_id())?;
            let fence = project_u64(&projected, &seam_facts::fields::fence_token())?;
            let generation = project_u64(&projected, &seam_facts::fields::generation())?;
            let sid = project_str(&projected, &seam_facts::fields::session_id())?;
            mm_dsl::MeerkatMachineInput::PrepareBindings {
                agent_runtime_id: mm_dsl::AgentRuntimeId::from(rt.to_string()),
                fence_token: mm_dsl::FenceToken(fence),
                generation: Some(mm_dsl::Generation(generation)),
                runtime_epoch_id: None,
                session_id: mm_dsl::SessionId::from(sid.to_string()),
            }
        } else if variant == seam_facts::inputs::ingest() {
            // Route binding `work_request_reaches_meerkat` delivers
            // producer `agent_runtime_id` into the consumer's canonical
            // `runtime_id` field and also carries the MobMachine-owned
            // binding facts that MeerkatMachine validates before admission.
            let sid = project_str(&projected, &seam_facts::fields::session_id())?;
            let rt = project_str(&projected, &seam_facts::fields::runtime_id())?;
            let fence = project_u64(&projected, &seam_facts::fields::fence_token())?;
            let generation = project_optional_u64(&projected, &seam_facts::fields::generation())?;
            let work_id = project_str(&projected, &seam_facts::fields::work_id())?;
            let origin = project_work_origin(&projected, &seam_facts::fields::origin())?;
            mm_dsl::MeerkatMachineInput::Ingest {
                session_id: mm_dsl::SessionId::from(sid.to_string()),
                runtime_id: mm_dsl::AgentRuntimeId::from(rt.to_string()),
                fence_token: mm_dsl::FenceToken(fence),
                generation: generation.map(mm_dsl::Generation),
                runtime_epoch_id: None,
                work_id: mm_dsl::WorkId::from(work_id.to_string()),
                origin,
            }
        } else if variant == seam_facts::inputs::retire() {
            let sid = project_str(&projected, &seam_facts::fields::session_id())?;
            mm_dsl::MeerkatMachineInput::Retire {
                session_id: mm_dsl::SessionId::from(sid.to_string()),
            }
        } else if variant == seam_facts::inputs::destroy() {
            let sid = project_str(&projected, &seam_facts::fields::session_id())?;
            mm_dsl::MeerkatMachineInput::Destroy {
                session_id: mm_dsl::SessionId::from(sid.to_string()),
            }
        } else {
            return Err(crate::composition::ConsumerError::new(
                "meerkat_consumer_surface_unsupported_input",
                format!(
                    "meerkat consumer surface does not accept routed input `{}`; \
                     only PrepareBindings/Ingest/Retire/Destroy are declared in the \
                     `meerkat_mob_seam` schema",
                    variant.as_str()
                ),
            ));
        };

        // Kernel→consumer leg stays typed: the per-variant stable
        // discriminant minted by the generated-machine refusal (e.g.
        // `dsl_guard_rejected`) crosses the seam verbatim instead of being
        // collapsed under one generic projection code.
        self.machine
            .apply_routed_meerkat_input(&session_id, input)
            .await
            .map_err(|refusal| {
                crate::composition::ConsumerError::new(refusal.error_code, refusal.message)
            })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::composition::{
        CatalogCompositionSignalDispatcher, OwnedFieldValue, RouteTable, SignalConsumerSurface,
    };
    use crate::meerkat_machine::{
        EnsureRuntimeExecutorAttachment, LocalSessionMaterializationMode,
        PreparedSessionMaterialization, RuntimeLoopAttachmentSlot,
    };
    use meerkat_core::lifecycle::RunId;
    use meerkat_core::lifecycle::core_executor::{
        CoreApplyOutput, CoreExecutor, CoreExecutorError,
    };
    use meerkat_core::lifecycle::run_primitive::{RunApplyBoundary, RunPrimitive};
    use meerkat_core::lifecycle::run_receipt::RunBoundaryReceiptDraft;
    use meerkat_machine_schema::identity::SignalVariantId;

    fn fld(slug: &str) -> FieldId {
        FieldId::parse(slug).expect("field slug")
    }

    fn iv(slug: &str) -> InputVariantId {
        InputVariantId::parse(slug).expect("input variant slug")
    }

    fn sid(slug: &str) -> SessionId {
        SessionId::parse(slug).expect("session id")
    }

    struct NoopExecutor;

    #[async_trait]
    impl CoreExecutor for NoopExecutor {
        async fn apply(
            &mut self,
            run_id: RunId,
            primitive: RunPrimitive,
        ) -> Result<CoreApplyOutput, CoreExecutorError> {
            Ok(CoreApplyOutput {
                receipt: RunBoundaryReceiptDraft {
                    run_id,
                    boundary: RunApplyBoundary::RunStart,
                    contributing_input_ids: primitive.contributing_input_ids().to_vec(),
                    conversation_digest: None,
                    message_count: 0,
                },
                session_snapshot: None,
                terminal: None,
            })
        }

        async fn cancel_after_boundary(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }

        async fn stop_runtime_executor(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }
    }

    struct StartupGatedNoopExecutor {
        reconciliation_started: Arc<tokio::sync::Notify>,
        allow_reconciliation: Arc<tokio::sync::Notify>,
        gate_first_reconciliation: std::sync::atomic::AtomicBool,
    }

    #[async_trait]
    impl CoreExecutor for StartupGatedNoopExecutor {
        async fn apply(
            &mut self,
            run_id: RunId,
            primitive: RunPrimitive,
        ) -> Result<CoreApplyOutput, CoreExecutorError> {
            Ok(CoreApplyOutput {
                receipt: RunBoundaryReceiptDraft {
                    run_id,
                    boundary: RunApplyBoundary::RunStart,
                    contributing_input_ids: primitive.contributing_input_ids().to_vec(),
                    conversation_digest: None,
                    message_count: 0,
                },
                session_snapshot: None,
                terminal: None,
            })
        }

        async fn reconcile_committed_compaction_projections(
            &mut self,
            _intents: &[meerkat_core::CompactionProjectionIntent],
        ) -> Result<(), CoreExecutorError> {
            if self
                .gate_first_reconciliation
                .swap(false, std::sync::atomic::Ordering::AcqRel)
            {
                self.reconciliation_started.notify_one();
                self.allow_reconciliation.notified().await;
            }
            Ok(())
        }

        async fn cancel_after_boundary(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }

        async fn stop_runtime_executor(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }
    }

    async fn begin_startup_gated_first_live_attachment(
        machine: &Arc<MeerkatMachine>,
        session_id: &SessionId,
        mut prepared: PreparedSessionMaterialization,
    ) -> (tokio::task::JoinHandle<()>, Arc<tokio::sync::Notify>) {
        let reconciliation_started = Arc::new(tokio::sync::Notify::new());
        let allow_reconciliation = Arc::new(tokio::sync::Notify::new());
        let registration = tokio::spawn({
            let reconciliation_started = Arc::clone(&reconciliation_started);
            let allow_reconciliation = Arc::clone(&allow_reconciliation);
            async move {
                let attachment = prepared
                    .ensure_executor_attachment(move |_| {
                        Box::new(StartupGatedNoopExecutor {
                            reconciliation_started,
                            allow_reconciliation,
                            gate_first_reconciliation: std::sync::atomic::AtomicBool::new(true),
                        })
                    })
                    .await
                    .expect("prepared first live attachment must reach startup reconciliation");
                let EnsureRuntimeExecutorAttachment::Pending(attachment) = attachment else {
                    panic!("missing-live materialization unexpectedly found a serving attachment");
                };
                attachment
                    .commit()
                    .await
                    .expect("first live attachment must finish after startup release");
            }
        });

        tokio::time::timeout(
            std::time::Duration::from_secs(2),
            reconciliation_started.notified(),
        )
        .await
        .expect("first live attachment must reach startup reconciliation");

        let attached = machine
            .session_dsl_state(session_id)
            .await
            .expect("pending first attachment authority exists");
        assert_eq!(attached.lifecycle_phase, mm_dsl::MeerkatPhase::Attached);
        assert_eq!(
            attached.registration_phase,
            mm_dsl::RegistrationPhase::Active
        );
        {
            let sessions = machine.sessions.read().await;
            let entry = sessions
                .get(session_id)
                .expect("pending first attachment remains registered");
            assert!(
                matches!(
                    &entry.attachment_slot,
                    RuntimeLoopAttachmentSlot::Pending(_)
                ),
                "startup reconciliation must retain a pending mechanical attachment"
            );
            assert!(
                !entry.has_live_attachment(),
                "startup reconciliation must not publish a serving attachment before commit"
            );
        }
        assert!(
            machine
                .current_executor_attachment_witness(session_id)
                .await
                .is_none(),
            "a pending startup attachment must not expose a serving witness"
        );

        (registration, allow_reconciliation)
    }

    #[allow(clippy::too_many_arguments)]
    async fn route_successor_binding_and_finish_gated_attachment(
        machine: &Arc<MeerkatMachine>,
        session_id: &SessionId,
        registration: tokio::task::JoinHandle<()>,
        allow_reconciliation: Arc<tokio::sync::Notify>,
        completion: crate::completion::CompletionHandle,
        replacement_runtime_id: &'static str,
        replacement_fence_token: u64,
        replacement_generation: u64,
    ) {
        // Queue the routed input while executor startup still owns the session
        // mutation gate. Tokio's FIFO mutex then gives this already-waiting
        // route the exact Attached seam before the runtime loop can dequeue
        // the preserved backlog.
        let route_started = Arc::new(tokio::sync::Notify::new());
        let routed = tokio::spawn({
            let machine = Arc::clone(machine);
            let session_id = session_id.clone();
            let route_started = Arc::clone(&route_started);
            async move {
                route_started.notify_one();
                MeerkatConsumerSurface::pinned(Arc::clone(&machine), session_id.clone())
                    .apply_routed_input(
                        iv("PrepareBindings"),
                        vec![
                            (
                                fld("agent_runtime_id"),
                                OwnedFieldValue::Str(replacement_runtime_id.into()),
                            ),
                            (
                                fld("fence_token"),
                                OwnedFieldValue::U64(replacement_fence_token),
                            ),
                            (
                                fld("generation"),
                                OwnedFieldValue::U64(replacement_generation),
                            ),
                            (
                                fld("session_id"),
                                OwnedFieldValue::Str(session_id.to_string()),
                            ),
                        ],
                    )
                    .await
                    .expect("routed successor binding is admitted at Attached");
            }
        });
        tokio::time::timeout(std::time::Duration::from_secs(2), route_started.notified())
            .await
            .expect("successor binding route must start");
        tokio::task::yield_now().await;
        assert!(
            !routed.is_finished(),
            "the routed input must wait behind executor startup's mutation-gate ownership"
        );

        allow_reconciliation.notify_one();
        tokio::time::timeout(std::time::Duration::from_secs(2), registration)
            .await
            .expect("first live attachment registration must finish")
            .expect("first live attachment registration task must not panic");
        tokio::time::timeout(std::time::Duration::from_secs(2), routed)
            .await
            .expect("successor binding route must finish")
            .expect("successor binding route task must not panic");

        let completion_outcome = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            completion.wait_authorized(),
        )
        .await;
        let completion_outcome = match completion_outcome {
            Ok(outcome) => outcome,
            Err(error) => {
                let snapshot = machine
                    .meerkat_machine_spine_snapshot(session_id)
                    .await
                    .expect("runtime spine exists after completion timeout");
                panic!(
                    "unassigned queued input must complete on the first live attachment after ownerless recovery: {error}; snapshot={snapshot:#?}"
                );
            }
        };
        match completion_outcome {
            crate::completion::CompletionOutcome::CompletedWithoutResult => {}
            other => panic!("expected preserved input completion, got {other:?}"),
        }

        let rebound = machine
            .session_dsl_state(session_id)
            .await
            .expect("rebound session authority exists");
        assert_eq!(rebound.lifecycle_phase, mm_dsl::MeerkatPhase::Attached);
        assert_eq!(
            rebound.registration_phase,
            mm_dsl::RegistrationPhase::Active
        );
        assert!(
            matches!(&rebound.active_runtime_id, Some(value) if value.0 == replacement_runtime_id)
        );
        assert_eq!(
            rebound.active_fence_token,
            Some(mm_dsl::FenceToken(replacement_fence_token))
        );
        assert_eq!(
            rebound.active_runtime_generation,
            Some(mm_dsl::Generation(replacement_generation))
        );
        assert_eq!(
            rebound.active_runtime_epoch_id, None,
            "the composition route does not project a runtime epoch id"
        );
    }

    fn assert_input_spine_preserved(
        before: &crate::meerkat_machine_types::MeerkatInputsSnapshot,
        after: &crate::meerkat_machine_types::MeerkatInputsSnapshot,
    ) {
        assert_eq!(after.queue, before.queue);
        assert_eq!(after.steer_queue, before.steer_queue);
        assert_eq!(after.current_run_id, before.current_run_id);
        assert_eq!(
            after.current_run_contributors,
            before.current_run_contributors
        );
        assert_eq!(after.post_admission_signal, before.post_admission_signal);
        assert_eq!(
            after.silent_intent_overrides,
            before.silent_intent_overrides
        );
        assert_eq!(after.admission_order.len(), before.admission_order.len());
        for (after_input, before_input) in after.admission_order.iter().zip(&before.admission_order)
        {
            assert_eq!(after_input.input_id, before_input.input_id);
            assert_eq!(after_input.content_shape, before_input.content_shape);
            assert_eq!(after_input.request_id, before_input.request_id);
            assert_eq!(after_input.reservation_key, before_input.reservation_key);
            assert_eq!(after_input.handling_mode, before_input.handling_mode);
            assert_eq!(
                after_input.live_interrupt_required,
                before_input.live_interrupt_required
            );
            assert_eq!(after_input.lifecycle, before_input.lifecycle);
            assert_eq!(after_input.terminal_outcome, before_input.terminal_outcome);
            assert_eq!(after_input.last_run_id, before_input.last_run_id);
            assert_eq!(
                after_input.last_boundary_sequence,
                before_input.last_boundary_sequence
            );
            assert_eq!(after_input.is_prompt, before_input.is_prompt);
        }
    }

    async fn bind_runtime(
        surface: &MeerkatConsumerSurface,
        session_id: &SessionId,
        runtime_id: &str,
    ) {
        surface
            .apply_routed_input(
                iv("PrepareBindings"),
                vec![
                    (
                        fld("agent_runtime_id"),
                        OwnedFieldValue::Str(runtime_id.into()),
                    ),
                    (fld("fence_token"), OwnedFieldValue::U64(1)),
                    (fld("generation"), OwnedFieldValue::U64(0)),
                    (
                        fld("session_id"),
                        OwnedFieldValue::Str(session_id.to_string()),
                    ),
                ],
            )
            .await
            .expect("bind runtime");
    }

    #[tokio::test]
    async fn prepare_bindings_requires_all_three_fields() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let surface = MeerkatConsumerSurface::new(Arc::clone(&machine));
        let err = surface
            .apply_routed_input(
                iv("PrepareBindings"),
                vec![
                    (fld("agent_runtime_id"), OwnedFieldValue::Str("rt-1".into())),
                    // fence_token missing on purpose.
                    (fld("generation"), OwnedFieldValue::U64(3)),
                    (
                        fld("session_id"),
                        OwnedFieldValue::Str("00000000-0000-0000-0000-000000000001".into()),
                    ),
                ],
            )
            .await
            .expect_err("missing fence_token");
        assert!(err.message().contains("fence_token"), "{err}");
    }

    #[tokio::test]
    async fn unknown_variant_is_refused_typed() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        // Pin the surface so resolve_session doesn't fail earlier on
        // missing session_id — this test focuses on variant-rejection,
        // not session resolution.
        let pinned =
            SessionId::parse("00000000-0000-0000-0000-000000000001").expect("uuid literal");
        let surface = MeerkatConsumerSurface::pinned(Arc::clone(&machine), pinned);
        let err = surface
            .apply_routed_input(iv("Recycle"), vec![])
            .await
            .expect_err("Recycle is not a routed variant");
        assert!(err.message().contains("Recycle"), "{err}");
    }

    #[tokio::test]
    async fn machine_rejection_keeps_per_variant_typed_code_across_consumer_seam() {
        // Row #14 gate (kernel→consumer leg): a generated-machine rejection of
        // a routed input must cross the consumer seam under its per-variant
        // stable discriminant, not be collapsed into one generic
        // `consumer_projection_failed` code.
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let session_id = sid("00000000-0000-0000-0000-000000000001");
        machine
            .register_session(session_id.clone())
            .await
            .expect("register session");
        let surface = MeerkatConsumerSurface::pinned(Arc::clone(&machine), session_id.clone());

        // Ingest before any runtime binding: the generated machine rejects
        // the transition; the typed discriminant must survive verbatim.
        let err = surface
            .apply_routed_input(
                iv("Ingest"),
                vec![
                    (fld("runtime_id"), OwnedFieldValue::Str("rt-none".into())),
                    (fld("fence_token"), OwnedFieldValue::U64(1)),
                    (fld("work_id"), OwnedFieldValue::Str("work-1".into())),
                    (
                        fld("origin"),
                        OwnedFieldValue::Opaque(Arc::new(mm_dsl::WorkOrigin::Ingest)),
                    ),
                    (
                        fld("session_id"),
                        OwnedFieldValue::Str(session_id.to_string()),
                    ),
                ],
            )
            .await
            .expect_err("ingest on an unbound session must be machine-rejected");
        assert!(
            err.error_code().starts_with("dsl_"),
            "machine rejection must keep its per-variant typed code, got `{}`: {err}",
            err.error_code()
        );
        assert_ne!(
            err.error_code(),
            "consumer_projection_failed",
            "kernel rejections must not be collapsed under the generic projection code"
        );
    }

    #[tokio::test]
    async fn unpinned_surface_requires_projected_session_id_for_retire() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let surface = MeerkatConsumerSurface::new(Arc::clone(&machine));
        // Retire has no fields in the schema; an unpinned surface
        // therefore cannot resolve a session and must refuse rather
        // than pick arbitrarily.
        let err = surface
            .apply_routed_input(iv("Retire"), vec![])
            .await
            .expect_err("Retire without target");
        assert!(err.message().contains("session_id"), "{err}");
    }

    #[tokio::test]
    async fn pinned_surface_rejects_mismatched_session_id() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let pinned =
            SessionId::parse("00000000-0000-0000-0000-000000000001").expect("uuid literal");
        let surface = MeerkatConsumerSurface::pinned(Arc::clone(&machine), pinned);
        let err = surface
            .apply_routed_input(
                iv("PrepareBindings"),
                vec![
                    (
                        fld("agent_runtime_id"),
                        OwnedFieldValue::Str("rt-other".into()),
                    ),
                    (fld("fence_token"), OwnedFieldValue::U64(1)),
                    (fld("generation"), OwnedFieldValue::U64(0)),
                    (
                        fld("session_id"),
                        OwnedFieldValue::Str("00000000-0000-0000-0000-000000000002".into()),
                    ),
                ],
            )
            .await
            .expect_err("session_id disagrees with pinned session");
        assert!(err.message().contains("pinned"), "{err}");
    }

    #[tokio::test]
    async fn ingest_prefers_projected_session_id() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let surface = MeerkatConsumerSurface::new(Arc::clone(&machine));
        let session_id = sid("00000000-0000-0000-0000-000000000001");
        machine
            .register_session(session_id.clone())
            .await
            .expect("register session");
        bind_runtime(&surface, &session_id, "rt-other").await;

        surface
            .apply_routed_input(
                iv("Ingest"),
                vec![
                    (fld("runtime_id"), OwnedFieldValue::Str("rt-other".into())),
                    (fld("fence_token"), OwnedFieldValue::U64(1)),
                    (fld("generation"), OwnedFieldValue::U64(0)),
                    (fld("work_id"), OwnedFieldValue::Str("work-1".into())),
                    (
                        fld("origin"),
                        OwnedFieldValue::Opaque(Arc::new(mm_dsl::WorkOrigin::Ingest)),
                    ),
                    (
                        fld("session_id"),
                        OwnedFieldValue::Str(session_id.to_string()),
                    ),
                ],
            )
            .await
            .expect("session_id targets the routed input");
    }

    #[tokio::test]
    async fn ingest_requires_projected_session_id() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let surface = MeerkatConsumerSurface::new(Arc::clone(&machine));
        let session_id = sid("00000000-0000-0000-0000-000000000001");
        machine
            .register_session(session_id.clone())
            .await
            .expect("register session");
        bind_runtime(&surface, &session_id, "rt-match").await;

        let err = surface
            .apply_routed_input(
                iv("Ingest"),
                vec![
                    (fld("runtime_id"), OwnedFieldValue::Str("rt-match".into())),
                    (fld("fence_token"), OwnedFieldValue::U64(1)),
                    (fld("generation"), OwnedFieldValue::U64(0)),
                    (fld("work_id"), OwnedFieldValue::Str("work-1".into())),
                    (
                        fld("origin"),
                        OwnedFieldValue::Opaque(Arc::new(mm_dsl::WorkOrigin::Ingest)),
                    ),
                ],
            )
            .await
            .expect_err("session_id is required for routed ingest");
        assert!(err.message().contains("session_id"), "{err}");
    }

    #[tokio::test]
    async fn ingest_without_matching_generated_binding_is_refused() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let surface = MeerkatConsumerSurface::new(Arc::clone(&machine));
        let session_id = sid("00000000-0000-0000-0000-000000000001");
        machine
            .register_session(session_id.clone())
            .await
            .expect("register session");
        bind_runtime(&surface, &session_id, "rt-current").await;

        let err = surface
            .apply_routed_input(
                iv("Ingest"),
                vec![
                    (fld("runtime_id"), OwnedFieldValue::Str("rt-missing".into())),
                    (fld("fence_token"), OwnedFieldValue::U64(1)),
                    (fld("generation"), OwnedFieldValue::U64(0)),
                    (fld("work_id"), OwnedFieldValue::Str("work-1".into())),
                    (
                        fld("origin"),
                        OwnedFieldValue::Opaque(Arc::new(mm_dsl::WorkOrigin::Ingest)),
                    ),
                    (
                        fld("session_id"),
                        OwnedFieldValue::Str(session_id.to_string()),
                    ),
                ],
            )
            .await
            .expect_err("generated binding guard rejects the routed input");
        assert!(err.message().contains("Ingest"), "{err}");
    }

    #[derive(Default)]
    struct RecordingSignalSurface {
        log: tokio::sync::Mutex<Vec<(SignalVariantId, Vec<(FieldId, OwnedFieldValue)>)>>,
    }

    #[async_trait]
    impl SignalConsumerSurface for RecordingSignalSurface {
        fn instance_id(&self) -> &MachineInstanceId {
            static ID: OnceLock<MachineInstanceId> = OnceLock::new();
            ID.get_or_init(|| MachineInstanceId::parse("mob").expect("canonical instance id"))
        }

        async fn receive_signal(
            &self,
            variant: SignalVariantId,
            projected_fields: Vec<(FieldId, OwnedFieldValue)>,
        ) -> Result<(), crate::composition::ConsumerError> {
            self.log.lock().await.push((variant, projected_fields));
            Ok(())
        }
    }

    #[tokio::test]
    async fn routed_prepare_bindings_dispatches_runtime_bound_signal() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let session_id = SessionId::new();
        machine
            .register_session(session_id.clone())
            .await
            .expect("register session");

        let signal_surface = Arc::new(RecordingSignalSurface::default());
        let schema = meerkat_machine_schema::catalog::meerkat_mob_seam_composition();
        let table = RouteTable::from_schema(&schema).expect("catalog routes");
        let dispatcher: CatalogCompositionSignalDispatcher<MeerkatSeamSignal> =
            CatalogCompositionSignalDispatcher::new(schema.name.clone(), table)
                .with_consumer(signal_surface.clone());
        machine.set_composition_signal_dispatcher(Arc::new(dispatcher));

        machine
            .apply_routed_meerkat_input(
                &session_id,
                mm_dsl::MeerkatMachineInput::PrepareBindings {
                    agent_runtime_id: mm_dsl::AgentRuntimeId("rt-1".into()),
                    fence_token: mm_dsl::FenceToken(11),
                    generation: Some(mm_dsl::Generation(0)),
                    runtime_epoch_id: None,
                    session_id: mm_dsl::SessionId(session_id.to_string()),
                },
            )
            .await
            .expect("routed input applies and emits signal");

        let log = signal_surface.log.lock().await;
        assert_eq!(log.len(), 1);
        assert_eq!(log[0].0.as_str(), "ObserveRuntimeReady");
        assert_eq!(log[0].1[0].0.as_str(), "agent_runtime_id");
        assert!(matches!(&log[0].1[0].1, OwnedFieldValue::Str(value) if value == "rt-1"));
        assert_eq!(log[0].1[1].0.as_str(), "fence_token");
        assert!(matches!(log[0].1[1].1, OwnedFieldValue::U64(11)));
    }

    /// Schema-enumerated completeness gate (mirror of the mob seam's
    /// `lift_covers_every_schema_declared_mob_effect_route`): every
    /// schema-declared meerkat-producer route must have a lift arm in
    /// `lift_routed_signal`, and the lift must not invent undeclared routes.
    #[test]
    fn lift_covers_every_schema_declared_meerkat_signal_route() {
        use std::collections::BTreeSet;

        let schema = meerkat_machine_schema::catalog::meerkat_mob_seam_composition();
        let declared: BTreeSet<String> = schema
            .routes
            .iter()
            .filter(|route| &route.from_machine == meerkat_instance_id())
            .map(|route| route.effect_variant.as_str().to_string())
            .collect();

        let liftable_bodies = [
            mm_dsl::MeerkatMachineEffect::RuntimeBound {
                agent_runtime_id: mm_dsl::AgentRuntimeId("rt-1".into()),
                fence_token: mm_dsl::FenceToken(1),
            },
            mm_dsl::MeerkatMachineEffect::RuntimeRetired {
                agent_runtime_id: mm_dsl::AgentRuntimeId("rt-1".into()),
                fence_token: mm_dsl::FenceToken(1),
            },
            mm_dsl::MeerkatMachineEffect::RuntimeDestroyed {
                agent_runtime_id: mm_dsl::AgentRuntimeId("rt-1".into()),
                fence_token: mm_dsl::FenceToken(1),
            },
        ];
        let liftable: BTreeSet<String> = liftable_bodies
            .iter()
            .map(|effect| {
                lift_routed_signal(effect)
                    .expect("declared routed effect must lift")
                    .variant_id()
                    .as_str()
                    .to_string()
            })
            .collect();

        assert_eq!(
            declared, liftable,
            "every schema-declared meerkat signal route must have a lift arm in \
             lift_routed_signal (and vice versa); update the lift AND this gate \
             together when the composition changes"
        );
    }

    #[test]
    fn routed_meerkat_signal_projection_tracks_generated_route_facts() {
        use crate::generated::meerkat_mob_seam as seam_facts;

        let cases = vec![
            (
                MeerkatSeamSignal::RuntimeBound {
                    agent_runtime_id: mm_dsl::AgentRuntimeId("rt-bound".into()),
                    fence_token: mm_dsl::FenceToken(11),
                },
                seam_facts::route_runtime_bound_reaches_mob(),
            ),
            (
                MeerkatSeamSignal::RuntimeRetired {
                    agent_runtime_id: mm_dsl::AgentRuntimeId("rt-retired".into()),
                    fence_token: mm_dsl::FenceToken(12),
                },
                seam_facts::route_runtime_retired_reaches_mob(),
            ),
            (
                MeerkatSeamSignal::RuntimeDestroyed {
                    agent_runtime_id: mm_dsl::AgentRuntimeId("rt-destroyed".into()),
                    fence_token: mm_dsl::FenceToken(13),
                },
                seam_facts::route_runtime_destroyed_reaches_mob(),
            ),
        ];

        for (signal, expected_route) in cases {
            let route = signal.generated_signal_route().expect("generated route");
            assert_eq!(route, expected_route);
            for (producer_field, _) in &route.bindings {
                assert!(
                    signal.field(producer_field).is_some(),
                    "generated route `{}` requires producer field `{}`",
                    route.route_id.as_str(),
                    producer_field.as_str()
                );
            }
        }
    }

    #[tokio::test]
    async fn local_session_bindings_do_not_dispatch_runtime_bound_signal() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let session_id = SessionId::new();

        let signal_surface = Arc::new(RecordingSignalSurface::default());
        let schema = meerkat_machine_schema::catalog::meerkat_mob_seam_composition();
        let table = RouteTable::from_schema(&schema).expect("catalog routes");
        let dispatcher: CatalogCompositionSignalDispatcher<MeerkatSeamSignal> =
            CatalogCompositionSignalDispatcher::new(schema.name.clone(), table)
                .with_consumer(signal_surface.clone());
        machine.set_composition_signal_dispatcher(Arc::new(dispatcher));

        let bindings = machine
            .prepare_local_session_bindings(session_id.clone())
            .await
            .expect("local bindings prepare");

        assert_eq!(bindings.session_id(), &session_id);
        let expected_epoch = {
            let sessions = machine.sessions.read().await;
            sessions
                .get(&session_id)
                .expect("session registered")
                .epoch_id
                .to_string()
        };
        assert!(
            signal_surface.log.lock().await.is_empty(),
            "local resource preparation must not publish cross-machine runtime readiness"
        );
        {
            let sessions = machine.sessions.read().await;
            let entry = sessions.get(&session_id).expect("session registered");
            let authority = entry
                .dsl_authority
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            assert!(
                authority.state().active_runtime_id.is_none(),
                "local resource preparation must leave binding identity unclaimed"
            );
            assert!(
                authority.state().active_fence_token.is_none(),
                "local resource preparation must leave binding fence unclaimed"
            );
        }

        machine
            .prepare_runtime_placement_binding(
                session_id.clone(),
                crate::identifiers::LogicalRuntimeId::new("rt-authoritative"),
                13,
                7,
            )
            .await
            .expect("authoritative binding still applies after local resource prep");
        machine
            .prepare_runtime_placement_binding(
                session_id.clone(),
                crate::identifiers::LogicalRuntimeId::new("rt-authoritative"),
                13,
                7,
            )
            .await
            .expect("exact placement replay is idempotent");

        let log = signal_surface.log.lock().await;
        assert_eq!(log.len(), 1);
        assert_eq!(log[0].0.as_str(), "ObserveRuntimeReady");
        assert!(
            matches!(&log[0].1[0].1, OwnedFieldValue::Str(value) if value == "rt-authoritative")
        );
        {
            let sessions = machine.sessions.read().await;
            let entry = sessions.get(&session_id).expect("session registered");
            let authority = entry
                .dsl_authority
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            assert!(
                matches!(&authority.state().active_runtime_id, Some(value) if value.0 == "rt-authoritative")
            );
            assert!(matches!(
                authority.state().active_fence_token,
                Some(mm_dsl::FenceToken(13))
            ));
            assert!(matches!(
                authority.state().active_runtime_generation,
                Some(mm_dsl::Generation(7))
            ));
            assert_eq!(
                authority
                    .state()
                    .active_runtime_epoch_id
                    .as_ref()
                    .map(|id| id.0.as_str()),
                Some(expected_epoch.as_str()),
                "exact member placement must still bind the current registration epoch"
            );
        }
    }

    #[tokio::test]
    async fn current_idle_stale_binding_is_normalized_before_routed_revival_rebinds() {
        let store = Arc::new(crate::store::InMemoryRuntimeStore::new());
        let runtime_store: Arc<dyn crate::store::RuntimeStore> = store.clone();
        let session_id = sid("00000000-0000-0000-0000-000000000034");
        let runtime_id = MeerkatMachine::logical_runtime_id(&session_id);

        crate::store::RuntimeStore::commit_machine_lifecycle(
            store.as_ref(),
            &runtime_id,
            crate::store::MachineLifecycleCommit::new_with_binding(
                crate::RuntimeState::Idle,
                crate::store::MachineLifecycleBindingFacts::new(
                    Some("stale-mob-runtime:7".into()),
                    Some(41),
                    Some(7),
                    Some("stale-runtime-epoch".into()),
                ),
                crate::store::SupervisorAuthoritySnapshot::UnboundNoReceipt,
            ),
            &[],
        )
        .await
        .expect("seed idle lifecycle with the interrupted epoch's binding tuple");

        let encoded =
            crate::store::RuntimeStore::load_machine_lifecycle_record(store.as_ref(), &runtime_id)
                .await
                .expect("load seeded lifecycle record")
                .expect("seeded lifecycle record exists");
        let encoded: serde_json::Value =
            serde_json::from_slice(&encoded).expect("lifecycle record is JSON");
        assert_eq!(
            encoded["record_version"],
            crate::store::MACHINE_LIFECYCLE_STORE_RECORD_VERSION,
            "the regression fixture must exercise the current durable lifecycle shape"
        );

        let machine = Arc::new(MeerkatMachine::persistent(
            runtime_store,
            Arc::new(meerkat_store::MemoryBlobStore::new()),
        ));
        let signal_surface = Arc::new(RecordingSignalSurface::default());
        let schema = meerkat_machine_schema::catalog::meerkat_mob_seam_composition();
        let table = RouteTable::from_schema(&schema).expect("catalog routes");
        let dispatcher: CatalogCompositionSignalDispatcher<MeerkatSeamSignal> =
            CatalogCompositionSignalDispatcher::new(schema.name.clone(), table)
                .with_consumer(signal_surface.clone());
        machine.set_composition_signal_dispatcher(Arc::new(dispatcher));

        machine
            .prepare_local_session_bindings(session_id.clone())
            .await
            .expect("delivery-time local preparation recovers the idle runtime");

        let recovered = machine
            .session_dsl_state(&session_id)
            .await
            .expect("recovered session authority exists");
        assert_eq!(recovered.lifecycle_phase, mm_dsl::MeerkatPhase::Idle);
        assert_eq!(
            recovered.registration_phase,
            mm_dsl::RegistrationPhase::Queuing,
            "the lifecycle row does not persist a live executor claim, so cold recovery must queue a replacement"
        );
        assert_eq!(
            recovered.active_runtime_id, None,
            "cold registration must release the stale runtime owner"
        );
        assert_eq!(
            recovered.active_fence_token, None,
            "cold registration must release the stale fence"
        );
        assert_eq!(
            recovered.active_runtime_generation, None,
            "cold registration must release the stale generation"
        );
        assert_eq!(
            recovered.active_runtime_epoch_id, None,
            "cold registration must release the stale runtime epoch"
        );
        assert!(
            signal_surface.log.lock().await.is_empty(),
            "local resource recovery must not publish stale runtime readiness"
        );

        // No physical attachment exists yet: this request belongs to the
        // machine's durable unassigned queue, not to an attachment A that a
        // later B could wrongly inherit.
        assert!(
            machine
                .current_executor_attachment_witness(&session_id)
                .await
                .is_none(),
            "cold Queuing recovery must not mint an attachment witness"
        );
        let queued_input = crate::input::Input::Prompt(crate::input::PromptInput::new(
            "durable work queued before missing-live materialization",
            None,
        ));
        let queued_input_id = queued_input.id().clone();
        let (outcome, completion) = machine
            .accept_input_with_completion(&session_id, queued_input)
            .await
            .expect("queue durable work before missing-live materialization");
        assert!(outcome.is_accepted());
        let completion = completion.expect("queued durable work installs a completion waiter");
        let durable_before =
            crate::store::RuntimeStore::load_input_states(store.as_ref(), &runtime_id)
                .await
                .expect("load queued durable work before missing-live preparation");
        assert_eq!(durable_before.len(), 1);
        assert_eq!(durable_before[0].state.input_id, queued_input_id);
        assert_eq!(
            durable_before[0].seed.phase,
            crate::input_state::InputLifecycleState::Queued
        );
        let spine_before_revival = machine
            .meerkat_machine_spine_snapshot(&session_id)
            .await
            .expect("runtime spine exists before missing-live materialization");
        assert_eq!(
            spine_before_revival.inputs.queue,
            vec![queued_input_id.clone()]
        );

        let prepared = machine
            .prepare_local_session_materialization_with_mode(
                session_id.clone(),
                LocalSessionMaterializationMode::MissingLiveRevival,
            )
            .await
            .expect("typed missing-live materialization claims the cold-normalized session");

        let normalized = machine
            .session_dsl_state(&session_id)
            .await
            .expect("normalized revival authority exists");
        assert_eq!(normalized.lifecycle_phase, mm_dsl::MeerkatPhase::Idle);
        assert_eq!(
            normalized.registration_phase,
            mm_dsl::RegistrationPhase::Queuing
        );
        assert_eq!(
            normalized.active_runtime_id, None,
            "missing-live preparation releases the stale runtime owner"
        );
        assert_eq!(
            normalized.active_fence_token, None,
            "missing-live preparation releases the stale fence"
        );
        assert_eq!(
            normalized.active_runtime_generation, None,
            "missing-live preparation releases the stale generation"
        );
        assert_eq!(
            normalized.active_runtime_epoch_id, None,
            "missing-live preparation releases the stale runtime epoch"
        );
        let after_revival = machine
            .meerkat_machine_spine_snapshot(&session_id)
            .await
            .expect("runtime spine remains available after missing-live preparation");
        assert_input_spine_preserved(&spine_before_revival.inputs, &after_revival.inputs);
        assert_eq!(
            after_revival.completion_waiters, spine_before_revival.completion_waiters,
            "typed exit/readmit must leave completion waiters verbatim"
        );
        let durable_after_revival =
            crate::store::RuntimeStore::load_input_states(store.as_ref(), &runtime_id)
                .await
                .expect("load queued durable work after missing-live preparation");
        assert_eq!(durable_after_revival.len(), 1);
        assert_eq!(durable_after_revival[0].state.input_id, queued_input_id);
        assert_eq!(
            durable_after_revival[0].seed.phase,
            crate::input_state::InputLifecycleState::Queued,
            "missing-live preparation must not terminalize or consume unassigned durable work"
        );
        assert!(
            signal_surface.log.lock().await.is_empty(),
            "missing-live preparation must not publish runtime readiness for the discarded stale tuple"
        );
        assert!(
            machine
                .current_executor_attachment_witness(&session_id)
                .await
                .is_none(),
            "missing-live preparation must leave the durable queue unassigned until its first live attachment"
        );
        crate::begin_session_runtime_actor_materialization(prepared.bindings())
            .expect("claim the normalized materialization for actor construction")
            .commit()
            .expect("record the normalized actor materialization");

        let (registration, allow_reconciliation) =
            begin_startup_gated_first_live_attachment(&machine, &session_id, prepared).await;
        let attached = machine
            .session_dsl_state(&session_id)
            .await
            .expect("first live attachment startup authority exists");
        assert_eq!(attached.active_runtime_id, None, "stale owner released");
        assert_eq!(attached.active_fence_token, None, "stale fence released");
        assert_eq!(
            attached.active_runtime_generation, None,
            "stale generation released"
        );
        assert_eq!(
            attached.active_runtime_epoch_id, None,
            "stale epoch released"
        );
        assert!(
            signal_surface.log.lock().await.is_empty(),
            "executor attachment alone must not publish runtime readiness"
        );

        let startup_persisted = crate::store::load_machine_lifecycle(store.as_ref(), &runtime_id)
            .await
            .expect("load startup-persisted healed lifecycle")
            .expect("startup-persisted lifecycle exists");
        assert_eq!(
            startup_persisted.runtime_state(),
            crate::RuntimeState::Idle,
            "replacement startup may retain the repaired Idle lifecycle projection; the V3 binding tuple below is the required healed fact"
        );
        assert_eq!(startup_persisted.binding().agent_runtime_id(), None);
        assert_eq!(startup_persisted.binding().fence_token(), None);
        assert_eq!(startup_persisted.binding().runtime_generation(), None);
        assert_eq!(startup_persisted.binding().runtime_epoch_id(), None);

        route_successor_binding_and_finish_gated_attachment(
            &machine,
            &session_id,
            registration,
            allow_reconciliation,
            completion,
            "replacement-mob-runtime:8",
            42,
            8,
        )
        .await;

        let healed_durable = crate::store::load_machine_lifecycle(store.as_ref(), &runtime_id)
            .await
            .expect("load healed lifecycle after replacement completion")
            .expect("healed lifecycle exists");
        assert_eq!(
            healed_durable.runtime_state(),
            crate::RuntimeState::Idle,
            "generated durability classification projects process-local Attached to recoverable Idle"
        );
        assert_eq!(
            healed_durable.binding().agent_runtime_id(),
            Some("replacement-mob-runtime:8")
        );
        assert_eq!(healed_durable.binding().fence_token(), Some(42));
        assert_eq!(healed_durable.binding().runtime_generation(), Some(8));
        assert_eq!(healed_durable.binding().runtime_epoch_id(), None);

        let log = signal_surface.log.lock().await;
        assert_eq!(log.len(), 1, "successor binding publishes readiness once");
        assert_eq!(log[0].0.as_str(), "ObserveRuntimeReady");
        assert_eq!(log[0].1[0].0.as_str(), "agent_runtime_id");
        assert!(
            matches!(&log[0].1[0].1, OwnedFieldValue::Str(value) if value == "replacement-mob-runtime:8")
        );
        assert_eq!(log[0].1[1].0.as_str(), "fence_token");
        assert!(matches!(log[0].1[1].1, OwnedFieldValue::U64(42)));
    }

    #[tokio::test]
    async fn ownerless_attached_claim_is_normalized_by_missing_live_materialization() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let session_id = sid("00000000-0000-0000-0000-000000000035");
        let signal_surface = Arc::new(RecordingSignalSurface::default());
        let schema = meerkat_machine_schema::catalog::meerkat_mob_seam_composition();
        let table = RouteTable::from_schema(&schema).expect("catalog routes");
        let dispatcher: CatalogCompositionSignalDispatcher<MeerkatSeamSignal> =
            CatalogCompositionSignalDispatcher::new(schema.name.clone(), table)
                .with_consumer(signal_surface.clone());
        machine.set_composition_signal_dispatcher(Arc::new(dispatcher));

        machine
            .prepare_local_session_bindings(session_id.clone())
            .await
            .expect("prepare the original in-process session entry");
        // This input is accepted before any physical executor attachment
        // exists, so it remains machine-owned and unassigned across the
        // ownerless-claim repair below.
        assert!(
            machine
                .current_executor_attachment_witness(&session_id)
                .await
                .is_none(),
            "local preparation must not mint an attachment witness"
        );
        let queued_input = crate::input::Input::Prompt(crate::input::PromptInput::new(
            "queued work survives an ownerless in-process executor claim",
            None,
        ));
        let queued_input_id = queued_input.id().clone();
        let (outcome, completion) = machine
            .accept_input_with_completion(&session_id, queued_input)
            .await
            .expect("queue work before manufacturing the ownerless claim");
        assert!(outcome.is_accepted());
        let completion = completion.expect("queued work installs a completion waiter");

        let (driver_before, authority_before, epoch_before) = {
            let sessions = machine.sessions.read().await;
            let entry = sessions.get(&session_id).expect("session entry exists");
            (
                entry.driver.clone(),
                Arc::clone(&entry.dsl_authority),
                entry.epoch_id.clone(),
            )
        };

        // Manufacture the exact limbo shape on this live entry: generated
        // Attached/Active authority with all stale binding facts, but no
        // runtime-loop attachment or teardown owner. No recovery or entry
        // reconstruction participates in this fixture.
        machine
            .stage_session_dsl_input(
                &session_id,
                mm_dsl::MeerkatMachineInput::PrepareBindings {
                    agent_runtime_id: mm_dsl::AgentRuntimeId(
                        "ownerless-stale-mob-runtime:9".into(),
                    ),
                    fence_token: mm_dsl::FenceToken(51),
                    generation: Some(mm_dsl::Generation(9)),
                    runtime_epoch_id: Some(mm_dsl::RuntimeEpochId(
                        "ownerless-stale-runtime-epoch".into(),
                    )),
                    session_id: mm_dsl::SessionId(session_id.to_string()),
                },
                "OwnerlessAttachedRegressionBinding",
            )
            .await
            .expect("stage the stale binding tuple on the same session entry");
        machine
            .stage_session_dsl_input(
                &session_id,
                mm_dsl::MeerkatMachineInput::EnsureSessionWithExecutor {
                    session_id: mm_dsl::SessionId(session_id.to_string()),
                },
                "OwnerlessAttachedRegressionClaim",
            )
            .await
            .expect("stage the ownerless active executor claim");
        {
            let mut driver = driver_before.lock().await;
            driver.sync_control_projection_from_dsl_authority();
        }

        let ownerless = machine
            .session_dsl_state(&session_id)
            .await
            .expect("ownerless authority exists");
        assert_eq!(ownerless.lifecycle_phase, mm_dsl::MeerkatPhase::Attached);
        assert_eq!(
            ownerless.registration_phase,
            mm_dsl::RegistrationPhase::Active
        );
        assert!(
            matches!(&ownerless.active_runtime_id, Some(value) if value.0 == "ownerless-stale-mob-runtime:9")
        );
        assert_eq!(ownerless.active_fence_token, Some(mm_dsl::FenceToken(51)));
        assert_eq!(
            ownerless.active_runtime_generation,
            Some(mm_dsl::Generation(9))
        );
        assert!(
            matches!(&ownerless.active_runtime_epoch_id, Some(value) if value.0 == "ownerless-stale-runtime-epoch")
        );
        {
            let sessions = machine.sessions.read().await;
            let entry = sessions.get(&session_id).expect("ownerless entry exists");
            assert!(
                !entry.has_live_attachment(),
                "an ownerless generated claim must not imply a serving attachment"
            );
            assert!(entry.runtime_loop_teardown.is_none());
        }

        let before_revival = machine
            .meerkat_machine_spine_snapshot(&session_id)
            .await
            .expect("ownerless runtime spine exists before missing-live preparation");
        assert_eq!(before_revival.inputs.queue, vec![queued_input_id.clone()]);
        let prepared = machine
            .prepare_local_session_materialization_with_mode(
                session_id.clone(),
                LocalSessionMaterializationMode::MissingLiveRevival,
            )
            .await
            .expect("typed missing-live materialization repairs the ownerless active claim");

        let normalized = machine
            .session_dsl_state(&session_id)
            .await
            .expect("normalized ownerless authority exists");
        assert_eq!(normalized.lifecycle_phase, mm_dsl::MeerkatPhase::Idle);
        assert_eq!(
            normalized.registration_phase,
            mm_dsl::RegistrationPhase::Queuing
        );
        assert_eq!(normalized.active_runtime_id, None);
        assert_eq!(normalized.active_fence_token, None);
        assert_eq!(normalized.active_runtime_generation, None);
        assert_eq!(normalized.active_runtime_epoch_id, None);
        let after_revival = machine
            .meerkat_machine_spine_snapshot(&session_id)
            .await
            .expect("ownerless runtime spine survives missing-live preparation");
        assert_input_spine_preserved(&before_revival.inputs, &after_revival.inputs);
        assert_eq!(
            after_revival.completion_waiters, before_revival.completion_waiters,
            "same-instance exit/readmit must leave completion waiters verbatim"
        );
        {
            let sessions = machine.sessions.read().await;
            let entry = sessions
                .get(&session_id)
                .expect("same entry survives missing-live preparation");
            assert!(Arc::ptr_eq(&driver_before, &entry.driver));
            assert!(Arc::ptr_eq(&authority_before, &entry.dsl_authority));
            assert_eq!(entry.epoch_id, epoch_before);
            assert!(
                !entry.has_live_attachment(),
                "missing-live normalization must leave no serving attachment"
            );
            assert!(entry.runtime_loop_teardown.is_none());
        }
        assert!(
            signal_surface.log.lock().await.is_empty(),
            "fixture staging and missing-live preparation must not publish stale runtime readiness"
        );
        assert!(
            machine
                .current_executor_attachment_witness(&session_id)
                .await
                .is_none(),
            "missing-live preparation must leave the queue unassigned until its first live attachment"
        );
        crate::begin_session_runtime_actor_materialization(prepared.bindings())
            .expect("claim the normalized materialization for actor construction")
            .commit()
            .expect("record the normalized actor materialization");

        let (registration, allow_reconciliation) =
            begin_startup_gated_first_live_attachment(&machine, &session_id, prepared).await;
        route_successor_binding_and_finish_gated_attachment(
            &machine,
            &session_id,
            registration,
            allow_reconciliation,
            completion,
            "ownerless-replacement-mob-runtime:10",
            52,
            10,
        )
        .await;

        let log = signal_surface.log.lock().await;
        assert_eq!(log.len(), 1, "successor binding publishes readiness once");
        assert_eq!(log[0].0.as_str(), "ObserveRuntimeReady");
        assert!(
            matches!(&log[0].1[0].1, OwnedFieldValue::Str(value) if value == "ownerless-replacement-mob-runtime:10")
        );
        assert!(matches!(log[0].1[1].1, OwnedFieldValue::U64(52)));
    }

    #[tokio::test]
    async fn completed_stop_cleanup_is_retired_by_idle_preparation() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let session_id = sid("00000000-0000-0000-0000-000000000036");
        machine
            .prepare_local_session_bindings(session_id.clone())
            .await
            .expect("prepare the original session entry");
        machine
            .ensure_session_with_executor(session_id.clone(), Box::new(NoopExecutor))
            .await
            .expect("attach the exact executor that will own stop cleanup");
        machine
            .stop_runtime_executor(&session_id, "completed cleanup regression")
            .await
            .expect("exact executor stop cleanup completes");

        let stopped = machine
            .session_dsl_state(&session_id)
            .await
            .expect("stopped authority remains registered");
        assert_eq!(stopped.lifecycle_phase, mm_dsl::MeerkatPhase::Stopped);
        {
            let sessions = machine.sessions.read().await;
            let entry = sessions.get(&session_id).expect("stopped entry remains");
            let coordinator = entry
                .runtime_stop_cleanup_coordinator
                .as_ref()
                .expect("completed exact cleanup receipt remains attached to the epoch");
            assert!(matches!(
                coordinator.result_rx.borrow().clone(),
                Some(Ok(()))
            ));
            assert!(
                !entry.has_live_attachment(),
                "completed exact stop cleanup must leave no live executor"
            );
            assert!(
                matches!(entry.attachment_slot, RuntimeLoopAttachmentSlot::Empty),
                "completed exact stop cleanup must retire its attachment slot"
            );
        }

        // Re-admit first, as the delivery path can do before its later local
        // bindings preparation. The subsequent idempotent preparation must
        // not turn the completed cleanup receipt into an in-progress owner.
        machine
            .stage_session_dsl_input(
                &session_id,
                mm_dsl::MeerkatMachineInput::RegisterSession {
                    session_id: mm_dsl::SessionId(session_id.to_string()),
                },
                "CompletedStopRegressionReadmit",
            )
            .await
            .expect("re-admit the stopped session without recreating its entry");
        machine
            .prepare_local_session_bindings(session_id.clone())
            .await
            .expect("local preparation preserves the re-admitted session");

        let prepared = machine
            .session_dsl_state(&session_id)
            .await
            .expect("prepared re-admitted authority exists");
        assert_eq!(prepared.lifecycle_phase, mm_dsl::MeerkatPhase::Idle);
        assert_eq!(
            prepared.registration_phase,
            mm_dsl::RegistrationPhase::Queuing
        );
        {
            let sessions = machine.sessions.read().await;
            let entry = sessions
                .get(&session_id)
                .expect("prepared entry remains registered");
            assert!(
                entry.runtime_stop_cleanup_coordinator.is_none(),
                "local preparation must retire the completed exact cleanup receipt"
            );
            assert!(entry.runtime_loop_teardown.is_none());
        }
    }

    #[tokio::test]
    async fn session_owned_prepare_bindings_is_idempotent_without_reemitting_runtime_bound() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let session_id = SessionId::new();

        let signal_surface = Arc::new(RecordingSignalSurface::default());
        let schema = meerkat_machine_schema::catalog::meerkat_mob_seam_composition();
        let table = RouteTable::from_schema(&schema).expect("catalog routes");
        let dispatcher: CatalogCompositionSignalDispatcher<MeerkatSeamSignal> =
            CatalogCompositionSignalDispatcher::new(schema.name.clone(), table)
                .with_consumer(signal_surface.clone());
        machine.set_composition_signal_dispatcher(Arc::new(dispatcher));

        machine
            .prepare_bindings(session_id.clone())
            .await
            .expect("initial session-owned binding prepares");
        machine
            .prepare_bindings(session_id.clone())
            .await
            .expect("duplicate session-owned binding returns existing handles");

        let log = signal_surface.log.lock().await;
        assert_eq!(
            log.len(),
            1,
            "duplicate handle resolution must not publish a second RuntimeBound signal"
        );
        assert_eq!(log[0].0.as_str(), "ObserveRuntimeReady");
        assert!(
            matches!(&log[0].1[0].1, OwnedFieldValue::Str(value) if value.starts_with("rt:session:"))
        );
    }

    #[tokio::test]
    async fn session_owned_prepare_bindings_rejects_conflicting_authoritative_runtime() {
        let machine = Arc::new(MeerkatMachine::ephemeral());
        let session_id = SessionId::new();
        machine
            .register_session(session_id.clone())
            .await
            .expect("register session");

        let signal_surface = Arc::new(RecordingSignalSurface::default());
        let schema = meerkat_machine_schema::catalog::meerkat_mob_seam_composition();
        let table = RouteTable::from_schema(&schema).expect("catalog routes");
        let dispatcher: CatalogCompositionSignalDispatcher<MeerkatSeamSignal> =
            CatalogCompositionSignalDispatcher::new(schema.name.clone(), table)
                .with_consumer(signal_surface.clone());
        machine.set_composition_signal_dispatcher(Arc::new(dispatcher));

        machine
            .apply_routed_meerkat_input(
                &session_id,
                mm_dsl::MeerkatMachineInput::PrepareBindings {
                    agent_runtime_id: mm_dsl::AgentRuntimeId("operator-rt:0".into()),
                    fence_token: mm_dsl::FenceToken(17),
                    generation: Some(mm_dsl::Generation(0)),
                    runtime_epoch_id: None,
                    session_id: mm_dsl::SessionId(session_id.to_string()),
                },
            )
            .await
            .expect("mob-owned authoritative binding applies");

        let err = machine
            .prepare_bindings(session_id.clone())
            .await
            .expect_err("session-owned binding must not overwrite mob-owned authority");
        assert!(
            err.to_string().contains("DSL authority (PrepareBindings)"),
            "{err}"
        );

        let state = machine
            .session_dsl_state(&session_id)
            .await
            .expect("session state remains available");
        assert!(
            matches!(&state.active_runtime_id, Some(value) if value.0 == "operator-rt:0"),
            "conflicting prepare_bindings must not rewrite active_runtime_id: {:?}",
            state.active_runtime_id
        );
        assert!(matches!(
            state.active_fence_token,
            Some(mm_dsl::FenceToken(17))
        ));

        let log = signal_surface.log.lock().await;
        assert_eq!(
            log.len(),
            1,
            "rejected session-owned binding must not publish a shadow RuntimeBound signal"
        );
        assert!(matches!(&log[0].1[0].1, OwnedFieldValue::Str(value) if value == "operator-rt:0"));
    }
}