liminal-server 0.25.4

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

use std::collections::BTreeMap;

use liminal::protocol::{
    Frame, MessageEnvelope, PUBLISH_ACK_POSITION_VERSION, PUBLISH_DELIVERED_FLAG, ProtocolError,
    ProtocolVersion, SchemaId as ProtocolSchemaId, WorkerRegisterOutcome, WorkerRegistration,
    negotiate_version,
};
use liminal_protocol::reason_code::PUBLISH_UNRESOLVED_CODE;
use liminal_protocol::wire::PARTICIPANT_FRAME_TYPE;

use super::link_route::{link_message_frame_response, link_open_frame_response};
use super::services::{
    ChannelOperation, ConnectionServices, access_to_server_error, reserved_namespace_refusal,
};
use super::state::{ConnectionProcessState, FrameAction};
use super::supervisor::push_types::{PushBinding, PushReplyDisposition};
use super::supervisor::runtime::ConnectionRuntime;
use super::worker_route::Request;
use crate::ServerError;
use crate::auth_lys::routes::{RouteClassification, classify_participant_route};
use crate::auth_lys::{
    DeliberateDecision, HotAction, RefusalCause, SubjectBinding, SubjectBindingError,
};
use crate::auth_membership::{ConnectionMembership, MembershipAction};
use crate::auth_pass::{PassVerifier, VerifiedHolder, VerifiedPass};
use crate::auth_revocation::RevocationRefusal;
use crate::config::types::ServiceProfile;
use crate::console::FlowRole;
use crate::server::participant::{
    ConnectionFateClass, PARTICIPANT_CAPABILITY_BIT, ParticipantConnectionContext,
    ParticipantDispatch, ParticipantIngress, ParticipantSemanticHandler, constant_time_eq,
    dispatch_generic_frame, encode_server_value, gate_generic_frame,
};
use liminal_protocol::credential::WireCredential;
use liminal_protocol::wire::{
    ClientRequest, ConversationId, ParticipantTransportRejected, ServerValue,
    TransportRejectionReason,
};

const SERVER_ERROR_CODE: u16 = 0xFFFF;
/// Protocol versions the server negotiates: 1.0, the version whose ack
/// carries the durable position, and the version whose `Deliver` names its
/// delivered id. A client offering only 1.0 still selects 1.0.
const SUPPORTED_PROTOCOLS: [ProtocolVersion; 3] = [
    ProtocolVersion::new(1, 0),
    PUBLISH_ACK_POSITION_VERSION,
    liminal::protocol::DELIVER_MESSAGE_ID_VERSION,
];

#[path = "worker_admission.rs"]
mod worker_admission;

pub(super) fn apply_frame(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    frame: Frame,
) -> FrameAction {
    // Auth gate. When a token is configured, a connection must clear the `Connect`
    // handshake before any application frame is honoured. The token check itself
    // lives in `connect_response`, reached only via a `Connect` frame, so gating
    // solely there would let a client that skips `Connect` and sends
    // `Publish`/`Subscribe`/`WorkerRegister` straight through to the fan-out — this
    // per-frame gate closes that bypass, and the observability-tap arm below sits
    // behind it too. Frames without an application side effect are still admitted
    // pre-auth: `Connect` (which authenticates), `Disconnect` (a clean bow-out),
    // `Ping` (liveness), and every server-to-client/unknown frame the server ignores
    // unconditionally. Any other frame from an unauthenticated peer tears the
    // connection down with a silent `Close`. With no token configured this gate is
    // inert and the pre-auth behaviour is byte-identical.
    if rejects_unauthenticated(runtime, state, &frame) {
        return FrameAction::Close;
    }
    dispatch_admitted_frame(pid, runtime, state, frame)
}

fn dispatch_admitted_frame(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    frame: Frame,
) -> FrameAction {
    match frame {
        Frame::Connect {
            min_version,
            max_version,
            auth_token,
            ..
        } => connect_once(pid, runtime, state, min_version, max_version, &auth_token),
        Frame::Disconnect { .. } => {
            FrameAction::CloseWithFate(ConnectionFateClass::CleanDisconnect)
        }
        Frame::Ping { .. } => FrameAction::Respond(Frame::Pong { flags: 0 }),
        Frame::Publish {
            stream_id,
            channel,
            envelope,
            idempotency_key,
            ..
        } => publish_frame_response(
            pid,
            runtime,
            state,
            stream_id,
            &channel,
            &envelope,
            idempotency_key.as_deref(),
        ),
        Frame::Subscribe {
            stream_id,
            channel,
            accepted_schemas: schemas,
            max_in_flight: window,
            ..
        } => subscribe_frame_response(pid, runtime, state, stream_id, &channel, &schemas, window),
        Frame::Unsubscribe {
            stream_id,
            subscription_id,
            ..
        } => unsubscribe_frame_response(pid, runtime, state, stream_id, subscription_id),
        Frame::ConversationOpen {
            stream_id,
            conversation_id,
            subject,
            ..
        } => conversation_open(pid, runtime, state, stream_id, conversation_id, &subject),
        Frame::ConversationMessage {
            flags,
            stream_id,
            conversation_id,
            envelope,
        } => {
            let request = Request::new(flags, stream_id, conversation_id);
            super::service_tap::conversation_message(pid, runtime, state, request, &envelope)
        }
        Frame::ConversationClose {
            stream_id,
            conversation_id,
            ..
        } => conversation_close(runtime.services(), state, stream_id, conversation_id),
        Frame::PushReply {
            flags,
            correlation_id,
            payload,
            ..
        } => push_reply_response(pid, runtime, state, flags, correlation_id, payload),
        Frame::WorkerRegister { registration, .. } => {
            worker_register_frame_response(pid, runtime, state, registration)
        }
        // ACCESS-002 R1: a link is a machine's grant. Opening one end is
        // deliberate and asks Lys live; a crossing is decided from both
        // machines' passes before any effect.
        Frame::LinkOpen {
            stream_id, offer, ..
        } => link_open_frame_response(pid, runtime, state, stream_id, &offer),
        Frame::LinkMessage {
            stream_id,
            subject,
            sealed,
            ..
        } => link_message_frame_response(pid, runtime, state, stream_id, &subject, &sealed),
        frame @ Frame::Unknown {
            type_id: PARTICIPANT_FRAME_TYPE,
            ..
        } => participant_frame_response(runtime, state, &frame),
        // Client backpressure signals ride the subscription delivery machinery, so
        // they are application frames: gated by auth (they are NOT on the pre-auth
        // allowlist) and refused by a services profile that serves no
        // subscriptions.
        frame @ (Frame::Accept { .. } | Frame::Defer { .. } | Frame::Reject { .. }) => {
            apply_pressure_frame(pid, runtime, state, &frame)
        }
        // `Push`/`Deliver`/`WorkerRegisterAck` are server-to-client only; a client
        // must never originate one. Ignore these (and any stray/unknown inbound
        // frame) rather than treating them as fatal so a confused or malicious
        // client cannot tear the connection down with a stray frame.
        frame @ (Frame::Push { .. }
        | Frame::Deliver { .. }
        | Frame::WorkerRegisterAck { .. }
        | Frame::LinkOpenAck { .. }
        | Frame::DisconnectReason { .. }
        | Frame::Unknown { .. }
        | Frame::ConnectAck { .. }
        | Frame::ConnectError { .. }
        | Frame::SubscribeAck { .. }
        | Frame::SubscribeError { .. }
        | Frame::PublishAck { .. }
        | Frame::PublishError { .. }
        | Frame::ConversationError { .. }
        | Frame::Pong { .. }) => ignore_stray_inbound_frame(&frame),
    }
}

pub(super) fn rejects_unauthenticated(
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    frame: &Frame,
) -> bool {
    // ACCESS-005: a revocation policy gates even an open-access server, so a
    // peer that skips `Connect` cannot reach an effect unbound.
    runtime.gates_connections() && !state.authenticated && !permitted_before_auth(frame)
}

/// `PushReply` is decided as `serve` on the subject the push was made on (the
/// access matrix's `push_binding`): the subject is read back from the reply
/// slot, decided through the connection's Lys session, and a refusal settles
/// the slot as [`ServerError::PushReplyRefused`](crate::ServerError::PushReplyRefused)
/// so the pusher learns it by type. A push made with no subject is refused the
/// same way on a Lys-admitted connection: the binding is recorded at push time
/// or not at all. A connection without a Lys session keeps the V1 path.
fn push_reply_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    flags: u8,
    correlation_id: u64,
    payload: Vec<u8>,
) -> FrameAction {
    let refusal = match runtime.push_binding(pid, correlation_id) {
        PushBinding::Unbound => None,
        PushBinding::Subjectless => state.lys_session.is_some().then(|| {
            "the push carries no subject binding; a Lys-admitted connection's reply is decided on the pushed subject".to_owned()
        }),
        // ACCESS-006 R3: a reply is an outbound service effect on a protected
        // channel, so it needs post there beside the serve grant.
        PushBinding::Subject(subject) => lys_refusal(runtime, state, &subject, HotAction::Serve)
            .or_else(|| membership_refusal(state, &subject, MembershipAction::Post)),
    };
    if let Some(reason) = refusal {
        tracing::warn!(
            pid,
            correlation_id,
            reason = reason.as_str(),
            "refused PushReply on the subject its push was made on"
        );
        log_push_disposition(
            pid,
            correlation_id,
            runtime.refuse_push(pid, correlation_id, reason),
        );
        return FrameAction::NoResponse;
    }
    if flags != 0 {
        return worker_refusal_response(pid, runtime, flags, correlation_id, &payload);
    }
    // Resolving the one-shot slot completes the round trip without another frame.
    log_push_disposition(
        pid,
        correlation_id,
        runtime.resolve_push(pid, correlation_id, payload),
    );
    FrameAction::NoResponse
}

fn worker_refusal_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    flags: u8,
    correlation_id: u64,
    payload: &[u8],
) -> FrameAction {
    use liminal::protocol::{PUSH_REPLY_REFUSED_FLAG, WorkerRefusal};
    let decoded = if flags & !PUSH_REPLY_REFUSED_FLAG == 0 {
        WorkerRefusal::decode(payload)
    } else {
        Err(ProtocolError::CodecError {
            message: Some("push_reply_reserved_flags".to_owned()),
        })
    };
    let refusal = match decoded {
        Ok(refusal) => refusal,
        Err(error) => {
            let station = runtime.worker_station(pid);
            tracing::warn!(
                pid,
                correlation_id,
                station = station.as_str(),
                protocol_fault = error.message().unwrap_or("worker_refusal_protocol_fault"),
                "worker sent a malformed refusal"
            );
            let Ok(refusal) = WorkerRefusal::new(
                "unavailable",
                format!("worker {station} sent a malformed refusal"),
            ) else {
                tracing::error!(
                    pid,
                    correlation_id,
                    protocol_fault = "worker_refusal_station_exceeds_bound",
                    "cannot encode the worker protocol fault"
                );
                log_push_disposition(
                    pid,
                    correlation_id,
                    runtime.refuse_push(
                        pid,
                        correlation_id,
                        "worker_refusal_station_exceeds_bound".to_owned(),
                    ),
                );
                return FrameAction::NoResponse;
            };
            refusal
        }
    };
    log_push_disposition(
        pid,
        correlation_id,
        runtime.resolve_worker_refusal(pid, correlation_id, refusal),
    );
    FrameAction::NoResponse
}

fn log_push_disposition(pid: u64, correlation_id: u64, disposition: PushReplyDisposition) {
    match disposition {
        PushReplyDisposition::Resolved => {}
        PushReplyDisposition::SenderMismatch => tracing::warn!(
            pid,
            correlation_id,
            reply_disposition = "sender_mismatch",
            "discarded PushReply from a connection other than its recipient"
        ),
        PushReplyDisposition::UnknownCorrelation => tracing::debug!(
            pid,
            correlation_id,
            reply_disposition = "unknown_correlation",
            "discarded PushReply for a missing slot"
        ),
        PushReplyDisposition::ReceiverDropped => tracing::debug!(
            pid,
            correlation_id,
            reply_disposition = "receiver_dropped",
            "discarded PushReply after its receiver was abandoned"
        ),
    }
}

fn apply_pressure_frame(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    frame: &Frame,
) -> FrameAction {
    let (stream, reference, response) = match frame {
        Frame::Accept {
            stream_id,
            referenced_message_id,
            ..
        } => (*stream_id, referenced_message_id.as_str(), "accept"),
        Frame::Defer {
            stream_id,
            referenced_message_id,
            ..
        } => (*stream_id, referenced_message_id.as_str(), "defer"),
        Frame::Reject {
            stream_id,
            referenced_message_id,
            ..
        } => (*stream_id, referenced_message_id.as_str(), "reject"),
        other => return ignore_stray_inbound_frame(other),
    };
    pressure_frame_response(pid, runtime, state, stream, reference, response)
}

fn pressure_frame_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    stream_id: u32,
    reference: &str,
    response: &'static str,
) -> FrameAction {
    let action = pressure_response(runtime.services(), stream_id);
    if !runtime.services().supports_channel_operations() {
        return action;
    }
    // Accept/Defer/Reject are decided as `subscribe` on the subject of the
    // subscription they signal for (the matrix's `subscription_binding`),
    // before the ledger is touched. The signal has no refusal frame: a refused
    // signal has no effect, is logged with its refusal and counted.
    let subjects: Vec<String> = state
        .subscriptions
        .values()
        .filter(|subscription| subscription.stream_id() == stream_id)
        .map(|subscription| subscription.channel().to_owned())
        .collect();
    for subject in &subjects {
        if let Some(reason) = lys_refusal(runtime, state, subject, HotAction::Subscribe)
            .or_else(|| membership_refusal(state, subject, MembershipAction::Read))
        {
            tracing::warn!(
                pid,
                stream_id,
                response,
                reason = reason.as_str(),
                "refused backpressure signal on its subscription's subject"
            );
            crate::metrics::pressure_refused();
            return action;
        }
    }
    let matched = state.subscriptions.values_mut().find_map(|subscription| {
        if subscription.stream_id() == stream_id
            && subscription.match_pressure(reference, response == "defer")
        {
            Some(subscription)
        } else {
            None
        }
    });
    if let Some(subscription) = matched {
        if matches!(subscription.channel(), "liminal.events" | "liminal.cost") {
            crate::metrics::self_stream_pressure_suppressed();
        } else {
            runtime.pressure(pid, response);
        }
    } else {
        crate::metrics::self_stream_pressure_unmatched();
    }
    action
}

/// The catch-all's body: warns with the frame-kind name, then keeps the
/// no-teardown `NoResponse` semantics.
fn ignore_stray_inbound_frame(frame: &Frame) -> FrameAction {
    warn_ignored_inbound_frame(ignored_inbound_frame_kind(frame));
    FrameAction::NoResponse
}

/// Names the frame variant for the ignored-inbound warn. Kind names only — no
/// payload is Debug-formatted, so a stray frame cannot spray opaque bytes into
/// the log.
const fn ignored_inbound_frame_kind(frame: &Frame) -> &'static str {
    match frame {
        Frame::Push { .. } => "push",
        Frame::Deliver { .. } => "deliver",
        Frame::WorkerRegisterAck { .. } => "worker_register_ack",
        Frame::LinkOpenAck { .. } => "link_open_ack",
        Frame::DisconnectReason { .. } => "disconnect_reason",
        Frame::Unknown { .. } => "unknown",
        Frame::ConnectAck { .. } => "connect_ack",
        Frame::ConnectError { .. } => "connect_error",
        Frame::SubscribeAck { .. } => "subscribe_ack",
        Frame::SubscribeError { .. } => "subscribe_error",
        Frame::PublishAck { .. } => "publish_ack",
        Frame::PublishError { .. } => "publish_error",
        Frame::ConversationError { .. } => "conversation_error",
        Frame::Pong { .. } => "pong",
        // Unreachable from the ignored arm (every other kind has its own
        // dispatch above); named honestly rather than panicking.
        _ => "other",
    }
}

/// Logs the ignored stray inbound frame. The no-teardown semantics are the
/// caller's; this is visibility only.
fn warn_ignored_inbound_frame(kind: &'static str) {
    tracing::warn!(
        frame_kind = kind,
        "ignored stray inbound frame; server-to-client-only or unknown frame kinds get no response and no teardown"
    );
}

/// Names a broken activation invariant at the point it closes the connection.
///
/// A complete participant service and a durable connection incarnation are one
/// invariant; either alone is internal configuration drift, not a client fault.
/// Closing is correct — the alternative is fabricating a lifecycle outcome — but
/// closing SILENTLY left an operator watching connections drop at the handshake
/// with nothing to read, while the sibling semantic-failure arm in the same
/// match already warned.
fn warn_partial_activation(stage: &'static str, service_installed: bool) {
    tracing::warn!(
        stage,
        service_installed,
        connection_incarnation_present = !service_installed,
        "closing on partial participant activation; a complete participant service \
         and a durable connection incarnation are one invariant and exactly one is \
         present (internal configuration drift, not a client fault)"
    );
}

/// Applies the core protocol's single-use connection handshake.
fn connect_once(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    min_version: ProtocolVersion,
    max_version: ProtocolVersion,
    auth_token: &[u8],
) -> FrameAction {
    if let Some(refused) = super::link_route::own_device_connect_refusal(runtime, auth_token) {
        return FrameAction::RespondThenClose(refused);
    }
    // The core lifecycle excludes `Connect` from its Active state; accepting a
    // second one would silently renegotiate capability/session state in place.
    if state.authenticated {
        FrameAction::Close
    } else {
        connect_response(pid, runtime, state, min_version, max_version, auth_token)
    }
}

/// Applies the shared participant transport gate before semantic dispatch.
///
/// Semantic request handling is installed by the participant lifecycle service;
/// this boundary already guarantees that malformed, unauthenticated, and
/// capability-missing frames receive the crate's exact typed rejection.
fn participant_frame_response(
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    frame: &Frame,
) -> FrameAction {
    match (runtime.participant_service(), state.connection_incarnation) {
        (Some(service), Some(connection_incarnation)) => {
            if let Some(refused) = participant_lys_refusal(runtime, state, service, frame) {
                return refused;
            }
            match dispatch_generic_frame(
                frame,
                state.authenticated,
                state.participant_session,
                // The mount fact is the CONNECTION's, stamped by its spawn path
                // before any inbound byte was read (design §10). It is read off
                // the connection state here — never derived from `frame`, whose
                // contents are exactly the thing a client controls.
                ParticipantConnectionContext::new(connection_incarnation, state.mount),
                state.pass_principal.as_ref(),
                &mut state.participant_conversations,
                service,
            ) {
                ParticipantDispatch::NotParticipant => FrameAction::NoResponse,
                ParticipantDispatch::Respond(response) => FrameAction::Respond(response),
                ParticipantDispatch::RespondThenClose(response) => {
                    FrameAction::RespondThenClose(response)
                }
                ParticipantDispatch::Fatal(error) => {
                    tracing::warn!(%error, "participant request failed closed");
                    FrameAction::Close
                }
            }
        }
        (None, None) => participant_frame_without_service(state, frame),
        // A complete service and a durable connection incarnation are one
        // activation invariant. Any mismatch is internal configuration drift;
        // close without fabricating a lifecycle outcome.
        (Some(_), None) | (None, Some(_)) => {
            warn_partial_activation(
                "participant frame dispatch",
                runtime.participant_service().is_some(),
            );
            FrameAction::Close
        }
    }
}

/// The participant routes' access decision for a connection admitted on a Lys
/// pass (the matrix's `participant_binding`): the decoded request is decided,
/// on every conversation it names, as the action its route is classified
/// with, before dispatch sees it. A refusal answers the participant transport
/// rejection `AccessRefused` carrying the refusal, without closing. `None`
/// means proceed: no Lys session, no decoded request, or every decision made.
fn participant_lys_refusal(
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    service: &dyn ParticipantSemanticHandler,
    frame: &Frame,
) -> Option<FrameAction> {
    // A connection bound under a revocation policy (ACCESS-005 R4) is
    // decided here too, whether it was admitted on a Lys pass or not.
    if state.lys_session.is_none() && state.revocation.is_none() {
        return None;
    }
    let ParticipantIngress::Request(request) =
        gate_generic_frame(frame, state.authenticated, state.participant_session)
    else {
        return None;
    };
    let refusal = participant_access_refusal(runtime, state, service, &request)?;
    tracing::warn!(
        route = ?request.discriminant(),
        reason = refusal.as_str(),
        "refused participant request on its conversation's subject"
    );
    let rejected = ServerValue::ParticipantTransportRejected(ParticipantTransportRejected {
        reason: TransportRejectionReason::AccessRefused { refusal },
    });
    match encode_server_value(rejected) {
        Ok(frame) => Some(FrameAction::Respond(frame)),
        Err(error) => {
            tracing::warn!(
                error = ?error,
                "a participant access refusal could not be encoded; closing"
            );
            Some(FrameAction::Close)
        }
    }
}

/// The decision behind [`participant_lys_refusal`]: `Some` is the first
/// refusal over the request's conversations, in route order; `None` is every
/// decision made. A conversation no authority maps to a subject is refused by
/// name: a subject is never guessed from the numeric id.
fn participant_access_refusal(
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    service: &dyn ParticipantSemanticHandler,
    request: &ClientRequest,
) -> Option<String> {
    let action = match classify_participant_route(request.discriminant()) {
        RouteClassification::Hot { action, .. } | RouteClassification::Cleanup { action, .. } => {
            action
        }
        RouteClassification::Admission
        | RouteClassification::Control
        | RouteClassification::ServerOnly
        | RouteClassification::ParticipantEnvelope
        | RouteClassification::Deliberate { .. }
        | RouteClassification::Crossing { .. }
        | RouteClassification::Unknown => {
            return Some(format!(
                "participant route {:?} has no hot or cleanup class; refused",
                request.discriminant()
            ));
        }
    };
    participant_conversations(request)
        .into_iter()
        .find_map(|conversation_id| {
            // ACCESS-006 R1: the subject comes from the handler's own
            // authority, else from the membership mapping the operator's
            // product schema supplies; never a guess from the id. A mapped
            // conversation is then decided on its pass rights and its
            // channel membership both.
            let subject = service.conversation_subject(conversation_id).or_else(|| {
                runtime
                    .membership_gate()
                    .and_then(|gate| gate.channel_for_conversation(conversation_id))
                    .map(str::to_owned)
            });
            subject.map_or_else(
                || {
                    Some(format!(
                        "no subject mapping for conversation {conversation_id}; a Lys-admitted connection's participant request is decided on its conversation's subject"
                    ))
                },
                |subject| {
                    lys_refusal(runtime, state, &subject, action).or_else(|| {
                        membership_refusal(state, &subject, MembershipAction::for_hot(action))
                    })
                },
            )
        })
}

/// Every conversation a participant request names, in request order. A
/// recovery batch names one per refusal it carries, each decided before any
/// effect.
fn participant_conversations(request: &ClientRequest) -> Vec<ConversationId> {
    match request {
        ClientRequest::Enrollment(request) => vec![request.conversation_id],
        ClientRequest::CredentialAttach(request) => vec![request.conversation_id],
        ClientRequest::Detach(request) => vec![request.conversation_id],
        ClientRequest::ParticipantAck(request) => vec![request.conversation_id],
        ClientRequest::Leave(request) => vec![request.conversation_id],
        ClientRequest::MarkerAck(request) => vec![request.conversation_id],
        ClientRequest::RecordAdmission(request) => vec![request.conversation_id],
        ClientRequest::SettlementQuery(request) => vec![request.conversation_id],
        ClientRequest::ObserverRecovery(request) => request
            .observer_refusals
            .iter()
            .map(|refusal| refusal.conversation_id)
            .collect(),
    }
}

/// Applies only the crate-owned pre-semantic gate while participant capability
/// is disabled. A decoded request cannot occur because the session is missing.
fn participant_frame_without_service(state: &ConnectionProcessState, frame: &Frame) -> FrameAction {
    match gate_generic_frame(frame, state.authenticated, state.participant_session) {
        ParticipantIngress::NotParticipant => FrameAction::NoResponse,
        // A decoded request is unreachable while the capability is deliberately
        // not advertised. Close if configuration drift ever makes it reachable;
        // silently consuming an authorized lifecycle operation would make a
        // retry indistinguishable from a lost commit. A locally unrepresentable
        // generic frame is likewise terminal.
        ParticipantIngress::Request(_) | ParticipantIngress::InvalidGenericFrame => {
            FrameAction::Close
        }
        ParticipantIngress::Rejected(rejection) => {
            let reason = format!("{:?}", rejection.reason);
            match encode_server_value(
                liminal_protocol::wire::ServerValue::ParticipantTransportRejected(rejection),
            ) {
                Ok(response) => FrameAction::RespondThenClose(response),
                Err(error) => {
                    // The client gets a bare close instead of the typed rejection
                    // it was owed, so neither the encode failure nor the reason it
                    // was rejected exists anywhere unless logged here.
                    tracing::warn!(
                        rejection_reason = %reason,
                        ?error,
                        "participant transport rejection could not be encoded; closing \
                         without telling the client why"
                    );
                    FrameAction::Close
                }
            }
        }
    }
}

/// Client backpressure signals (`Accept`/`Defer`/`Reject`). Full mode consumes
/// them with no wire response, exactly as before. The worker front door serves no
/// subscriptions — no delivery can exist for a client to signal pressure on — so
/// the frame is rejected on the subscription error channel (`SubscribeError`, the
/// same closest-honest-fit vocabulary as the unsubscribe rejection).
fn pressure_response(services: &dyn ConnectionServices, stream_id: u32) -> FrameAction {
    if services.supports_channel_operations() {
        FrameAction::NoResponse
    } else {
        FrameAction::Respond(Frame::SubscribeError {
            flags: 0,
            stream_id,
            reason_code: SERVER_ERROR_CODE,
            message: Some(unsupported_by_front_door("backpressure signaling")),
        })
    }
}

/// Renders the worker-front-door refusal text for `operation` from the typed
/// [`ServerError::UnsupportedOperation`] variant, so every front-door rejection —
/// whether raised in the services adapter or short-circuited here — speaks the one
/// error vocabulary.
fn unsupported_by_front_door(operation: &str) -> String {
    ServerError::UnsupportedOperation {
        operation: operation.to_owned(),
        profile: ServiceProfile::WORKER_FRONT_DOOR,
    }
    .to_string()
}

/// Associates a worker registration with this connection and invokes the
/// configured connection notifier.
///
/// The notifier is consulted FIRST: only after the application accepts (or when
/// no notifier is configured) is the registration stored on the connection
/// record, so the close-path `on_worker_unregistered` fires for exactly the
/// connections the application accepted — a rejected worker leaves no record and
/// triggers no later deregistration. The ack is synchronous: a notifier error
/// yields a `Rejected` ack carrying the reason so the worker never believes it is
/// registered after the application declined it. With no notifier configured the
/// registration is accepted unconditionally, keeping liminal usable standalone.
/// A `WorkerRegister` frame; an accepted one makes this connection a worker,
/// whose flows are line stops from now on (SRV-012 R7).
fn worker_register_frame_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    registration: WorkerRegistration,
) -> FrameAction {
    // A station must fit in the named malformed-refusal explanation without
    // truncating either its identity or the caller's wire-bounded words.
    if registration.identity.len() > WORKER_REFUSAL_STATION_MAX {
        return worker_register_rejected(format!(
            "worker_station_too_long: identity exceeds {WORKER_REFUSAL_STATION_MAX} UTF-8 bytes"
        ));
    }
    // ACCESS-004 R2: a connection that proved who it is registers under
    // that name and no other.
    // R3: an operator who requires a holder refuses a connection that
    // proved none.
    match state.verified_holder.as_ref() {
        Some(holder) if !holder.is_named(&registration.identity) => {
            return worker_register_rejected(REGISTRATION_NOT_HOLDER.to_owned());
        }
        None if runtime
            .pass_verifier()
            .is_some_and(PassVerifier::requires_verified_worker) =>
        {
            return worker_register_rejected(REGISTRATION_WITHOUT_HOLDER.to_owned());
        }
        Some(_) | None => {}
    }
    if let Some(refused) = worker_admission::decide(runtime, state, &registration) {
        return refused;
    }
    // SRV-028 R4: a service process registers its own subjects only, and
    // its first accepted registration makes its service live.
    let trial = match runtime.services().prepare_site_trial(
        pid,
        state.lys_session.as_deref(),
        &registration,
        state.service_process.as_ref(),
        unix_seconds_now().saturating_mul(1000),
    ) {
        Ok(trial) => trial,
        Err(error) => return worker_register_rejected(error.to_string()),
    };
    let process = state.service_process.clone();
    let action =
        worker_register_response(pid, runtime, registration, state.verified_holder.as_ref());
    if matches!(
        action,
        FrameAction::Respond(Frame::WorkerRegisterAck {
            outcome: WorkerRegisterOutcome::Accepted,
            ..
        })
    ) {
        if let Some(trial) = trial {
            if let Err(error) = trial.commit() {
                if let Err(rollback) = runtime.clear_registration(pid) {
                    return worker_register_rejected(format!(
                        "trial_commit_failed: {error}; registration_rollback_failed: {rollback}"
                    ));
                }
                return worker_register_rejected(error.to_string());
            }
        }
    }
    if let Some(process) = process
        && matches!(
            action,
            FrameAction::Respond(Frame::WorkerRegisterAck {
                outcome: WorkerRegisterOutcome::Accepted,
                ..
            })
        )
        && let Some(lifecycle) = runtime.lifecycle()
        && let Err(error) =
            lifecycle.mark_live(&process.service, unix_seconds_now().saturating_mul(1000))
    {
        tracing::warn!(service = %process.service, %error, "a live service could not be recorded");
    }
    if matches!(
        action,
        FrameAction::Respond(Frame::WorkerRegisterAck {
            outcome: WorkerRegisterOutcome::Accepted,
            ..
        })
    ) {
        state.worker_flows.get_or_insert_with(BTreeMap::new);
    }
    action
}

/// The wire-configured words ceiling less the fixed malformed-refusal wording.
/// This derived registration bound guarantees a fault can name the full station.
pub(super) const WORKER_REFUSAL_STATION_MAX: usize =
    liminal::protocol::WORKER_REFUSAL_WORDS_MAX - "worker  sent a malformed refusal".len();

fn worker_register_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    registration: WorkerRegistration,
    holder: Option<&VerifiedHolder>,
) -> FrameAction {
    if let Some(notifier) = runtime.notifier() {
        if let Err(error) = notifier.on_worker_registered_by(pid, &registration, holder) {
            return worker_register_rejected(error.to_string());
        }
    }
    // Store only after acceptance. A poisoned-registry error here means the
    // accepted registration cannot be tracked for deregistration, so reject the
    // worker (and undo the application-side registration) rather than leave a
    // silent, never-deregistered association.
    if let Err(error) = runtime.set_registration(pid, registration) {
        if let Some(notifier) = runtime.notifier() {
            notifier.on_worker_unregistered(pid);
        }
        return worker_register_rejected(error.to_string());
    }
    FrameAction::Respond(Frame::WorkerRegisterAck {
        flags: 0,
        outcome: WorkerRegisterOutcome::Accepted,
    })
}

/// The `Rejected` reason for a registration whose name is not the verified
/// holder's. It names neither, so no holder bytes reach the worker's log.
const REGISTRATION_NOT_HOLDER: &str = "registration identity is not the verified holder";

/// The `Rejected` reason for a registration from a connection that proved no
/// holder, when the operator requires one.
const REGISTRATION_WITHOUT_HOLDER: &str = "worker registration requires a verified holder";

const fn worker_register_rejected(reason: String) -> FrameAction {
    FrameAction::Respond(Frame::WorkerRegisterAck {
        flags: 0,
        outcome: WorkerRegisterOutcome::Rejected { reason },
    })
}

/// Whether `frame` may be processed before the connection clears the auth gate.
///
/// Default-deny: only the handshake (`Connect`), a clean disconnect, a liveness
/// `Ping`, and the frames the server ignores unconditionally (server-to-client and
/// unknown kinds, which return `NoResponse` regardless) are admitted. Every
/// application frame — publish, subscribe, unsubscribe, conversation, worker-register,
/// push-reply, and the `Accept`/`Defer`/`Reject` backpressure signals (which act on
/// subscription delivery state) — is held back until a successful `Connect`, so a
/// newly added frame is gated by default until it is explicitly listed here.
const fn permitted_before_auth(frame: &Frame) -> bool {
    matches!(
        frame,
        Frame::Connect { .. }
            | Frame::Disconnect { .. }
            | Frame::Ping { .. }
            | Frame::Push { .. }
            | Frame::Deliver { .. }
            | Frame::WorkerRegisterAck { .. }
            | Frame::LinkOpenAck { .. }
            | Frame::DisconnectReason { .. }
            | Frame::Unknown { .. }
            | Frame::ConnectAck { .. }
            | Frame::ConnectError { .. }
            | Frame::SubscribeAck { .. }
            | Frame::SubscribeError { .. }
            | Frame::PublishAck { .. }
            | Frame::PublishError { .. }
            | Frame::ConversationError { .. }
            | Frame::Pong { .. }
    )
}

/// Whether the connection may use `channel`, decided from the holder its
/// `Connect` verified (ACCESS-004 R4): a holder may use only channels under
/// its pass's live prefix, and a connection that proved no holder is not
/// restricted here. Rights from a Lys pass wait for ACCESS-001 R2.
/// `ConnectError` for a Lys pass record the admitter refused, naming the
/// refusal and never the pass bytes.
fn lys_connect_refused(reason: &str) -> FrameAction {
    let error = ProtocolError::AuthenticationFailure {
        message: Some(format!("lys pass admission refused: {reason}")),
    };
    FrameAction::RespondThenClose(Frame::ConnectError {
        flags: 0,
        reason_code: error.reason_code(),
        message: error.message().map(str::to_owned),
    })
}

/// Seconds since the Unix epoch, the `now` every Lys decision is made at.
pub(super) fn unix_seconds_now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |elapsed| elapsed.as_secs())
}

/// Decides one hot action on `channel` from the connection's admitted Lys
/// pass, offline. `None` lets the operation proceed: either the pass allows
/// it, or the connection holds no Lys pass and the V1 rules apply instead.
/// `Some` is the refusal frame in the one shape: the four-field refusal as
/// the message, under the route's refused reason code.
fn lys_decision(
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    channel: &str,
    action: HotAction,
    refused: impl FnOnce(String) -> Frame,
) -> Option<FrameAction> {
    lys_refusal(runtime, state, channel, action)
        .or_else(|| membership_refusal(state, channel, MembershipAction::for_hot(action)))
        .map(|message| FrameAction::Respond(refused(message)))
}

/// ACCESS-006 R1, R3: a membership-protected channel's admission, decided on
/// the connection's verified subject after (and in addition to) its pass
/// rights, before any effect. `None` proceeds: the channel is not protected,
/// or the membership allows the act. `Some` is the refusal's stable name and
/// words, naming no resource and no holder.
fn membership_refusal(
    state: &ConnectionProcessState,
    channel: &str,
    action: MembershipAction,
) -> Option<String> {
    let refusal = state.membership.check(channel, action).err()?;
    tracing::warn!(
        refusal = refusal.name(),
        action = action.as_str(),
        "refused a membership-protected act"
    );
    Some(refusal.to_string())
}

/// The decision behind [`lys_decision`], for the routes that carry no refusal
/// frame (`PushReply`, `Accept`/`Defer`/`Reject`): `None` is the same
/// "proceed" as there; `Some` is the refusal message in the one shape.
fn lys_refusal(
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    channel: &str,
    action: HotAction,
) -> Option<String> {
    // SRV-028 R4: a service process serves its own subjects and does
    // nothing else on this connection.
    if let Some(process) = state.service_process.as_ref()
        && !(action == HotAction::Serve && process.serves(channel))
    {
        return Some(
            "service_process_scope: a service process serves its own subjects and nothing else"
                .to_owned(),
        );
    }
    // ACCESS-005 R4: a revoked right is refused first, by name, from the
    // connection's own bound rights; no Lys call is made here.
    if let Some(grants) = state.revocation.as_ref()
        && let Err(refusal) = grants.allows(action, channel)
    {
        return Some(refusal.name().to_owned());
    }
    if let Err(refused) =
        crate::auth_membership::check_agent_binding(state.lys_session.as_deref(), action, channel)
    {
        return Some(refused.to_string());
    }
    let session = state.lys_session.as_ref()?;
    let Some((_, network_id)) = runtime.lys_admitter() else {
        return Some("no lys admitter is installed".to_owned());
    };
    let subject = match SubjectBinding::new(
        network_id.to_owned(),
        channel.to_owned(),
        channel.to_owned(),
    ) {
        Ok(subject) => subject,
        Err(SubjectBindingError(member)) => {
            return Some(format!("subject binding refused: {member}"));
        }
    };
    let now = unix_seconds_now();
    let error = match session.decide(&subject, action, now) {
        Ok(_receipt) => return None,
        Err(error) => error,
    };
    // SRV-028: a service placed after this pass was issued is not among its
    // rights, so the offline refusal is for want of a placement and not of a
    // grant: Lys is asked live, once per such act, until the pass renews.
    let placed_after_pass = error.cause == RefusalCause::MissingGrant
        && session.issued_at().is_some_and(|issued| {
            runtime.lifecycle().is_some_and(|lifecycle| {
                lifecycle.placed_since(channel, issued.saturating_mul(1000))
            })
        });
    if placed_after_pass
        && let Ok(DeliberateDecision::Outright(_receipt)) =
            session.decide_live(subject.resource(), action.into(), now)
    {
        return None;
    }
    Some(serde_json::to_string(&error.refusal).unwrap_or_else(|_| error.cause.to_string()))
}

fn pass_allows_channel(state: &ConnectionProcessState, channel: &str) -> bool {
    state
        .verified_holder
        .as_ref()
        .is_none_or(|holder| holder.allows_channel(channel))
}

fn publish_frame_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    stream_id: u32,
    channel: &str,
    envelope: &MessageEnvelope,
    idempotency_key: Option<&str>,
) -> FrameAction {
    if let Some(refused) = lys_decision(runtime, state, channel, HotAction::Publish, |message| {
        Frame::PublishError {
            flags: 0,
            stream_id,
            reason_code: 0x0202,
            message: Some(message),
        }
    }) {
        return refused;
    }
    if !pass_allows_channel(state, channel) {
        return FrameAction::Respond(Frame::PublishError {
            flags: 0,
            stream_id,
            reason_code: 0x0202,
            message: Some(format!("publish refused for channel {channel}")),
        });
    }
    // SRV-012 R1: the console guard comes first, so a notifier is never
    // offered a console subject's payload.
    if crate::console::tappable(channel)
        && runtime.notifier_channel_publish(pid, channel, &envelope.payload)
    {
        FrameAction::NoResponse
    } else {
        let action = publish_response(
            pid,
            &crate::agents::admitted_services::AdmittedServices::new(
                pid,
                runtime.services(),
                state.lys_session.as_deref(),
            ),
            state.negotiated_version,
            stream_id,
            channel,
            envelope,
            idempotency_key,
        );
        flowed(pid, runtime, state, channel, FlowRole::Publishes, action)
    }
}

/// SRV-012 R7: a registered worker's first acknowledged publish or subscribe
/// on `channel` tells the topology which way connection `pid` uses it, then
/// `action` is answered unchanged. A repeat, or any other connection's, reads
/// connection state only: no allocation and no console lock.
fn flowed(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    channel: &str,
    role: FlowRole,
    action: FrameAction,
) -> FrameAction {
    let bit = flow_bit(role);
    if let Some(flows) = state.worker_flows.as_mut()
        && flows.get(channel).is_none_or(|known| known & bit == 0)
        && matches!(
            action,
            FrameAction::Respond(Frame::PublishAck { .. } | Frame::SubscribeAck { .. })
        )
    {
        *flows.entry(channel.to_owned()).or_default() |= bit;
        runtime.flow(pid, channel, role, true);
    }
    action
}

/// The bit a [`FlowRole`] holds in [`ConnectionProcessState::flows`].
const fn flow_bit(role: FlowRole) -> u8 {
    match role {
        FlowRole::Publishes => 1,
        FlowRole::Subscribes => 2,
    }
}

fn subscribe_frame_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    stream_id: u32,
    channel: &str,
    accepted_schemas: &[ProtocolSchemaId],
    max_in_flight: u32,
) -> FrameAction {
    if let Some(refused) = lys_decision(runtime, state, channel, HotAction::Subscribe, |message| {
        Frame::SubscribeError {
            flags: 0,
            stream_id,
            reason_code: 0x0201,
            message: Some(message),
        }
    }) {
        return refused;
    }
    if pass_allows_channel(state, channel) {
        let action = subscribe_response(
            pid,
            runtime,
            state,
            stream_id,
            channel,
            accepted_schemas,
            max_in_flight,
        );
        flowed(pid, runtime, state, channel, FlowRole::Subscribes, action)
    } else {
        FrameAction::Respond(Frame::SubscribeError {
            flags: 0,
            stream_id,
            reason_code: 0x0201,
            message: Some(format!("subscribe refused for channel {channel}")),
        })
    }
}

/// The `ConnectError` closing a connection whose credential failed its check.
fn authentication_failed(message: String) -> FrameAction {
    let error = ProtocolError::AuthenticationFailure {
        message: Some(message),
    };
    FrameAction::RespondThenClose(Frame::ConnectError {
        flags: 0,
        reason_code: error.reason_code(),
        message: error.message().map(str::to_owned),
    })
}

/// Admits the connection's credential before version negotiation, so an
/// unauthenticated peer learns nothing about the negotiated protocol: the
/// configured bearer token, a Lys pass record through the installed admitter
/// (offline, or refused by name), or a V1 pass through the verifier; then
/// the ACCESS-005 revocation fence, which refuses a connection with no bound
/// pass by name. When no token is configured the server is open and the
/// bearer check is skipped, keeping the handshake byte-identical to the
/// pre-auth behaviour. `Err` is the frame action that answers a refusal.
fn admit_credential(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    (min_version, max_version): (ProtocolVersion, ProtocolVersion),
    auth_token: &[u8],
) -> Result<(), Box<FrameAction>> {
    // SRV-028 R4: a service process's own credential admits it to serve
    // its subjects and nothing else; it is never the bearer.
    if let Some(grant) = runtime
        .lifecycle()
        .and_then(|lifecycle| lifecycle.admit_process(auth_token))
    {
        state.service_process = Some(grant);
        return Ok(());
    }
    let bearer_matches = runtime
        .auth_token()
        .is_some_and(|expected| constant_time_eq(expected, auth_token));
    if !bearer_matches {
        if let Ok(WireCredential::LysPass(pass)) = WireCredential::classify(auth_token) {
            // A Lys pass record: admitted by the installed admitter, offline,
            // or refused by name. It never falls through to the V1 checker.
            // ACCESS-010 R2: an exchange that gates nothing has no admitter
            // and admits the record as an open-access connection, no holder.
            if let Some((admitter, _)) = runtime.lys_admitter() {
                match admitter.admit(pass, unix_seconds_now()) {
                    Ok(session) => {
                        // ACCESS-004 R1's second producer: the Lys holder is
                        // the connection's one proof of who it is, so a worker
                        // registers under that name and no other (R2).
                        state.verified_holder =
                            Some(VerifiedHolder::from_lys_session(session.as_ref()));
                        state.lys_session = Some(std::sync::Arc::from(session));
                    }
                    Err(refusal) => return Err(Box::new(lys_connect_refused(&refusal.reason))),
                }
            } else if runtime.gates_connections() {
                return Err(Box::new(lys_connect_refused(
                    "no lys admitter is installed",
                )));
            }
        } else if let Some(verifier) = runtime.pass_verifier() {
            match verifier.verify(auth_token) {
                Ok(VerifiedPass { principal, holder }) => {
                    // ACCESS-005 R3: under a revocation policy the binding is
                    // fenced before any attach is announced.
                    revocation_connect(
                        pid,
                        runtime,
                        state,
                        (min_version, max_version),
                        auth_token,
                        holder.participant(),
                    )?;
                    runtime.pass_attached(pid, state.mount, holder.participant());
                    state.pass_principal = Some(principal);
                    state.verified_holder = Some(holder);
                }
                Err(failure) => {
                    return Err(Box::new(authentication_failed(format!(
                        "connection pass {} check failed",
                        failure.check_name()
                    ))));
                }
            }
        } else if runtime.auth_token().is_some() {
            return Err(Box::new(authentication_failed(
                "connection authentication token rejected".to_owned(),
            )));
        }
    }
    // ACCESS-005 R1/R3: a Lys-pass connection is fenced here, and a bearer or
    // open-access one, which carries no bound pass, is refused by name.
    if runtime.revocation().is_some() && state.revocation.is_none() {
        let holder = state
            .verified_holder
            .as_ref()
            .map(|holder| holder.participant().to_vec());
        holder.map_or_else(
            || {
                Err(Box::new(revocation_connect_refused(
                    RevocationRefusal::BindingMissing,
                )))
            },
            |holder| {
                revocation_connect(
                    pid,
                    runtime,
                    state,
                    (min_version, max_version),
                    auth_token,
                    &holder,
                )
            },
        )?;
    }
    Ok(())
}

fn connect_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    min_version: ProtocolVersion,
    max_version: ProtocolVersion,
    auth_token: &[u8],
) -> FrameAction {
    if let Err(refused) =
        admit_credential(pid, runtime, state, (min_version, max_version), auth_token)
    {
        return *refused;
    }
    // ACCESS-006 R1: membership is bound to the subject this same
    // verification proved; under a scoped-guest mapping a Lys holder must
    // hold a current grant in the workspace before anything is admitted.
    let membership = ConnectionMembership::bind(
        runtime.membership_gate().cloned(),
        pid,
        state.lys_session.as_deref(),
    );
    if state.lys_session.is_some()
        && let Err(refusal) = membership.admit_connect()
    {
        return lys_connect_refused(refusal.name());
    }
    state.membership = membership;
    let selected_version =
        match negotiate_version(min_version, max_version, supported_protocols(runtime)) {
            Ok(selected_version) => selected_version,
            Err(error) => {
                return FrameAction::RespondThenClose(Frame::ConnectError {
                    flags: 0,
                    reason_code: error.reason_code(),
                    message: error.message().map(str::to_owned),
                });
            }
        };
    let (participant_session, capabilities) =
        match (runtime.participant_service(), state.connection_incarnation) {
            (Some(service), Some(_)) => {
                let mut participant_session =
                    crate::server::participant::ParticipantSession::default();
                participant_session.negotiate_v1(service.frame_limit());
                (participant_session, PARTICIPANT_CAPABILITY_BIT)
            }
            // A generic durable channel store alone does not activate the participant
            // protocol. Both service and incarnation are absent.
            (None, None) => (crate::server::participant::ParticipantSession::default(), 0),
            // Fail closed on impossible partial activation without inventing a
            // participant response.
            (Some(_), None) | (None, Some(_)) => {
                warn_partial_activation(
                    "connection handshake",
                    runtime.participant_service().is_some(),
                );
                return FrameAction::Close;
            }
        };

    // A pass-stamped connection announces its attach exactly once, HERE —
    // after authentication, version negotiation, and participant posture have
    // all admitted it — never on the verify alone, so a pass that verified but
    // failed a later check announces nothing and no detach can follow an
    // attach that never fired. The runtime stores the principal on the
    // connection record so the one close funnel fires the matching detach. A
    // principal the runtime cannot record is a connection whose detach could
    // never fire, so the handshake fails closed rather than attach silently.
    if let Some(principal) = state.pass_principal.as_ref() {
        if let Err(error) = runtime.attach_pass_principal(pid, principal) {
            tracing::warn!(
                %error,
                connection_pid = pid,
                "pass-stamped connection could not record its principal; closing"
            );
            return FrameAction::Close;
        }
    }

    // Publish handshake state only after authentication, version negotiation,
    // and participant posture have all succeeded. Every rejection above leaves
    // the pre-handshake state untouched.
    state.authenticated = true;
    state.negotiated_version = Some(selected_version);
    state.participant_session = participant_session;
    FrameAction::Respond(Frame::ConnectAck {
        flags: 0,
        selected_version,
        capabilities,
    })
}

pub(super) fn publish_response(
    pid: u64,
    services: &dyn ConnectionServices,
    negotiated_version: Option<ProtocolVersion>,
    stream_id: u32,
    channel: &str,
    envelope: &MessageEnvelope,
    idempotency_key: Option<&str>,
) -> FrameAction {
    if let Some(error) = reserved_namespace_refusal(channel) {
        return FrameAction::Respond(Frame::PublishError {
            flags: 0,
            stream_id,
            reason_code: SERVER_ERROR_CODE,
            message: Some(error.to_string()),
        });
    }
    // Admission BEFORE delegation. A roster refusal is decided here, by the
    // component holding the roster, and stamped with its own reason code at the
    // moment of the decision — so the code cannot disagree with the read that
    // produced it. Nothing is published against a refused channel: the service is
    // not called at all.
    if let Err(refusal) = services.admit_channel(ChannelOperation::Publish, channel) {
        return FrameAction::Respond(Frame::PublishError {
            flags: 0,
            stream_id,
            reason_code: refusal.reason_code(),
            message: Some(access_to_server_error(&refusal).to_string()),
        });
    }
    match services.publish(pid, channel, envelope, idempotency_key) {
        Ok(outcome) => FrameAction::Respond(Frame::PublishAck {
            // Set the genuine-delivery flag only when the publish was accepted by
            // at least one subscriber. The ack is always sent on success (the
            // backpressure contract is unchanged); the flag bit is the additive
            // delivery-ack signal the caller can observe.
            flags: if outcome.delivered {
                PUBLISH_DELIVERED_FLAG
            } else {
                0
            },
            stream_id,
            message_id: outcome.message_id,
            // The position rides the ack only on a connection that negotiated the
            // version carrying it; a 1.0 peer keeps the older ack, byte for byte.
            durable_position: outcome.durable_position.filter(|_| {
                negotiated_version.is_some_and(|version| version >= PUBLISH_ACK_POSITION_VERSION)
            }),
        }),
        // Admitted, then refused by the service. This keeps the undifferentiated
        // code and today's exact bytes even when the cause WAS the roster — a
        // quiesce that landed in the window between the admission above and this
        // call surfaces here, not as `0x0102`. Degraded, never lying: a roster
        // code is a reliable positive signal and never a complete one, and
        // recovering the "real" cause by a second roster read is the exact lie
        // the probe-before form exists to make impossible. An unresolved publish
        // alone carries its own code, chosen by the error's TYPE, never its text.
        Err(error) => FrameAction::Respond(Frame::PublishError {
            flags: 0,
            stream_id,
            reason_code: if matches!(error, ServerError::PublishUnresolved { .. }) {
                PUBLISH_UNRESOLVED_CODE
            } else {
                SERVER_ERROR_CODE
            },
            message: Some(error.to_string()),
        }),
    }
}

fn subscribe_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    stream_id: u32,
    channel: &str,
    accepted_schemas: &[ProtocolSchemaId],
    max_in_flight: u32,
) -> FrameAction {
    let limits = runtime.limits();
    let max_subscriptions = limits.max_subscriptions_per_connection;
    // §5 `max_subscriptions_per_connection`: refuse a subscription past the cap
    // with the subscription error channel (the same vocabulary an unsupported or
    // failed subscribe uses), before touching the services adapter so an over-cap
    // subscribe never spawns a subscriber process.
    if state.subscriptions.len() >= max_subscriptions {
        return FrameAction::Respond(Frame::SubscribeError {
            flags: 0,
            stream_id,
            reason_code: SERVER_ERROR_CODE,
            message: Some(
                ServerError::ConnectionCapReached {
                    operation: "subscribe".to_owned(),
                    cap: "max_subscriptions_per_connection",
                    limit: max_subscriptions,
                }
                .to_string(),
            ),
        });
    }
    // Admission BEFORE delegation, on the same grounds as `publish_response`.
    //
    // It sits AFTER the §5 per-connection subscription cap and BEFORE the inbox
    // budget is built. After the cap, because the cap is a statement about THIS
    // connection and the roster is a statement about the server: a connection
    // already at its cap is refused for that reason today, and moving the roster
    // ahead of it would change which of two true refusals an over-cap subscribe
    // to an absent channel receives. Before the budget, because
    // `get_or_insert_with` below MINTS the connection's shared inbox pool on
    // first use, and a refused frame must leave connection state exactly as it
    // found it.
    let services = runtime.services();
    if let Err(refusal) = services.admit_channel(ChannelOperation::Subscribe, channel) {
        return FrameAction::Respond(Frame::SubscribeError {
            flags: 0,
            stream_id,
            reason_code: refusal.reason_code(),
            message: Some(access_to_server_error(&refusal).to_string()),
        });
    }
    // R3 + §5: build the install spec CARRIED INTO subscribe, so the shared
    // connection byte budget, per-inbox fairness cap, and wake notifier are
    // installed on the inbox at construction — strictly BEFORE the registration
    // is published to the channel actor. There is no pre-install window: no
    // envelope can be admitted uncharged, past the depth cap, or without a wake.
    // The budget is created lazily on the first subscribe and shared across
    // every later subscription, so the 4 MiB is one connection-scoped pool. The
    // notifier captures the CONNECTION scheduler's `READY` enqueue handle here
    // (§1.2(2), Vesper advisory 3); under the busy loop the wake is redundant
    // (the every-slice pump still drains the inbox), so a missing waker —
    // scheduler-free unit tests — is harmless. PARK-FLIP: this is the wake that
    // replaces the delivery pump's every-slice assumption.
    let budget = state
        .inbox_budget
        .get_or_insert_with(|| {
            liminal::channel::ConnectionInboxBudget::new(limits.max_connection_inbox_bytes)
        })
        .clone();
    let notifier: Option<liminal::channel::InboxNotifier> = runtime.ready_waker(pid).map(|waker| {
        std::sync::Arc::new(move || {
            waker.fire();
        }) as liminal::channel::InboxNotifier
    });
    // A1 §2: the `Subscribe` frame's `max_in_flight` has been on the wire and
    // decoded (and non-zero-validated) all along, and was consumed nowhere.
    // THIS is where it becomes a bound. `max_buffer_depth` stays bus policy —
    // the client declares what it can process concurrently, not how much the
    // bus may hold for it — so it takes the library default rather than a
    // client-supplied number.
    //
    // A zero or unrepresentable value falls back to the library default rather
    // than refusing: the frame decoder already rejects zero, so this arm is
    // unreachable from a well-formed wire, and a defaulted window is a safer
    // answer than a window of zero (which would Reject every publish).
    //
    // AND IT IS CLAMPED. The declaration is a CLIENT's, and until it is clamped
    // nothing stops a client declaring a window so large that the A1 Reject
    // band sits ABOVE this connection's §5 depth cap — at which point the
    // terminal fairness shed fires first and a slow consumer loses its whole
    // subscription instead of pacing one message. `Frame::validate` refuses
    // only zero, so the wire cannot be relied on for this.
    //
    // `clamp_capacity_to_depth_cap` derives the bound from the two numbers it
    // is given, so the invariant follows the config: it is a control, not a
    // note. Bus policy (the buffer band) wins over the client's declaration,
    // which is §2's split.
    let capacity = usize::try_from(max_in_flight)
        .ok()
        .filter(|window| *window > 0)
        .map(|window| liminal::pressure::ConsumerCapacity {
            max_in_flight: window,
            max_buffer_depth: liminal::channel::DEFAULT_MAX_BUFFER_DEPTH,
        })
        .map(|declared| {
            liminal::channel::clamp_capacity_to_depth_cap(
                declared,
                limits.max_subscription_inbox_depth,
            )
        });
    let install = liminal::channel::InboxInstall {
        budget,
        depth_cap: limits.max_subscription_inbox_depth,
        notifier,
        capacity,
    };
    match crate::agents::admitted_services::AdmittedServices::new(
        pid,
        services,
        state.lys_session.as_deref(),
    )
    .subscribe(channel, accepted_schemas, Some(install))
    {
        Ok(mut subscription) => {
            // Record the client-chosen delivery stream so the pump can address
            // every `Deliver` to the stream the client is reading this subscription
            // on.
            subscription.set_stream_id(stream_id);
            // ACCESS-006 R3: the delivery pump's release check reads the
            // channel the subscriber was admitted on, so the connection stamps
            // it from the frame rather than trusting a services impl to.
            subscription.set_channel(channel.to_owned());
            if let Some(subscriber) = subscription.subscriber_pid() {
                runtime.receiver(pid, subscriber);
            }
            subscription.set_pressure_ledger_depth(limits.max_subscription_inbox_depth);
            let subscription_id = subscription.id();
            let selected_schema = subscription.selected_schema();
            state.subscriptions.insert(subscription_id, subscription);
            FrameAction::Respond(Frame::SubscribeAck {
                flags: 0,
                stream_id,
                subscription_id,
                selected_schema,
            })
        }
        // Admitted, then refused by the service — the same degraded arm as
        // `publish_response`'s, on the same grounds.
        Err(error) => FrameAction::Respond(Frame::SubscribeError {
            flags: 0,
            stream_id,
            reason_code: SERVER_ERROR_CODE,
            message: Some(error.to_string()),
        }),
    }
}

/// An `Unsubscribe` frame; a worker's last subscription to a line leaving
/// takes its subscribe stop off that line (SRV-012 R7).
fn unsubscribe_frame_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    stream_id: u32,
    subscription_id: u64,
) -> FrameAction {
    let line = state
        .subscriptions
        .get(&subscription_id)
        .filter(|_| state.worker_flows.is_some())
        .map(|subscription| subscription.channel().to_owned());
    let action = unsubscribe_response(runtime.services(), state, stream_id, subscription_id);
    let bit = flow_bit(FlowRole::Subscribes);
    if let Some(line) = line
        && !state
            .subscriptions
            .values()
            .any(|subscription| subscription.channel() == line)
        && let Some(flows) = state.worker_flows.as_mut()
        && let Some(known) = flows.get_mut(&line)
        && *known & bit != 0
    {
        *known &= !bit;
        if *known == 0 {
            flows.remove(&line);
        }
        runtime.flow(pid, &line, FlowRole::Subscribes, false);
    }
    action
}

fn unsubscribe_response(
    services: &dyn ConnectionServices,
    state: &mut ConnectionProcessState,
    stream_id: u32,
    subscription_id: u64,
) -> FrameAction {
    if let Some(subscription) = state.subscriptions.remove(&subscription_id) {
        // Drop the delivery-sequence counter and any held-back frame with the
        // subscription so a re-subscribe that reuses the id restarts clean at 1 and
        // never flushes a stale delivery.
        state.delivery_seqs.remove(&subscription_id);
        state.held_deliveries.remove(&subscription_id);
        // The wire stays silent about this failure on purpose. The server warns,
        // so the fault is not lost, but the client-visible contract for
        // `Unsubscribe` is removal from THIS connection's state — which the
        // `remove` calls above have already completed unconditionally. The
        // adapter-side teardown is the server's own bookkeeping; reporting its
        // failure would tell the client its subscription is still live when, as
        // far as this connection is concerned, it is not.
        if let Err(error) = services.unsubscribe(subscription) {
            tracing::warn!(subscription_id, %error, "liminal unsubscribe failed");
        }
        return FrameAction::NoResponse;
    }
    // No such subscription on this connection. Full mode keeps the idempotent no-op
    // (unsubscribing an unknown id is harmless). A capability-scoped adapter that
    // serves no channels never issued a subscription, so this frame targets an
    // operation the profile does not support: reject it explicitly rather than
    // silently accept it. There is no dedicated `UnsubscribeError` frame in the
    // vocabulary, so the closest honest fit — `SubscribeError`, the subscription
    // error channel — carries the rejection.
    if services.supports_channel_operations() {
        FrameAction::NoResponse
    } else {
        FrameAction::Respond(Frame::SubscribeError {
            flags: 0,
            stream_id,
            reason_code: SERVER_ERROR_CODE,
            message: Some(unsupported_by_front_door("unsubscribe")),
        })
    }
}

// Every `ConversationError` this function emits rides the REQUEST'S stream id
// (Sol round 2): a client that opened on stream 17 must see its typed refusal on
// stream 17 — a refusal on a hard-coded stream would leave the client's actual
// stream silent, turning the fail-closed refusals into a silent-timeout shape.
fn conversation_open(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    stream_id: u32,
    conversation_id: u64,
    subject: &str,
) -> FrameAction {
    // ACCESS-001 R2, `ConversationOpen` = Hot(Call, FrameSubject): decided
    // from the admitted pass before any duplicate, cap or actor question, so a
    // holder without `call` on the subject learns nothing else about it.
    let site_call = runtime.services().admit_site_call(
        state.lys_session.as_deref(),
        subject,
        unix_seconds_now().saturating_mul(1000),
    );
    match site_call {
        Err(error) => return conversation_error(stream_id, conversation_id, &error.to_string()),
        Ok(false)
            if !super::services::is_site_route(subject)
                && !crate::agents::binding::is_host_route(subject) =>
        {
            if let Some(refused) =
                lys_decision(runtime, state, subject, HotAction::Call, |message| {
                    Frame::ConversationError {
                        flags: 0,
                        stream_id,
                        conversation_id,
                        reason_code: SERVER_ERROR_CODE,
                        message: Some(message),
                    }
                })
            {
                return refused;
            }
        }
        Ok(_) => {}
    }
    // Duplicate open of a LIVE conversation id is refused fail-closed (review
    // ruling, round 1 item 3): an insert-replace would drop the old resource
    // without close/finalize (violating the D4 every-teardown-path-finalizes
    // discipline) and leave its pending/tombstone reply entries to FIFO-correlate
    // against the NEW instance's replies — cross-instance mis-correlation, the
    // corruption class the tombstone ruling exists to kill. Nothing sanctions
    // re-open-as-replace: the SDK explicitly guards against re-sending
    // `ConversationOpen` for an open id and calls a duplicate a defect
    // (`liminal-sdk/src/remote/tcp/connection.rs:48`). The remedy is named in the
    // error: close the conversation first, or use a fresh id.
    if state.conversations.contains_key(&conversation_id) {
        return conversation_error(
            stream_id,
            conversation_id,
            "conversation id is already open on this connection; close it before \
             reopening or use a fresh id",
        );
    }
    let max_conversations = runtime.limits().max_conversations_per_connection;
    // §5 `max_conversations_per_connection`: refuse opening past the cap before
    // constructing any supervised conversation actor. Duplicate ids were refused
    // above, so every admission here is a distinct live conversation.
    if state.conversations.len() >= max_conversations {
        return conversation_error(
            stream_id,
            conversation_id,
            &ServerError::ConnectionCapReached {
                operation: "conversation open".to_owned(),
                cap: "max_conversations_per_connection",
                limit: max_conversations,
            }
            .to_string(),
        );
    }
    match runtime
        .services()
        .open_conversation(conversation_id, subject)
    {
        Ok(conversation) => {
            // R1(vi)(a): install the reply-availability notifier PERMANENTLY at
            // conversation open (normative — not per-message). It fires the
            // connection's `READY` marker on the reply queue's empty→non-empty edge
            // and on terminal actor error, capturing the CONNECTION scheduler's
            // enqueue handle here at install. Under the busy loop the wake is
            // redundant (the slice polls pending conversations every slice); it is
            // the park-flip wake source. The notifier is cleared by the
            // conversation core at close/finalize, so a marker never fires after
            // teardown.
            let reply_notifier: std::sync::Arc<dyn Fn() + Send + Sync> =
                match runtime.ready_waker(pid) {
                    Some(waker) => std::sync::Arc::new(move || {
                        waker.fire();
                    }),
                    None => std::sync::Arc::new(|| {}),
                };
            // Ownership registration is mandatory even without a wake handle: the
            // busy-loop connection still polls the tagged reply queue every slice.
            conversation.register_reply_notifier(reply_notifier);
            state.conversations.insert(conversation_id, conversation);
            FrameAction::NoResponse
        }
        Err(error) => FrameAction::Respond(Frame::ConversationError {
            flags: 0,
            stream_id,
            conversation_id,
            reason_code: SERVER_ERROR_CODE,
            message: Some(error.to_string()),
        }),
    }
}

fn route_conversation_message(
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    request: Request,
    subject: &str,
    envelope: &MessageEnvelope,
) -> Option<FrameAction> {
    let Request {
        flags,
        stream_id,
        conversation_id,
    } = request;
    if let Some(action) = super::services::site_frame_response(super::services::SiteFrame {
        services: runtime.services(),
        session: state.lys_session.as_deref(),
        flags,
        stream_id,
        conversation_id,
        subject,
        envelope,
        at_ms: unix_seconds_now().saturating_mul(1000),
    }) {
        return Some(action);
    }
    // ACCESS-003 R1: a conversation on a service subject carries requests to
    // that service, decided and served on the admitted session; the message
    // never reaches the channel.
    // SRV-028 R3: a lifecycle verb's subject carries requests to the
    // services registry, decided live as deploy_service.
    if super::lifecycle_route::is_lifecycle(subject) {
        return Some(super::lifecycle_route::lifecycle_frame_response(
            runtime,
            state,
            flags,
            stream_id,
            conversation_id,
            subject,
            envelope,
        ));
    }
    if crate::services::broker::serves_subject(subject) {
        return Some(super::broker_route::broker_frame_response(
            runtime, state, request, subject, envelope,
        ));
    }
    if crate::services::service_of(subject).is_some() {
        return Some(super::service_route::service_frame_response(
            runtime,
            state,
            flags,
            stream_id,
            conversation_id,
            subject,
            envelope,
        ));
    }
    None
}

#[path = "apply/service_message.rs"]
mod service_message;
pub(super) use service_message::conversation_message;

fn conversation_error(stream_id: u32, conversation_id: u64, message: &str) -> FrameAction {
    FrameAction::Respond(Frame::ConversationError {
        flags: 0,
        stream_id,
        conversation_id,
        reason_code: SERVER_ERROR_CODE,
        message: Some(message.to_owned()),
    })
}

fn conversation_close(
    services: &dyn ConnectionServices,
    state: &mut ConnectionProcessState,
    stream_id: u32,
    conversation_id: u64,
) -> FrameAction {
    if let Some(conversation) = state.conversations.remove(&conversation_id) {
        // §1.2(3b) close sweep — one of only TWO sanctioned tombstone-reclamation
        // triggers (review round 1 item 2): synchronously remove EVERY pending and
        // tombstone entry for this conversation, IN the close transaction, before
        // the actor close/finalize below and before any same-id reopen can be
        // applied from the same buffer. Without this, a tombstone-only
        // conversation's entries linger to connection teardown (the lazy
        // service_pending_replies sweep only visits conversations with PENDING
        // entries) and could FIFO-correlate against a reopened id's replies.
        state.pending_replies.remove_conversation(conversation_id);
        if let Err(error) = services.close_conversation(conversation) {
            tracing::warn!(conversation_id, %error, "liminal conversation close failed");
        }
        return FrameAction::NoResponse;
    }
    // No such conversation on this connection. Full mode keeps the idempotent
    // no-op; the worker front door serves no conversations, so a close targets an
    // unsupported operation — reject it explicitly rather than swallow it.
    if services.supports_channel_operations() {
        FrameAction::NoResponse
    } else {
        conversation_error(
            stream_id,
            conversation_id,
            &unsupported_by_front_door("conversation close"),
        )
    }
}

#[cfg(test)]
#[path = "process_tests.rs"]
mod tests;

/// ACCESS-004: a worker's registration bound to the holder its `Connect`
/// verified.
#[cfg(test)]
#[path = "apply_worker_holder_tests.rs"]
mod worker_holder_tests;

/// ACCESS-001 R2: every hot wire route decided by its class from the admitted
/// Lys pass before its effect.
#[cfg(test)]
#[path = "apply_lys_routes_tests.rs"]
mod lys_routes_tests;

/// The wire leg's own instruments. A separate module from `tests` above because
/// those exercise the frame surface against a recording stand-in, and these have
/// to run against a REAL roster: the claim is that the typed code survives the
/// trip from the roster to the response frame, and a stand-in that answers the
/// admission question itself would be asserting on its own fixture.
#[cfg(test)]
#[path = "apply_admission_tests.rs"]
mod admission_tests;

/// A1 §2's capacity declaration, observed where the wire hands it over. Kept
/// out of `admission_tests` because it needs a spy over a real adapter rather
/// than the real adapter alone: the claim is about the `InboxInstall` the
/// server BUILDS, which nothing else on the path reports.
#[cfg(test)]
#[path = "apply_capacity_tests.rs"]
mod capacity_tests;

/// The publish reply's two additions: the unresolved publish's own reason code
/// and the durable position on the ack of a connection that negotiated it.
#[cfg(test)]
#[path = "apply_publish_outcome_tests.rs"]
mod publish_outcome_tests;

/// ACCESS-005: the protocol versions a server under a revocation policy
/// negotiates — the two it always does, plus the reason-bearing close's.
const REVOCATION_PROTOCOLS: [ProtocolVersion; 4] = [
    ProtocolVersion::new(1, 0),
    PUBLISH_ACK_POSITION_VERSION,
    liminal::protocol::DELIVER_MESSAGE_ID_VERSION,
    liminal::protocol::REVOCATION_CLOSE_VERSION,
];

/// The versions this server negotiates: unchanged without a revocation
/// policy, so every legacy and private session keeps its bytes.
fn supported_protocols(runtime: &ConnectionRuntime) -> &'static [ProtocolVersion] {
    if runtime.revocation().is_some() {
        &REVOCATION_PROTOCOLS
    } else {
        &SUPPORTED_PROTOCOLS
    }
}

/// `ConnectError` for a revocation refusal (ACCESS-005 R5): reason `0x0006`
/// (`AuthenticationFailure`) and the refusal's stable name as the whole
/// message, never any pass, holder, live-prefix or grant-chain bytes.
fn revocation_connect_refused(refusal: crate::auth_revocation::RevocationRefusal) -> FrameAction {
    let error = ProtocolError::AuthenticationFailure {
        message: Some(refusal.name().to_owned()),
    };
    FrameAction::RespondThenClose(Frame::ConnectError {
        flags: 0,
        reason_code: error.reason_code(),
        message: error.message().map(str::to_owned),
    })
}

/// The revocation fence at `Connect` (ACCESS-005 R3, R5): the peer must be
/// able to negotiate the reason-bearing close, then the authority verifies
/// the binding for `credential` held by `holder` and commits it in one
/// ordered transition. Nothing is attached or announced before this passes,
/// and the committed binding is set once on the connection. `Ok` without a
/// revocation policy, untouched.
fn revocation_connect(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    (min_version, max_version): (ProtocolVersion, ProtocolVersion),
    credential: &[u8],
    holder: &[u8],
) -> Result<(), Box<FrameAction>> {
    let Some(authority) = runtime.revocation() else {
        return Ok(());
    };
    if state.revocation.is_some() {
        // A second Connect never replaces the verified binding.
        return Err(Box::new(FrameAction::Close));
    }
    let closes_with_reason = negotiate_version(min_version, max_version, &REVOCATION_PROTOCOLS)
        .is_ok_and(|selected| selected >= liminal::protocol::REVOCATION_CLOSE_VERSION);
    if !closes_with_reason {
        return Err(Box::new(revocation_connect_refused(
            RevocationRefusal::ProtocolUnsupported,
        )));
    }
    let grants = authority
        .admit(pid, credential, holder)
        .map_err(|refusal| Box::new(revocation_connect_refused(refusal)))?;
    state.revocation_swept = grants.changes();
    state.revocation = Some(grants);
    Ok(())
}

/// The connection's own revocation sweep (ACCESS-005 R4): every subscription
/// and conversation whose right was withdrawn is retired through its
/// existing cleanup path and answered with a named terminal outcome. Runs
/// only after the rights changed; returns the frames to enqueue.
pub(super) fn retire_withdrawn_rights(
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
) -> Vec<Frame> {
    let Some(changes) = state
        .revocation
        .as_ref()
        .map(crate::auth_revocation::ConnectionGrants::changes)
    else {
        return Vec::new();
    };
    if changes == state.revocation_swept {
        return Vec::new();
    }
    let Some(grants) = state.revocation.clone() else {
        return Vec::new();
    };
    state.revocation_swept = changes;
    let services = runtime.services();
    let withdrawn: Vec<(u64, u32)> = state
        .subscriptions
        .iter()
        .filter(|(_, subscription)| !grants.permits(HotAction::Subscribe, subscription.channel()))
        .map(|(id, subscription)| (*id, subscription.stream_id()))
        .collect();
    let mut frames = Vec::with_capacity(withdrawn.len());
    for (subscription_id, stream_id) in withdrawn {
        unsubscribe_response(services, state, stream_id, subscription_id);
        frames.push(Frame::SubscribeError {
            flags: 0,
            stream_id,
            reason_code: 0x0201,
            message: Some(RevocationRefusal::GrantRevoked.name().to_owned()),
        });
    }
    let calls: Vec<u64> = state
        .conversations
        .iter()
        .filter(|(_, conversation)| !grants.permits(HotAction::Call, conversation.subject()))
        .map(|(id, _)| *id)
        .collect();
    for conversation_id in calls {
        // The conversation's stream is not retained per conversation, so its
        // terminal outcome is this named record and the existing close path.
        tracing::warn!(
            connection_pid = grants.pid(),
            conversation_id,
            reason = RevocationRefusal::GrantRevoked.name(),
            "conversation retired: its call right was revoked"
        );
        conversation_close(services, state, 0, conversation_id);
    }
    frames
}

/// ACCESS-005: the revocation fence at `Connect`, the hot refusals and the
/// withdrawn-rights sweep, against a real authority.
#[cfg(test)]
#[path = "apply_revocation_tests.rs"]
mod revocation_tests;

/// ACCESS-006 R1, R3: every protected admission and final data release
/// decided on the connection's verified subject.
#[cfg(test)]
#[path = "apply_membership_tests.rs"]
mod membership_tests;