daaki-imap 0.2.0

An IMAP4rev1/IMAP4rev2 async client library
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
//! Driver task. Owns the `WireReader` and `ProtocolState` exclusively.
//! The public API submits commands over mpsc and awaits oneshot replies.
//!
//! The driver task is the only code that touches the wire reader and
//! protocol state directly. All command execution flows through
//! `run_one_command`, which runs the dispatch loop on decomposed
//! primitives (`WireReader`, `ProtocolState`, tag generator,
//! `DriverEventSink`).

use std::sync::Arc;

use bytes::BytesMut;
use tokio::sync::{mpsc, oneshot, watch};
use tracing::{debug, trace, warn};

use crate::codec::classification::{self, ClassificationContext, SolicitationRule};
use crate::codec::encode::{encode_command, EncodeOptions, LiteralMode};
use crate::error::Error;
use crate::types::response::{Capability, ResponseCode, StatusKind, UntaggedResponse};
use crate::types::validated::MailboxName;
use crate::types::Command;

use super::dispatch::{
    CapabilityConsumer, Consumer, ConsumerContext, ContinuationConsumer, ContinuationReply,
    Finalized, TaggedOkConsumer,
};
use super::typed_event::TypedEvent;
use super::NotifyFlags;

/// Per-command result type for pipelined batch execution.
///
/// Each element corresponds to one command in the pipeline: `Ok` holds
/// the consumer's type-erased output, `Err` holds a per-command error
/// (e.g., server `NO` response).
pub(super) type PipelineResults = Vec<Result<Box<dyn std::any::Any + Send>, Error>>;

/// A command submitted to the driver task over `cmd_tx`.
///
/// Either a regular protocol command (with a type-erased consumer for
/// response routing) or a stream upgrade (STARTTLS / COMPRESS) that
/// the driver handles atomically without a consumer.
pub(super) enum DriverCommand {
    /// Regular command — the driver encodes/sends it and routes responses
    /// to the consumer via the classification-based dispatcher.
    Run {
        payload: DriverCommandPayload,
        consumer: DriverConsumer,
        result_tx: oneshot::Sender<Result<Box<dyn std::any::Any + Send>, Error>>,
    },
    /// Stream upgrade — the driver sends the protocol command, awaits
    /// the tagged OK, then atomically swaps the stream using the
    /// `Poisoned` sentinel (I9, I10). No consumer needed.
    Upgrade {
        payload: UpgradePayload,
        result_tx: oneshot::Sender<Result<Box<dyn std::any::Any + Send>, Error>>,
    },
    /// Pipelined batch — multiple commands submitted in one write,
    /// responses routed to each consumer by tag.
    Pipeline {
        /// Commands to encode and send as a batch.
        commands: Vec<Command>,
        /// Per-command consumers, parallel to `commands`.
        consumers: Vec<Box<dyn ConsumerErased>>,
        /// Channel for the per-command results.
        result_tx: oneshot::Sender<Result<PipelineResults, Error>>,
    },
    /// Set TCP keepalive socket options (OS-level, not IMAP protocol).
    ///
    /// Delegates to `WireReader::set_keepalive` which sets `setsockopt(2)`
    /// options on the underlying TCP socket. No data is sent on the wire.
    SetKeepalive {
        /// Keepalive configuration to apply.
        keepalive: super::TcpKeepalive,
        /// Channel for the result.
        result_tx: oneshot::Sender<Result<(), Error>>,
    },
    /// IDLE session — the driver enters IDLE mode on the wire, reads
    /// events and publishes them via the event sink, and exits when
    /// `done_rx` fires or the server terminates IDLE (RFC 2177).
    Idle {
        /// Handle signals DONE via this channel.
        done_rx: oneshot::Receiver<()>,
        /// Driver reports how IDLE ended.
        result_tx: oneshot::Sender<Result<IdleTermination, Error>>,
    },
}

/// How an IDLE session ended (RFC 2177 Section 3).
#[derive(Debug)]
pub(super) enum IdleTermination {
    /// Client sent DONE (normal exit).
    ClientDone,
    /// Server sent tagged OK (server-terminated IDLE).
    ServerTerminated,
}

/// Payload for a [`DriverCommand::Run`].
///
/// Standard commands are encoded by the driver via [`encode_command`].
/// Pre-built commands (APPEND/MULTIAPPEND) carry wire bytes built by
/// the handle side, which the driver sends with literal synchronization.
pub(super) enum DriverCommandPayload {
    /// Standard IMAP command — encoded and sent by the driver.
    Standard(Command),
    /// Pre-built wire bytes (APPEND / MULTIAPPEND).
    ///
    /// The handle builds the complete wire bytes (including the tag) and
    /// provides the tag separately so the driver can match the tagged
    /// response. The driver sends the bytes with literal synchronization
    /// and runs the response classification loop.
    PreBuilt {
        /// Complete wire bytes to send, including the tag prefix.
        wire_bytes: BytesMut,
        /// The tag embedded in `wire_bytes`, used for response matching.
        tag: String,
        /// Command kind for response classification.
        cmd_kind: crate::types::CommandKind,
        /// Optional mailbox target for classification context.
        cmd_target: Option<MailboxName>,
    },
}

/// Payload for a [`DriverCommand::Upgrade`].
///
/// Stream upgrades are handled atomically by the driver task using the
/// `Poisoned` sentinel pattern (I9, I10). The driver sends the protocol
/// command (STARTTLS / COMPRESS), awaits the tagged OK, then swaps the
/// stream without any `.await` between the buffer check and the swap.
pub(super) enum UpgradePayload {
    /// STARTTLS upgrade (RFC 3501 Section 6.2.1 / RFC 9051 Section 6.2.1).
    ///
    /// The driver sends STARTTLS, awaits OK, verifies the buffer is empty,
    /// mem-replaces the stream with `Poisoned`, performs the TLS handshake,
    /// and installs a fresh `WireReader` on the TLS stream. Capabilities
    /// are re-fetched after the upgrade.
    StartTls {
        /// TLS configuration for the handshake.
        tls_config: Arc<rustls::ClientConfig>,
        /// Server name for TLS SNI and certificate verification.
        server_name: rustls_pki_types::ServerName<'static>,
    },
    /// COMPRESS=DEFLATE upgrade (RFC 4978).
    ///
    /// The driver sends COMPRESS, awaits OK, takes remaining buffer bytes
    /// (already compressed), wraps the stream in a `CompressedStream`,
    /// and installs a fresh `WireReader`.
    Compress,
}

/// Object-safe wrapper for [`Consumer`] that erases the `Output` type.
///
/// The blanket impl below bridges any `Consumer` whose `Output` is
/// `Send + 'static` into this trait by boxing the output.
pub(super) trait ConsumerErased: Send {
    /// Forwards to [`Consumer::on_response`].
    fn on_response(
        &mut self,
        resp: UntaggedResponse,
        notify_snapshot: NotifyFlags,
        ctx: &ConsumerContext,
    );

    /// Forwards to [`Consumer::finalize`], boxing the output.
    fn finalize_erased(
        self: Box<Self>,
        tagged: crate::types::response::TaggedResponse,
        ctx: &ConsumerContext,
    ) -> Result<Finalized<Box<dyn std::any::Any + Send>>, Error>;
}

/// Blanket impl that erases `C::Output` to `Box<dyn Any + Send>`.
impl<C: Consumer + 'static> ConsumerErased for C
where
    C::Output: 'static,
{
    fn on_response(
        &mut self,
        resp: UntaggedResponse,
        notify_snapshot: NotifyFlags,
        ctx: &ConsumerContext,
    ) {
        <C as Consumer>::on_response(self, resp, notify_snapshot, ctx);
    }

    fn finalize_erased(
        self: Box<Self>,
        tagged: crate::types::response::TaggedResponse,
        ctx: &ConsumerContext,
    ) -> Result<Finalized<Box<dyn std::any::Any + Send>>, Error> {
        let finalized = <C as Consumer>::finalize(self, tagged, ctx)?;
        Ok(Finalized {
            output: Box::new(finalized.output) as Box<dyn std::any::Any + Send>,
            reclassified_as_events: finalized.reclassified_as_events,
        })
    }
}

/// Object-safe wrapper for [`ContinuationConsumer`] that extends
/// [`ConsumerErased`] with continuation handling.
///
/// Used by AUTHENTICATE and future multi-round SASL commands that
/// expect `+` continuations during the response loop.
pub(super) trait ContinuationConsumerErased: ConsumerErased {
    /// Forwards to [`ContinuationConsumer::on_continuation`].
    fn on_continuation_erased(
        &mut self,
        cont: crate::types::response::ContinuationRequest,
        ctx: &ConsumerContext,
    ) -> Result<ContinuationReply, Error>;
}

/// Blanket impl that bridges any [`ContinuationConsumer`] into
/// [`ContinuationConsumerErased`].
impl<C: ContinuationConsumer + 'static> ContinuationConsumerErased for C
where
    C::Output: 'static,
{
    fn on_continuation_erased(
        &mut self,
        cont: crate::types::response::ContinuationRequest,
        ctx: &ConsumerContext,
    ) -> Result<ContinuationReply, Error> {
        <C as ContinuationConsumer>::on_continuation(self, cont, ctx)
    }
}

/// Type-erased consumer submitted to the driver task.
///
/// Either a regular consumer (errors on unexpected `+`) or a
/// continuation-aware consumer (routes `+` to `on_continuation`).
pub(super) enum DriverConsumer {
    /// Regular consumer — unexpected continuations are a protocol error.
    Regular(Box<dyn ConsumerErased>),
    /// Continuation consumer — `+` responses are routed to the
    /// consumer's `on_continuation` handler (AUTHENTICATE, SASL).
    WithContinuations(Box<dyn ContinuationConsumerErased>),
}

impl DriverConsumer {
    /// Forwards to [`ConsumerErased::on_response`].
    fn on_response(
        &mut self,
        resp: UntaggedResponse,
        notify_snapshot: NotifyFlags,
        ctx: &ConsumerContext,
    ) {
        match self {
            Self::Regular(c) => c.on_response(resp, notify_snapshot, ctx),
            Self::WithContinuations(c) => c.on_response(resp, notify_snapshot, ctx),
        }
    }

    /// Forwards to [`ConsumerErased::finalize_erased`].
    fn finalize_erased(
        self,
        tagged: crate::types::response::TaggedResponse,
        ctx: &ConsumerContext,
    ) -> Result<Finalized<Box<dyn std::any::Any + Send>>, Error> {
        match self {
            Self::Regular(c) => c.finalize_erased(tagged, ctx),
            Self::WithContinuations(c) => c.finalize_erased(tagged, ctx),
        }
    }

    /// Handle a `+` continuation. Returns `Err` for regular consumers
    /// (unexpected continuation is a protocol error per RFC 3501 §7.5).
    fn on_continuation(
        &mut self,
        cont: crate::types::response::ContinuationRequest,
        ctx: &ConsumerContext,
    ) -> Result<ContinuationReply, Error> {
        match self {
            Self::Regular(_) => Err(Error::Protocol(
                "unexpected continuation during command that does not expect one".into(),
            )),
            Self::WithContinuations(c) => c.on_continuation_erased(cont, ctx),
        }
    }
}

/// Read-only snapshot of connection state published by the driver
/// via `watch::Sender`.
///
/// Holds session state, capabilities, notify flags, selected mailbox,
/// and enabled extensions (RFC 3501 §3, §7.2.1; RFC 5161 §3.2;
/// RFC 5465 §5.1–5.8).
#[derive(Debug, Clone)]
pub(super) struct ConnectionStateSnapshot {
    /// Current session state (RFC 3501 §3).
    pub session_state: super::SessionState,
    /// Cached server capabilities (RFC 3501 §7.2.1).
    pub capabilities: Vec<Capability>,
    /// Successfully `ENABLE`d extensions (RFC 5161 §3.2).
    pub enabled: Vec<String>,
}

impl Default for ConnectionStateSnapshot {
    fn default() -> Self {
        Self {
            session_state: super::SessionState::NotAuthenticated,
            capabilities: Vec::new(),
            enabled: Vec::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// Driver task body
// ---------------------------------------------------------------------------

/// Driver-task body. Owns the wire reader, protocol state, and tag generator.
///
/// Receives `DriverCommand`s from the mpsc, runs each command using
/// the classification-based dispatch loop, and publishes events via
/// [`DriverEventSink`](event_sink::DriverEventSink). Publishes state
/// snapshots via `watch::Sender` after every command.
///
/// The caller (typically `ImapConnection::connect`) creates the wire
/// reader and protocol state, reads the greeting, fetches initial
/// capabilities, and then passes the pre-initialized components here.
pub(super) async fn driver_task(
    mut wire_reader: super::wire::WireReader,
    mut state: super::state::ProtocolState,
    mut tag_gen: super::tag::TagGenerator,
    mut cmd_rx: mpsc::Receiver<DriverCommand>,
    state_tx: watch::Sender<ConnectionStateSnapshot>,
    mut event_sink: event_sink::DriverEventSink,
) {
    loop {
        // Opportunistic drain of pending critical events (D7).
        // Ignore CallerGone — the cmd_rx.recv() below will also
        // observe the caller being gone via channel close.
        let _ = event_sink.drain_pending_nonblocking();

        tokio::select! {
            biased;
            maybe_cmd = cmd_rx.recv() => {
                let Some(cmd) = maybe_cmd else { break; };
                match cmd {
                    DriverCommand::Run { payload, consumer, result_tx } => {
                        let result = match payload {
                            DriverCommandPayload::Standard(command) => {
                                run_one_command(
                                    &mut wire_reader,
                                    &mut state,
                                    &mut tag_gen,
                                    &mut event_sink,
                                    command,
                                    consumer,
                                ).await
                            }
                            DriverCommandPayload::PreBuilt {
                                wire_bytes, tag, cmd_kind, cmd_target,
                            } => {
                                run_prebuilt_command(
                                    &mut wire_reader,
                                    &mut state,
                                    &mut event_sink,
                                    wire_bytes,
                                    &tag,
                                    cmd_kind,
                                    cmd_target,
                                    consumer,
                                ).await
                            }
                        };
                        let _ = result_tx.send(result);
                    }
                    DriverCommand::Upgrade { payload, result_tx } => {
                        let result = run_upgrade(
                            &mut wire_reader,
                            &mut state,
                            &mut tag_gen,
                            &mut event_sink,
                            payload,
                        ).await;
                        let _ = result_tx.send(result.map(|()| {
                            Box::new(()) as Box<dyn std::any::Any + Send>
                        }));
                    }
                    DriverCommand::Pipeline { commands, consumers, result_tx } => {
                        let result = run_pipeline(
                            &mut wire_reader,
                            &mut state,
                            &mut tag_gen,
                            &mut event_sink,
                            commands,
                            consumers,
                        ).await;
                        let _ = result_tx.send(result);
                    }
                    DriverCommand::SetKeepalive { keepalive, result_tx } => {
                        let result = wire_reader.set_keepalive(&keepalive);
                        let _ = result_tx.send(result);
                        // No protocol state changed — skip snapshot publish.
                        continue;
                    }
                    DriverCommand::Idle { done_rx, result_tx } => {
                        let result = run_idle(
                            &mut wire_reader,
                            &mut state,
                            &mut tag_gen,
                            &mut event_sink,
                            done_rx,
                        ).await;
                        let _ = result_tx.send(result);
                    }
                }
                let _ = state_tx.send_replace(state.snapshot());

                // RFC 3501 §3.4: once the session reaches Logout state
                // (either via BYE or tagged OK for LOGOUT), the
                // connection is closing. Exit the driver loop so
                // cmd_rx is dropped and subsequent submit calls
                // observe DriverGone instead of hanging.
                if state.session_state() == super::SessionState::Logout {
                    break;
                }
            }
        }
    }

    // Graceful shutdown: send LOGOUT if still authenticated.
    // Best-effort; ignore errors.
    let _ = logout_best_effort(&mut wire_reader, &mut state, &mut tag_gen).await;
}

// ---------------------------------------------------------------------------
// Command execution
// ---------------------------------------------------------------------------

/// Execute a single command through the classification-based dispatcher.
///
/// Encodes and sends the command (handling literal synchronization
/// per RFC 3501 §4.3),
/// reads responses in a loop, classifies each untagged response via
/// [`classify`](crate::codec::classification::classify), and routes it
/// to either the consumer (solicited / ambiguous) or the event sink
/// (unsolicited / impossible). Errors on unexpected continuations
/// (RFC 3501 §7.5).
pub(in crate::connection) async fn run_one_command(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    tag_gen: &mut super::tag::TagGenerator,
    event_sink: &mut event_sink::DriverEventSink,
    cmd: Command,
    mut consumer: DriverConsumer,
) -> Result<Box<dyn std::any::Any + Send>, Error> {
    let cmd_kind = cmd.kind();
    let cmd_target: Option<MailboxName> = cmd.mailbox_target().cloned();

    // RFC 3501 §6.1.3: tell apply_tagged to transition to Logout on
    // the tagged OK. Must be set before the dispatch loop so the
    // side-effect handler sees it when the tagged response arrives.
    if matches!(cmd, Command::Logout) {
        state.set_in_logout(true);
    }

    // RFC 3501 §6.2.2, §6.2.3: tell apply_tagged to transition to
    // Authenticated on the tagged OK for LOGIN or AUTHENTICATE.
    if matches!(cmd, Command::Login { .. } | Command::Authenticate { .. }) {
        state.set_in_auth(true);
    }

    // RFC 3501 §6.3.1–§6.3.2: tell apply_tagged to transition to
    // Selected on tagged OK, or Authenticated on tagged NO, for
    // SELECT or EXAMINE.
    if matches!(cmd, Command::Select { .. } | Command::Examine { .. }) {
        state.set_in_select(cmd_target.clone());
    }

    // RFC 3501 §6.4.2, RFC 3691 §3, RFC 9051 §6.4.2: tell apply_tagged
    // to transition to Authenticated on tagged OK for CLOSE or UNSELECT.
    if matches!(cmd, Command::Close | Command::Unselect) {
        state.set_in_close(true);
    }

    // RFC 8437 §2: tell apply_tagged to transition to NotAuthenticated
    // on tagged OK for UNAUTHENTICATE.
    if matches!(cmd, Command::Unauthenticate) {
        state.set_in_unauthenticate(true);
    }

    // RFC 5465 §3: tell apply_tagged to update NOTIFY per-type flags
    // on tagged OK. NOTIFY SET computes flags from the registration
    // params; NOTIFY NONE resets to default (no notifications).
    if let Command::NotifySet(ref params) = cmd {
        let (list, status, metadata) = super::extensions::compute_notify_flags(params);
        state.set_in_notify_set(Some(super::NotifyFlags {
            list,
            status,
            metadata,
        }));
    }
    if matches!(cmd, Command::NotifyNone) {
        state.set_in_notify_set(Some(super::NotifyFlags::default()));
    }

    // Encode, tag, and send the command (handles literal sync).
    let tag = send_command_on_wire(wire_reader, state, tag_gen, event_sink, &cmd).await?;

    loop {
        let notify_before = state.notify();
        let utf8 = utf8_mode(state);
        let resp = wire_reader.read_one(utf8).await?;
        let _digest = state.apply_side_effects(&resp);

        match resp {
            crate::types::Response::Tagged(t) if t.tag == tag => {
                // (I13): emit alert/notification overflow from
                // tagged response codes before finalization.
                emit_tagged_response_code_events(&t, event_sink);
                let ctx = build_consumer_context(state, cmd_target.as_ref(), &tag);
                let finalized = consumer.finalize_erased(t, &ctx)?;
                // Re-emit any responses the consumer marked as events.
                // Skip those whose critical code (ALERT/NOTIFICATIONOVERFLOW)
                // was already emitted in the pre-classification pass
                // — re-emitting would double-deliver the alert.
                for resp in finalized.reclassified_as_events {
                    if !has_critical_response_code(&resp) {
                        let _ = event_sink.emit(resp.into());
                    }
                }
                return Ok(finalized.output);
            }
            crate::types::Response::Tagged(t) => {
                return Err(Error::Protocol(format!(
                    "unexpected tag {:?} (expected {:?})",
                    t.tag, tag,
                )));
            }
            crate::types::Response::Untagged(u) => {
                // (I13): emit alert/notification overflow before
                // classification so they reach the event queue even
                // when the response is routed to a consumer.
                let code_emitted = emit_untagged_response_code_events(&u, event_sink);

                let class_ctx = ClassificationContext {
                    notify: notify_before,
                    command_target: cmd_target.as_ref(),
                };
                let rule = classification::classify(cmd_kind, &u, &class_ctx);
                match rule {
                    SolicitationRule::OnlySolicited | SolicitationRule::Either => {
                        let ctx = build_consumer_context(state, cmd_target.as_ref(), &tag);
                        consumer.on_response(*u, notify_before, &ctx);
                    }
                    SolicitationRule::OnlyUnsolicited | SolicitationRule::Impossible => {
                        // Skip event_sink.emit for responses whose
                        // critical content (ALERT / NOTIFICATIONOVERFLOW)
                        // was already emitted above — avoid double-emit.
                        if !code_emitted {
                            let _ = event_sink.emit((*u).into());
                        }
                    }
                }
            }
            crate::types::Response::Continuation(c) => {
                // Route to the consumer's continuation handler if
                // supported (RFC 3501 §7.5). Regular consumers error.
                let ctx = build_consumer_context(state, cmd_target.as_ref(), &tag);
                let ContinuationReply::Write(bytes) = consumer.on_continuation(c, &ctx)?;
                wire_reader.write_all(&bytes).await?;
            }
            crate::types::Response::Greeting(_) => {
                return Err(Error::Protocol("unexpected greeting mid-command".into()));
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Pre-built command execution (APPEND / MULTIAPPEND)
// ---------------------------------------------------------------------------

/// Execute a pre-built command whose wire bytes were constructed by the
/// handle side.
///
/// Sends the pre-built bytes using [`send_with_literal_sync`] (which
/// handles synchronizing literal boundaries per RFC 3501 §4.3), then
/// runs the same classification-based response loop as
/// [`run_one_command`].
///
/// APPEND and MULTIAPPEND use this path because their literal encoding
/// is handled by the handle side rather than by [`encode_command`].
#[allow(clippy::too_many_arguments)]
pub(in crate::connection) async fn run_prebuilt_command(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    event_sink: &mut event_sink::DriverEventSink,
    wire_bytes: BytesMut,
    tag: &str,
    cmd_kind: crate::types::CommandKind,
    cmd_target: Option<MailboxName>,
    mut consumer: DriverConsumer,
) -> Result<Box<dyn std::any::Any + Send>, Error> {
    trace!(tag, ?cmd_kind, "driver: sending pre-built command");

    // Send pre-built bytes with literal synchronization.
    send_with_literal_sync(wire_reader, state, event_sink, &wire_bytes).await?;

    // Response classification loop — identical to run_one_command.
    loop {
        let notify_before = state.notify();
        let utf8 = utf8_mode(state);
        let resp = wire_reader.read_one(utf8).await?;
        let _digest = state.apply_side_effects(&resp);

        match resp {
            crate::types::Response::Tagged(t) if t.tag == tag => {
                emit_tagged_response_code_events(&t, event_sink);
                let ctx = build_consumer_context(state, cmd_target.as_ref(), tag);
                let finalized = consumer.finalize_erased(t, &ctx)?;
                for resp in finalized.reclassified_as_events {
                    if !has_critical_response_code(&resp) {
                        let _ = event_sink.emit(resp.into());
                    }
                }
                return Ok(finalized.output);
            }
            crate::types::Response::Tagged(t) => {
                return Err(Error::Protocol(format!(
                    "unexpected tag {:?} (expected {:?})",
                    t.tag, tag,
                )));
            }
            crate::types::Response::Untagged(u) => {
                let code_emitted = emit_untagged_response_code_events(&u, event_sink);

                let class_ctx = ClassificationContext {
                    notify: notify_before,
                    command_target: cmd_target.as_ref(),
                };
                let rule = classification::classify(cmd_kind, &u, &class_ctx);
                match rule {
                    SolicitationRule::OnlySolicited | SolicitationRule::Either => {
                        let ctx = build_consumer_context(state, cmd_target.as_ref(), tag);
                        consumer.on_response(*u, notify_before, &ctx);
                    }
                    SolicitationRule::OnlyUnsolicited | SolicitationRule::Impossible => {
                        if !code_emitted {
                            let _ = event_sink.emit((*u).into());
                        }
                    }
                }
            }
            crate::types::Response::Continuation(_) => {
                // APPEND/MULTIAPPEND should not receive continuations
                // after all bytes have been sent. Error per RFC 3501 §7.5.
                return Err(Error::Protocol(
                    "unexpected continuation after pre-built command fully sent".into(),
                ));
            }
            crate::types::Response::Greeting(_) => {
                return Err(Error::Protocol("unexpected greeting mid-command".into()));
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Pipeline sub-batch grouping
// ---------------------------------------------------------------------------

/// A sub-batch entry: `(original_index, command, consumer)`.
type SubBatchEntry = (usize, Command, Box<dyn ConsumerErased>);

/// Group commands into sub-batches where each sub-batch contains at most
/// one command per [`CommandKind`](crate::types::CommandKind).
///
/// RFC 3501 §5.5: when multiple commands of the same kind are pipelined,
/// their untagged responses may interleave and the head-consumer routing
/// heuristic cannot disambiguate which consumer owns which response. By
/// splitting duplicate kinds into separate sub-batches executed
/// sequentially, each batch is guaranteed to have unique kinds and
/// head-consumer routing is correct.
///
/// Each entry in the returned sub-batches carries its original index in
/// the input `commands` vec for result reassembly.
fn group_into_sub_batches(
    commands: Vec<Command>,
    consumers: Vec<Box<dyn ConsumerErased>>,
) -> Vec<Vec<SubBatchEntry>> {
    let mut sub_batches: Vec<(
        std::collections::HashSet<crate::types::CommandKind>,
        Vec<SubBatchEntry>,
    )> = vec![(std::collections::HashSet::new(), Vec::new())];

    // Tracks the highest batch index assigned so far. Commands are never
    // placed in a batch before max_batch, preserving their original order
    // across sub-batches.
    let mut max_batch: usize = 0;

    for (original_idx, (cmd, consumer)) in
        commands.into_iter().zip(consumers.into_iter()).enumerate()
    {
        let kind = cmd.kind();
        // Find the first sub-batch at or after max_batch that doesn't
        // already have this kind. The max_batch constraint ensures
        // commands are never placed in a batch before any preceding
        // command, preserving original pipeline order across sub-batches.
        let batch_idx = sub_batches
            .iter()
            .enumerate()
            .skip(max_batch)
            .find_map(|(i, (kinds_seen, _))| (!kinds_seen.contains(&kind)).then_some(i));
        let batch_idx = if let Some(i) = batch_idx {
            i
        } else {
            sub_batches.push((std::collections::HashSet::new(), Vec::new()));
            sub_batches.len() - 1
        };
        sub_batches[batch_idx].0.insert(kind);
        max_batch = batch_idx;
        sub_batches[batch_idx].1.push((original_idx, cmd, consumer));
    }

    sub_batches
        .into_iter()
        .map(|(_, entries)| entries)
        .collect()
}

// ---------------------------------------------------------------------------
// Pipeline execution
// ---------------------------------------------------------------------------

/// Execute a batch of pipelined commands, splitting into sub-batches
/// when duplicate [`CommandKind`]s are present.
///
/// RFC 3501 §5.5: clients may send multiple commands without waiting for
/// a response, but untagged responses may interleave and the head-consumer
/// routing heuristic cannot disambiguate when two consumers share the same
/// `CommandKind`. This function groups commands into sub-batches where each
/// sub-batch contains at most one command per `CommandKind`, then executes
/// each sub-batch via [`run_pipeline_batch`]. Results are reassembled in
/// original command order.
///
/// When all commands have unique kinds (the common case), only one
/// sub-batch is created and the function delegates directly without
/// grouping overhead.
async fn run_pipeline(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    tag_gen: &mut super::tag::TagGenerator,
    event_sink: &mut event_sink::DriverEventSink,
    commands: Vec<Command>,
    consumers: Vec<Box<dyn ConsumerErased>>,
) -> Result<PipelineResults, Error> {
    let count = commands.len();
    if count == 0 {
        return Ok(Vec::new());
    }

    // Check whether all commands have unique kinds. If so, skip the
    // grouping overhead and delegate directly to run_pipeline_batch.
    let has_duplicates = {
        let mut seen = std::collections::HashSet::with_capacity(count);
        commands.iter().any(|cmd| !seen.insert(cmd.kind()))
    };

    if !has_duplicates {
        // Fast path — all kinds unique, single batch is safe.
        return run_pipeline_batch(wire_reader, state, tag_gen, event_sink, commands, consumers)
            .await;
    }

    let sub_batches = group_into_sub_batches(commands, consumers);

    let num_batches = sub_batches.len();
    trace!(
        count,
        num_batches,
        "driver: splitting pipeline into sub-batches"
    );

    // Pre-allocate results vec indexed by original command position.
    let mut all_results: Vec<Option<Result<Box<dyn std::any::Any + Send>, Error>>> =
        (0..count).map(|_| None).collect();

    // Execute each sub-batch sequentially.
    for entries in sub_batches {
        let original_indices: Vec<usize> = entries.iter().map(|(idx, _, _)| *idx).collect();
        let (batch_cmds, batch_consumers): (Vec<Command>, Vec<Box<dyn ConsumerErased>>) = entries
            .into_iter()
            .map(|(_, cmd, cons)| (cmd, cons))
            .unzip();

        let batch_results = run_pipeline_batch(
            wire_reader,
            state,
            tag_gen,
            event_sink,
            batch_cmds,
            batch_consumers,
        )
        .await?;

        // Place batch results at their original indices.
        for (batch_pos, result) in batch_results.into_iter().enumerate() {
            all_results[original_indices[batch_pos]] = Some(result);
        }
    }

    // Convert Option<Result> to Result. Every entry should be Some
    // after executing all sub-batches.
    Ok(all_results
        .into_iter()
        .map(|r| r.unwrap_or_else(|| Err(Error::Internal("missing pipeline result".into()))))
        .collect())
}

/// Execute a single sub-batch of pipelined commands through the
/// classification-based dispatcher with tag-completion barrier.
///
/// **Precondition**: all commands in the batch have unique
/// [`CommandKind`]s. This is guaranteed by [`run_pipeline`] which splits
/// duplicate kinds into separate sub-batches.
///
/// RFC 3501 §5.5: clients may send multiple commands without waiting for
/// a response. The server processes them in order, but responses may
/// interleave. This function:
///
/// 1. Snapshots encode options (C7 fix — capability state at batch start).
/// 2. Encodes all commands before sending any bytes. Any encode failure
///    aborts the entire batch.
/// 3. Sends all commands on the wire (batch write for LITERAL+ mode).
/// 4. Reads responses, routing each to the correct consumer by tag.
///    Untagged responses are classified against the head (first
///    non-finalized) consumer's command kind. Once a consumer is
///    finalized (its tagged response arrived), it can no longer receive
///    untagged responses — the tag-completion barrier.
///
/// Continuations (`+`) are errors in pipeline context — pipelinable
/// commands do not produce continuations (the `Pipelinable` sealed trait
/// enforces this at the type level).
#[allow(clippy::too_many_lines)]
async fn run_pipeline_batch(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    tag_gen: &mut super::tag::TagGenerator,
    event_sink: &mut event_sink::DriverEventSink,
    commands: Vec<Command>,
    consumers: Vec<Box<dyn ConsumerErased>>,
) -> Result<PipelineResults, Error> {
    let count = commands.len();
    if count == 0 {
        return Ok(Vec::new());
    }

    // 1. Snapshot encode options at start-of-batch (C7 fix).
    // All commands in the batch are encoded against the same capability
    // state, preventing mid-pipeline staleness.
    let opts = build_encode_options(state);
    let allow_literal8 = state.capabilities().contains(&Capability::Binary) && !is_rev2(state);

    // 2. Encode all commands. Any encode failure aborts the whole batch
    //    before any bytes go on the wire.
    let mut tags: Vec<String> = Vec::with_capacity(count);
    let mut kinds: Vec<crate::types::CommandKind> = Vec::with_capacity(count);
    let mut targets: Vec<Option<MailboxName>> = Vec::with_capacity(count);
    let mut encoded_commands = Vec::with_capacity(count);

    for cmd in &commands {
        let tag = tag_gen.next();
        let kind = cmd.kind();
        let target = cmd.mailbox_target().cloned();
        let encoded = encode_command(&tag, cmd, &opts)?;
        tags.push(tag);
        kinds.push(kind);
        targets.push(target);
        encoded_commands.push(encoded);
    }

    trace!(count, "driver: sending pipelined batch");

    // 3. Send all commands on the wire. For LITERAL+ mode, batch all
    //    into a single buffer for a single-write send. For other modes,
    //    send each command individually with literal synchronization as
    //    needed (RFC 3501 §4.3).
    match opts.literal_mode {
        LiteralMode::LiteralPlus => {
            // RFC 7888 §4: all literals are non-synchronizing — batch
            // everything into a single write.
            let bufs: Vec<BytesMut> = encoded_commands
                .into_iter()
                .map(|e| {
                    let flat = e.into_buf();
                    super::patch_literals_to_plus_with_binary(&flat, allow_literal8)
                })
                .collect();
            let total: usize = bufs.iter().map(BytesMut::len).sum();
            let mut batch = BytesMut::with_capacity(total);
            for buf in bufs {
                batch.extend_from_slice(&buf);
            }
            wire_reader.write_all(&batch).await?;
        }
        LiteralMode::LiteralMinus => {
            // RFC 7888 §5: small literals (≤4096) are non-synchronizing;
            // larger ones need sync. Send each command with patching.
            for encoded in encoded_commands {
                let flat = encoded.into_buf();
                let patched =
                    super::patch_small_literals_to_plus_with_binary(&flat, allow_literal8);
                send_with_literal_sync(wire_reader, state, event_sink, &patched).await?;
            }
        }
        LiteralMode::Synchronizing => {
            // RFC 3501 §4.3: all literals are synchronizing. Send each
            // command's segments with literal sync.
            for encoded in encoded_commands {
                send_encoded_segments(wire_reader, state, event_sink, encoded.segments()).await?;
            }
        }
    }

    // 4. Response loop with tag-completion barrier.
    //
    // Build a tag->index lookup for O(1) matching. Consumers are stored
    // in an Option vec — None means finalized.
    let mut tag_to_idx: std::collections::HashMap<String, usize> =
        std::collections::HashMap::with_capacity(count);
    for (i, tag) in tags.iter().enumerate() {
        tag_to_idx.insert(tag.clone(), i);
    }

    let mut consumers: Vec<Option<Box<dyn ConsumerErased>>> =
        consumers.into_iter().map(Some).collect();
    let mut results: Vec<Option<Result<Box<dyn std::any::Any + Send>, Error>>> =
        (0..count).map(|_| None).collect();
    let mut completed = 0usize;

    while completed < count {
        let notify_before = state.notify();
        let utf8 = utf8_mode(state);
        let resp = wire_reader.read_one(utf8).await?;

        // Set pre-flight state mutations before apply_side_effects
        // processes the tagged response. Among pipelinable commands,
        // only NOTIFY SET/NONE need this (RFC 5465 §3).
        //
        // Design note: State-changing commands (ENABLE, SELECT, CLOSE, UNSELECT)
        // are excluded from pipeline execution by API design — no pipeline methods
        // exist for them. This is enforced structurally via the Pipeline type, not
        // by runtime validation. There is no `set_in_close` call here for the
        // same reason.
        if let crate::types::Response::Tagged(ref t) = resp {
            if let Some(&idx) = tag_to_idx.get(&t.tag) {
                match commands[idx] {
                    Command::NotifySet(ref params) => {
                        let (list, status, metadata) =
                            super::extensions::compute_notify_flags(params);
                        state.set_in_notify_set(Some(super::NotifyFlags {
                            list,
                            status,
                            metadata,
                        }));
                    }
                    Command::NotifyNone => {
                        state.set_in_notify_set(Some(super::NotifyFlags::default()));
                    }
                    _ => {}
                }
            }
        }

        let _digest = state.apply_side_effects(&resp);

        match resp {
            crate::types::Response::Tagged(t) => {
                emit_tagged_response_code_events(&t, event_sink);
                if let Some(&idx) = tag_to_idx.get(&t.tag) {
                    if let Some(consumer) = consumers[idx].take() {
                        let ctx = build_consumer_context(state, targets[idx].as_ref(), &tags[idx]);
                        match consumer.finalize_erased(t, &ctx) {
                            Ok(finalized) => {
                                for ev in finalized.reclassified_as_events {
                                    if !has_critical_response_code(&ev) {
                                        let _ = event_sink.emit(ev.into());
                                    }
                                }
                                results[idx] = Some(Ok(finalized.output));
                            }
                            Err(e) => {
                                results[idx] = Some(Err(e));
                            }
                        }
                        completed += 1;
                    }
                    // Duplicate tagged response for already-finalized
                    // command — ignore silently (Postel's law).
                } else {
                    return Err(Error::Protocol(format!(
                        "unknown tag in pipeline response: {:?}",
                        t.tag,
                    )));
                }
            }
            crate::types::Response::Untagged(u) => {
                let code_emitted = emit_untagged_response_code_events(&u, event_sink);

                // Find the head consumer — first still-active
                // (non-finalized) consumer. Per the tag-completion
                // barrier, only consumers whose tagged response hasn't
                // arrived yet can receive untagged responses.
                let head_idx = consumers.iter().position(Option::is_some);
                if let Some(idx) = head_idx {
                    let class_ctx = ClassificationContext {
                        notify: notify_before,
                        command_target: targets[idx].as_ref(),
                    };
                    let rule = classification::classify(kinds[idx], &u, &class_ctx);
                    match rule {
                        SolicitationRule::OnlySolicited | SolicitationRule::Either => {
                            let ctx =
                                build_consumer_context(state, targets[idx].as_ref(), &tags[idx]);
                            if let Some(ref mut consumer) = consumers[idx] {
                                consumer.on_response(*u, notify_before, &ctx);
                            }
                        }
                        SolicitationRule::OnlyUnsolicited | SolicitationRule::Impossible => {
                            // Forward-classify: the head consumer does not
                            // want this response. Scan later consumers to
                            // see if it is OnlySolicited for one of them —
                            // non-conformant servers may interleave responses
                            // across pipelined commands (Postel's law).
                            let mut u = Some(u);
                            for later in (idx + 1)..consumers.len() {
                                if consumers[later].is_none() {
                                    continue;
                                }
                                let claimed = match u {
                                    Some(ref inner) => {
                                        let later_ctx = ClassificationContext {
                                            notify: notify_before,
                                            command_target: targets[later].as_ref(),
                                        };
                                        matches!(
                                            classification::classify(
                                                kinds[later],
                                                inner,
                                                &later_ctx,
                                            ),
                                            SolicitationRule::OnlySolicited
                                        )
                                    }
                                    None => false,
                                };
                                if claimed {
                                    if let Some(taken) = u.take() {
                                        let ctx = build_consumer_context(
                                            state,
                                            targets[later].as_ref(),
                                            &tags[later],
                                        );
                                        if let Some(ref mut consumer) = consumers[later] {
                                            consumer.on_response(*taken, notify_before, &ctx);
                                        }
                                    }
                                    break;
                                }
                            }
                            // No later consumer claimed it — emit as event.
                            if let Some(unclaimed) = u {
                                if !code_emitted {
                                    let _ = event_sink.emit((*unclaimed).into());
                                }
                            }
                        }
                    }
                } else {
                    // All consumers finalized — late-flushed server data.
                    if !code_emitted {
                        let _ = event_sink.emit((*u).into());
                    }
                }
            }
            crate::types::Response::Continuation(_) => {
                // Pipelinable commands do not produce continuations
                // (enforced by the Pipelinable sealed trait).
                // An unexpected + is a protocol error (RFC 3501 §7.5).
                return Err(Error::Protocol(
                    "unexpected continuation in pipeline response loop".into(),
                ));
            }
            crate::types::Response::Greeting(_) => {
                return Err(Error::Protocol("unexpected greeting mid-pipeline".into()));
            }
        }
    }

    // Collect results in command order. Every entry should be Some after
    // the loop — the while guard ensures `completed == count`.
    Ok(results
        .into_iter()
        .map(|r| r.unwrap_or_else(|| Err(Error::Internal("missing pipeline result".into()))))
        .collect())
}

// ---------------------------------------------------------------------------
// IDLE session (RFC 2177)
// ---------------------------------------------------------------------------

/// Enter IDLE mode, read and publish events, exit on DONE or server
/// termination (RFC 2177 Sections 2–4).
///
/// 1. Sends the IDLE command on the wire (tagged, via the encoder).
/// 2. Waits for the `+` continuation (RFC 2177 Section 3).
/// 3. Enters a reading loop: `select!` between wire reads and `done_rx`.
///    - Untagged responses are emitted as events via `event_sink`.
///    - The tagged OK means the server terminated IDLE.
///    - `done_rx` fires when the handle wants to exit IDLE.
/// 4. On `done_rx`: sends `DONE\r\n` (untagged, RFC 2177 Section 3),
///    reads remaining responses until the tagged OK, returns `ClientDone`.
/// 5. On server-sent tagged OK: returns `ServerTerminated`.
async fn run_idle(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    tag_gen: &mut super::tag::TagGenerator,
    event_sink: &mut event_sink::DriverEventSink,
    done_rx: oneshot::Receiver<()>,
) -> Result<IdleTermination, Error> {
    // 1. Send IDLE command (RFC 2177 Section 2).
    let tag = send_command_on_wire(wire_reader, state, tag_gen, event_sink, &Command::Idle).await?;

    // 2. Wait for `+` continuation (RFC 2177 Section 3).
    wait_for_continuation(wire_reader, state, event_sink).await?;

    trace!(tag, "driver: entered IDLE mode");

    // 3. IDLE reading loop.
    let mut done_rx = done_rx;
    loop {
        // Opportunistic drain of pending critical events (D7).
        let _ = event_sink.drain_pending_nonblocking();

        // Use a flag to signal which branch won, avoiding borrow
        // conflicts between the done_rx handler and wire_reader.
        let done_signaled = tokio::select! {
            biased;
            _ = &mut done_rx => true,
            result = wire_reader.read_one(utf8_mode(state)) => {
                let resp = result?;
                let digest = state.apply_side_effects(&resp);
                match resp {
                    crate::types::Response::Tagged(t) if t.tag == tag => {
                        // RFC 2177 Section 3: server terminated IDLE.
                        emit_tagged_response_code_events(&t, event_sink);
                        // Check status — NO/BAD is an error, not a
                        // successful server termination.
                        match t.status {
                            StatusKind::Ok => {
                                trace!(tag, "driver: server terminated IDLE");
                                return Ok(IdleTermination::ServerTerminated);
                            }
                            StatusKind::No => {
                                return Err(Error::no_with_code(t.text, t.code));
                            }
                            StatusKind::Bad => {
                                return Err(Error::bad_with_code(t.text, t.code));
                            }
                        }
                    }
                    crate::types::Response::Tagged(t) => {
                        return Err(Error::Protocol(format!(
                            "unexpected tag {:?} during IDLE (expected {:?})",
                            t.tag, tag,
                        )));
                    }
                    crate::types::Response::Untagged(u) => {
                        let code_emitted =
                            emit_untagged_response_code_events(&u, event_sink);
                        // RFC 3501 §7.1.5: BYE means the server is
                        // closing. State already transitioned to Logout
                        // by apply_side_effects.
                        if digest.had_bye {
                            let (text, code) = match *u {
                                UntaggedResponse::Status { text, code, .. } => {
                                    (text, code)
                                }
                                _ => (String::new(), None),
                            };
                            warn!(text, "received BYE during IDLE");
                            return Err(Error::bye_with_code(text, code));
                        }
                        if !code_emitted {
                            let _ = event_sink.emit((*u).into());
                        }
                    }
                    crate::types::Response::Continuation(_) => {
                        // Unexpected continuation during IDLE —
                        // Postel's law: ignore and continue reading.
                        debug!(tag, "ignoring unexpected continuation during IDLE");
                    }
                    crate::types::Response::Greeting(_) => {
                        return Err(Error::Protocol(
                            "unexpected greeting during IDLE".into(),
                        ));
                    }
                }
                false
            }
        };

        if done_signaled {
            // 4. Client requested DONE (RFC 2177 Section 3).
            trace!(tag, "driver: sending DONE");
            wire_reader.write_all(b"DONE\r\n").await?;
            drain_idle_responses(wire_reader, state, event_sink, &tag).await?;
            trace!(tag, "driver: exited IDLE mode");
            return Ok(IdleTermination::ClientDone);
        }
    }
}

/// Drain remaining responses after DONE until the tagged OK arrives
/// (RFC 2177 Section 3).
///
/// The server may send additional untagged responses between the
/// client's DONE and the tagged OK. These are emitted as events.
async fn drain_idle_responses(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    event_sink: &mut event_sink::DriverEventSink,
    tag: &str,
) -> Result<(), Error> {
    loop {
        let utf8 = utf8_mode(state);
        let resp = wire_reader.read_one(utf8).await?;
        let digest = state.apply_side_effects(&resp);
        match resp {
            crate::types::Response::Tagged(t) if t.tag == tag => {
                emit_tagged_response_code_events(&t, event_sink);
                // Check status — NO/BAD after DONE is an error.
                match t.status {
                    StatusKind::Ok => return Ok(()),
                    StatusKind::No => return Err(Error::no_with_code(t.text, t.code)),
                    StatusKind::Bad => return Err(Error::bad_with_code(t.text, t.code)),
                }
            }
            crate::types::Response::Tagged(t) => {
                return Err(Error::Protocol(format!(
                    "unexpected tag {:?} during IDLE drain (expected {:?})",
                    t.tag, tag,
                )));
            }
            crate::types::Response::Untagged(u) => {
                let code_emitted = emit_untagged_response_code_events(&u, event_sink);
                // RFC 3501 §7.1.5: BYE during IDLE drain.
                if digest.had_bye {
                    let (text, code) = match *u {
                        UntaggedResponse::Status { text, code, .. } => (text, code),
                        _ => (String::new(), None),
                    };
                    warn!(text, "received BYE during IDLE drain");
                    return Err(Error::bye_with_code(text, code));
                }
                if !code_emitted {
                    let _ = event_sink.emit((*u).into());
                }
            }
            crate::types::Response::Continuation(_) | crate::types::Response::Greeting(_) => {
                // Postel's law: ignore unexpected continuations/greetings
                // during IDLE drain.
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Command sending with literal synchronization
// ---------------------------------------------------------------------------

/// Encode and send a command over the wire, handling literal
/// synchronization (RFC 3501 §4.3).
///
/// Returns the generated tag on success. Mirrors
/// `ImapConnection::send_command` adapted for the driver's
/// decomposed primitives.
async fn send_command_on_wire(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    tag_gen: &mut super::tag::TagGenerator,
    event_sink: &mut event_sink::DriverEventSink,
    cmd: &Command,
) -> Result<String, Error> {
    let tag = tag_gen.next();
    trace!(tag, ?cmd, "driver: sending IMAP command");
    let opts = build_encode_options(state);
    let encoded = encode_command(&tag, cmd, &opts)?;

    let allow_literal8 = state.capabilities().contains(&Capability::Binary) && !is_rev2(state);

    match opts.literal_mode {
        LiteralMode::LiteralPlus => {
            // LITERAL+ path (RFC 7888 §4): patch all synchronizing
            // markers to non-synchronizing and send in one shot.
            let flat = encoded.into_buf();
            let patched = super::patch_literals_to_plus_with_binary(&flat, allow_literal8);
            send_with_literal_sync(wire_reader, state, event_sink, &patched).await?;
        }
        LiteralMode::LiteralMinus => {
            // LITERAL- path (RFC 7888 §5): patch small (≤4096 byte)
            // literals to non-synchronizing; larger ones stay sync.
            let flat = encoded.into_buf();
            let patched = super::patch_small_literals_to_plus_with_binary(&flat, allow_literal8);
            send_with_literal_sync(wire_reader, state, event_sink, &patched).await?;
        }
        LiteralMode::Synchronizing => {
            // No literal extension — all literals are synchronizing
            // (RFC 3501 §4.3). Use pre-split segments from the encoder.
            send_encoded_segments(wire_reader, state, event_sink, encoded.segments()).await?;
        }
    }
    Ok(tag)
}

/// Send bytes that may contain synchronizing literals, handling
/// continuation requests at each literal boundary (RFC 3501 §4.3).
///
/// Mirrors `ImapConnection::send_with_literal_sync`.
async fn send_with_literal_sync(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    event_sink: &mut event_sink::DriverEventSink,
    buf: &[u8],
) -> Result<(), Error> {
    let mut pos = 0;
    while pos < buf.len() {
        if let Some((marker_end, literal_size)) = super::find_literal_boundary(&buf[pos..]) {
            // marker_end is the offset past `\r\n` within buf[pos..]
            let send_end = pos + marker_end;
            wire_reader.write_all(&buf[pos..send_end]).await?;
            wait_for_continuation(wire_reader, state, event_sink).await?;
            // Send the literal body data (RFC 3501 §4.3).
            wire_reader
                .write_all(&buf[send_end..send_end + literal_size])
                .await?;
            pos = send_end + literal_size;
        } else {
            // No more literals — send the rest.
            wire_reader.write_all(&buf[pos..]).await?;
            break;
        }
    }
    Ok(())
}

/// Send pre-split [`EncodedCommand`](crate::codec::encode::EncodedCommand)
/// segments, waiting for a `+` continuation response between each pair
/// of consecutive segments (RFC 3501 §4.3).
///
/// Mirrors `ImapConnection::send_encoded_segments`.
async fn send_encoded_segments(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    event_sink: &mut event_sink::DriverEventSink,
    segments: &[BytesMut],
) -> Result<(), Error> {
    for (i, segment) in segments.iter().enumerate() {
        wire_reader.write_all(segment).await?;
        // After every segment except the last, wait for `+`
        // (RFC 3501 §4.3).
        if i + 1 < segments.len() {
            wait_for_continuation(wire_reader, state, event_sink).await?;
        }
    }
    Ok(())
}

/// Wait for a server continuation response (`+ ...`) during
/// synchronizing-literal sends (RFC 3501 §4.3, §7.5).
///
/// Reads responses until the definitive signal arrives. Untagged
/// responses are emitted as events. BYE transitions state to Logout.
///
/// Mirrors `ImapConnection::wait_for_continuation`.
async fn wait_for_continuation(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    event_sink: &mut event_sink::DriverEventSink,
) -> Result<(), Error> {
    loop {
        let utf8 = utf8_mode(state);
        let resp = wire_reader.read_one(utf8).await?;
        let digest = state.apply_side_effects(&resp);
        match resp {
            crate::types::Response::Continuation(_) => return Ok(()),
            crate::types::Response::Tagged(t) => {
                // Server rejected the command before the literal was
                // sent. Side effects already applied (RFC 3501 §4.3).
                emit_tagged_response_code_events(&t, event_sink);
                return match t.status {
                    StatusKind::No => Err(Error::no_with_code(t.text, t.code)),
                    StatusKind::Bad => Err(Error::bad_with_code(t.text, t.code)),
                    StatusKind::Ok => Err(Error::Protocol(
                        "unexpected OK before literal continuation \
                         (RFC 3501 §4.3)"
                            .into(),
                    )),
                };
            }
            crate::types::Response::Untagged(u) => {
                // (I13): emit alert/notification overflow before
                // BYE handling to ensure ALERT codes on BYE responses
                // are not lost.
                let code_emitted = emit_untagged_response_code_events(&u, event_sink);

                // RFC 3501 §7.1.5: BYE means the server is closing.
                // State already transitioned to Logout by
                // apply_side_effects.
                if digest.had_bye {
                    let (text, code) = match *u {
                        UntaggedResponse::Status { text, code, .. } => (text, code),
                        _ => (String::new(), None),
                    };
                    warn!(text, "received BYE during literal sync");
                    return Err(Error::bye_with_code(text, code));
                }
                if !code_emitted {
                    let _ = event_sink.emit((*u).into());
                }
            }
            crate::types::Response::Greeting(_) => {
                return Err(Error::Protocol("unexpected greeting".into()));
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Stream upgrades — STARTTLS and COMPRESS
// ---------------------------------------------------------------------------

/// Execute a stream upgrade atomically.
///
/// Dispatches to the appropriate upgrade handler based on the payload.
/// The driver runs the protocol command internally (using a
/// `TaggedOkConsumer`), then atomically swaps the stream using the
/// `Poisoned` sentinel (I9, I10).
async fn run_upgrade(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    tag_gen: &mut super::tag::TagGenerator,
    event_sink: &mut event_sink::DriverEventSink,
    payload: UpgradePayload,
) -> Result<(), Error> {
    match payload {
        UpgradePayload::StartTls {
            tls_config,
            server_name,
        } => {
            run_starttls_upgrade(
                wire_reader,
                state,
                tag_gen,
                event_sink,
                tls_config,
                server_name,
            )
            .await
        }
        UpgradePayload::Compress => {
            run_compress_upgrade(wire_reader, state, tag_gen, event_sink).await
        }
    }
}

/// STARTTLS upgrade (RFC 3501 Section 6.2.1 / RFC 9051 Section 6.2.1).
///
/// 1. Send STARTTLS, await tagged OK.
/// 2. Verify the wire buffer is empty (B10 fix — no injected bytes).
/// 3. `mem::replace` the reader with a `Poisoned`-stream reader. No
///    `.await` between the buffer check and the replace.
/// 4. TLS handshake (may suspend). If the handshake fails or the
///    future is cancelled, the reader stays wrapping `Poisoned`
///    forever and the connection is dead (I9).
/// 5. Install a fresh `WireReader` on the new TLS stream. The fresh
///    reader has an empty buffer — the old buffer was dropped with
///    the old reader in step 3 (I10).
/// 6. Re-fetch capabilities (RFC 3501 §6.2.1).
pub(in crate::connection) async fn run_starttls_upgrade(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    tag_gen: &mut super::tag::TagGenerator,
    event_sink: &mut event_sink::DriverEventSink,
    tls_config: Arc<rustls::ClientConfig>,
    server_name: rustls_pki_types::ServerName<'static>,
) -> Result<(), Error> {
    // Step 1: Send STARTTLS command, await tagged OK (RFC 3501 §6.2.1).
    let consumer =
        DriverConsumer::Regular(Box::new(TaggedOkConsumer::default()) as Box<dyn ConsumerErased>);
    run_one_command(
        wire_reader,
        state,
        tag_gen,
        event_sink,
        Command::StartTls,
        consumer,
    )
    .await?;

    // Step 2: Verify buffer is empty BEFORE the swap (B10 fix).
    // RFC 3501 §6.2.1: After STARTTLS OK, the client MUST discard
    // cached data. Extra bytes here could be injected by a MITM
    // before TLS was established.
    // No .await between this check and the mem::replace below.
    if !wire_reader.buffer_is_empty() {
        *wire_reader = super::wire::WireReader::new(super::ImapStream::Poisoned);
        state.apply_infrastructure_failure();
        return Err(Error::Protocol(
            "STARTTLS: unexpected bytes in buffer at upgrade boundary \
             (possible MITM — RFC 3501 Section 6.2.1)"
                .into(),
        ));
    }

    // Step 3: Atomic swap — replace the reader with one on a Poisoned
    // stream. The old reader is consumed — its buffer is dropped — and
    // we get the old stream back (I10).
    let old_reader = std::mem::replace(
        wire_reader,
        super::wire::WireReader::new(super::ImapStream::Poisoned),
    );
    let old_stream = old_reader.into_stream();
    let Some(tcp) = old_stream.into_tcp() else {
        // Should be unreachable — the handle validates the stream
        // type before submitting the upgrade. Defensive: leave the
        // connection dead (Poisoned is already installed).
        state.apply_infrastructure_failure();
        return Err(Error::Protocol(
            "STARTTLS requires a plain TCP stream (already TLS or compressed)".into(),
        ));
    };

    // Step 4: TLS handshake (may suspend). If the handshake fails
    // or the future is cancelled, wire_reader stays wrapping Poisoned
    // forever and the connection is dead (I9).
    let connector = tokio_rustls::TlsConnector::from(tls_config);
    let tls_stream = match connector.connect(server_name, tcp).await {
        Ok(s) => s,
        Err(e) => {
            // TLS handshake failed — connection is dead (Poisoned stays).
            state.apply_infrastructure_failure();
            return Err(Error::Io(Arc::new(std::io::Error::other(e))));
        }
    };

    // Step 5: Install a fresh WireReader on the new TLS stream.
    // The reader has a fresh empty buffer — the old buffer was
    // dropped with old_reader in Step 3 (I10).
    *wire_reader = super::wire::WireReader::new(super::ImapStream::Tls(tls_stream));

    // Step 6: Re-read capabilities after TLS upgrade (RFC 3501 §6.2.1).
    state.apply_capability_fetch(Vec::new());
    let cap_consumer =
        DriverConsumer::Regular(Box::new(CapabilityConsumer::default()) as Box<dyn ConsumerErased>);
    let result = run_one_command(
        wire_reader,
        state,
        tag_gen,
        event_sink,
        Command::Capability,
        cap_consumer,
    )
    .await?;
    let caps = result
        .downcast::<Vec<Capability>>()
        .map_err(|_| Error::Internal("CapabilityConsumer output downcast failed".into()))?;
    state.apply_capability_fetch(*caps);

    debug!("STARTTLS upgrade complete (RFC 3501 Section 6.2.1)");
    Ok(())
}

/// COMPRESS=DEFLATE upgrade (RFC 4978).
///
/// 1. Send COMPRESS, await tagged OK.
/// 2. Take remaining buffer bytes (already compressed data).
/// 3. `mem::replace` the reader with a `Poisoned`-stream reader.
/// 4. Wrap the old stream in a `CompressedStream`.
/// 5. Install a fresh `WireReader` on the compressed stream,
///    preserving any buffered compressed bytes.
async fn run_compress_upgrade(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    tag_gen: &mut super::tag::TagGenerator,
    event_sink: &mut event_sink::DriverEventSink,
) -> Result<(), Error> {
    // Step 1: Send COMPRESS command, await tagged OK (RFC 4978 §4).
    let consumer =
        DriverConsumer::Regular(Box::new(TaggedOkConsumer::default()) as Box<dyn ConsumerErased>);
    run_one_command(
        wire_reader,
        state,
        tag_gen,
        event_sink,
        Command::Compress,
        consumer,
    )
    .await?;

    // Step 2: Take remaining buffer bytes — they are compressed data
    // that must be preserved in the new CompressedStream's raw read
    // buffer (RFC 4978 §3: server begins compressing immediately
    // after the CRLF ending the tagged OK).
    let remaining = wire_reader.take_buffer();

    // Step 3: Atomic swap with Poisoned sentinel.
    let old_reader = std::mem::replace(
        wire_reader,
        super::wire::WireReader::new(super::ImapStream::Poisoned),
    );
    let old_stream = old_reader.into_stream();

    // Step 4: Wrap the old stream in a CompressedStream.
    // After the mem::replace above, Poisoned is installed. If any of
    // these error paths fire, the connection is dead — transition state
    // to Logout so `require_state` rejects subsequent commands cleanly.
    let inner = match old_stream {
        super::ImapStream::Plain(tcp) => super::InnerStream::Plain(tcp),
        super::ImapStream::Tls(tls) => super::InnerStream::Tls(tls),
        super::ImapStream::Compressed(_) => {
            state.apply_infrastructure_failure();
            return Err(Error::Protocol(
                "COMPRESS=DEFLATE already active on this connection".into(),
            ));
        }
        super::ImapStream::Poisoned => {
            state.apply_infrastructure_failure();
            return Err(Error::Protocol(
                "stream poisoned — connection is dead".into(),
            ));
        }
        #[cfg(test)]
        super::ImapStream::Memory(_) => {
            state.apply_infrastructure_failure();
            return Err(Error::Protocol(
                "COMPRESS=DEFLATE not supported on in-memory test streams".into(),
            ));
        }
    };

    // Step 5: Build the CompressedStream and install.
    // RFC 4978 §3: the server begins compressing immediately after the
    // CRLF ending the tagged OK.
    let mut compressed = super::CompressedStream::new(inner);
    if !remaining.is_empty() {
        compressed.raw_read_buf.extend_from_slice(&remaining);
    }
    *wire_reader = super::wire::WireReader::new(super::ImapStream::Compressed(compressed));

    debug!("COMPRESS=DEFLATE activated (RFC 4978)");
    Ok(())
}

// ---------------------------------------------------------------------------
// Graceful shutdown
// ---------------------------------------------------------------------------

/// Best-effort LOGOUT on graceful shutdown (RFC 3501 §6.1.3).
///
/// Sends LOGOUT and reads the BYE/OK response. Errors are ignored —
/// the connection is being torn down and the caller has already
/// dropped `cmd_tx`.
async fn logout_best_effort(
    wire_reader: &mut super::wire::WireReader,
    state: &mut super::state::ProtocolState,
    tag_gen: &mut super::tag::TagGenerator,
) -> Result<(), Error> {
    if state.session_state() == super::SessionState::Logout {
        return Ok(());
    }
    let tag = tag_gen.next();
    // LOGOUT is a trivial command with no literals — write raw bytes.
    let logout_line = format!("{tag} LOGOUT\r\n");
    wire_reader.write_all(logout_line.as_bytes()).await?;

    // Read responses until the tagged OK or an error. Apply side
    // effects so state transitions to Logout on the BYE/tagged OK.
    loop {
        let utf8 = utf8_mode(state);
        let resp = wire_reader.read_one(utf8).await?;
        let _digest = state.apply_side_effects(&resp);
        match resp {
            crate::types::Response::Tagged(t) if t.tag == tag => break,
            crate::types::Response::Tagged(_) => break,
            _ => {}
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Pure helpers — derive protocol context from ProtocolState
// ---------------------------------------------------------------------------

/// Derive whether the connection is in `IMAP4rev2` mode.
///
/// RFC 9051 §6.3.1: on dual-mode servers (both rev1 and rev2), rev2
/// behavior requires explicit ENABLE.
fn is_rev2(state: &super::state::ProtocolState) -> bool {
    let has_rev2 = state.capabilities().contains(&Capability::Imap4Rev2);
    let has_rev1 = state.capabilities().contains(&Capability::Imap4Rev1);
    if has_rev2 && has_rev1 {
        state
            .enabled()
            .iter()
            .any(|e| e.eq_ignore_ascii_case("IMAP4rev2"))
    } else {
        has_rev2
    }
}

/// Derive the UTF-8 wire mode from protocol state.
///
/// True when `UTF8=ACCEPT` (RFC 6855 §3) has been enabled or `IMAP4rev2`
/// is active (RFC 9051 §7).
fn utf8_mode(state: &super::state::ProtocolState) -> bool {
    state
        .enabled()
        .iter()
        .any(|e| e.eq_ignore_ascii_case("UTF8=ACCEPT"))
        || is_rev2(state)
}

/// Derive the literal negotiation mode from capabilities.
///
/// RFC 7888 §4 (LITERAL+), §5 (LITERAL-), RFC 3501 §4.3 (synchronizing).
fn literal_mode(state: &super::state::ProtocolState) -> LiteralMode {
    if state.capabilities().contains(&Capability::LiteralPlus) {
        LiteralMode::LiteralPlus
    } else if state.capabilities().contains(&Capability::LiteralMinus) || is_rev2(state) {
        LiteralMode::LiteralMinus
    } else {
        LiteralMode::Synchronizing
    }
}

/// Build an [`EncodeOptions`] snapshot from protocol state.
///
/// Mirrors `ImapConnection::encode_options`.
fn build_encode_options(state: &super::state::ProtocolState) -> EncodeOptions {
    EncodeOptions {
        utf8_mode: utf8_mode(state),
        literal_mode: literal_mode(state),
        capabilities: state.capabilities().to_vec(),
    }
}

/// Build a [`ConsumerContext`] from protocol state.
///
/// Mirrors `ImapConnection::build_consumer_context`. The driver
/// constructs this inline instead of going through a method on
/// `ImapConnection`.
fn build_consumer_context<'a>(
    state: &'a super::state::ProtocolState,
    command_target: Option<&'a MailboxName>,
    command_tag: &'a str,
) -> ConsumerContext<'a> {
    ConsumerContext {
        capabilities: state.capabilities(),
        enabled: state.enabled(),
        command_target,
        command_tag,
    }
}

// ---------------------------------------------------------------------------
// Response-code event emission (I13)
// ---------------------------------------------------------------------------

/// Emit [`TypedEvent::Alert`] or [`TypedEvent::NotificationOverflow`]
/// from an untagged response's response code, if present.
///
/// RFC 3501 §7.1: `[ALERT]` response codes MUST be presented to the
/// user. RFC 5465 §5.8: `[NOTIFICATIONOVERFLOW]` means the NOTIFY
/// registration was dropped. Both must reach the event queue regardless
/// of how the response is classified (solicited, unsolicited, or
/// impossible). The driver calls this *before* classification so the
/// event is emitted even when the response is routed to a consumer.
///
/// Returns `true` if a critical event was extracted (caller may skip
/// the redundant `From<UntaggedResponse>` conversion to avoid
/// double-emitting the same data).
fn emit_untagged_response_code_events(
    u: &UntaggedResponse,
    event_sink: &mut event_sink::DriverEventSink,
) -> bool {
    match u {
        UntaggedResponse::Status {
            code: Some(ResponseCode::Alert),
            text,
            ..
        } => {
            let _ = event_sink.emit(TypedEvent::Alert(text.clone()));
            true
        }
        UntaggedResponse::Status {
            code: Some(ResponseCode::NotificationOverflow(detail)),
            text,
            ..
        } => {
            let _ = event_sink.emit(TypedEvent::NotificationOverflow {
                code: detail.clone(),
                text: text.clone(),
            });
            true
        }
        _ => false,
    }
}

/// Emit [`TypedEvent::Alert`] or [`TypedEvent::NotificationOverflow`]
/// from a tagged response's response code, if present.
///
/// Tagged responses go to `consumer.finalize_erased()` and never reach
/// the `From<UntaggedResponse>` event conversion. Without this
/// explicit emission, `[ALERT]` and `[NOTIFICATIONOVERFLOW]` in tagged
/// responses would be captured by `apply_side_effects` (state mutation)
/// but never published as typed events (bug B7, I13).
fn emit_tagged_response_code_events(
    t: &crate::types::response::TaggedResponse,
    event_sink: &mut event_sink::DriverEventSink,
) {
    match &t.code {
        Some(ResponseCode::Alert) => {
            let _ = event_sink.emit(TypedEvent::Alert(t.text.clone()));
        }
        Some(ResponseCode::NotificationOverflow(detail)) => {
            let _ = event_sink.emit(TypedEvent::NotificationOverflow {
                code: detail.clone(),
                text: t.text.clone(),
            });
        }
        _ => {}
    }
}

/// Check whether an untagged response carries `[ALERT]` or
/// `[NOTIFICATIONOVERFLOW]` — response codes that were already emitted
/// as typed events in the pre-classification pass.
///
/// Used by the reclassified-as-events loop: if a consumer reclassifies
/// a response that was already emitted by `emit_untagged_response_code_events`,
/// the reclassified copy must be skipped to prevent double-delivery.
fn has_critical_response_code(u: &UntaggedResponse) -> bool {
    matches!(
        u,
        UntaggedResponse::Status {
            status,
            code: Some(ResponseCode::Alert),
            ..
        } | UntaggedResponse::Status {
            status,
            code: Some(ResponseCode::NotificationOverflow(_)),
            ..
        }
        if !matches!(status, crate::types::response::UntaggedStatus::Bye)
    )
}

pub(super) mod event_sink;

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