liminal-server 0.19.0

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
//! 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 std::time::Instant;

use liminal::protocol::{
    CONVERSATION_REPLY_REQUESTED_FLAG, 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::services::{
    ChannelOperation, ConnectionServices, access_to_server_error, reserved_namespace_refusal,
};
use super::state::{ConnectionProcessState, FrameAction};
use super::supervisor::{ConnectionRuntime, PushReplyDisposition};
use crate::ServerError;
use crate::auth_pass::{PassVerifier, VerifiedHolder, VerifiedPass};
use crate::config::types::ServiceProfile;
use crate::console::FlowRole;
use crate::server::participant::{
    ConnectionFateClass, PARTICIPANT_CAPABILITY_BIT, ParticipantConnectionContext,
    ParticipantDispatch, ParticipantIngress, constant_time_eq, dispatch_generic_frame,
    encode_server_value, gate_generic_frame,
};

const SERVER_ERROR_CODE: u16 = 0xFFFF;
/// Protocol versions the server negotiates: 1.0, and the version whose ack
/// carries the durable position. A client offering only 1.0 still selects 1.0.
const SUPPORTED_PROTOCOLS: [ProtocolVersion; 2] =
    [ProtocolVersion::new(1, 0), PUBLISH_ACK_POSITION_VERSION];

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;
    }
    let services = runtime.services();
    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,
        } => conversation_message(
            services,
            state,
            flags,
            stream_id,
            conversation_id,
            &envelope,
        ),
        Frame::ConversationClose {
            stream_id,
            conversation_id,
            ..
        } => conversation_close(services, state, stream_id, conversation_id),
        Frame::PushReply {
            correlation_id,
            payload,
            ..
        } => push_reply_response(pid, runtime, correlation_id, payload),
        Frame::WorkerRegister { registration, .. } => {
            worker_register_frame_response(pid, runtime, state, registration)
        }
        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::Unknown { .. }
        | Frame::ConnectAck { .. }
        | Frame::ConnectError { .. }
        | Frame::SubscribeAck { .. }
        | Frame::SubscribeError { .. }
        | Frame::PublishAck { .. }
        | Frame::PublishError { .. }
        | Frame::ConversationError { .. }
        | Frame::Pong { .. }) => ignore_stray_inbound_frame(&frame),
    }
}

fn rejects_unauthenticated(
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    frame: &Frame,
) -> bool {
    (runtime.auth_token().is_some() || runtime.pass_verifier().is_some())
        && !state.authenticated
        && !permitted_before_auth(frame)
}

fn push_reply_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    correlation_id: u64,
    payload: Vec<u8>,
) -> FrameAction {
    // Resolving the one-shot slot completes the round trip without another frame.
    match runtime.resolve_push(pid, correlation_id, payload) {
        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"
        ),
    }
    FrameAction::NoResponse
}

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;
    }
    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::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 {
    // 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)) => {
            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
        }
    }
}

/// 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 {
    // 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 => {}
    }
    let action =
        worker_register_response(pid, runtime, registration, state.verified_holder.as_ref());
    if matches!(
        action,
        FrameAction::Respond(Frame::WorkerRegisterAck {
            outcome: WorkerRegisterOutcome::Accepted,
            ..
        })
    ) {
        state.worker_flows.get_or_insert_with(BTreeMap::new);
    }
    action
}

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::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.
fn pass_allows_channel(state: &ConnectionProcessState, channel: &str) -> bool {
    state
        .verified_holder
        .as_ref()
        .is_none_or(|holder| !holder.live().is_empty() && channel.starts_with(holder.live()))
}

fn publish_frame_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    stream_id: u32,
    channel: &str,
    envelope: &MessageEnvelope,
    idempotency_key: Option<&str>,
) -> FrameAction {
    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,
            runtime.services(),
            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 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}")),
        })
    }
}

fn connect_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &mut ConnectionProcessState,
    min_version: ProtocolVersion,
    max_version: ProtocolVersion,
    auth_token: &[u8],
) -> FrameAction {
    // The auth check runs before version negotiation: an unauthenticated peer learns
    // nothing about the negotiated protocol. When no token is configured the server
    // is open and this check is skipped entirely, keeping the handshake byte-identical
    // to the pre-auth behaviour.
    let bearer_matches = runtime
        .auth_token()
        .is_some_and(|expected| constant_time_eq(expected, auth_token));
    if !bearer_matches {
        if let Some(verifier) = runtime.pass_verifier() {
            match verifier.verify(auth_token) {
                Ok(VerifiedPass { principal, holder }) => {
                    runtime.pass_attached(pid, state.mount, holder.participant());
                    state.pass_principal = Some(principal);
                    state.verified_holder = Some(holder);
                }
                Err(failure) => {
                    let error = ProtocolError::AuthenticationFailure {
                        message: Some(format!(
                            "connection pass {} check failed",
                            failure.check_name()
                        )),
                    };
                    return FrameAction::RespondThenClose(Frame::ConnectError {
                        flags: 0,
                        reason_code: error.reason_code(),
                        message: error.message().map(str::to_owned),
                    });
                }
            }
        } else if runtime.auth_token().is_some() {
            let error = ProtocolError::AuthenticationFailure {
                message: Some("connection authentication token rejected".to_owned()),
            };
            return FrameAction::RespondThenClose(Frame::ConnectError {
                flags: 0,
                reason_code: error.reason_code(),
                message: error.message().map(str::to_owned),
            });
        }
    }
    let selected_version = match negotiate_version(min_version, max_version, &SUPPORTED_PROTOCOLS) {
        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,
    })
}

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 services.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);
            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 {
    // 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 conversation_message(
    services: &dyn ConnectionServices,
    state: &mut ConnectionProcessState,
    flags: u8,
    stream_id: u32,
    conversation_id: u64,
    envelope: &MessageEnvelope,
) -> FrameAction {
    // A capability-scoped adapter serves no conversations, so a conversation could
    // never have been opened: reject with a clear "not supported" message rather
    // than the misleading "not open" one. Full mode keeps the existing path.
    if !services.supports_channel_operations() {
        return conversation_error(
            stream_id,
            conversation_id,
            &unsupported_by_front_door("conversation messaging"),
        );
    }
    let Some(conversation) = state.conversations.get(&conversation_id) else {
        return conversation_error(
            stream_id,
            conversation_id,
            "conversation is not open on this connection",
        );
    };
    // Pre-existing fire-and-forget semantics: without the reply-requested flag the
    // message is forwarded and the server stays silent on success, exactly as
    // before. The reply leg is purely additive and only runs when the client
    // explicitly asked for a correlated reply on this frame.
    if flags & CONVERSATION_REPLY_REQUESTED_FLAG == 0 {
        if let Err(error) = services.conversation_message(conversation, envelope, None) {
            return conversation_error(stream_id, conversation_id, &error.to_string());
        }
        return FrameAction::NoResponse;
    }
    // R1(vi) (§1.2(3b)) — THE LIVE BEHAVIOR CHANGE. The old path BLOCKED the
    // connection slice for up to 5 s draining the participant's reply
    // (`receive_reply`); now the reply-requested operation rides the bounded
    // per-connection pending-reply table and the slice returns immediately.
    //
    // ADMISSION COMES FIRST (cap-before-mutation, review round 1 item 1): the
    // reservation is made BEFORE the message is forwarded, so a cap-refused
    // request — including the tombstone self-wedge — NEVER reaches the
    // participant. A refused-but-forwarded request would produce an orphan
    // reply with no table entry, which could later FIFO-match a younger
    // admitted operation on the same conversation: wrong-reply delivery, the
    // corruption class the tombstone ruling kills. If the forward itself fails
    // after admission, the exact reservation is rolled back (no reply can ever
    // arrive for a message the participant never received, so the entry must
    // not linger to time out into a spurious tombstone).
    let op_id = match state
        .pending_replies
        .admit(conversation_id, stream_id, Instant::now())
    {
        Ok(op_id) => op_id,
        Err(error) => {
            return FrameAction::Respond(super::pending_reply::cap_refusal_frame(
                stream_id,
                conversation_id,
                &error,
            ));
        }
    };
    if let Err(error) = services.conversation_message(conversation, envelope, Some(op_id)) {
        state.pending_replies.cancel(op_id);
        return conversation_error(stream_id, conversation_id, &error.to_string());
    }
    FrameAction::NoResponse
}

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;

/// 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;