eggsact 1.2.2

Deterministic MCP and in-process utility tools for coding agents
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
use crate::agent::{Profile, ToolAudience, ToolCallError, ToolCallOutcome, ToolRegistry};
use crate::mcp::budget::budget_for_tool;
use crate::mcp::compat::CompatibilityMode;
use crate::mcp::execution;
use crate::mcp::machine_codes;
use crate::mcp::protocol::{
    already_initialized, invalid_request, json_rpc_error, json_rpc_error_with_data,
    method_not_found, not_initialized, EggsactExtensions, ExperimentalCapabilities,
    InitializeParams, InitializeResult, JsonRpcRequest, JsonRpcResponse, ServerCapabilities,
    ServerInfo, ToolsCapability,
};
use crate::mcp::registry;
use crate::mcp::response::{wrap_tool_response, ToolResponse};
use crate::mcp::runtime::{
    apply_cancellation, complete_request, get_active_audience, get_active_profile,
    get_schema_detail, negotiate_protocol_version, new_active_requests, register_request,
    MetricGuard, NegotiatedProtocol, RegisterRequestError, SessionState, MAX_REQUEST_BYTES,
    MAX_REQUEST_ID_LENGTH, MAX_TOOL_WORKERS, MCP_SERVER_NAME, RUNTIME_METRICS,
};
use serde_json::Value;
use std::io::Write;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::Mutex;

pub fn mcp_tool_count() -> usize {
    registry::tool_count()
}

/// Truncate a string to at most `max_bytes` UTF-8 bytes, appending `suffix`.
///
/// Always returns a valid UTF-8 string. If the input fits within `max_bytes`,
/// it is returned unchanged. Otherwise the content is truncated at a valid
/// UTF-8 character boundary before `max_bytes` and `suffix` is appended.
fn truncate_utf8_bytes(input: &str, max_bytes: usize, suffix: &str) -> String {
    if input.len() <= max_bytes {
        return input.to_string();
    }
    let suffix_bytes = suffix.len();
    if suffix_bytes >= max_bytes {
        return suffix.to_string();
    }
    let mut end = max_bytes - suffix_bytes;
    while end > 0 && !input.is_char_boundary(end) {
        end -= 1;
    }
    let mut result = String::with_capacity(max_bytes + suffix.len());
    result.push_str(&input[..end]);
    result.push_str(suffix);
    result
}

/// Truncate a request ID for display in error messages, avoiding DoS via
/// oversized IDs in log output.
fn truncate_id_display(id: &Value) -> String {
    let s = id.to_string();
    truncate_utf8_bytes(&s, 128, "...")
}

/// Result of reading one bounded line from the JSONL input.
#[derive(Debug)]
enum LimitedLine {
    /// A complete line (without the trailing newline).
    Line(String),
    /// The line exceeded `MAX_REQUEST_BYTES`. Contains the number of bytes
    /// observed before the limit was exceeded. The remainder of the line
    /// (through the next newline) has been drained.
    TooLarge { observed_at_least: usize },
    /// End of input (clean EOF with no buffered data).
    Eof,
}

/// Read one line from `reader` with a hard byte cap of `max_bytes`.
///
/// Uses `fill_buf`/`consume` exclusively so framing never consumes bytes
/// past the next newline. Tracks the exact line length — including bytes
/// discarded past the cap while waiting for a terminator — so a
/// `max_bytes` payload followed by LF, CRLF, or EOF is accepted, while a
/// strictly larger payload (whether terminated or not) is rejected.
async fn read_bounded_line<R: tokio::io::AsyncBufRead + Unpin>(
    reader: &mut R,
    max_bytes: usize,
) -> LimitedLine {
    let mut buf: Vec<u8> = Vec::with_capacity(max_bytes);
    // Every byte consumed before the terminating LF, including bytes no
    // longer retained in `buf`.
    let mut bytes_before_lf: usize = 0;
    // The last byte of the most recently consumed chunk lets us detect CRLF
    // when the LF is the first byte in the next fill.
    let mut last_byte: Option<u8> = None;

    loop {
        let (chunk_len, last_chunk_byte, newline_pos, byte_before_lf) = {
            let chunk = match reader.fill_buf().await {
                Ok(c) => c,
                Err(_) => break,
            };
            if chunk.is_empty() {
                break;
            }
            let last = *chunk.last().expect("non-empty chunk has a last byte");
            let pos = chunk.iter().position(|&b| b == b'\n');
            let before_lf = pos.and_then(|pos| {
                if pos == 0 {
                    last_byte
                } else {
                    Some(chunk[pos - 1])
                }
            });
            (chunk.len(), last, pos, before_lf)
        };

        if let Some(pos) = newline_pos {
            // The LF itself is not part of the payload. A CR immediately
            // before it is also a terminator byte, even when it came from a
            // previous fill.
            let crlf = byte_before_lf == Some(b'\r');
            let line_bytes = bytes_before_lf
                .saturating_add(pos)
                .saturating_sub(usize::from(crlf));
            if line_bytes > max_bytes {
                reader.consume(pos + 1);
                return LimitedLine::TooLarge {
                    observed_at_least: line_bytes,
                };
            }

            // The line fits, so all payload bytes from earlier fills are in
            // `buf`. Remove a CR retained from an earlier fill before
            // appending any payload from this fill.
            if crlf && pos == 0 && buf.last() == Some(&b'\r') {
                buf.pop();
            }
            let payload_in_chunk = if pos > 0 && crlf { pos - 1 } else { pos };
            let can_take = max_bytes.saturating_sub(buf.len()).min(payload_in_chunk);
            if can_take > 0 {
                let chunk = reader.fill_buf().await.expect("buffer readable");
                buf.extend_from_slice(&chunk[..can_take]);
            }
            reader.consume(pos + 1);
            return LimitedLine::Line(string_from_utf8_lossy(&buf));
        }

        // No newline in this chunk. Count the entire chunk, but retain only
        // the bounded prefix needed to reconstruct an accepted line.
        let can_take = max_bytes.saturating_sub(buf.len()).min(chunk_len);
        if can_take > 0 {
            let chunk = reader.fill_buf().await.expect("buffer readable");
            buf.extend_from_slice(&chunk[..can_take]);
        }
        bytes_before_lf = bytes_before_lf.saturating_add(chunk_len);
        last_byte = Some(last_chunk_byte);
        reader.consume(chunk_len);
    }

    // EOF.
    if bytes_before_lf > max_bytes {
        LimitedLine::TooLarge {
            observed_at_least: bytes_before_lf,
        }
    } else if buf.is_empty() {
        LimitedLine::Eof
    } else {
        LimitedLine::Line(string_from_utf8_lossy(&buf))
    }
}

fn string_from_utf8_lossy(bytes: &[u8]) -> String {
    String::from_utf8(bytes.to_vec())
        .unwrap_or_else(|e| String::from_utf8_lossy(&e.into_bytes()).into_owned())
}

fn write_json_line(value: &Value) {
    if let Ok(output) = serde_json::to_string(value) {
        println!("{}", output);
    }
}

fn build_server_capabilities() -> ServerCapabilities {
    ServerCapabilities {
        tools: ToolsCapability {
            list_changed: false,
        },
        experimental: Some(ExperimentalCapabilities {
            eggsact: EggsactExtensions {
                profiles: true,
                schema_detail: true,
                audience_filtering: true,
            },
        }),
    }
}

async fn handle_request_async(
    request: &JsonRpcRequest,
    cancel_flag: &Arc<std::sync::atomic::AtomicBool>,
    tool_semaphore: &Arc<tokio::sync::Semaphore>,
    session_state: &Arc<Mutex<SessionState>>,
) -> Option<serde_json::Value> {
    // NOTE: Process-global ensure_mcp_defaults() has been removed.
    // MCP evaluator defaults are now set per-request via the eval-context
    // bridge: EvalContext::mcp_mode() is installed as a thread-local in
    // the tools/call handler before dispatching to the tool.

    // ── Lifecycle enforcement ──────────────────────────────────────────
    let method = request.method.as_str();

    match method {
        "initialize" => {
            // Parse typed initialize parameters.
            let params = match request.params.as_ref() {
                Some(p) => {
                    if !p.is_object() {
                        return Some(invalid_request(
                            "Invalid params: expected object",
                            request.id.clone(),
                        ));
                    }
                    p
                }
                None => {
                    return Some(invalid_request(
                        "Invalid params: expected object",
                        request.id.clone(),
                    ));
                }
            };

            // Parse typed InitializeParams
            let init_params: InitializeParams = match serde_json::from_value(params.clone()) {
                Ok(p) => p,
                Err(e) => {
                    return Some(invalid_request(
                        format!("Invalid initialize params: {}", e),
                        request.id.clone(),
                    ));
                }
            };

            // Validate required fields
            if init_params.client_info.name.is_empty() {
                return Some(invalid_request(
                    "Invalid params: clientInfo.name is required and must not be empty",
                    request.id.clone(),
                ));
            }

            // Negotiate protocol version
            let negotiated_version = negotiate_protocol_version(&init_params.protocol_version);

            // Attempt lifecycle transition
            let negotiated = NegotiatedProtocol {
                version: negotiated_version.clone(),
                client_name: init_params.client_info.name,
                client_version: init_params.client_info.version,
                client_capabilities: init_params.capabilities,
            };

            {
                let mut state = session_state.lock().await;
                if state.transition_to_awaiting(negotiated).is_err() {
                    return Some(already_initialized(request.id.clone()));
                }
            }

            // Build initialize result
            let result = InitializeResult {
                protocol_version: negotiated_version.to_string(),
                capabilities: build_server_capabilities(),
                server_info: ServerInfo {
                    name: MCP_SERVER_NAME.to_string(),
                    version: env!("CARGO_PKG_VERSION").to_string(),
                },
            };

            Some(serde_json::to_value(result).unwrap())
        }

        "ping" => Some(serde_json::json!({})),

        "notifications/initialized" => {
            // This branch is only reachable from the request path (with an id),
            // because the notification path (no id) handles it inline at the
            // read loop. A request-form notification is a protocol violation:
            // the client must use the notification form (no id).
            Some(invalid_request(
                "notifications/initialized must be sent as a notification (without 'id'), not as a request",
                request.id.clone(),
            ))
        }

        // All other methods: enforce Ready state, then dispatch
        _ => {
            {
                let state = session_state.lock().await;
                if !state.allows_method(method) {
                    let err = match *state {
                        SessionState::Uninitialized | SessionState::AwaitingInitialized { .. } => {
                            not_initialized(method, request.id.clone())
                        }
                        SessionState::Ready { .. } => method_not_found(
                            format!("Method not found: {}", method),
                            request.id.clone(),
                        ),
                    };
                    return Some(err);
                }
            }

            match method {
                "tools/list" => {
                    let params = request.params.as_ref();
                    if let Some(p) = params {
                        if !p.is_object() {
                            return Some(invalid_request(
                                "Invalid params: expected object",
                                request.id.clone(),
                            ));
                        }
                    }
                    // Validate param types (matching Python messages exactly)
                    if let Some(p) = params {
                        if let Some(d) = p.get("schema_detail") {
                            if !d.is_string()
                                || !matches!(d.as_str(), Some("compact" | "normal" | "full"))
                            {
                                return Some(invalid_request(
                            "Invalid 'schema_detail' parameter: expected compact, normal, or full",
                            request.id.clone(),
                        ));
                            }
                        }
                        if let Some(t) = p.get("tier") {
                            // Python treats bool as int (isinstance(True, int) == True)
                            if !t.is_i64() && !t.is_u64() && !t.is_boolean() {
                                return Some(invalid_request(
                                    "Invalid 'tier' parameter: expected integer",
                                    request.id.clone(),
                                ));
                            }
                        }
                        if let Some(t) = p.get("tags") {
                            match t.as_array() {
                                Some(tags) if tags.iter().all(|v| v.is_string()) => {}
                                Some(_) => {
                                    return Some(invalid_request(
                                        "Invalid 'tags' parameter: all items must be strings",
                                        request.id.clone(),
                                    ));
                                }
                                None => {
                                    return Some(invalid_request(
                                        "Invalid 'tags' parameter: expected array",
                                        request.id.clone(),
                                    ));
                                }
                            }
                        }
                        if let Some(n) = p.get("names") {
                            match n.as_array() {
                                Some(names) if names.iter().all(|v| v.is_string()) => {}
                                Some(_) => {
                                    return Some(invalid_request(
                                        "Invalid 'names' parameter: all items must be strings",
                                        request.id.clone(),
                                    ));
                                }
                                None => {
                                    return Some(invalid_request(
                                        "Invalid 'names' parameter: expected array",
                                        request.id.clone(),
                                    ));
                                }
                            }
                        }
                        if let Some(pr) = p.get("profile") {
                            if !pr.is_string() {
                                return Some(invalid_request(
                                    "Invalid 'profile' parameter: expected string",
                                    request.id.clone(),
                                ));
                            }
                        }
                        if let Some(a) = p.get("audience") {
                            if !a.is_string()
                                || !matches!(a.as_str(), Some("model" | "harness" | "debug"))
                            {
                                return Some(invalid_request(
                            "Invalid 'audience' parameter: expected model, harness, or debug",
                            request.id.clone(),
                        ));
                            }
                        }
                    }
                    let schema_detail = get_schema_detail();
                    let detail = params
                        .and_then(|p| p.get("schema_detail"))
                        .and_then(|d| d.as_str())
                        .unwrap_or(&schema_detail);
                    let names_filter = params
                        .and_then(|p| p.get("names"))
                        .and_then(|n| n.as_array());
                    let profile_filter = params
                        .and_then(|p| p.get("profile"))
                        .and_then(|p| p.as_str());
                    let audience_filter: Option<&str> = params
                        .and_then(|p| p.get("audience"))
                        .and_then(|a| a.as_str());
                    let tier_filter = params.and_then(|p| p.get("tier")).and_then(|t| {
                        // Python treats bool as int (isinstance(True, int) == True)
                        match t {
                            Value::Number(n) => n.as_u64(),
                            Value::Bool(b) => Some(if *b { 1 } else { 0 }),
                            _ => None,
                        }
                    });
                    let tags_filter = params
                        .and_then(|p| p.get("tags"))
                        .and_then(|t| t.as_array());

                    let active_profile = get_active_profile();
                    let effective_profile = profile_filter.unwrap_or(&active_profile);
                    // Default to the active audience when no explicit audience is provided,
                    // so harness-only tools are excluded from Model listings and the listing
                    // agrees with what tools/call will dispatch.
                    let effective_audience_str =
                        audience_filter.unwrap_or_else(|| match get_active_audience() {
                            ToolAudience::Model => "model",
                            ToolAudience::Harness => "harness",
                            ToolAudience::Debug => "debug",
                        });
                    if effective_profile != "full"
                        && !registry::PROFILE_NAMES.contains(&effective_profile)
                    {
                        let available = registry::PROFILE_NAMES.join(", ");
                        return Some(serde_json::json!({
                            "jsonrpc": "2.0",
                            "error": {
                                "code": -32602,
                                "message": format!("Unknown MCP profile: '{}'. Available profiles: {}", effective_profile, available)
                            },
                            "id": request.id
                        }));
                    }
                    // Build options and delegate to registry
                    let names_vec: Option<Vec<String>> = names_filter.map(|n| {
                        n.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect()
                    });
                    let tags_vec: Option<Vec<String>> = tags_filter.map(|t| {
                        t.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect()
                    });
                    let audience = Some(match effective_audience_str {
                        "harness" => registry::ToolListAudience::Harness,
                        "debug" => registry::ToolListAudience::Debug,
                        _ => registry::ToolListAudience::Model,
                    });
                    let options = registry::ToolListOptions {
                        profile: effective_profile,
                        names: names_vec.as_deref(),
                        tier: tier_filter.map(|t| t as u8),
                        tags: tags_vec.as_deref(),
                        schema_detail: detail,
                        audience,
                    };
                    let tools = registry::list_tool_definitions(options);
                    Some(serde_json::json!({"tools": tools}))
                }

                "tools/call" => {
                    let params = match request.params.as_ref() {
                        Some(p) => {
                            if !p.is_object() {
                                return Some(invalid_request(
                                    "Invalid params: expected object",
                                    request.id.clone(),
                                ));
                            }
                            p
                        }
                        None => {
                            return Some(invalid_request(
                                "Invalid params: expected object",
                                request.id.clone(),
                            ));
                        }
                    };
                    let name = match params.get("name").and_then(|v| v.as_str()) {
                        Some(n) => n,
                        None => {
                            return Some(invalid_request(
                                "Invalid params: missing tool name",
                                request.id.clone(),
                            ));
                        }
                    };
                    let arguments_val = match params.get("arguments") {
                        Some(v) if v.is_object() => v.clone(),
                        Some(_) => {
                            return Some(invalid_request(
                                "Invalid arguments: expected object",
                                request.id.clone(),
                            ));
                        }
                        None => serde_json::Value::Object(serde_json::Map::new()),
                    };

                    // Check if request was cancelled before execution
                    if cancel_flag.load(Ordering::Acquire) {
                        return Some(wrap_tool_response(&ToolResponse::error_with_code(
                            "cancelled",
                            machine_codes::CANCELLED,
                            &format!("Tool '{}' request was cancelled by the client", name),
                            Some(vec![
                                "The request was cancelled before execution started".to_string()
                            ]),
                            Some(name),
                        )));
                    }

                    // Delegate lookup, profile check, and validation to ToolRegistry
                    let active_profile = get_active_profile();
                    let profile = Profile::from_str_opt(&active_profile)
                        .unwrap_or_else(|| Profile::custom(&active_profile));
                    let registry =
                        ToolRegistry::with_profile_and_audience(profile, get_active_audience())
                            .with_compat_mode(CompatibilityMode::EggcalcPython);
                    let handler = match registry.prepare_tool_call(name, &arguments_val) {
                        ToolCallOutcome::Ready { handler } => handler,
                        ToolCallOutcome::PreExecutionError(e) => {
                            return match e {
                        ToolCallError::UnknownTool(tool_name) => {
                            let tool_names = registry::tool_names();
                            let tool_name_refs: Vec<&str> = tool_names.to_vec();
                            let msg = match registry::find_close_match(&tool_name, &tool_name_refs) {
                                Some(m) => format!("Unknown tool: {}. Did you mean: {}?", tool_name, m),
                                None => format!("Unknown tool: {}", tool_name),
                            };
                            Some(method_not_found(msg, request.id.clone()))
                        }
                        ToolCallError::ToolUnavailable { tool, profile } => {
                            Some(json_rpc_error(
                                -32602,
                                format!(
                                    "Tool '{}' is not available in profile '{}'. Check the tool's declared profiles, or switch to a profile that includes it.",
                                    tool, profile
                                ),
                                request.id.clone(),
                            ))
                        }
                        ToolCallError::ToolNotAllowedForAudience {
                            tool,
                            profile,
                            audience,
                            exposure,
                        } => {
                            Some(json_rpc_error(
                                -32602,
                                format!(
                                    "Tool '{}' (exposure: {}) cannot be executed by {} audience in profile '{}'. Use tools/list with appropriate audience, or use the in-process API with a different audience.",
                                    tool, exposure, audience, profile
                                ),
                                request.id.clone(),
                            ))
                        }
                        ToolCallError::InvalidArguments(msg) => {
                            Some(json_rpc_error(
                                -32602,
                                format!("Invalid arguments for tool '{}': {}", name, msg),
                                request.id.clone(),
                            ))
                        }
                        ToolCallError::Internal(msg) => {
                            Some(json_rpc_error(-32603, msg, request.id.clone()))
                        }
                    };
                        }
                    };

                    let name_owned = name.to_string();
                    let args_clone = arguments_val.clone();
                    let sem = tool_semaphore.clone();

                    // Resolve budget for this tool from its declared cost.
                    // Composite tools get HEAVY budgets; others map from ToolCost.
                    let tool_budget = registry::get_tool(name)
                        .map(|spec| budget_for_tool(name, spec.cost))
                        .unwrap_or(crate::mcp::budget::ToolBudget::MODERATE);

                    let outcome = execution::execute_tool_bounded(
                        handler,
                        args_clone,
                        name_owned.clone(),
                        tool_budget,
                        cancel_flag.clone(),
                        sem,
                    )
                    .await;

                    Some(execution::build_tool_response(
                        outcome,
                        &name_owned,
                        &tool_budget,
                    ))
                }

                "profiles/list" => {
                    if let Some(ref params) = request.params {
                        if !params.is_object() {
                            return Some(invalid_request(
                                "Invalid params: expected object",
                                request.id.clone(),
                            ));
                        }
                    }
                    let active = get_active_profile();
                    let mut profiles_info = serde_json::Map::new();
                    for &name in registry::PROFILE_NAMES {
                        let tool_specs = registry::tools_for_profile(name);
                        let mut tool_names: Vec<Value> = tool_specs
                            .into_iter()
                            .map(|spec| Value::String(spec.name.to_string()))
                            .collect();
                        tool_names
                            .sort_by(|a, b| a.as_str().unwrap_or("").cmp(b.as_str().unwrap_or("")));
                        profiles_info.insert(
                            name.to_string(),
                            serde_json::json!({
                                "tools": tool_names,
                                "tool_count": tool_names.len(),
                            }),
                        );
                    }
                    Some(serde_json::json!({
                        "active_profile": active,
                        "profiles": serde_json::Value::Object(profiles_info),
                        "available_profiles": registry::PROFILE_NAMES,
                    }))
                }

                _ => {
                    let display_method = if request.method.len() > 100 {
                        // Python truncates by byte length: method[:100]
                        let truncated = &request.method.as_bytes()[..100];
                        // Find a valid UTF-8 boundary
                        let mut end = truncated.len();
                        while end > 0 && !request.method.is_char_boundary(end) {
                            end -= 1;
                        }
                        format!("{}...", &request.method[..end])
                    } else {
                        request.method.clone()
                    };
                    Some(method_not_found(
                        format!("Method not found: {}", display_method),
                        request.id.clone(),
                    ))
                }
            }
        }
    }
}

pub async fn main() -> ! {
    let stdin = tokio::io::stdin();
    let mut reader = BufReader::new(stdin);

    let tool_semaphore = Arc::new(tokio::sync::Semaphore::new(MAX_TOOL_WORKERS));
    let active_requests = new_active_requests();
    let session_state = Arc::new(Mutex::new(SessionState::Uninitialized));

    // Dedicated writer task: all stdout writes go through this channel
    // to prevent interleaved output from concurrent request handlers.
    let (tx, mut rx) = tokio::sync::mpsc::channel::<Value>(64);
    let writer_handle = tokio::spawn(async move {
        while let Some(response) = rx.recv().await {
            write_json_line(&response);
        }
    });

    // Track spawned request tasks so we can wait for them on shutdown.
    let mut join_set = tokio::task::JoinSet::new();

    loop {
        let line = match read_bounded_line(&mut reader, MAX_REQUEST_BYTES).await {
            LimitedLine::Line(line) => line,
            LimitedLine::TooLarge { observed_at_least } => {
                let _ = tx
                    .send(json_rpc_error(
                        -32700,
                        format!(
                            "Request exceeds maximum size: at least {} bytes received, {} bytes maximum",
                            observed_at_least,
                            MAX_REQUEST_BYTES
                        ),
                        None,
                    ))
                    .await;
                continue;
            }
            LimitedLine::Eof => break,
        };

        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        // Reject batch requests (check before JSON parse, matching Python)
        if trimmed.starts_with('[') {
            let _ = tx
                .send(invalid_request("Batch requests are not supported", None))
                .await;
            continue;
        }

        // Parse JSON into generic Value for field-level validation
        let request_value: serde_json::Value = match serde_json::from_str(trimmed) {
            Ok(v) => v,
            Err(_) => {
                let _ = tx
                    .send(json_rpc_error(-32700, "Parse error: invalid JSON", None))
                    .await;
                continue;
            }
        };

        // Validate top-level is object
        if !request_value.is_object() {
            let _ = tx
                .send(invalid_request(
                    "Invalid Request: expected JSON object",
                    None,
                ))
                .await;
            continue;
        }

        // Validate jsonrpc version
        let actual_version = request_value
            .get("jsonrpc")
            .and_then(|v| v.as_str())
            .unwrap_or("null");
        if actual_version != "2.0" {
            let _ = tx
                .send(invalid_request(
                    format!(
                        "Invalid Request: jsonrpc must be '2.0', got '{}'",
                        actual_version
                    ),
                    request_value.get("id").cloned(),
                ))
                .await;
            continue;
        }

        // Validate method
        let method = match request_value.get("method") {
            Some(Value::String(method)) => method.clone(),
            Some(_) => {
                let _ = tx
                    .send(invalid_request(
                        "Invalid Request: 'method' must be a string",
                        request_value.get("id").cloned(),
                    ))
                    .await;
                continue;
            }
            None => {
                let _ = tx
                    .send(invalid_request(
                        "Invalid Request: missing 'method'",
                        request_value.get("id").cloned(),
                    ))
                    .await;
                continue;
            }
        };

        // Validate request id (before constructing JsonRpcRequest)
        let id = request_value.get("id");
        if let Some(id_val) = id {
            // Reject boolean, array, object, and float ids per JSON-RPC 2.0 spec
            if id_val.is_boolean() || id_val.is_array() || id_val.is_object() {
                let _ = tx
                    .send(invalid_request(
                        "Invalid Request: 'id' must be a string, integer, or null",
                        None,
                    ))
                    .await;
                continue;
            }
            // Reject float IDs (JSON numbers that aren't integers)
            if id_val.is_number() && id_val.as_i64().is_none() && id_val.as_u64().is_none() {
                let _ = tx
                    .send(invalid_request(
                        "Invalid Request: 'id' must be a string, integer, or null",
                        None,
                    ))
                    .await;
                continue;
            }
            let id_str = id_val.to_string();
            if id_str.len() > MAX_REQUEST_ID_LENGTH {
                let _ = tx
                    .send(invalid_request(
                        format!(
                            "Invalid Request: 'id' exceeds maximum length of {}",
                            MAX_REQUEST_ID_LENGTH
                        ),
                        None,
                    ))
                    .await;
                continue;
            }
        }

        // Construct JsonRpcRequest from validated value
        let request = JsonRpcRequest {
            jsonrpc: "2.0".to_string(),
            method,
            params: request_value.get("params").cloned(),
            id: id.cloned(),
        };

        // Notifications (no id) are handled inline; requests (with id) are
        // spawned as concurrent tasks that send responses through the channel.
        // Notifications bypass the ordinary request rate limiter.
        if request.id.is_none() {
            match request.method.as_str() {
                "notifications/initialized" => {
                    // Lifecycle transition: AwaitingInitialized → Ready
                    let mut state = session_state.lock().await;
                    if let Err(e) = state.transition_to_ready() {
                        eprintln!(
                            "Warning: notifications/initialized ignored: {} (state: {:?})",
                            e, *state
                        );
                    }
                }
                "notifications/cancelled" => {
                    // Set the cancel flag on the active request, if any.
                    // Uses async lock to avoid losing cancellations under
                    // contention (the old try_lock approach could silently
                    // drop valid cancellation notifications).
                    if let Some(params) = &request.params {
                        if let Some(request_id) = params.get("requestId") {
                            apply_cancellation(&active_requests, request_id).await;
                        } else {
                            eprintln!(
                                "Warning: notifications/cancelled missing 'requestId' parameter, ignoring"
                            );
                        }
                    } else {
                        eprintln!("Warning: notifications/cancelled missing 'params', ignoring");
                    }
                }
                _ => {
                    // Unknown notifications are silently ignored.
                }
            }
            continue;
        }

        // ── Request path (has id) ──────────────────────────────────────
        // Reject null IDs: concurrent tracking and error correlation
        // become ambiguous with null, and notifications use absent ID,
        // not null.
        if request.id.as_ref().is_some_and(|v| v.is_null()) {
            let _ = tx
                .send(json_rpc_error(
                    -32600,
                    "Invalid Request: 'id' must not be null",
                    None,
                ))
                .await;
            continue;
        }

        // Register the active request atomically under one lock acquisition.
        // This checks in-flight limits, duplicate IDs, and inserts the entry
        // in a single lock window — no separate contains_key/insert race.
        let cancel_flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let request_id = request.id.clone().unwrap();
        let (guard, registration) = match register_request(
            &active_requests,
            &cancel_flag,
            request_id.clone(),
            request.method.clone(),
        )
        .await
        {
            Ok(pair) => pair,
            Err(RegisterRequestError::DuplicateId) => {
                let _ = tx
                    .send(json_rpc_error(
                        -32600,
                        format!(
                            "Duplicate request id: {:?}",
                            truncate_id_display(&request_id)
                        ),
                        request.id.clone(),
                    ))
                    .await;
                continue;
            }
            Err(RegisterRequestError::CapacityExceeded) => {
                let _ = tx
                    .send(json_rpc_error_with_data(
                        -32000,
                        "Too many in-flight requests",
                        Some(serde_json::json!({
                            "code": "RESOURCE_EXHAUSTED",
                            "limit": crate::mcp::runtime::MAX_IN_FLIGHT_REQUESTS,
                        })),
                        request.id.clone(),
                    ))
                    .await;
                continue;
            }
        };

        // Handle initialize inline (not spawned) to avoid race with
        // notifications/initialized. The lifecycle state transition must
        // complete before the next line is read.
        if request.method == "initialize" {
            let result =
                handle_request_async(&request, &cancel_flag, &tool_semaphore, &session_state).await;
            // Awaited cleanup — guaranteed, not best-effort
            complete_request(&active_requests, &registration).await;
            drop(guard);
            if let Some(result) = result {
                if result.get("error").is_some() && result.get("result").is_none() {
                    let _ = tx.send(result).await;
                } else {
                    let response = JsonRpcResponse {
                        jsonrpc: "2.0".to_string(),
                        result,
                        id: Some(request_id),
                    };
                    if let Ok(value) = serde_json::to_value(response) {
                        let _ = tx.send(value).await;
                    }
                }
            }
            continue;
        }

        // Spawn the request handler without awaiting — the read loop
        // continues to process the next line immediately.
        let tx = tx.clone();
        let semaphore_clone = tool_semaphore.clone();
        let cancel_flag_clone = cancel_flag.clone();
        let session_state_clone = session_state.clone();
        let request_clone = JsonRpcRequest {
            jsonrpc: request.jsonrpc.clone(),
            method: request.method.clone(),
            params: request.params.clone(),
            id: request.id.clone(),
        };
        let request_id_for_response = request_id.clone();
        let active_requests_clone = active_requests.clone();
        let registration_clone = registration.clone();

        join_set.spawn(async move {
            // RAII guard tracks active request count for diagnostics.
            let _active_guard = MetricGuard::new(&RUNTIME_METRICS.active_requests);

            let inner = tokio::spawn(async move {
                handle_request_async(
                    &request_clone,
                    &cancel_flag_clone,
                    &semaphore_clone,
                    &session_state_clone,
                )
                .await
            });

            let outcome = inner.await;

            // Awaited cleanup — guaranteed, not best-effort
            complete_request(&active_requests_clone, &registration_clone).await;

            // Debug-only assertion on drop; correctness is via complete_request
            drop(guard);

            // Send response through the channel.
            let maybe_result = outcome.unwrap_or_else(|e| {
                // JoinError = panic in the handler task
                Some(json_rpc_error(
                    -32000,
                    format!("Handler panic: {}", e),
                    Some(request_id_for_response.clone()),
                ))
            });
            if let Some(result) = maybe_result {
                if result.get("error").is_some() && result.get("result").is_none() {
                    let _ = tx.send(result).await;
                } else {
                    let response = JsonRpcResponse {
                        jsonrpc: "2.0".to_string(),
                        result,
                        id: Some(request_id_for_response),
                    };
                    if let Ok(value) = serde_json::to_value(response) {
                        let _ = tx.send(value).await;
                    }
                }
            }
        });
    }

    // Graceful shutdown: wait for all in-flight tasks to complete,
    // then drop the sender so the writer task drains and finishes.
    while join_set.join_next().await.is_some() {}
    drop(tx);
    let _ = writer_handle.await;
    // Flush stdout before exit — println! buffers when piped, and
    // std::process::exit does not run destructors or flush stdio.
    let _ = std::io::stdout().flush();
    std::process::exit(0);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mcp::compat::CompatibilityMode;
    use crate::mcp::schema_validation::validate_property_inner;
    use serde_json::json;
    use std::collections::HashSet;

    #[test]
    fn tool_registration_tables_are_in_sync() {
        let definitions = registry::mcp_tool_definitions();
        let mut definition_names = HashSet::new();
        for tool in &definitions {
            assert!(
                definition_names.insert(tool.name.as_str()),
                "duplicate tool definition: {}",
                tool.name
            );
        }

        let registry_names = registry::tool_names();
        for &name in &registry_names {
            assert!(
                definition_names.contains(name),
                "registry tool lacks definition: {name}"
            );
            assert!(
                registry::tool_handler_for(name).is_some(),
                "registry tool lacks handler: {name}"
            );
        }

        for name in &definition_names {
            assert!(
                registry_names.contains(name),
                "tool definition lacks registry entry: {name}"
            );
        }

        assert_eq!(mcp_tool_count(), registry::tool_count());
    }

    #[test]
    fn test_bug018_pattern_matches_anywhere_in_string() {
        let schema = json!({"type": "string", "pattern": "[0-9]+"});
        let result = validate_property_inner(
            &json!("abc123"),
            &schema,
            "test",
            10,
            CompatibilityMode::EggcalcPython,
        );
        assert!(
            result.is_none(),
            "pattern [0-9]+ should match 'abc123' at position 3, got: {:?}",
            result
        );
    }

    #[test]
    fn test_bug018_pattern_anchored_accepts() {
        let schema = json!({"type": "string", "pattern": "^[A-Z]"});
        let result = validate_property_inner(
            &json!("Hello"),
            &schema,
            "test",
            10,
            CompatibilityMode::EggcalcPython,
        );
        assert!(
            result.is_none(),
            "pattern ^[A-Z] should match 'Hello', got: {:?}",
            result
        );
    }

    #[test]
    fn test_bug018_pattern_anchored_rejects() {
        let schema = json!({"type": "string", "pattern": "^[A-Z]"});
        let result = validate_property_inner(
            &json!("hello"),
            &schema,
            "test",
            10,
            CompatibilityMode::EggcalcPython,
        );
        assert!(result.is_some(), "pattern ^[A-Z] should reject 'hello'");
    }

    #[test]
    fn test_bug018_pattern_no_match_rejects() {
        let schema = json!({"type": "string", "pattern": "^[0-9]+$"});
        let result = validate_property_inner(
            &json!("abc123def"),
            &schema,
            "test",
            10,
            CompatibilityMode::EggcalcPython,
        );
        assert!(
            result.is_some(),
            "pattern ^[0-9]+$ should reject 'abc123def'"
        );
    }

    #[test]
    fn test_bug019_multipleof_relative_tolerance() {
        let schema = json!({"type": "number", "multipleOf": 3.0});
        let result = validate_property_inner(
            &json!(9.000000001),
            &schema,
            "test",
            10,
            CompatibilityMode::EggcalcPython,
        );
        assert!(
            result.is_none(),
            "9.000000001 should pass multipleOf 3.0 with relative tolerance, got: {:?}",
            result
        );
    }

    #[test]
    fn test_bug019_multipleof_exact_value() {
        let schema = json!({"type": "number", "multipleOf": 5.0});
        let result = validate_property_inner(
            &json!(15.0),
            &schema,
            "test",
            10,
            CompatibilityMode::EggcalcPython,
        );
        assert!(
            result.is_none(),
            "15.0 should pass multipleOf 5.0, got: {:?}",
            result
        );
    }

    #[test]
    fn test_bug019_multipleof_rejects_non_multiple() {
        let schema = json!({"type": "number", "multipleOf": 3.0});
        let result = validate_property_inner(
            &json!(7.5),
            &schema,
            "test",
            10,
            CompatibilityMode::EggcalcPython,
        );
        assert!(result.is_some(), "7.5 should fail multipleOf 3.0");
    }

    #[test]
    fn test_bug019_multipleof_large_value() {
        // 10000000000.0000001 is very close to 10^10, and 1e-9 * 10^19 = 1e10.
        // Due to f64 precision, use a large value that IS a clean multiple:
        // 3000000000.0 = 3.0 * 1000000000.0
        let schema = json!({"type": "number", "multipleOf": 3.0});
        let result = validate_property_inner(
            &json!(3000000000.0),
            &schema,
            "test",
            10,
            CompatibilityMode::EggcalcPython,
        );
        assert!(
            result.is_none(),
            "3000000000.0 should pass multipleOf 3.0, got: {:?}",
            result
        );
    }
}

#[cfg(test)]
mod truncate_utf8_bytes_tests {
    use super::truncate_utf8_bytes;

    #[test]
    fn ascii_below_limit() {
        assert_eq!(truncate_utf8_bytes("hello", 128, "..."), "hello");
    }

    #[test]
    fn ascii_above_limit() {
        let input = "a".repeat(200);
        let result = truncate_utf8_bytes(&input, 128, "...");
        assert!(result.len() <= 128 + 3);
        assert!(result.ends_with("..."));
        assert_eq!(&result[..125], "a".repeat(125).as_str());
    }

    #[test]
    fn multibyte_cut_at_char_boundary() {
        // "é" is 2 bytes in UTF-8; 124 is even so it is a char boundary
        let input = "é".repeat(100); // 200 bytes total
        let result = truncate_utf8_bytes(&input, 128, "...");
        assert!(result.len() <= 128 + 3);
        assert!(result.ends_with("..."));
        // The content before "..." should be valid UTF-8
        let content_len = result.len() - 3;
        assert!(result[..content_len].is_char_boundary(content_len));
    }

    #[test]
    fn multibyte_cut_inside_codepoint() {
        // "é" is 2 bytes; 125 is odd, so it falls inside a code point
        let input = "é".repeat(100); // 200 bytes
        let result = truncate_utf8_bytes(&input, 125, "...");
        assert!(result.ends_with("..."));
        // content_bytes = 125 - 3 = 122, 122 / 2 = 61 "é" chars
        assert_eq!(&result[..122], "é".repeat(61).as_str());
    }

    #[test]
    fn mixed_ascii_and_multibyte() {
        let mut input = "hello".to_string();
        for _ in 0..50 {
            input.push('é');
        }
        // "hello" = 5 bytes, 50 * "é" = 100 bytes, total = 105 bytes
        let result = truncate_utf8_bytes(&input, 50, "...");
        assert!(result.len() <= 50 + 3);
        assert!(result.ends_with("..."));
        // Content before suffix should be valid UTF-8
        let content = &result[..result.len() - 3];
        assert!(content.is_char_boundary(content.len()));
    }

    #[test]
    fn zero_limit() {
        assert_eq!(truncate_utf8_bytes("hello", 0, "..."), "...");
    }

    #[test]
    fn suffix_larger_than_limit() {
        assert_eq!(truncate_utf8_bytes("hello", 2, "..."), "...");
    }

    #[test]
    fn truncate_id_display_with_unicode() {
        use super::truncate_id_display;
        use serde_json::json;

        // Long Unicode string ID should not panic
        let long_id = json!("id-".to_string() + &"🎉".repeat(100));
        let result = truncate_id_display(&long_id);
        assert!(result.len() <= 128 + 3);
        assert!(result.ends_with("..."));
    }

    #[test]
    fn duplicate_unicode_id_produces_error_not_panic() {
        use super::*;
        use serde_json::json;

        // Verify that a long Unicode request ID does not panic
        // when passed through truncate_id_display
        let long_unicode = json!("id-".to_string() + &"🎉".repeat(100));
        let result = truncate_id_display(&long_unicode);
        // Should produce a bounded string, not panic
        assert!(result.len() < 200);
    }

    // ═══════════════════════════════════════════════════════════════════════
    // read_bounded_line tests
    // ═══════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn bounded_line_short_lf() {
        use super::*;
        let data = b"hello world\n";
        let mut cursor = std::io::Cursor::new(data);
        let result = read_bounded_line(&mut cursor, 1000).await;
        match result {
            LimitedLine::Line(s) => assert_eq!(s, "hello world"),
            _ => panic!("expected Line"),
        }
    }

    #[tokio::test]
    async fn bounded_line_short_crlf() {
        use super::*;
        let data = b"hello world\r\n";
        let mut cursor = std::io::Cursor::new(data);
        let result = read_bounded_line(&mut cursor, 1000).await;
        match result {
            LimitedLine::Line(s) => assert_eq!(s, "hello world"),
            _ => panic!("expected Line"),
        }
    }

    #[tokio::test]
    async fn bounded_line_exactly_max_bytes() {
        use super::*;
        let payload = "x".repeat(100);
        let data = format!("{}\n", payload);
        let mut cursor = std::io::Cursor::new(data.as_bytes());
        let result = read_bounded_line(&mut cursor, 100).await;
        match result {
            LimitedLine::Line(s) => assert_eq!(s, payload),
            _ => panic!("expected Line for exactly max_bytes"),
        }
    }

    #[tokio::test]
    async fn bounded_line_one_over_max_rejected() {
        use super::*;
        let payload = "x".repeat(101);
        let data = format!("{}\n", payload);
        let mut cursor = std::io::Cursor::new(data.as_bytes());
        let result = read_bounded_line(&mut cursor, 100).await;
        match result {
            LimitedLine::TooLarge { observed_at_least } => {
                assert!(observed_at_least >= 100);
            }
            _ => panic!("expected TooLarge for limit+1"),
        }
    }

    #[tokio::test]
    async fn bounded_line_unterminated_large_input() {
        use super::*;
        // 5 MB of data with no newline — should NOT retain a 5 MB string
        let payload = "x".repeat(5 * 1024 * 1024);
        let mut cursor = std::io::Cursor::new(payload.as_bytes());
        let result = read_bounded_line(&mut cursor, 1_000_000).await;
        match result {
            LimitedLine::TooLarge { observed_at_least } => {
                assert!(observed_at_least >= 1_000_000);
            }
            _ => panic!("expected TooLarge for multi-MB unterminated input"),
        }
    }

    #[tokio::test]
    async fn bounded_line_oversized_then_valid() {
        use super::*;
        // Oversized line followed by a valid short line
        let big = "a".repeat(200);
        let data = format!("{}\nshort\n", big);
        let mut cursor = std::io::Cursor::new(data.as_bytes());

        // First read: oversized
        let r1 = read_bounded_line(&mut cursor, 100).await;
        assert!(matches!(r1, LimitedLine::TooLarge { .. }));

        // Second read: valid short line
        let r2 = read_bounded_line(&mut cursor, 100).await;
        match r2 {
            LimitedLine::Line(s) => assert_eq!(s, "short"),
            _ => panic!("expected Line for second request"),
        }
    }

    #[tokio::test]
    async fn bounded_line_eof_after_final_non_newline() {
        use super::*;
        // Final line without newline (EOF at end of data)
        let data = b"no-newline-at-end";
        let mut cursor = std::io::Cursor::new(data);
        let result = read_bounded_line(&mut cursor, 1000).await;
        match result {
            LimitedLine::Line(s) => assert_eq!(s, "no-newline-at-end"),
            _ => panic!("expected Line for EOF-terminated final line"),
        }
    }

    #[tokio::test]
    async fn bounded_line_empty_lines_ignored() {
        use super::*;
        // Empty line (just newline) should return an empty string
        let data = b"\n";
        let mut cursor = std::io::Cursor::new(data);
        let result = read_bounded_line(&mut cursor, 1000).await;
        match result {
            LimitedLine::Line(s) => assert_eq!(s, ""),
            _ => panic!("expected Line for empty line"),
        }
    }

    #[tokio::test]
    async fn bounded_line_clean_eof() {
        use super::*;
        let data = b"";
        let mut cursor = std::io::Cursor::new(data);
        let result = read_bounded_line(&mut cursor, 1000).await;
        assert!(matches!(result, LimitedLine::Eof));
    }

    #[tokio::test]
    async fn bounded_line_oversized_payload_then_later_crlf_preserves_next_frame() {
        use super::*;
        // The payload crosses the cap before a later fill supplies CRLF.
        // The old split accounting omitted the discarded Y bytes and
        // incorrectly accepted the first line.
        let data = b"xxxYYY\r\nnext\n";
        let mut reader = buffered_cursor(data, 3);

        let first = read_bounded_line(&mut reader, 3).await;
        assert!(matches!(first, LimitedLine::TooLarge { .. }));

        let second = read_bounded_line(&mut reader, 100).await;
        match second {
            LimitedLine::Line(s) => assert_eq!(s, "next"),
            other => panic!("expected preserved next frame, got {:?}", other),
        }
    }

    // ── WS2 chunk-boundary regression tests ────────────────────────────────
    //
    // These tests use a small-capacity `tokio::io::BufReader` over an
    // in-memory cursor so `fill_buf` returns controlled-sized chunks.
    // They reproduce the framing regressions that the old `read(&mut …)`
    // drain path introduced and that the new `fill_buf/consume`-only
    // drain path must prevent.

    use tokio::io::BufReader;

    fn buffered_cursor(data: &[u8], cap: usize) -> BufReader<std::io::Cursor<Vec<u8>>> {
        BufReader::with_capacity(cap, std::io::Cursor::new(data.to_vec()))
    }

    #[tokio::test]
    async fn bounded_line_exactly_cap_lf_in_next_chunk() {
        use super::*;
        let payload = "x".repeat(100);
        let data = format!("{}\nfollow", payload);
        // Buffer capacity forces fill_buf to return the 100-byte payload
        // and the trailing "\nfollow" in separate fills.
        let mut reader = buffered_cursor(data.as_bytes(), 16);
        let result = read_bounded_line(&mut reader, 100).await;
        match result {
            LimitedLine::Line(s) => assert_eq!(s, payload),
            other => panic!("expected Line for exactly cap+LF, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn bounded_line_exactly_cap_crlf_split_across_chunks() {
        use super::*;
        let payload = "x".repeat(3);
        // Put the final payload byte and CR in one fill, and LF in the next.
        let data = format!("{}\r\n", payload);
        let mut reader = buffered_cursor(data.as_bytes(), 4);
        let result = read_bounded_line(&mut reader, 3).await;
        match result {
            LimitedLine::Line(s) => assert_eq!(s, payload),
            other => panic!("expected Line for exactly cap+CRLF, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn bounded_line_exactly_cap_eof_terminated() {
        use super::*;
        let payload = "x".repeat(100);
        // EOF-terminated final line at the cap.
        let mut reader = buffered_cursor(payload.as_bytes(), 16);
        let result = read_bounded_line(&mut reader, 100).await;
        match result {
            LimitedLine::Line(s) => assert_eq!(s, payload),
            other => panic!("expected Line for cap+EOF, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn bounded_line_cap_plus_one_payload_rejected() {
        use super::*;
        let payload = "x".repeat(101);
        let data = format!("{}\n", payload);
        let mut reader = buffered_cursor(data.as_bytes(), 16);
        let result = read_bounded_line(&mut reader, 100).await;
        assert!(
            matches!(result, LimitedLine::TooLarge { .. }),
            "expected TooLarge for cap+1 payload, got {:?}",
            result
        );
        // Following valid line must still be readable.
        let next = read_bounded_line(&mut reader, 1000).await;
        assert!(matches!(next, LimitedLine::Eof));
    }

    #[tokio::test]
    async fn bounded_line_cap_plus_one_crlf_rejected_across_chunks() {
        use super::*;
        let payload = "x".repeat(4);
        let data = format!("{}\r\nfollow\n", payload);
        // The payload crosses the cap before a later fill supplies CRLF.
        let mut reader = buffered_cursor(data.as_bytes(), 4);

        let first = read_bounded_line(&mut reader, 3).await;
        assert!(matches!(first, LimitedLine::TooLarge { .. }));

        let second = read_bounded_line(&mut reader, 100).await;
        assert!(matches!(second, LimitedLine::Line(s) if s == "follow"));
    }

    #[tokio::test]
    async fn bounded_line_oversized_crlf_then_multiple_valid_frames() {
        use super::*;
        let data = b"xxxxxx\r\nfirst\nsecond\r\n";
        let mut reader = buffered_cursor(data, 3);

        assert!(matches!(
            read_bounded_line(&mut reader, 3).await,
            LimitedLine::TooLarge { .. }
        ));
        assert!(matches!(
            read_bounded_line(&mut reader, 100).await,
            LimitedLine::Line(s) if s == "first"
        ));
        assert!(matches!(
            read_bounded_line(&mut reader, 100).await,
            LimitedLine::Line(s) if s == "second"
        ));
    }

    #[tokio::test]
    async fn bounded_line_cap_plus_one_eof_rejected() {
        use super::*;
        let payload = "x".repeat(4);
        let mut reader = buffered_cursor(payload.as_bytes(), 2);
        assert!(matches!(
            read_bounded_line(&mut reader, 3).await,
            LimitedLine::TooLarge { .. }
        ));
    }

    #[tokio::test]
    async fn bounded_line_oversized_then_valid_preserves_next_frame() {
        use super::*;
        // Oversized line: 200 payload bytes (cap = 100), followed by a
        // valid short line in the same underlying buffer. The newline of
        // the oversized line and the beginning of the valid line would
        // appear in one fill_buf. The drain path must consume exactly
        // through the oversized line's newline and leave the next frame
        // intact.
        let big = "a".repeat(200);
        let data = format!("{}\nshort\n", big);
        let mut reader = buffered_cursor(data.as_bytes(), 8);

        let r1 = read_bounded_line(&mut reader, 100).await;
        assert!(matches!(r1, LimitedLine::TooLarge { .. }));

        let r2 = read_bounded_line(&mut reader, 100).await;
        match r2 {
            LimitedLine::Line(s) => assert_eq!(s, "short"),
            other => panic!("expected Line for second request, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn bounded_line_oversized_then_two_valid_preserved() {
        use super::*;
        let big = "a".repeat(200);
        let data = format!("{}\nfirst\nsecond\n", big);
        let mut reader = buffered_cursor(data.as_bytes(), 8);

        let r1 = read_bounded_line(&mut reader, 100).await;
        assert!(matches!(r1, LimitedLine::TooLarge { .. }));

        let r2 = read_bounded_line(&mut reader, 100).await;
        let r3 = read_bounded_line(&mut reader, 100).await;
        match (r2, r3) {
            (LimitedLine::Line(a), LimitedLine::Line(b)) => {
                assert_eq!(a, "first");
                assert_eq!(b, "second");
            }
            other => panic!("expected two Lines, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn bounded_line_unterminated_oversized_does_not_consume_next() {
        use super::*;
        // Multi-megabyte unterminated payload (cap = 100), followed by a
        // valid short line. The unterminated line must be rejected with
        // bounded memory and the following valid line must still be
        // processable.
        let payload = "x".repeat(64 * 1024);
        let data = format!("{}\nfollow\n", payload);
        let mut reader = buffered_cursor(data.as_bytes(), 16);

        let r1 = read_bounded_line(&mut reader, 100).await;
        assert!(matches!(r1, LimitedLine::TooLarge { .. }));

        let r2 = read_bounded_line(&mut reader, 100).await;
        match r2 {
            LimitedLine::Line(s) => assert_eq!(s, "follow"),
            other => panic!("expected Line for follow-up, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn bounded_line_cap_reached_with_oversized_chunk_in_next_fill() {
        use super::*;
        // 90 bytes of payload (cap = 100), then a chunk that contains
        // 20 more bytes plus the newline in a single fill_buf. The line
        // is oversized; the newline terminates the line and the next
        // valid line follows.
        let prefix = "a".repeat(90);
        let mid = "b".repeat(20);
        let data = format!("{}{}\nfollow\n", prefix, mid);
        // Single, large buffer: one fill_buf contains the whole oversize
        // payload plus the newline. The reader must reject and consume
        // exactly through the newline.
        let mut reader = buffered_cursor(data.as_bytes(), data.len());
        let r1 = read_bounded_line(&mut reader, 100).await;
        assert!(matches!(r1, LimitedLine::TooLarge { .. }));
        let r2 = read_bounded_line(&mut reader, 100).await;
        match r2 {
            LimitedLine::Line(s) => assert_eq!(s, "follow"),
            other => panic!("expected Line for follow-up, got {:?}", other),
        }
    }
}