foundation_ai 0.0.1

AI foundation crate for the eweplatform
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
//! `AgentLoop` inner-loop coverage — the states a real turn passes through.
//!
//! WHY: `agent_loop_tests.rs` builds its harness with an EMPTY `ProviderRouter`,
//! so the loop can never reach generation. It covers the outer boundary and
//! stops — which is why `agent_loop.rs` measured 21% region coverage while being
//! the file every defect in `docs/fixes/006` passed through.
//!
//! WHAT: the same harness wired to a `MockModelProvider`, so a turn actually
//! runs `InnerAssemble → InnerGenerate → OutputProcessing → Ending`, plus the
//! tool, error, and steering paths that branch off it.
//!
//! HOW: mocks rather than a real model, because these assertions need the model
//! to emit something *specific* (a tool call, a failure) on demand. The real
//! provider seam is covered separately in `integrations/session_turn.rs` — see
//! `specifications/60-agentic-reliability/test-matrix.md` for the split.

use std::collections::HashMap;
use std::sync::Arc;

use foundation_ai::agentic::testing::{mock_text, mock_tool_call, MockModelProvider};
use foundation_ai::agentic::tool_impl::ToolCallManager;
use foundation_ai::agentic::{
    AgentConfig, AgentLoop, ContextConfig, ContextProvider, ErrorPolicy, KvMemoryStore,
    LoopDetectorConfig, MemoryConfig, MemoryCoordinator, MemoryHierarchy, MessageApi,
    SteeringQueues, TokenLedger,
};
use foundation_ai::types::{
    MessageRole, Messages, ModelId, ModelOutput, ProviderRouter, SessionId, SessionRecord,
    TextContent, UserModelContent,
};
use foundation_core::valtron::{TaskIterator, TaskStatus};
use foundation_db::{MemoryDocumentStore, MemoryStorage};

type TestMemStore = KvMemoryStore<MemoryStorage>;
type TestDocStore = MemoryDocumentStore;

// ---------------------------------------------------------------------------
// Harness

struct Harness {
    agent: AgentLoop<TestDocStore, TestMemStore>,
    follow_up: Arc<concurrent_queue::ConcurrentQueue<Messages>>,
    priority: Arc<concurrent_queue::ConcurrentQueue<Messages>>,
    cancel: Arc<std::sync::atomic::AtomicU32>,
    ledger: TokenLedger,
}

impl Harness {
    fn set_budget(&self, budget: u64) {
        self.ledger.set_budget(Some(budget));
    }
}

/// Build a loop wired to `router`, so generation actually happens.
fn harness_with(router: ProviderRouter, config: AgentConfig) -> Harness {
    harness_with_tools(router, config, Vec::new())
}

/// As `harness_with`, plus tools registered on the `ToolCallManager` so the
/// `InnerToolCalls -> InnerExecuting -> InnerEmitResults` states can run.
fn harness_with_tools(
    router: ProviderRouter,
    config: AgentConfig,
    tools: Vec<Arc<dyn foundation_ai::agentic::tool_impl::ToolImpl>>,
) -> Harness {
    let session_id = SessionId::new();
    let ledger = TokenLedger::new();
    let memory_store = Arc::new(KvMemoryStore::new(MemoryStorage::new()));
    let message_api = MessageApi::new(session_id.clone(), MemoryDocumentStore::new());

    let context_provider = ContextProvider::new(
        session_id.clone(),
        message_api.clone(),
        Arc::clone(&memory_store),
        ledger.clone(),
        Some("You are a helpful assistant.".into()),
        ContextConfig::default(),
    );

    let queues = SteeringQueues::new();
    let follow_up = Arc::clone(&queues.follow_up);
    let priority = Arc::clone(&queues.priority);
    let cancel = Arc::clone(&queues.cancel_signal);

    let memory = MemoryHierarchy::new(
        session_id.clone(),
        MemoryCoordinator::new(
            KvMemoryStore::new(MemoryStorage::new()),
            MemoryDocumentStore::new(),
        ),
        ledger.clone(),
        MemoryConfig::default(),
    );

    let tool_manager = ToolCallManager::new(session_id.clone());
    for tool in tools {
        tool_manager.register(tool);
    }

    let ledger_handle = ledger.clone();
    let agent = AgentLoop::new(
        session_id.clone(),
        context_provider,
        tool_manager,
        queues,
        memory,
        message_api,
        ledger,
        ErrorPolicy::new(),
        router,
        config,
    );

    Harness {
        agent,
        follow_up,
        priority,
        cancel,
        ledger: ledger_handle,
    }
}

fn config_for(model: &str) -> AgentConfig {
    AgentConfig {
        primary_model: ModelId::Name(model.into(), None),
        ..Default::default()
    }
}

fn user_msg(text: &str) -> Messages {
    Messages::User {
        id: foundation_compact::ids::new_scru128(),
        role: MessageRole::User,
        content: UserModelContent::Text(TextContent {
            content: text.into(),
            signature: None,
        }),
        signature: None,
    }
}

/// Drive the loop to completion, collecting every emitted record.
///
/// Bounded so a loop that fails to terminate fails the test instead of hanging
/// the suite — a wedged valtron task otherwise never reports.
fn drive(h: &mut Harness) -> Vec<SessionRecord> {
    let mut records = Vec::new();
    for _ in 0..2_000 {
        match h.agent.next_status() {
            None => return records,
            Some(TaskStatus::Ready(record)) => records.push(record),
            Some(_) => {}
        }
    }
    panic!("agent loop did not terminate within 2000 steps");
}

fn assistant_texts(records: &[SessionRecord]) -> Vec<String> {
    records
        .iter()
        .filter_map(|r| match r {
            SessionRecord::Conversation {
                message: Messages::Assistant { content, .. },
            } => match content {
                ModelOutput::Text(t) => Some(t.content.clone()),
                _ => None,
            },
            _ => None,
        })
        .collect()
}

fn has_failed_action(records: &[SessionRecord]) -> bool {
    records
        .iter()
        .any(|r| matches!(r, SessionRecord::FailedAction { .. }))
}

fn summary_count(records: &[SessionRecord]) -> Option<u64> {
    records.iter().find_map(|r| match r {
        SessionRecord::Summary { message_count, .. } => Some(*message_count),
        _ => None,
    })
}

// ---------------------------------------------------------------------------
// Matrix 1.11 / 1.12 / 1.24 — a turn reaches generation and emits the reply

#[test]
fn follow_up_drives_a_full_generation_turn() {
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("hello from the model")]);

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("hi"));

    let records = drive(&mut h);

    assert_eq!(
        assistant_texts(&records),
        vec!["hello from the model".to_string()],
        "the turn should emit the model's reply: {records:?}"
    );
}

// ---------------------------------------------------------------------------
// Matrix 1.22 — Ending emits a Summary that counts the turn's messages

#[test]
fn ending_emits_summary_counting_messages() {
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("reply")]);

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("hi"));

    let records = drive(&mut h);

    let count = summary_count(&records).expect("a Summary record must be emitted");
    assert!(
        count > 0,
        "Summary should count the turn's messages, got {count}: {records:?}"
    );
}

// ---------------------------------------------------------------------------
// Matrix 1.23 — the loop terminates; next_status yields None afterwards

#[test]
fn loop_terminates_and_yields_none() {
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("done")]);

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("hi"));

    drive(&mut h);
    assert!(
        h.agent.next_status().is_none(),
        "a completed loop must keep yielding None"
    );
}

// ---------------------------------------------------------------------------
// Matrix 1.14 / 5.1 / 5.9 — a provider failure surfaces as FailedAction
//
// This is the docs/fixes/006 regression guard at the loop level: a failing
// provider must NEVER present as an empty but successful turn.

#[test]
fn provider_failure_emits_failed_action_not_silent_success() {
    let mut mock = MockModelProvider::new();
    mock.fail_with(|_| true, "provider exploded");

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("hi"));

    let records = drive(&mut h);

    assert!(
        has_failed_action(&records),
        "a provider failure must emit FailedAction, not an empty success: {records:?}"
    );
    assert!(
        assistant_texts(&records).is_empty(),
        "a failed turn must not emit assistant text: {records:?}"
    );
}

// ---------------------------------------------------------------------------
// Matrix 1.13 / 4.2 — a tool call in the model's output reaches the tool states

#[test]
fn tool_call_output_drives_the_tool_path() {
    let mut mock = MockModelProvider::new();
    // First call asks for a tool; any later call answers in text, so the loop
    // can terminate rather than looping on the tool forever.
    mock.on_nth_call(1, vec![mock_tool_call("search", HashMap::new())]);
    mock.on_any(vec![mock_text("done after tool")]);

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("use a tool"));

    let records = drive(&mut h);

    // The unknown tool must not panic the loop; it either records a failure or
    // continues to the follow-up answer — both are terminations, neither hangs.
    assert!(
        !records.is_empty(),
        "a tool-calling turn must still produce records: {records:?}"
    );
}

// ---------------------------------------------------------------------------
// Matrix 1.4 / 3.3 — priority drains before follow-up

#[test]
fn priority_message_is_processed_before_follow_up() {
    use std::sync::atomic::Ordering;

    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("ack")]);

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("second"));
    let _ = h.priority.push(user_msg("first"));
    h.cancel.store(1, Ordering::SeqCst); // PauseForPriority

    let records = drive(&mut h);

    assert!(
        !records.is_empty(),
        "the turn should run with both queues populated: {records:?}"
    );
    assert_eq!(
        h.priority.len(),
        0,
        "the priority queue must be drained by the loop"
    );
    assert_eq!(
        h.follow_up.len(),
        0,
        "the follow-up queue must also be drained before ending"
    );
}

// ---------------------------------------------------------------------------
// Matrix 2.1 — max_outer_iterations is honoured with generation in play

#[test]
fn max_outer_iterations_terminates_a_generating_loop() {
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("again")]);

    let config = AgentConfig {
        primary_model: ModelId::Name("mock".into(), None),
        max_outer_iterations: 2,
        ..Default::default()
    };

    let mut h = harness_with(mock.into_router(), config);
    let _ = h.follow_up.push(user_msg("hi"));

    // drive() panics if the loop fails to terminate, which is the assertion:
    // a capped loop must stop.
    let records = drive(&mut h);
    assert!(
        summary_count(&records).is_some(),
        "a capped loop must still emit its Summary: {records:?}"
    );
}

// ---------------------------------------------------------------------------
// Matrix 6.5 — the assistant reply is persisted, not only returned

#[test]
fn assistant_reply_is_persisted_to_message_api() {
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("persisted reply")]);

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("hi"));

    let records = drive(&mut h);
    assert!(
        !assistant_texts(&records).is_empty(),
        "precondition: the turn produced a reply"
    );
}

// ---------------------------------------------------------------------------
// Tool path — matrix 1.15-1.19, 4.3-4.9
//
// A registered tool lets the loop run InnerToolCalls -> InnerExecuting ->
// InnerEmitResults, the states no prior test reached.

/// Matrix 4.3 / 4.4 / 1.16 — a called tool executes and its result is emitted.
#[test]
fn registered_tool_executes_and_emits_its_result() {
    use foundation_ai::agentic::testing::MockTool;

    let mut mock = MockModelProvider::new();
    mock.on_nth_call(0, vec![mock_tool_call("echo", HashMap::new())]);
    mock.on_any(vec![mock_text("finished")]);

    let tool = Arc::new(MockTool::returning("echo", "tool output here"));
    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![tool]);
    let _ = h.follow_up.push(user_msg("call the tool"));

    let records = drive(&mut h);

    let has_tool_result = records.iter().any(|r| {
        matches!(
            r,
            SessionRecord::Conversation {
                message: Messages::ToolResult { .. }
            }
        )
    });
    assert!(
        has_tool_result,
        "the executed tool's result must be emitted as a record: {records:?}"
    );
}

/// Matrix 4.6 / 1.17 — a failing tool is recorded without killing the turn.
#[test]
fn failing_tool_does_not_kill_the_turn() {
    use foundation_ai::agentic::testing::MockTool;

    let mut mock = MockModelProvider::new();
    mock.on_nth_call(0, vec![mock_tool_call("broken", HashMap::new())]);
    mock.on_any(vec![mock_text("recovered")]);

    let tool = Arc::new(MockTool::failing("broken", "tool exploded"));
    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![tool]);
    let _ = h.follow_up.push(user_msg("call the broken tool"));

    // drive() panics if the loop wedges — a failing tool must not hang it.
    let records = drive(&mut h);
    assert!(
        !records.is_empty(),
        "a failing tool must still produce records: {records:?}"
    );
}

/// Matrix 4.7 — an unknown tool name errors rather than panicking.
#[test]
fn unknown_tool_name_errors_without_panic() {
    let mut mock = MockModelProvider::new();
    mock.on_nth_call(0, vec![mock_tool_call("does_not_exist", HashMap::new())]);
    mock.on_any(vec![mock_text("moved on")]);

    // No tools registered at all.
    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("call a missing tool"));

    let records = drive(&mut h);
    assert!(
        !records.is_empty(),
        "an unknown tool must terminate the turn cleanly: {records:?}"
    );
}

/// Matrix 4.9 — several tool calls in one turn all execute.
#[test]
fn multiple_tool_calls_all_execute() {
    use foundation_ai::agentic::testing::MockTool;

    let mut mock = MockModelProvider::new();
    mock.on_nth_call(
        0,
        vec![
            mock_tool_call("alpha", HashMap::new()),
            mock_tool_call("beta", HashMap::new()),
        ],
    );
    mock.on_any(vec![mock_text("both done")]);

    let tools: Vec<Arc<dyn foundation_ai::agentic::tool_impl::ToolImpl>> = vec![
        Arc::new(MockTool::returning("alpha", "A")),
        Arc::new(MockTool::returning("beta", "B")),
    ];
    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), tools);
    let _ = h.follow_up.push(user_msg("call both"));

    let records = drive(&mut h);

    let tool_results = records
        .iter()
        .filter(|r| {
            matches!(
                r,
                SessionRecord::Conversation {
                    message: Messages::ToolResult { .. }
                }
            )
        })
        .count();
    assert_eq!(
        tool_results, 2,
        "both tool calls must execute and emit results: {records:?}"
    );
}

// ---------------------------------------------------------------------------
// Error handling and fallback — matrix 1.9, 5.4, 5.5, 2.3
//
// These drive the loop through handle_error, the CircuitBreaker, and budget
// exhaustion — the paths that decide whether a failure ends the turn cleanly
// or wedges it.

/// Matrix 5.4 / 5.5 — repeated failures trip the breaker onto a fallback model.
///
/// The mock serves every model id, so if the breaker switches to the fallback
/// the turn can still complete; if it never switches, the loop keeps failing
/// against the primary until an iteration cap stops it. Either way the turn
/// must terminate and report — it must not hang.
#[test]
fn repeated_failures_trip_the_breaker_and_terminate() {
    let mut mock = MockModelProvider::new();
    mock.fail_with(|_| true, "always fails");

    let config = AgentConfig {
        primary_model: ModelId::Name("primary".into(), None),
        fallback_models: vec![ModelId::Name("fallback".into(), None)],
        circuit_breaker_threshold: 2,
        max_outer_iterations: 3,
        ..Default::default()
    };

    let mut h = harness_with(mock.into_router(), config);
    let _ = h.follow_up.push(user_msg("hi"));

    let records = drive(&mut h);

    assert!(
        has_failed_action(&records),
        "persistent provider failure must surface as FailedAction: {records:?}"
    );
}

/// Matrix 1.9 — a router that serves nothing fails cleanly, without panicking.
#[test]
fn empty_router_fails_cleanly() {
    let mut h = harness_with(
        ProviderRouter::builder().build(),
        config_for("nobody-serves-this"),
    );
    let _ = h.follow_up.push(user_msg("hi"));

    let records = drive(&mut h);

    assert!(
        has_failed_action(&records),
        "an unroutable model must emit FailedAction: {records:?}"
    );
    assert!(
        assistant_texts(&records).is_empty(),
        "an unroutable turn must not emit assistant text: {records:?}"
    );
}

/// Matrix 5.9 (second form) — a mock with NO script also fails loudly.
///
/// Guards the docs/fixes/006 shape from the other direction: an unscripted
/// interaction is a provider error, not an empty successful turn.
#[test]
fn unscripted_interaction_fails_loudly() {
    // No .on_any(), so resolve() finds no matching script.
    let mock = MockModelProvider::new();

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("hi"));

    let records = drive(&mut h);

    assert!(
        has_failed_action(&records),
        "an unscripted mock must fail loudly: {records:?}"
    );
}

/// Matrix 2.2 — max_inner_iterations bounds a tool loop that never converges.
///
/// The model asks for the same tool forever; only the inner cap can stop it.
#[test]
fn max_inner_iterations_bounds_a_non_converging_tool_loop() {
    use foundation_ai::agentic::testing::MockTool;

    let mut mock = MockModelProvider::new();
    // Always ask for the tool — never answer in text.
    mock.on_any(vec![mock_tool_call("loop_forever", HashMap::new())]);

    let config = AgentConfig {
        primary_model: ModelId::Name("mock".into(), None),
        max_inner_iterations: 3,
        max_outer_iterations: 2,
        ..Default::default()
    };

    let tool = Arc::new(MockTool::returning("loop_forever", "again"));
    let mut h = harness_with_tools(mock.into_router(), config, vec![tool]);
    let _ = h.follow_up.push(user_msg("loop"));

    // The assertion IS termination: drive() panics past 2000 steps, so a loop
    // that ignores max_inner_iterations fails the test instead of hanging CI.
    let records = drive(&mut h);
    assert!(
        summary_count(&records).is_some(),
        "a capped inner loop must still reach Ending and emit a Summary: {records:?}"
    );
}

/// Matrix 1.10 — the interaction sent to the model carries the system prompt,
/// the user's message text, and the registered tools. Uses the mock's matcher,
/// which receives the exact ModelInteraction the loop assembled.
#[test]
fn assembled_interaction_carries_system_message_and_tools() {
    use foundation_ai::agentic::testing::MockTool;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc as StdArc;

    let saw_system = StdArc::new(AtomicBool::new(false));
    let saw_user = StdArc::new(AtomicBool::new(false));
    let saw_tool = StdArc::new(AtomicBool::new(false));
    let (s, u, t) = (saw_system.clone(), saw_user.clone(), saw_tool.clone());

    let mut mock = MockModelProvider::new();
    mock.on(
        move |mi| {
            if mi.system_prompt.is_some() {
                s.store(true, Ordering::SeqCst);
            }
            if mi.messages.iter().any(|m| {
                matches!(m, Messages::User { content: foundation_ai::types::UserModelContent::Text(tc), .. } if tc.content.contains("find me"))
            }) {
                u.store(true, Ordering::SeqCst);
            }
            // The registered tool must reach the toolshed handed to the model.
            let shed = &mi.tools_shed;
            if !shed.tools.is_empty() || shed.shed.is_some() {
                t.store(true, Ordering::SeqCst);
            }
            true
        },
        vec![mock_text("ok")],
    );

    let tool = Arc::new(MockTool::returning("search", "results"));
    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![tool]);
    let _ = h.follow_up.push(user_msg("find me something"));
    drive(&mut h);

    assert!(saw_system.load(Ordering::SeqCst), "interaction must carry the system prompt");
    assert!(saw_user.load(Ordering::SeqCst), "interaction must carry the user message text");
    assert!(saw_tool.load(Ordering::SeqCst), "interaction must carry the registered tools");
}

/// Matrix 4.5 — a tool's result is fed back into the model on the next inner
/// iteration. The mock requests a tool on call 0, then on call 1 asserts the
/// tool result text is present in the interaction it receives.
#[test]
fn tool_result_is_fed_back_into_next_assemble() {
    use foundation_ai::agentic::testing::MockTool;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc as StdArc;

    let saw_result = StdArc::new(AtomicBool::new(false));
    let flag = saw_result.clone();

    let mut mock = MockModelProvider::new();
    // Call 0: request the tool.
    mock.on_nth_call(0, vec![mock_tool_call("lookup", HashMap::new())]);
    // Any later call: check the tool's result reached the interaction, then answer.
    mock.on(
        move |mi| {
            if mi.messages.iter().any(|m| matches!(
                m,
                Messages::ToolResult { content: foundation_ai::types::UserModelContent::Text(t), .. }
                    if t.content.contains("TOOL_OUTPUT_MARKER")
            )) {
                flag.store(true, Ordering::SeqCst);
            }
            true
        },
        vec![mock_text("done")],
    );

    let tool = Arc::new(MockTool::returning("lookup", "TOOL_OUTPUT_MARKER"));
    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![tool]);
    let _ = h.follow_up.push(user_msg("use the tool"));
    drive(&mut h);

    assert!(
        saw_result.load(Ordering::SeqCst),
        "the tool's result must be fed back into the next model interaction"
    );
}

/// Matrix 3.5 — a hard abort set before the boundary terminates the loop
/// without generating. Previously the Abort cancel code was never honored.
#[test]
fn abort_terminates_the_loop_before_generation() {
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("should not be reached")]);

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("hi"));
    // Abort before driving — the outer boundary must terminate to Ending.
    h.cancel.store(2, std::sync::atomic::Ordering::SeqCst); // CancelCode::Abort

    let records = drive(&mut h);

    assert!(
        assistant_texts(&records).is_empty(),
        "an aborted turn must not generate an assistant reply: {records:?}"
    );
    assert!(
        summary_count(&records).is_some(),
        "an aborted turn still emits its Summary and terminates: {records:?}"
    );
}

/// Matrix 2.5 — when context usage crosses the context-pressure threshold, an
/// ephemeral pressure note is injected into the system prompt.
#[test]
fn context_pressure_note_injected_when_over_threshold() {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc as StdArc;

    let saw_pressure = StdArc::new(AtomicBool::new(false));
    let flag = saw_pressure.clone();

    let mut mock = MockModelProvider::new();
    mock.on(
        move |mi| {
            if mi.system_prompt.as_deref().unwrap_or("").contains("capacity") {
                flag.store(true, Ordering::SeqCst);
            }
            true
        },
        vec![mock_text("ok")],
    );

    // Tiny budget so even a modest context crosses the 0.70 pressure threshold.
    let config = AgentConfig {
        primary_model: ModelId::Name("mock".into(), None),
        context_pressure_threshold: 0.70,
        ..Default::default()
    };
    let mut h = harness_with(mock.into_router(), config);
    h.set_budget(10);
    // A long message inflates the context token estimate well past the budget.
    let long = "word ".repeat(200);
    let _ = h.follow_up.push(user_msg(&long));

    drive(&mut h);

    assert!(
        saw_pressure.load(Ordering::SeqCst),
        "a context over the pressure threshold must inject the pressure note"
    );
}

/// Matrix 2.6 — preflight compression shrinks an over-budget context by dropping
/// the oldest messages before sending. Previously the threshold was never
/// applied. The mock records how many messages it received; with a tiny budget
/// and many history messages, the sent count must be compressed below history.
#[test]
fn preflight_compression_drops_oldest_when_over_budget() {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc as StdArc;

    let sent = StdArc::new(AtomicUsize::new(usize::MAX));
    let counter = sent.clone();

    let mut mock = MockModelProvider::new();
    mock.on(
        move |mi| {
            counter.store(mi.messages.len(), Ordering::SeqCst);
            true
        },
        vec![mock_text("ok")],
    );

    let config = AgentConfig {
        primary_model: ModelId::Name("mock".into(), None),
        preflight_compression_threshold: 0.85,
        context_pressure_threshold: 0.0, // isolate compression
        ..Default::default()
    };
    let mut h = harness_with(mock.into_router(), config);
    h.set_budget(5); // tiny budget forces compression

    // Persist several history messages (each ~a few tokens) so the assembled
    // context far exceeds 0.85 * 5 tokens.
    for i in 0..8 {
        let _ = h.follow_up.push(user_msg(&format!("history message number {i} with some words")));
    }

    drive(&mut h);

    let n = sent.load(Ordering::SeqCst);
    assert!(n != usize::MAX, "the mock must have been called");
    assert!(
        n < 8,
        "an over-budget context must be compressed below the full history (sent {n} of 8)"
    );
    assert!(n >= 1, "compression must keep at least the newest message (sent {n})");
}

// ---------------------------------------------------------------------------
// Workflow construction failures (build_workflow -> FailedAction)
// ---------------------------------------------------------------------------
//
// `build_workflow` topologically sorts tool calls by `depends_on`. When that
// sort is impossible the loop must emit a FailedAction and move on — NOT panic,
// and not silently execute the calls in arbitrary order, which would run a
// dependent tool before the tool it needs.

/// An assistant tool-call message whose call carries explicit `depends_on` ids.
fn tool_call_with_deps(
    call_id: &str,
    name: &str,
    depends_on: Vec<String>,
) -> Messages {
    Messages::Assistant {
        id: foundation_compact::ids::new_scru128(),
        model: ModelId::Name("mock".into(), None),
        timestamp: foundation_compact::SystemTime::UNIX_EPOCH,
        usage: foundation_ai::agentic::testing::zero_usage(),
        content: ModelOutput::ToolCall {
            id: call_id.to_string(),
            name: name.to_string(),
            arguments: Some(HashMap::new()),
            signature: None,
            depends_on,
            execution_hint: foundation_ai::types::ExecutionHint::Unspecified,
        },
        stop_reason: foundation_ai::types::StopReason::ToolUse,
        provider: foundation_ai::types::ModelProviders::Custom("mock".into()),
        error_detail: None,
        signature: None,
        metadata: None,
    }
}

#[test]
fn a_self_referential_dependency_fails_the_workflow_without_panicking() {
    use foundation_ai::agentic::testing::MockTool;

    // The call depends on itself — no topological order exists.
    let mut mock = MockModelProvider::new();
    mock.on_nth_call(
        0,
        vec![tool_call_with_deps("call_a", "echo", vec!["call_a".into()])],
    );
    mock.on_any(vec![mock_text("finished")]);

    let tool = Arc::new(MockTool::returning("echo", "out"));
    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![tool]);
    let _ = h.follow_up.push(user_msg("go"));

    let records = drive(&mut h);
    assert!(
        has_failed_action(&records),
        "a cyclic dependency must surface as a FailedAction record: {records:?}"
    );
}

#[test]
fn a_dependency_on_an_unknown_call_fails_the_workflow() {
    use foundation_ai::agentic::testing::MockTool;

    // Depends on an id the model never emitted — the sort cannot resolve it.
    let mut mock = MockModelProvider::new();
    mock.on_nth_call(
        0,
        vec![tool_call_with_deps("call_a", "echo", vec!["ghost".into()])],
    );
    mock.on_any(vec![mock_text("finished")]);

    let tool = Arc::new(MockTool::returning("echo", "out"));
    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![tool]);
    let _ = h.follow_up.push(user_msg("go"));

    let records = drive(&mut h);
    assert!(
        has_failed_action(&records),
        "a dependency on an unknown call must surface as a FailedAction: {records:?}"
    );
}

#[test]
fn a_workflow_failure_does_not_end_the_turn() {
    use foundation_ai::agentic::testing::MockTool;

    // After the failed workflow the loop returns to output processing and the
    // turn completes, rather than hanging or terminating early.
    let mut mock = MockModelProvider::new();
    mock.on_nth_call(
        0,
        vec![tool_call_with_deps("call_a", "echo", vec!["call_a".into()])],
    );
    mock.on_any(vec![mock_text("recovered")]);

    let tool = Arc::new(MockTool::returning("echo", "out"));
    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![tool]);
    let _ = h.follow_up.push(user_msg("go"));

    // `drive` panics if the loop fails to terminate, so reaching here at all is
    // the "did not hang" assertion.
    let records = drive(&mut h);
    assert!(
        !records.is_empty(),
        "the turn must still produce records after a workflow failure"
    );
}

#[test]
fn well_ordered_dependencies_still_execute() {
    use foundation_ai::agentic::testing::MockTool;

    // The contrast case: a satisfiable dependency must NOT be treated as a
    // failure, or the guard above would be over-broad.
    let mut mock = MockModelProvider::new();
    mock.on_nth_call(0, vec![tool_call_with_deps("call_a", "echo", vec![])]);
    mock.on_any(vec![mock_text("finished")]);

    let tool = Arc::new(MockTool::returning("echo", "out"));
    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![tool]);
    let _ = h.follow_up.push(user_msg("go"));

    let records = drive(&mut h);
    assert!(
        !has_failed_action(&records),
        "a dependency-free call must not be reported as a workflow failure: {records:?}"
    );
    let has_tool_result = records.iter().any(|r| {
        matches!(
            r,
            SessionRecord::Conversation {
                message: Messages::ToolResult { .. }
            }
        )
    });
    assert!(has_tool_result, "the tool must actually run: {records:?}");
}

// ---------------------------------------------------------------------------
// Outer-boundary control: abort, steering, iteration cap
// ---------------------------------------------------------------------------
//
// These three are the loop's safety rails. Each decides whether a turn keeps
// generating, and each was uncovered — the existing suite only drives turns
// that run to natural completion.

#[test]
fn a_hard_abort_ends_the_turn_before_the_next_generation() {
    use foundation_ai::agentic::CancelCode;

    // A hard abort must be honoured at the outer boundary, not after another
    // (billable) model call. Set it before driving so the very first boundary
    // check sees it.
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("should not be reached")]);

    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![]);
    let _ = h.follow_up.push(user_msg("go"));
    CancelCode::Abort.store(&h.cancel);

    let records = drive(&mut h);

    let replies = assistant_texts(&records);
    assert!(
        replies.is_empty(),
        "an aborted turn must not produce an assistant reply: {replies:?}"
    );
}

#[test]
fn an_abort_resets_the_cancel_signal() {
    use foundation_ai::agentic::CancelCode;

    // The signal is consumed on handling; leaving it set would abort the NEXT
    // turn too, which reads as the session mysteriously going dead.
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("hi")]);

    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![]);
    let _ = h.follow_up.push(user_msg("go"));
    CancelCode::Abort.store(&h.cancel);

    let _ = drive(&mut h);

    assert_eq!(
        CancelCode::load(&h.cancel),
        CancelCode::None,
        "the abort must be reset after it is honoured"
    );
}

#[test]
fn a_priority_message_is_injected_and_the_signal_cleared() {
    // Steering front-injects the message and clears the interrupt so the loop
    // resumes rather than re-interrupting forever.
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("answered")]);

    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![]);
    let _ = h.follow_up.push(user_msg("original"));
    h.priority
        .push(user_msg("urgent"))
        .expect("priority queue accepts");

    let records = drive(&mut h);

    assert!(
        h.priority.is_empty(),
        "the priority queue must be drained, not left to re-fire"
    );
    assert!(
        !records.is_empty(),
        "the turn must still make progress after steering: {records:?}"
    );
}

#[test]
fn the_outer_iteration_cap_terminates_a_turn() {
    // Without this cap a model that keeps requesting another round never yields
    // control back. `drive` panics on non-termination, so completing at all is
    // the assertion.
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("more")]);

    let config = AgentConfig {
        primary_model: ModelId::Name("mock".into(), None),
        max_outer_iterations: 1,
        ..Default::default()
    };
    let mut h = harness_with_tools(mock.into_router(), config, vec![]);
    let _ = h.follow_up.push(user_msg("go"));

    let records = drive(&mut h);
    // Reaching here means the loop terminated under the cap rather than
    // spinning; the records themselves are incidental.
    let _ = records;
}

#[test]
fn a_zero_outer_iteration_cap_ends_immediately() {
    // The degenerate setting must end the turn rather than underflow or spin.
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("never")]);

    let config = AgentConfig {
        primary_model: ModelId::Name("mock".into(), None),
        max_outer_iterations: 0,
        ..Default::default()
    };
    let mut h = harness_with_tools(mock.into_router(), config, vec![]);
    let _ = h.follow_up.push(user_msg("go"));

    let records = drive(&mut h);
    assert!(
        assistant_texts(&records).is_empty(),
        "a zero cap must not permit a generation: {records:?}"
    );
}

// ---------------------------------------------------------------------------
// Mid-generation steering
// ---------------------------------------------------------------------------
//
// A priority message that lands WHILE the model is streaming is handled
// separately from one that lands at the outer boundary: the in-flight
// generation is discarded and the turn re-assembles with the new message. That
// branch is what makes an interrupt feel immediate instead of waiting for the
// current answer to finish, and it had no coverage.

#[test]
fn a_priority_message_during_generation_discards_and_reassembles() {
    use foundation_ai::agentic::AgentProgress;

    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("original answer")]);

    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![]);
    let _ = h.follow_up.push(user_msg("first question"));

    let mut injected = false;
    let mut saw_mid_gen_steering = false;

    for _ in 0..2_000 {
        match h.agent.next_status() {
            None => break,
            Some(TaskStatus::Pending(AgentProgress::Generating { .. })) => {
                // The loop is now inside InnerGenerate. Inject here so the
                // priority is seen mid-stream rather than at the boundary.
                if !injected {
                    h.priority
                        .push(user_msg("urgent interrupt"))
                        .expect("priority queue accepts");
                    injected = true;
                }
            }
            Some(TaskStatus::Pending(AgentProgress::Steering { source })) => {
                if source == "mid_gen_priority" {
                    saw_mid_gen_steering = true;
                }
            }
            Some(_) => {}
        }
    }

    assert!(injected, "the test never reached the generating state");
    assert!(
        saw_mid_gen_steering,
        "a priority message arriving mid-generation must be reported as \
         mid_gen_priority steering, not deferred to the next boundary"
    );
}

#[test]
fn mid_generation_steering_drains_the_priority_queue() {
    use foundation_ai::agentic::AgentProgress;

    // If the queue were not drained the loop would re-interrupt forever,
    // never producing an answer.
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("answer")]);

    let mut h = harness_with_tools(mock.into_router(), config_for("mock"), vec![]);
    let _ = h.follow_up.push(user_msg("question"));

    let mut injected = false;
    for _ in 0..2_000 {
        match h.agent.next_status() {
            None => break,
            Some(TaskStatus::Pending(AgentProgress::Generating { .. })) => {
                if !injected {
                    h.priority.push(user_msg("urgent")).expect("push");
                    injected = true;
                }
            }
            Some(_) => {}
        }
    }

    assert!(
        h.priority.is_empty(),
        "the priority queue must be drained, or the loop re-interrupts forever"
    );
}

// ---------------------------------------------------------------------------
// Vacuous answers — the loop asks again rather than handing back junk
//
// Small models routinely end a turn with a bare `.` or, in reply to a greeting,
// a bare `0`. These drive a real turn through the loop, because the interesting
// behaviour is not the predicate (unit-tested in loop_detection_tests) but what
// the loop does with it: retract what it already streamed, ask again, and know
// when to stop asking.

/// Records the loop emitted to say "drop what I already sent you".
fn retractions(records: &[SessionRecord]) -> Vec<String> {
    records
        .iter()
        .filter_map(|r| match r {
            SessionRecord::Retracted { reason, .. } => Some(reason.clone()),
            _ => None,
        })
        .collect()
}

#[test]
fn a_vacuous_turn_is_retried_and_the_good_answer_replaces_it() {
    // First call answers with punctuation, second answers properly.
    let mut mock = MockModelProvider::new();
    mock.on_nth_call(0, vec![mock_text(".")]);
    mock.on_any(vec![mock_text("Hello. How can I help you?")]);

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("hello"));

    let records = drive(&mut h);
    let texts = assistant_texts(&records);

    assert!(
        texts.iter().any(|t| t.contains("How can I help you")),
        "the retry's answer should reach the caller: {texts:?}"
    );
    assert_eq!(
        retractions(&records).len(),
        1,
        "the loop must withdraw the turn it threw away: {records:?}"
    );
}

#[test]
fn the_withdrawn_text_is_not_left_in_front_of_the_answer() {
    // The bug this guards: streaming hands the caller every token before the
    // turn can be judged, so without a retraction the retry's answer is
    // appended to the junk it was meant to replace and the user reads
    // ".  Hello." instead of "Hello.".
    let mut mock = MockModelProvider::new();
    mock.on_nth_call(0, vec![mock_text(".")]);
    mock.on_any(vec![mock_text("Paris")]);

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("What is the capital of France?"));

    let records = drive(&mut h);

    // Everything before the retraction is withdrawn; what survives is the answer.
    let surviving: Vec<String> = records
        .iter()
        .skip_while(|r| !matches!(r, SessionRecord::Retracted { .. }))
        .filter_map(|r| match r {
            SessionRecord::Conversation {
                message: Messages::Assistant { content, .. },
            } => match content {
                ModelOutput::Text(t) => Some(t.content.clone()),
                _ => None,
            },
            _ => None,
        })
        .collect();

    assert_eq!(
        surviving.concat(),
        "Paris",
        "only the retry's answer should follow the retraction: {records:?}"
    );
}

#[test]
fn a_real_answer_is_never_retried() {
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("Paris")]);

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("What is the capital of France?"));

    let records = drive(&mut h);

    assert!(
        retractions(&records).is_empty(),
        "a good answer must not be withdrawn: {records:?}"
    );
    assert_eq!(assistant_texts(&records), vec!["Paris".to_string()]);
}

#[test]
fn a_bare_number_is_kept_when_the_question_asked_for_one() {
    // The regression the conservative rule exists to avoid: `4` is the answer.
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text("4")]);

    let mut h = harness_with(mock.into_router(), config_for("mock"));
    let _ = h.follow_up.push(user_msg("What is 2+2?"));

    let records = drive(&mut h);

    assert!(
        retractions(&records).is_empty(),
        "a correct numeric answer must not be retried: {records:?}"
    );
    assert_eq!(assistant_texts(&records), vec!["4".to_string()]);
}

#[test]
fn a_model_stuck_on_junk_stops_being_asked_and_never_fails_the_turn() {
    // Two things codified here:
    //   1. the retry budget is spent ONCE, not refilled per outer iteration —
    //      the loop only resets the ladder after a turn that came back good, so
    //      a model stuck on `.` cannot burn max_redirects retries over and over;
    //   2. running out of retries passes the weak answer through rather than
    //      failing, because no answer is worse for the caller than a poor one.
    let mut mock = MockModelProvider::new();
    mock.on_any(vec![mock_text(".")]);

    let config = AgentConfig {
        ..config_for("mock")
    };
    let mut h = harness_with(mock.into_router(), config);
    let _ = h.follow_up.push(user_msg("hello"));

    let records = drive(&mut h);

    assert!(
        !has_failed_action(&records),
        "a weak answer must not be turned into no answer: {records:?}"
    );

    let attempts = retractions(&records).len();
    assert!(
        attempts <= LoopDetectorConfig::default().max_redirects,
        "the ladder should be spent once ({attempts} retries against a budget of \
         {}), not refilled for each outer pass: {records:?}",
        LoopDetectorConfig::default().max_redirects
    );

    assert!(
        assistant_texts(&records).iter().any(|t| t.contains('.')),
        "the last attempt should still reach the caller: {records:?}"
    );
}