switchyard-libsy 0.4.0

Provider-neutral multi-LLM routing and orchestration for Switchyard
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
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use serde_json::json;
use switchyard_protocol::{
    AggLlmResponse, Category, ContentBlock, FormatId, LlmClientError, LlmResponse, Message,
    Metadata, ModelId, Request, Response, ResponseOutput, Role, StopReason, ToolCall, WireFormat,
};

use super::super::config::{ACTIVE_APPROVAL, ServingMode, VgrConfig};
use super::super::tests::{call, request, result};
use super::{FOLLOW_UP_QUIET_SECS, LAST_ANSWER_FINAL_KEY, answers_final_reply, unix_seconds};
use crate::Result;
use crate::algorithms::vgr::Vgr;
use crate::core::algorithm::{Algorithm, AnswerSummary};
use crate::core::state::{State, StateValue};
use crate::core::testing::{category_models, reply, test_drive_with_models};

fn route(configure: impl FnOnce(&mut VgrConfig)) -> Result<Arc<dyn Algorithm>> {
    let mut config = VgrConfig::new(ModelId::new("efficient"), ModelId::new("capable"));
    config.targets.judge = Some(ModelId::new("judge"));
    config.targets.capable_judge = Some(ModelId::new("capable-judge"));
    config.mode = ServingMode::Active {
        approval: ACTIVE_APPROVAL.into(),
    };
    config.task_typing = false;
    configure(&mut config);
    Ok(Arc::new(Vgr::new(config)?))
}

fn session(messages: Vec<Message>) -> Request {
    let mut request = request(messages);
    request.metadata = Some(Metadata {
        session_id: Some("session-1".into()),
        ..Metadata::default()
    });
    request
}

fn agg(response: AggLlmResponse) -> Response {
    Response {
        llm_response: LlmResponse::Agg(response),
        metadata: None,
        upstream_headers: http::HeaderMap::new(),
    }
}

fn tool_call(arguments: serde_json::Value, stop_reason: StopReason) -> Response {
    agg(AggLlmResponse {
        outputs: vec![ResponseOutput {
            role: Role::Assistant,
            content: vec![ContentBlock::ToolCall(ToolCall {
                id: "next".into(),
                name: "bash".into(),
                arguments,
            })],
            url_citations: Vec::new(),
            stop_reason: Some(stop_reason),
        }],
        ..Default::default()
    })
}

/// A verifier reply whose first token puts probability `p` on "yes".
fn scored(p: f64) -> Response {
    let mut response = AggLlmResponse::default();
    response.preservation.responses.insert(
        FormatId::from(WireFormat::OpenAiChat),
        json!({"choices": [{"logprobs": {"content": [{"top_logprobs": [
            {"token": "yes", "logprob": p.ln()},
            {"token": "no", "logprob": (1.0 - p).ln()}
        ]}]}}]}),
    );
    agg(response)
}

#[derive(Default)]
struct Calls(AtomicUsize, AtomicUsize);

async fn drive(
    route: &Arc<dyn Algorithm>,
    request: Request,
    calls: Arc<Calls>,
    efficient: fn() -> Response,
    judge_p: f64,
) -> Result<String> {
    let (selected, _) = test_drive_with_models(
        Arc::clone(route),
        request,
        category_models(Category::Any, &["efficient", "capable"]),
        move |target: ModelId, _| {
            let calls = Arc::clone(&calls);
            async move {
                match target.as_str() {
                    "efficient" => calls.0.fetch_add(1, Ordering::Relaxed),
                    "capable-judge" => calls.1.fetch_add(1, Ordering::Relaxed),
                    _ => 0,
                };
                Ok(match target.as_str() {
                    "efficient" => efficient(),
                    "judge" => scored(judge_p),
                    "capable-judge" => reply("yes"),
                    _ => reply("capable answer"),
                })
            }
        },
    )
    .await?;
    Ok(selected.to_string())
}

fn complete_call() -> Response {
    tool_call(json!({"command": "ls"}), StopReason::ToolUse)
}

#[tokio::test]
async fn malformed_tool_calls_escalate_and_complete_ones_are_judged() -> Result<()> {
    let route = route(|_| {})?;
    let calls = Arc::new(Calls::default());
    let truncated = || tool_call(json!(r#"{"command":"l"#), StopReason::MaxTokens);
    let task = || session(vec![Message::text(Role::User, "list files")]);
    assert_eq!(
        drive(&route, task(), calls.clone(), truncated, 0.0).await?,
        "capable"
    );
    let malformed = || tool_call(json!("not JSON"), StopReason::ToolUse);
    assert_eq!(
        drive(&route, task(), calls.clone(), malformed, 0.0).await?,
        "capable"
    );
    assert_eq!(
        drive(&route, task(), calls, complete_call, 0.1).await?,
        "efficient"
    );
    Ok(())
}

#[tokio::test]
async fn a_truncated_efficient_attempt_is_judged_before_it_escalates() -> Result<()> {
    let route = route(|config| {
        config.targets.judge = None;
        config.targets.capable_judge = None;
    })?;
    let calls = Arc::new(Calls::default());
    let task = session(vec![Message::text(Role::User, "explain quicksort")]);
    let cut_off = || {
        let mut response = reply("Quicksort picks a pivot, then recurses because");
        if let LlmResponse::Agg(agg) = &mut response.llm_response {
            agg.outputs[0].stop_reason = Some(StopReason::MaxTokens);
        }
        response
    };
    let selected = drive(&route, task, calls.clone(), cut_off, 0.0).await?;
    assert_eq!(selected, "capable");
    // Attempt, readout, deliberation and its verdict; read as absent, only the attempt runs.
    assert_eq!(calls.0.load(Ordering::Relaxed), 4);
    Ok(())
}

#[tokio::test]
async fn two_consecutive_escalation_votes_latch_the_session() -> Result<()> {
    let route = route(|_| {})?;
    let calls = Arc::new(Calls::default());
    let task = || session(vec![Message::text(Role::User, "fix the build")]);
    assert_eq!(
        drive(&route, task(), calls.clone(), complete_call, 0.9).await?,
        "efficient"
    );
    assert_eq!(
        drive(&route, task(), calls.clone(), complete_call, 0.9).await?,
        "capable"
    );
    assert_eq!(calls.0.load(Ordering::Relaxed), 2);

    // Latched past the user turn: no further efficient attempt is produced.
    assert_eq!(
        drive(&route, task(), calls.clone(), complete_call, 0.0).await?,
        "capable"
    );
    assert_eq!(calls.0.load(Ordering::Relaxed), 2);
    Ok(())
}

#[tokio::test]
async fn final_answers_commit_only_on_a_verified_clean_record() -> Result<()> {
    let answer = || reply("the build passes");
    let run = |tool_output: &str| {
        session(vec![
            Message::text(Role::User, "fix the build"),
            call("c1"),
            result("c1", tool_output),
        ])
    };
    let calls = Arc::new(Calls::default());
    let clean = route(|_| {})?;
    assert_eq!(
        drive(&clean, run("ok"), calls.clone(), answer, 0.3).await?,
        "efficient"
    );
    assert_eq!(
        drive(&clean, run("ok"), calls.clone(), answer, 0.1).await?,
        "capable"
    );

    // A failure longer ago than the clean tail is forgiven only on the capable judge.
    let mut long = vec![Message::text(Role::User, "fix the build")];
    long.extend([call("e"), result("e", r#"{"error": "missing file"}"#)]);
    for index in 0..101 {
        let id = format!("c{index}");
        long.extend([call(&id), result(&id, "ok")]);
    }
    assert_eq!(
        drive(&clean, session(long.clone()), calls.clone(), answer, 0.99).await?,
        "capable"
    );
    assert_eq!(calls.1.load(Ordering::Relaxed), 0);
    let confirmed = route(|config| config.confirmed_recovery_min_clean_tail = Some(1))?;
    assert_eq!(
        drive(&confirmed, session(long), calls.clone(), answer, 0.99).await?,
        "efficient"
    );
    assert_eq!(calls.1.load(Ordering::Relaxed), 1);
    Ok(())
}

#[tokio::test]
async fn a_typed_follow_up_answer_is_judged_on_the_answer_itself() -> Result<()> {
    let route = route(|config| config.task_typing = true)?;
    let conversation = session(vec![
        Message::text(Role::User, "fix the build"),
        call("c1"),
        result("c1", "ok"),
        Message::text(Role::Assistant, "The build passes."),
        Message::text(Role::User, "What is 1+1?"),
    ]);
    // A confident readout serves on the efficient tier with no capable-tier call; a weak one asks the
    // capable tier's answer verifier, with no efficient deliberation first.
    for (readout, expected_calls) in [
        (0.95, vec!["judge: typing", "judge: answer"]),
        (
            0.5,
            vec!["judge: typing", "judge: answer", "capable-judge: answer"],
        ),
    ] {
        let calls = Arc::new(parking_lot::Mutex::new(Vec::new()));
        let seen = Arc::clone(&calls);
        let (selected, _) = test_drive_with_models(
            Arc::clone(&route),
            conversation.clone(),
            category_models(Category::Any, &["efficient", "capable"]),
            move |target: ModelId, request: Request| {
                let seen = Arc::clone(&seen);
                async move {
                    let system = request
                        .llm_request
                        .instructions
                        .first()
                        .and_then(|block| block.content.first())
                        .and_then(|block| match block {
                            ContentBlock::Text { text } => Some(text.clone()),
                            _ => None,
                        })
                        .unwrap_or_default();
                    let question = if system.starts_with("You are a strict answer verifier") {
                        "answer"
                    } else if request
                        .llm_request
                        .extensions
                        .fields
                        .contains_key("logprobs")
                    {
                        "evidence"
                    } else {
                        "typing"
                    };
                    if target.as_str().contains("judge") {
                        seen.lock().push(format!("{}: {question}", target.as_str()));
                    }
                    Ok(match target.as_str() {
                        "efficient" => reply("2"),
                        "judge" if question == "typing" => reply("Answer"),
                        "judge" => scored(readout),
                        "capable-judge" => reply("yes"),
                        _ => reply("capable answer"),
                    })
                }
            },
        )
        .await?;
        assert_eq!(selected.as_str(), "efficient", "readout {readout}");
        assert_eq!(*calls.lock(), expected_calls, "readout {readout}");
    }
    Ok(())
}

#[tokio::test]
async fn an_unavailable_efficient_tier_escalates_and_other_failures_surface() -> Result<()> {
    let route = route(|_| {})?;
    for (status, escalates) in [(503, true), (400, false)] {
        let outcome = test_drive_with_models(
            Arc::clone(&route),
            session(vec![Message::text(Role::User, "task")]),
            category_models(Category::Any, &["efficient", "capable"]),
            move |target: ModelId, _| async move {
                match target.as_str() {
                    "efficient" => Err(LlmClientError::UpstreamHttp {
                        status: http::StatusCode::from_u16(status).unwrap_or_default(),
                        body: String::new(),
                        headers: Box::default(),
                    }),
                    _ => Ok(reply("capable answer")),
                }
            },
        )
        .await;
        assert_eq!(
            outcome.is_ok_and(|(selected, _)| selected == "capable"),
            escalates
        );
    }
    Ok(())
}

fn recovering_classifier() -> super::VgrClassifier {
    let mut config = VgrConfig::new(ModelId::new("efficient"), ModelId::new("capable"));
    config.mode = ServingMode::Evaluate;
    config.breaker.threshold = 1;
    config.breaker.cooldown = std::time::Duration::ZERO;
    let classifier = super::VgrClassifier {
        breaker: super::CircuitBreaker::new(config.breaker),
        config,
    };
    classifier.breaker.failure();
    classifier
}

#[tokio::test]
async fn verifier_budget_exhaustion_is_not_an_endpoint_failure() -> Result<()> {
    use std::time::{Duration, Instant};

    use crate::core::algorithm::{Driver, RuntimeModels, Step};

    let mut config = VgrConfig::new(ModelId::new("efficient"), ModelId::new("capable"));
    config.deadline = Duration::from_millis(100);
    config.breaker.threshold = 1;
    config.breaker.cooldown = Duration::from_secs(60);
    assert!(config.targets.judge.is_none());
    let classifier = super::VgrClassifier {
        breaker: super::CircuitBreaker::new(config.breaker),
        config,
    };
    let mut state = State::default();
    let task = session(vec![Message::text(Role::User, "list files")]);
    let LlmResponse::Agg(proposed) = complete_call().llm_response else {
        unreachable!();
    };
    let (driver, mut steps) = Driver::new("vgr", Arc::new(RuntimeModels::default()));
    let context = super::RequestContext {
        driver: &driver,
        request: &task,
        started: Instant::now(),
    };
    let mut judging = Box::pin(classifier.verify_turn(&context, &proposed, &mut state));
    assert!(futures::poll!(&mut judging).is_pending());
    let Step::CallModel(pending_call) = steps.try_recv().expect("judge call should be queued")?
    else {
        unreachable!();
    };
    assert_eq!(pending_call.models, vec![ModelId::new("efficient")]);
    let escalates = judging.await;
    drop(pending_call);
    assert!(!escalates);
    assert!(super::turn_streak(&state) < super::TURN_CONFIRMATIONS);
    assert!(classifier.breaker.attempt().is_some());
    Ok(())
}

#[tokio::test]
async fn skipped_requests_leave_the_recovery_trial_available() -> Result<()> {
    use crate::core::classifier::Classifier;
    use crate::core::testing::empty_driver;
    use switchyard_protocol::ImageSource;

    for skip in ["image", "latched", "off", "kill", "deadline"] {
        let mut classifier = recovering_classifier();
        let mut state = State::default();
        let mut task = request(vec![Message::text(Role::User, "task")]);
        match skip {
            "image" => {
                task.llm_request.messages[0].content = vec![ContentBlock::Image {
                    source: ImageSource::Url {
                        url: "https://example.test/image.png".into(),
                        detail: None,
                    },
                }]
            }
            "latched" => {
                state.extra.insert(
                    super::TURN_STREAK_KEY.to_string(),
                    StateValue::Count(super::TURN_CONFIRMATIONS),
                );
            }
            "off" => classifier.config.mode = ServingMode::Off,
            "kill" => {
                let switch = super::super::KillSwitch::new();
                switch.engage();
                classifier.config.kill_switch = Some(switch);
            }
            "deadline" => classifier.config.deadline = std::time::Duration::ZERO,
            _ => unreachable!(),
        }
        classifier
            .score(&mut state, &mut task, &empty_driver())
            .await?;
        assert!(
            classifier.breaker.attempt().is_some(),
            "{skip} reserved the recovery trial"
        );
    }
    Ok(())
}

#[tokio::test]
async fn cancelling_efficient_generation_releases_the_recovery_trial() -> Result<()> {
    use crate::core::algorithm::{Driver, RuntimeModels};
    use crate::core::classifier::Classifier;

    let classifier = recovering_classifier();
    let mut state = State::default();
    let mut task = request(vec![Message::text(Role::User, "task")]);
    let (driver, _steps) = Driver::new("vgr", Arc::new(RuntimeModels::default()));
    let mut pending = classifier.score(&mut state, &mut task, &driver);
    assert!(futures::poll!(&mut pending).is_pending());
    assert!(classifier.breaker.attempt().is_none());
    drop(pending);
    assert!(classifier.breaker.attempt().is_some());
    Ok(())
}

#[tokio::test]
async fn decisions_attach_the_reason_and_exclude_efficient_capable_fallbacks() -> Result<()> {
    use crate::core::algorithm::Call;
    use crate::core::testing::serve_decision;

    for (mode, reason, served) in [
        (ServingMode::Off, "mode_off", "capable"),
        (ServingMode::Evaluate, "decided", "efficient"),
        (ServingMode::Shadow, "decided", "capable"),
    ] {
        let algorithm = route(|config| config.mode = mode)?;
        let outcome = crate::drive(
            algorithm,
            request(vec![Message::text(Role::User, "task")]),
            Arc::new(category_models(Category::Any, &["efficient", "capable"]).into()),
            |call| async move {
                match call {
                    Call::Model(call) => {
                        let response = if call.models[0] == ModelId::new("efficient") {
                            reply("done")
                        } else {
                            scored(0.9)
                        };
                        call.respond(std::future::ready(Ok(response))).await
                    }
                    Call::Decision(call) => serve_decision(*call).await,
                }
            },
        )
        .await?;
        assert_eq!(outcome.selected_model_ids, vec![ModelId::new(served)]);
        let evidence = outcome
            .metadata
            .and_then(|metadata| metadata.evidence)
            .unwrap_or_default();
        assert_eq!(evidence["source"], "vgr");
        assert_eq!(evidence["reason_code"], reason);
        assert_eq!(evidence["verdict"], served);
        assert_eq!(evidence["policy_version"], "1.3");
        if reason == "decided" {
            assert_eq!(evidence["branch"], "DefaultVerified");
        }
    }
    Ok(())
}

#[tokio::test]
async fn capable_only_work_does_not_get_an_efficient_handoff_notice() -> Result<()> {
    for scenario in ["shadow", "kill_switch", "efficient_turn_budget"] {
        let route = route(|config| {
            config.agentic_handoff = true;
            match scenario {
                "shadow" => config.mode = ServingMode::Shadow,
                "kill_switch" => {
                    let switch = super::super::safety::KillSwitch::new();
                    switch.engage();
                    config.kill_switch = Some(switch);
                }
                _ => config.efficient_turn_budget = Some(std::time::Duration::ZERO),
            }
        })?;
        let task = session(vec![
            Message::text(Role::User, "fix the build"),
            call("c1"),
            result("c1", "ok"),
        ]);
        let (selected, _) = test_drive_with_models(
            route,
            task,
            category_models(Category::Any, &["efficient", "capable"]),
            move |target: ModelId, request: Request| async move {
                Ok(match target.as_str() {
                    "efficient" => complete_call(),
                    "judge" => scored(0.0),
                    _ => {
                        let text = serde_json::to_string(&request.llm_request.messages)
                            .unwrap_or_default();
                        assert!(!text.contains("Routing notice"), "{scenario}");
                        reply("capable answer")
                    }
                })
            },
        )
        .await?;
        assert_eq!(selected, "capable");
    }
    Ok(())
}

#[tokio::test]
async fn latched_sessions_do_not_repeat_the_handoff_on_later_user_turns() -> Result<()> {
    let route = route(|config| config.agentic_handoff = true)?;
    assert_eq!(
        drive(
            &route,
            session(vec![Message::text(Role::User, "fix the build")]),
            Arc::new(Calls::default()),
            complete_call,
            0.9,
        )
        .await?,
        "efficient"
    );
    let sent = Arc::new(parking_lot::Mutex::new(Vec::new()));
    for new_user_turn in [false, true] {
        let mut messages = vec![
            Message::text(Role::User, "fix the build"),
            call("c1"),
            result("c1", "ok"),
        ];
        if new_user_turn {
            messages.push(Message::text(Role::User, "now run the tests"));
        }
        let sent = Arc::clone(&sent);
        let (selected, _) = test_drive_with_models(
            Arc::clone(&route),
            session(messages),
            category_models(Category::Any, &["efficient", "capable"]),
            move |target: ModelId, request: Request| {
                let sent = Arc::clone(&sent);
                async move {
                    Ok(match target.as_str() {
                        "efficient" => complete_call(),
                        "judge" => scored(0.9),
                        _ => {
                            sent.lock().push(
                                serde_json::to_string(&request.llm_request.messages)
                                    .unwrap_or_default(),
                            );
                            reply("capable answer")
                        }
                    })
                }
            },
        )
        .await?;
        assert_eq!(selected, "capable");
    }
    let sent = sent.lock();
    assert_eq!(sent.len(), 2);
    assert!(sent[0].contains("Routing notice"));
    assert!(!sent[1].contains("Routing notice"));
    Ok(())
}

#[tokio::test]
async fn compact_handoff_is_optional_and_replays_before_retained_capable_routing() -> Result<()> {
    let previous = vec![
        Message::text(Role::User, "inspect the repository"),
        call("old"),
        result("old", "previous output"),
        Message::text(Role::Assistant, "inspection complete"),
    ];
    for compact_handoff in [None, Some(false), Some(true)] {
        let route = route(|config| {
            config.agentic_handoff = true;
            if let Some(enabled) = compact_handoff {
                config.compact_handoff = enabled;
            }
        })?;
        assert_eq!(
            drive(
                &route,
                session(
                    previous
                        .iter()
                        .cloned()
                        .chain([Message::text(Role::User, "fix the build")])
                        .collect(),
                ),
                Arc::new(Calls::default()),
                complete_call,
                0.0,
            )
            .await?,
            "efficient"
        );
        let sent = Arc::new(parking_lot::Mutex::new(Vec::new()));
        let efficient_calls = Arc::new(AtomicUsize::new(0));
        for follow_up in [false, true] {
            let mut messages = previous.clone();
            messages.extend([
                Message::text(Role::User, "fix the build"),
                call("c1"),
                result("c1", "ok"),
            ]);
            if follow_up {
                messages.extend([call("capable-1"), result("capable-1", "capable output")]);
            }
            let sent = Arc::clone(&sent);
            let efficient_calls = Arc::clone(&efficient_calls);
            let (selected, _) = test_drive_with_models(
                Arc::clone(&route),
                session(messages),
                category_models(Category::Any, &["efficient", "capable"]),
                move |target: ModelId, request: Request| {
                    let sent = Arc::clone(&sent);
                    let efficient_calls = Arc::clone(&efficient_calls);
                    async move {
                        Ok(match target.as_str() {
                            "efficient" => {
                                efficient_calls.fetch_add(1, Ordering::Relaxed);
                                reply("the build passes")
                            }
                            "judge" => scored(0.0),
                            "capable" => {
                                sent.lock().push(request.llm_request.messages);
                                reply("capable answer")
                            }
                            _ => reply("no"),
                        })
                    }
                },
            )
            .await?;
            assert_eq!(selected, "capable");
        }
        assert_eq!(efficient_calls.load(Ordering::Relaxed), 1);
        let sent = sent.lock();
        assert_eq!(sent.len(), 2);
        if compact_handoff == Some(true) {
            assert_eq!(sent[0].len(), 5);
            assert_eq!(&sent[0][..4], previous.as_slice());
            assert_eq!(sent[1].len(), 7);
            assert_eq!(sent[0], sent[1][..5]);
            let digest = sent[0][4].text_content("").unwrap_or_default();
            assert!(digest.starts_with("fix the build"));
            assert!(digest.contains("<condensed_history>"));
            assert!(digest.contains("the build passes"));
            assert!(digest.contains("Routing notice"));
            assert_eq!(sent[1][5], call("capable-1"));
            assert_eq!(sent[1][6], result("capable-1", "capable output"));
        } else {
            let mut original = previous.clone();
            original.extend([
                Message::text(Role::User, "fix the build"),
                call("c1"),
                result("c1", "ok"),
            ]);
            assert_eq!(&sent[0][..7], original.as_slice());
            assert_eq!(sent[0].len(), 8);
            assert!(
                sent[0][7]
                    .text_content("")
                    .unwrap_or_default()
                    .contains("Routing notice")
            );
            let mut follow_up = original;
            follow_up.extend([call("capable-1"), result("capable-1", "capable output")]);
            assert_eq!(sent[1], follow_up);
        }
    }
    Ok(())
}

#[tokio::test]
async fn an_escalated_agentic_run_hands_off_once_with_the_unverified_claim() -> Result<()> {
    let route = route(|config| config.agentic_handoff = true)?;
    assert_eq!(
        drive(
            &route,
            session(vec![Message::text(Role::User, "fix the build")]),
            Arc::new(Calls::default()),
            complete_call,
            0.0,
        )
        .await?,
        "efficient"
    );
    let sent = Arc::new(parking_lot::Mutex::new(Vec::new()));
    let task = || {
        session(vec![
            Message::text(Role::User, "fix the build"),
            call("c1"),
            result("c1", "ok"),
        ])
    };
    for _ in 0..2 {
        let sent = Arc::clone(&sent);
        test_drive_with_models(
            Arc::clone(&route),
            task(),
            category_models(Category::Any, &["efficient", "capable"]),
            move |target: ModelId, request: Request| {
                let sent = Arc::clone(&sent);
                async move {
                    Ok(match target.as_str() {
                        "efficient" => reply("the build passes"),
                        "judge" => scored(0.0),
                        "capable" => {
                            let text = serde_json::to_string(&request.llm_request.messages)
                                .unwrap_or_default();
                            sent.lock().push(text);
                            reply("capable answer")
                        }
                        _ => reply("no"),
                    })
                }
            },
        )
        .await?;
    }
    let sent = sent.lock();
    assert_eq!(sent.len(), 2);
    assert!(sent[0].contains("Routing notice") && sent[0].contains("the build passes"));
    assert!(
        !sent[1].contains("Routing notice"),
        "sent once per user turn"
    );
    Ok(())
}

#[tokio::test]
async fn a_spent_efficient_turn_budget_skips_the_efficient_attempt() -> Result<()> {
    let route = route(|config| config.efficient_turn_budget = Some(std::time::Duration::ZERO))?;
    let calls = Arc::new(Calls::default());
    let task = session(vec![Message::text(Role::User, "fix the build")]);
    assert_eq!(
        drive(&route, task, calls.clone(), complete_call, 0.0).await?,
        "capable"
    );
    assert_eq!(calls.0.load(Ordering::Relaxed), 0);
    Ok(())
}

#[test]
fn handoff_preserves_existing_messages_and_non_text_content() {
    use switchyard_protocol::ImageSource;

    let mut classifier = recovering_classifier();
    classifier.config.agentic_handoff = true;
    let mut task = request(vec![
        Message::text(Role::User, "finish the task"),
        Message::text(Role::User, "keep the original files"),
        call("c1"),
        result("c1", "the command failed"),
        Message::text(Role::User, "preserve this requirement"),
        Message::text(Role::User, "continue"),
        Message::text(Role::User, "then report the result"),
    ]);
    if let ContentBlock::ToolResult(result) = &mut task.llm_request.messages[3].content[0] {
        result.content.push(ContentBlock::Image {
            source: ImageSource::Url {
                url: "https://example.test/result.png".into(),
                detail: None,
            },
        });
    }
    let original = task.llm_request.messages.clone();
    let mut state = State::default();
    super::set_flag(&mut state, super::EFFICIENT_SERVED_KEY, true);
    classifier.hand_off(&mut task, &mut state, Some("unchecked result"));
    // A notice may be appended, but all original content stays unchanged.
    let messages = &task.llm_request.messages;
    assert_eq!(messages.len(), original.len() + 1);
    assert_eq!(&messages[..original.len()], original.as_slice());
    let last = messages.last().expect("handoff note");
    assert!(
        last.text_content("")
            .is_some_and(|text| text.contains("unchecked result"))
    );
    let after_first = task.llm_request.messages.clone();
    classifier.hand_off(&mut task, &mut state, Some("duplicate notice"));
    assert_eq!(task.llm_request.messages, after_first);
}

#[tokio::test]
async fn a_blank_prompt_escalates_without_an_efficient_attempt() -> Result<()> {
    let continuing = route(|_| {})?;
    let route = route(|_| {})?;
    let calls = Arc::new(Calls::default());
    let blank_follow_up = vec![
        Message::text(Role::User, "what is 2 + 2?"),
        Message::text(Role::Assistant, "4"),
        Message::text(Role::User, " "),
    ];
    for messages in [
        vec![Message::text(Role::User, "  \n ")],
        vec![Message::text(Role::User, "\u{200B}\u{FEFF}")],
        blank_follow_up,
    ] {
        assert_eq!(
            drive(&route, session(messages), calls.clone(), complete_call, 0.0).await?,
            "capable"
        );
    }
    assert_eq!(calls.0.load(Ordering::Relaxed), 0);

    // Tool results sent as a user message continue the task; they are not a blank prompt.
    let mut results = result("a", "file.txt");
    results.role = Role::User;
    let continuation = session(vec![
        Message::text(Role::User, "list files"),
        call("a"),
        results,
    ]);
    drive(&continuing, continuation, calls.clone(), complete_call, 0.0).await?;
    assert_eq!(calls.0.load(Ordering::Relaxed), 1);
    Ok(())
}

#[tokio::test]
async fn an_agent_marked_nudge_keeps_a_single_escalation_on_capable() -> Result<()> {
    let route = route(|_| {})?;
    let calls = Arc::new(Calls::default());
    let truncated = || tool_call(json!(r#"{"command":"l"#), StopReason::MaxTokens);
    let task = session(vec![Message::text(Role::User, "fix the build")]);
    drive(&route, task, calls.clone(), truncated, 0.0).await?;
    let nudge = vec![
        Message::text(Role::User, "fix the build"),
        Message::text(Role::Assistant, "fixed"),
        Message::text(Role::User, "Verify the change before you stop."),
    ];
    let nudge = initiated_by(session(nudge), "agent");
    assert_eq!(
        drive(&route, nudge, calls.clone(), complete_call, 0.0).await?,
        "capable"
    );
    assert_eq!(calls.0.load(Ordering::Relaxed), 1);
    Ok(())
}

fn initiated_by(mut request: Request, initiator: &str) -> Request {
    let metadata = request.metadata.get_or_insert_with(Metadata::default);
    metadata
        .http_headers
        .get_or_insert_with(http::HeaderMap::new)
        .insert("x-initiator", initiator.parse().unwrap());
    request
}

#[tokio::test]
async fn a_held_follow_up_records_the_latch_as_its_reason() -> Result<()> {
    use crate::core::algorithm::Call;
    use crate::core::testing::serve_decision;

    let algorithm = route(|config| config.mode = ServingMode::Shadow)?;
    let models = Arc::new(category_models(Category::Any, &["efficient", "capable"]).into());
    let serve = |call| async move {
        match call {
            Call::Model(call) => call.respond(std::future::ready(Ok(reply("done")))).await,
            Call::Decision(call) => serve_decision(*call).await,
        }
    };
    let escalated = crate::drive(
        Arc::clone(&algorithm),
        session(vec![Message::text(Role::User, "fix the build")]),
        Arc::clone(&models),
        serve,
    )
    .await?;
    assert_eq!(escalated.selected_model_ids, vec![ModelId::new("capable")]);

    let held = crate::drive(
        algorithm,
        session(vec![
            Message::text(Role::User, "fix the build"),
            call("c1"),
            result("c1", "ok"),
        ]),
        models,
        serve,
    )
    .await?;
    assert_eq!(held.selected_model_ids, vec![ModelId::new("capable")]);
    let evidence = held
        .metadata
        .and_then(|metadata| metadata.evidence)
        .unwrap_or_default();
    assert_eq!(evidence["source"], "vgr");
    assert_eq!(evidence["reason_code"], "turn_verification_latched");
    assert_eq!(evidence["verdict"], "capable");
    Ok(())
}

#[tokio::test]
async fn shadow_rechecks_new_user_turns_with_session_latching_enabled() -> Result<()> {
    let route = route(|config| {
        config.mode = ServingMode::Shadow;
        config.latch_escalation = true;
    })?;
    let calls = Arc::new(Calls::default());
    for messages in [
        vec![Message::text(Role::User, "fix the build")],
        vec![
            Message::text(Role::User, "fix the build"),
            Message::text(Role::Assistant, "fixed"),
            Message::text(Role::User, "now add a test"),
        ],
    ] {
        assert_eq!(
            drive(&route, session(messages), calls.clone(), complete_call, 0.0).await?,
            "capable"
        );
    }
    assert_eq!(calls.0.load(Ordering::Relaxed), 2);
    Ok(())
}

#[tokio::test]
async fn an_escalation_latch_holds_the_session_past_new_questions() -> Result<()> {
    let route = route(|config| config.latch_escalation = true)?;
    let calls = Arc::new(Calls::default());
    let truncated = || tool_call(json!(r#"{"command":"l"#), StopReason::MaxTokens);
    let task = session(vec![Message::text(Role::User, "fix the build")]);
    assert_eq!(
        drive(&route, task, calls.clone(), truncated, 0.0).await?,
        "capable"
    );
    let follow_up = session(vec![
        Message::text(Role::User, "fix the build"),
        Message::text(Role::Assistant, "fixed"),
        Message::text(Role::User, "now add a test"),
    ]);
    assert_eq!(
        drive(&route, follow_up, calls.clone(), complete_call, 0.0).await?,
        "capable"
    );
    assert_eq!(calls.0.load(Ordering::Relaxed), 1);
    Ok(())
}

#[tokio::test]
async fn an_initiator_header_decides_when_the_turn_latch_releases() -> Result<()> {
    let route = route(|_| {})?;
    let calls = Arc::new(Calls::default());
    let task = || session(vec![Message::text(Role::User, "fix the build")]);
    drive(&route, task(), calls.clone(), complete_call, 0.9).await?;
    drive(&route, task(), calls.clone(), complete_call, 0.9).await?;
    assert_eq!(calls.0.load(Ordering::Relaxed), 2);

    // A client nudge after a final reply looks like a new question; marked agent, it keeps the latch.
    let nudge = vec![
        Message::text(Role::User, "fix the build"),
        Message::text(Role::Assistant, "fixed"),
        Message::text(Role::User, "Verify the change before you stop."),
    ];
    assert_eq!(
        drive(
            &route,
            initiated_by(session(nudge), "agent"),
            calls.clone(),
            complete_call,
            0.0
        )
        .await?,
        "capable"
    );
    assert_eq!(calls.0.load(Ordering::Relaxed), 2);

    // A person's correction after tool results looks like a continuation; marked user, it is verified afresh.
    let steer = vec![
        Message::text(Role::User, "fix the build"),
        call("c1"),
        result("c1", "ok"),
        Message::text(Role::User, "use the staging config instead"),
    ];
    assert_eq!(
        drive(
            &route,
            initiated_by(session(steer), "user"),
            calls.clone(),
            complete_call,
            0.0
        )
        .await?,
        "efficient"
    );
    assert_eq!(calls.0.load(Ordering::Relaxed), 3);
    Ok(())
}

#[tokio::test]
async fn tool_work_from_an_earlier_user_turn_is_not_handed_off() -> Result<()> {
    let route = route(|config| config.agentic_handoff = true)?;
    let (selected, _) = test_drive_with_models(
        route,
        session(vec![
            Message::text(Role::User, "fix the build"),
            call("c1"),
            result("c1", "ok"),
            Message::text(Role::Assistant, "the build passes"),
            Message::text(Role::User, "What is 41 plus 42?"),
        ]),
        category_models(Category::Any, &["efficient", "capable"]),
        |target: ModelId, request: Request| async move {
            Ok(match target.as_str() {
                "efficient" => reply("83"),
                "capable" => {
                    let text =
                        serde_json::to_string(&request.llm_request.messages).unwrap_or_default();
                    assert!(text.contains("41 plus 42"));
                    assert!(!text.contains("Routing notice"));
                    reply("83")
                }
                _ => scored(0.0),
            })
        },
    )
    .await?;
    assert_eq!(selected, "capable");
    Ok(())
}

#[tokio::test]
async fn a_capable_decision_falls_back_to_efficient_without_the_handoff_note() -> Result<()> {
    use crate::core::algorithm::Call;
    use crate::core::testing::serve_decision;

    let task = || {
        session(vec![
            Message::text(Role::User, "fix the build"),
            call("c1"),
            result("c1", "ok"),
        ])
    };
    let noted = |request: &Request| {
        serde_json::to_string(&request.llm_request.messages)
            .is_ok_and(|text| text.contains("Routing notice"))
    };
    for killed in [false, true] {
        let switch = super::super::KillSwitch::new();
        let algorithm = route(|config| {
            config.agentic_handoff = true;
            config.kill_switch = Some(switch.clone());
        })?;
        drive(
            &algorithm,
            session(vec![Message::text(Role::User, "fix the build")]),
            Arc::new(Calls::default()),
            complete_call,
            0.0,
        )
        .await?;
        if killed {
            switch.engage();
        }
        let outcome = crate::drive(
            algorithm,
            task(),
            Arc::new(category_models(Category::Any, &["efficient", "capable"]).into()),
            |call| async move {
                match call {
                    Call::Model(call) => {
                        let response = match call.models[0].as_str() {
                            "efficient" => reply("the build passes"),
                            "judge" => scored(0.0),
                            _ => reply("no"),
                        };
                        call.respond(std::future::ready(Ok(response))).await
                    }
                    Call::Decision(call) => serve_decision(*call).await,
                }
            },
        )
        .await?;
        assert!(noted(&outcome.request));
        if killed {
            assert_eq!(outcome.selected_model_ids, vec![ModelId::new("capable")]);
            assert!(outcome.fallback_request.is_none());
        } else {
            assert_eq!(
                outcome.selected_model_ids,
                vec![ModelId::new("capable"), ModelId::new("efficient")]
            );
            let fallback = outcome
                .fallback_request
                .expect("an efficient fallback request");
            assert_eq!(fallback.llm_request.messages, task().llm_request.messages);
        }
    }
    Ok(())
}

#[tokio::test]
async fn default_verification_asks_capable_evidence_then_answer() -> Result<()> {
    for (evidence, answer, expected) in [
        ("yes", "yes", "efficient"),
        ("yes", "no", "capable"),
        ("yes", "unclear", "capable"),
        ("no", "yes", "capable"),
        ("unclear", "yes", "capable"),
    ] {
        let route = route(|_| {})?;
        let calls = Arc::new(parking_lot::Mutex::new(Vec::new()));
        let seen = Arc::clone(&calls);
        let (selected, _) = test_drive_with_models(
            route,
            session(vec![Message::text(Role::User, "explain quicksort")]),
            category_models(Category::Any, &["efficient", "capable"]),
            move |target: ModelId, request: Request| {
                let seen = Arc::clone(&seen);
                async move {
                    Ok(match target.as_str() {
                        "efficient" => reply("Choose a pivot and partition the input."),
                        "judge" => scored(0.1),
                        "capable-judge" => {
                            let is_answer = request
                                .llm_request
                                .instructions
                                .iter()
                                .flat_map(|block| &block.content)
                                .any(|block| {
                                    matches!(block, ContentBlock::Text { text }
                                    if text.starts_with("You are a strict answer verifier"))
                                });
                            seen.lock().push(is_answer);
                            reply(if is_answer { answer } else { evidence })
                        }
                        _ => reply("capable answer"),
                    })
                }
            },
        )
        .await?;
        assert_eq!(selected.as_str(), expected, "{evidence}, {answer}");
        assert_eq!(
            *calls.lock(),
            if evidence == "yes" {
                vec![false, true]
            } else {
                vec![false]
            }
        );
    }
    Ok(())
}

#[tokio::test]
async fn shadow_keeps_judging_a_turn_until_vgr_escalates_it() -> Result<()> {
    fn truncated() -> Response {
        tool_call(json!(r#"{"command":"l"#), StopReason::MaxTokens)
    }
    for latch_escalation in [false, true] {
        let route = route(|config| {
            config.mode = ServingMode::Shadow;
            config.latch_escalation = latch_escalation;
        })?;
        let calls = Arc::new(Calls::default());
        let mut messages = vec![Message::text(Role::User, "fix the build")];
        for (step, efficient) in [complete_call, complete_call, truncated, complete_call]
            .into_iter()
            .enumerate()
        {
            assert_eq!(
                drive(
                    &route,
                    session(messages.clone()),
                    calls.clone(),
                    efficient,
                    0.1
                )
                .await?,
                "capable"
            );
            let id = format!("c{step}");
            messages.extend([call(&id), result(&id, "ok")]);
        }
        assert_eq!(calls.0.load(Ordering::Relaxed), 3);
        messages.push(Message::text(Role::User, "keep going"));
        drive(
            &route,
            initiated_by(session(messages.clone()), "agent"),
            calls.clone(),
            complete_call,
            0.1,
        )
        .await?;
        assert_eq!(calls.0.load(Ordering::Relaxed), 3);
        drive(
            &route,
            initiated_by(session(messages), "user"),
            calls.clone(),
            complete_call,
            0.1,
        )
        .await?;
        assert_eq!(calls.0.load(Ordering::Relaxed), 4);
    }
    Ok(())
}

#[tokio::test]
async fn shadow_final_answer_commits_do_not_latch_but_rejections_do() -> Result<()> {
    let route = route(|config| {
        config.mode = ServingMode::Shadow;
        config.targets.capable_judge = None;
    })?;
    let calls = Arc::new(Calls::default());
    let mut messages = vec![Message::text(Role::User, "explain quicksort")];
    for probability in [0.9, 0.9, 0.1, 0.9] {
        let task = initiated_by(session(messages.clone()), "agent");
        assert_eq!(
            drive(
                &route,
                task,
                calls.clone(),
                || reply("Partition around a pivot."),
                probability
            )
            .await?,
            "capable"
        );
        messages.push(Message::text(Role::Assistant, "Partition around a pivot."));
        messages.push(Message::text(Role::User, "continue"));
    }
    assert_eq!(calls.0.load(Ordering::Relaxed), 3);
    Ok(())
}

#[tokio::test]
async fn client_recovery_messages_keep_the_turn_latch() -> Result<()> {
    let route = route(|_| {})?;
    assert!(route.tracks_answers());
    let calls = Arc::new(Calls::default());
    let task = || session(vec![Message::text(Role::User, "fix the build")]);
    for _ in 0..2 {
        drive(&route, task(), calls.clone(), complete_call, 0.9).await?;
    }
    // Hermes-style recovery: a nudge after an empty answer, and one sent the moment a
    // complete-looking answer promised a tool call it never made.
    for (final_reply, previous, nudge) in [
        (
            false,
            "(empty)",
            "You just executed tool calls but returned an empty response.",
        ),
        (
            true,
            "Let me run the tests.",
            "Your previous turn indicated a tool call but none was included.",
        ),
    ] {
        route
            .observe_answer("session-1", AnswerSummary { final_reply })
            .await;
        let recovery = session(vec![
            Message::text(Role::User, "fix the build"),
            Message::text(Role::Assistant, previous),
            Message::text(Role::User, nudge),
        ]);
        assert_eq!(
            drive(&route, recovery, calls.clone(), complete_call, 0.0).await?,
            "capable"
        );
    }
    assert_eq!(calls.0.load(Ordering::Relaxed), 2);
    let next = initiated_by(
        session(vec![
            Message::text(Role::User, "fix the build"),
            Message::text(Role::Assistant, "Let me run the tests."),
            Message::text(Role::User, "now do another task"),
        ]),
        "user",
    );
    assert_eq!(
        drive(&route, next, calls.clone(), complete_call, 0.0).await?,
        "efficient"
    );
    assert_eq!(calls.0.load(Ordering::Relaxed), 3);
    Ok(())
}

#[test]
fn only_a_paused_reply_to_a_reported_final_answer_releases_the_latch() {
    let messages = [
        Message::text(Role::User, "fix the build"),
        Message::text(Role::Assistant, "fixed"),
        Message::text(Role::User, "now add a test"),
    ];
    let now = unix_seconds();
    for (reported, releases) in [
        (None, true),
        (Some(0), false),
        (Some(now), false),
        (Some(now - FOLLOW_UP_QUIET_SECS), true),
    ] {
        let mut state = State::default();
        if let Some(finished) = reported {
            state
                .extra
                .insert(LAST_ANSWER_FINAL_KEY.into(), StateValue::Count(finished));
        }
        assert_eq!(
            answers_final_reply(&state, &messages),
            releases,
            "{reported:?}"
        );
    }
}

#[tokio::test]
async fn a_failed_capable_verifier_still_offers_the_efficient_answer() -> Result<()> {
    use crate::core::algorithm::Call;
    use crate::core::testing::serve_decision;

    let algorithm = route(|config| config.task_typing = true)?;
    let task = || session(vec![Message::text(Role::User, "What is 1+1?")]);
    // Exercise production error propagation through CallModel::respond.
    let outcome = crate::drive(
        algorithm,
        task(),
        Arc::new(category_models(Category::Any, &["efficient", "capable"]).into()),
        |call| async move {
            match call {
                Call::Model(call) => {
                    let target = call.models[0].clone();
                    let readout = call
                        .request
                        .llm_request
                        .extensions
                        .fields
                        .contains_key("logprobs");
                    let response = match target.as_str() {
                        "efficient" => Ok(reply("2")),
                        "judge" if readout => Ok(scored(0.05)),
                        "judge" => Ok(reply("Answer")),
                        _ => Err(crate::LibsyError::client_call(
                            target,
                            LlmClientError::UpstreamHttp {
                                status: http::StatusCode::BAD_GATEWAY,
                                body: String::new(),
                                headers: Box::default(),
                            },
                        )),
                    };
                    call.respond(std::future::ready(response)).await
                }
                Call::Decision(call) => serve_decision(*call).await,
            }
        },
    )
    .await?;
    assert_eq!(
        outcome.selected_model_ids,
        vec![ModelId::new("capable"), ModelId::new("efficient")]
    );
    let fallback = outcome
        .fallback_request
        .expect("an efficient fallback request");
    assert_eq!(fallback.llm_request.messages, task().llm_request.messages);
    Ok(())
}

#[tokio::test]
async fn a_step_that_cannot_commit_over_a_tool_error_skips_local_checks() -> Result<()> {
    let failed = session(vec![
        Message::text(Role::User, "What is happening today?"),
        call("c1"),
        result("c1", r#"{"error": "search-only backend"}"#),
    ]);
    // A typed answer with tool use in its turn is judged as chat, which needs a clean record.
    for (typed, expected) in [
        ("Answer", vec!["judge", "efficient", "capable"]),
        ("Chat", vec!["judge", "capable"]),
    ] {
        let calls = Arc::new(parking_lot::Mutex::new(Vec::new()));
        let seen = Arc::clone(&calls);
        let (selected, _) = test_drive_with_models(
            route(|config| config.task_typing = true)?,
            failed.clone(),
            category_models(Category::Any, &["efficient", "capable"]),
            move |target: ModelId, _| {
                seen.lock().push(target.to_string());
                std::future::ready(Ok(reply(typed)))
            },
        )
        .await?;
        assert_eq!(selected.as_str(), "capable");
        assert_eq!(*calls.lock(), expected, "typed {typed}");
    }
    Ok(())
}

#[tokio::test]
async fn attachment_verifiers_receive_the_evidence_even_without_user_text() -> Result<()> {
    use switchyard_protocol::{FileSource, ImageSource, ToolResult};
    let image = ContentBlock::Image {
        source: ImageSource::Url {
            url: "https://example.test/invoice.png".into(),
            detail: None,
        },
    };
    for content in [
        vec![
            ContentBlock::Text {
                text: "What is the total?".into(),
            },
            image.clone(),
        ],
        vec![image.clone()],
        vec![ContentBlock::Text { text: "   ".into() }, image.clone()],
        vec![
            ContentBlock::Text {
                text: "Read the screenshot".into(),
            },
            ContentBlock::ToolResult(ToolResult {
                tool_call_id: "shot".into(),
                content: vec![image.clone()],
                is_error: None,
            }),
        ],
    ] {
        let expects_typing = content
            .iter()
            .any(|block| matches!(block, ContentBlock::Text { text } if !text.trim().is_empty()));
        let route = route(|config| {
            config.efficient_supports_attachments = true;
            config.task_typing = true;
        })?;
        let evidence = image.clone();
        let checks = Arc::new(AtomicUsize::new(0));
        let seen = checks.clone();
        let (selected, _) = test_drive_with_models(
            route,
            request(vec![Message::new(Role::User, content)]),
            category_models(Category::Any, &["efficient", "capable"]),
            move |target: ModelId, request: Request| {
                let evidence = evidence.clone();
                let seen = seen.clone();
                async move {
                    if matches!(target.as_str(), "judge" | "capable-judge") {
                        assert!(
                            request
                                .llm_request
                                .messages
                                .iter()
                                .any(|m| m.content.contains(&evidence)),
                            "{target} did not receive the image"
                        );
                        let n = seen.fetch_add(1, Ordering::Relaxed);
                        return Ok(if expects_typing && n == 0 {
                            reply("answer")
                        } else {
                            scored(0.99)
                        });
                    }
                    Ok(reply("$482.17"))
                }
            },
        )
        .await?;
        assert_eq!(selected.as_str(), "efficient");
        assert_eq!(
            checks.load(Ordering::Relaxed),
            if expects_typing { 2 } else { 1 }
        );
    }
    let pdf = ContentBlock::File {
        source: FileSource::FileData {
            data: "data:application/pdf;base64,cGRm".into(),
            filename: Some("invoice.pdf".into()),
        },
    };
    let route = route(|_| {})?;
    let (selected, _) = test_drive_with_models(
        route,
        request(vec![Message::new(
            Role::User,
            vec![
                ContentBlock::Text {
                    text: "Read the PDF".into(),
                },
                pdf,
            ],
        )]),
        category_models(Category::Any, &["efficient", "capable"]),
        |target: ModelId, _| async move {
            assert_eq!(
                target.as_str(),
                "capable",
                "attachments disabled must skip efficient"
            );
            Ok(reply("$482.17"))
        },
    )
    .await?;
    assert_eq!(selected.as_str(), "capable");
    Ok(())
}

#[tokio::test]
async fn every_verification_rung_receives_the_attachment() -> Result<()> {
    let image = ContentBlock::Image {
        source: switchyard_protocol::ImageSource::Url {
            url: "https://example.test/invoice.png".into(),
            detail: None,
        },
    };
    let route = route(|config| config.efficient_supports_attachments = true)?;
    let checks = Arc::new(AtomicUsize::new(0));
    let observed = checks.clone();
    let evidence = image.clone();
    let (selected, _) = test_drive_with_models(
        route,
        request(vec![Message::new(
            Role::User,
            vec![
                ContentBlock::Text {
                    text: "Read the invoice".into(),
                },
                image,
            ],
        )]),
        category_models(Category::Any, &["efficient", "capable"]),
        move |target: ModelId, request: Request| {
            let observed = observed.clone();
            let evidence = evidence.clone();
            async move {
                if target.as_str().contains("judge") {
                    assert!(
                        request
                            .llm_request
                            .messages
                            .iter()
                            .any(|m| m.content.contains(&evidence))
                    );
                    observed.fetch_add(1, Ordering::Relaxed);
                    return Ok(if target.as_str() == "judge" {
                        scored(0.01)
                    } else {
                        reply("no")
                    });
                }
                Ok(reply("$482.17"))
            }
        },
    )
    .await?;
    assert_eq!(selected.as_str(), "capable");
    // Confidence, deliberation, scored verdict, and capable confirmation.
    assert_eq!(checks.load(Ordering::Relaxed), 4);
    Ok(())
}

#[tokio::test]
async fn disabled_attachments_skip_all_media_and_prevent_efficient_stand_in() -> Result<()> {
    use switchyard_protocol::{FileSource, ImageSource, MediaSource, ToolResult};
    for block in [
        ContentBlock::Image {
            source: ImageSource::Url {
                url: "https://example.test/a.png".into(),
                detail: None,
            },
        },
        ContentBlock::File {
            source: FileSource::FileId("pdf".into()),
        },
        ContentBlock::Audio {
            source: MediaSource::Url {
                url: "https://example.test/a.wav".into(),
                media_type: None,
            },
        },
        ContentBlock::Video {
            source: MediaSource::Url {
                url: "https://example.test/a.mp4".into(),
                media_type: None,
            },
        },
    ] {
        for nested in [false, true] {
            let block = if nested {
                ContentBlock::ToolResult(ToolResult {
                    tool_call_id: "media".into(),
                    content: vec![block.clone()],
                    is_error: None,
                })
            } else {
                block.clone()
            };
            let route = route(|_| {})?;
            let mut input = request(vec![Message::new(
                Role::User,
                vec![
                    ContentBlock::Text {
                        text: "Read the attachment".into(),
                    },
                    block,
                ],
            )]);
            input
                .llm_request
                .instructions
                .push(switchyard_protocol::InstructionBlock {
                    role: Role::System,
                    content: vec![ContentBlock::Text {
                        text: "Read carefully".into(),
                    }],
                });
            let outcome = crate::core::testing::test_drive_with_state(
                route,
                input,
                category_models(Category::Any, &["efficient", "capable"]),
                State::default(),
                |_target: ModelId, _request: Request| async {
                    panic!("no efficient or verifier calls expected")
                },
            )
            .await?;
            assert_eq!(outcome.selected_model_ids, vec![ModelId::new("capable")]);
        }
    }
    Ok(())
}