foundation_ai 0.0.2

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
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
//! `AgentLoop` — the orchestrator state machine (F19).
//!
//! WHY: Everything else in the agentic layer is a component; nothing runs a
//! *turn*. The loop sequences: context assembly → model generate/stream →
//! tool execution → output processing → follow-up continuation, all as a
//! non-blocking valtron `TaskIterator`.
//!
//! WHAT: `AgentLoop` implements `TaskIterator` with
//! `Ready = SessionRecord`, `Pending = AgentProgress`. The inner loop handles
//! tool calls + steering; the outer loop handles follow-up messages.
//!
//! HOW: State machine transitions drive components (F12 router, F11 tools,
//! F16 context, F15 memory, F17 loop detection, F02 circuit breaker). The
//! loop orchestrates — it owns no logic beyond sequencing.

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

use foundation_core::valtron::{
    CancelOutcome, CancellableFutureTask, Ctx, DrivenTaskIterator, Stream, TaskIterator,
    TaskStatus,
};
use foundation_db::traits::DocumentStore;

use crate::agentic::access::{AllowAllAccess, SessionAccessProvider};
use crate::agentic::context::{AgentContext, ContextProvider};
use crate::agentic::errors::{AgentAction, AgenticError, CircuitBreaker, ErrorPolicy, UserId};
use crate::agentic::loop_detection::{
    is_vacuous_answer, Escalation, LoopDetection, LoopDetector, LoopDetectorConfig,
};
use crate::agentic::memory::{MemoryAction, MemoryHierarchy};
use crate::agentic::memory_store::MemoryStore;
use crate::agentic::message_api::MessageApi;
use crate::agentic::progress::{lift_model_item, AgentProgress, MemoryKind};
use crate::agentic::steering::SteeringQueues;
use crate::agentic::token_ledger::TokenLedger;
use crate::agentic::tool_impl::{ToolCallManager, ToolCallRequest, ToolCallResult, ToolError};
use crate::types::{
    MessageRole, Messages, ModelId, ModelInteraction, ModelOutput, ModelParams, ModelState,
    SessionId, SessionRecord, StopReason, TextBasedFormatter, TextContent, ToolFormatter,
    UserModelContent,
};

// ---------------------------------------------------------------------------
// ModelSelection

/// The models a session runs on — the single place they are set.
///
/// WHY: models used to live both on the builder and in `AgentConfig`, and
/// an `AgentConfig::default()` silently carried an empty model name. Keeping
/// them in one value, filled by the builder, means a session either has a
/// primary model or fails to build.
///
/// WHAT: the primary model, the circuit-breaker fallbacks (tried in order),
/// and an optional model for memory generation.
///
/// HOW: `AgentSessionBuilder::build` assembles it from `with_model`,
/// `with_fallback_models` and `with_memory_model`; `AgentLoop::new` takes it
/// next to `AgentConfig`. Custom loops and tests build one with
/// [`ModelSelection::new`].
#[derive(Debug, Clone, PartialEq)]
pub struct ModelSelection {
    pub primary: ModelId,
    pub fallbacks: Vec<ModelId>,
    pub memory: Option<ModelId>,
}

impl ModelSelection {
    /// A selection with only a primary model.
    #[must_use]
    pub fn new(primary: impl Into<ModelId>) -> Self {
        Self {
            primary: primary.into(),
            fallbacks: Vec::new(),
            memory: None,
        }
    }

    /// Set the circuit-breaker fallbacks, in order.
    #[must_use]
    pub fn with_fallbacks<I>(mut self, models: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<ModelId>,
    {
        self.fallbacks = models.into_iter().map(Into::into).collect();
        self
    }

    /// Set the model used for memory generation.
    #[must_use]
    pub fn with_memory(mut self, model: impl Into<ModelId>) -> Self {
        self.memory = Some(model.into());
        self
    }
}

// ---------------------------------------------------------------------------
// AgentConfig

/// Tunable knobs for `AgentLoop` behaviour.
///
/// WHY: Hard-coding iteration caps, budget thresholds, and model fallback
/// lists inside the loop would force recompilation on every tuning change.
/// Externalising them lets callers (CLI, server, tests) vary policy without
/// touching orchestration logic.
///
/// WHAT: Flat bag of limits and thresholds — inner/outer iteration caps,
/// circuit-breaker threshold, context-pressure ratio, and base
/// `ModelParams`. All fields have sensible defaults via `Default`. The
/// models are not here: they live in [`ModelSelection`], which the session
/// builder fills from `with_model` / `with_fallback_models` /
/// `with_memory_model`.
///
/// HOW: Passed to `AgentLoop::new`; the loop reads fields at each state
/// transition. Thresholds gate the context-pressure and
/// preflight-compression layers.
#[derive(Debug, Clone)]
pub struct AgentConfig {
    pub max_inner_iterations: usize,
    pub max_outer_iterations: usize,
    pub circuit_breaker_threshold: u32,
    pub preflight_compression_threshold: f32,
    pub context_pressure_threshold: f32,
    pub model_params: ModelParams,
}

impl Default for AgentConfig {
    fn default() -> Self {
        Self {
            max_inner_iterations: 25,
            max_outer_iterations: 10,
            circuit_breaker_threshold: 3,
            preflight_compression_threshold: 0.85,
            context_pressure_threshold: 0.70,
            model_params: ModelParams::default(),
        }
    }
}

// ---------------------------------------------------------------------------
// Type aliases for complex types

/// Type alias for the driven tool-execution future used in `InnerExecuting`.
type ToolDrivenIterator = DrivenTaskIterator<
    CancellableFutureTask<
        core::pin::Pin<
            Box<dyn core::future::Future<Output = Result<ToolCallResult, ToolError>> + Send>,
        >,
    >,
>;

// ---------------------------------------------------------------------------
// AgentLoopState

/// The state machine driving the orchestrator.
///
/// WHY: The agent loop is a non-blocking `TaskIterator` — it cannot park on
/// async I/O. A flat enum encodes every suspension point so `next_status`
/// can resume exactly where it left off without a call stack.
///
/// WHAT: Ten states forming two nested loops. The *outer* loop
/// (`OuterBoundary`) drains follow-up messages; the *inner* loop
/// (`InnerAssemble → InnerGenerate → InnerToolCalls → InnerExecuting →
/// InnerEmitResults`) runs one model turn + tool execution cycle.
/// `OutputProcessing` fires memory triggers; `Ending` emits a summary;
/// `Done` is terminal.
///
/// HOW: Each variant carries the state needed to resume — stream handles,
/// partial results, indices. `next_status` pattern-matches the current
/// variant, does one quantum of work, and replaces `self` with the next
/// variant.
pub enum AgentLoopState {
    /// Initial setup — emit Init, transition to `OuterBoundary`.
    Initializing,
    /// Check `FollowUpQueue` for continuation; if empty, go to Ending.
    OuterBoundary,
    /// Run input processors, assemble context, generate.
    InnerAssemble,
    /// Model generation in progress — pump the stream step-wise.
    InnerGenerate {
        stream: Box<dyn Iterator<Item = Stream<Messages, ModelState>> + Send>,
        collected: Vec<Messages>,
    },
    /// Tool calls extracted from the model's output.
    InnerToolCalls { calls: Vec<ToolCallRequest> },
    /// Tool execution in progress — drives `CancellableFutureTask` per call.
    InnerExecuting {
        calls: Vec<ToolCallRequest>,
        results: Vec<(ToolCallRequest, Result<ToolCallResult, ToolError>)>,
        idx: usize,
        active: Option<ToolDrivenIterator>,
        cancel_signals: Vec<Arc<AtomicBool>>,
    },
    /// Emit tool results back as records and loop back to `InnerAssemble`.
    InnerEmitResults { results: Vec<Messages>, idx: usize },
    /// Output processing — fire memory triggers, persist.
    OutputProcessing,
    /// Emit the final Summary record and end.
    Ending,
    /// Terminal state.
    Done,
}

impl AgentLoopState {
    /// The variant's name, for diagnostics.
    ///
    /// WHY: the state carries live stream handles, so it cannot derive `Debug`.
    /// Each `transition_*` method takes the state by value and requires one
    /// specific variant; when that expectation is violated the panic needs to
    /// say which state was actually found, or the report is just "entered
    /// unreachable code" and the caller has to reconstruct the sequence by hand.
    pub(crate) const fn variant_name(&self) -> &'static str {
        match self {
            Self::Initializing => "Initializing",
            Self::OuterBoundary => "OuterBoundary",
            Self::InnerAssemble => "InnerAssemble",
            Self::InnerGenerate { .. } => "InnerGenerate",
            Self::InnerToolCalls { .. } => "InnerToolCalls",
            Self::InnerExecuting { .. } => "InnerExecuting",
            Self::InnerEmitResults { .. } => "InnerEmitResults",
            Self::OutputProcessing => "OutputProcessing",
            Self::Ending => "Ending",
            Self::Done => "Done",
        }
    }
}

// ---------------------------------------------------------------------------
// AgentLoop

/// The agentic orchestrator — a valtron `TaskIterator` state machine.
///
/// WHY: Every other agentic component is a leaf: context assembly, memory
/// generation, tool execution, steering. Nothing sequences them into a
/// *turn*. `AgentLoop` is the single piece that drives the full cycle
/// (context → generate → tools → emit → follow-up) as a non-blocking
/// iterator the valtron executor can schedule alongside other work.
///
/// WHAT: Implements `TaskIterator<Ready = SessionRecord, Pending =
/// AgentProgress>`. The outer loop
/// drains `SteeringQueues` for follow-up messages; the inner loop runs
/// model generation, tool execution, and output processing until the model
/// stops requesting tool calls or a guard (budget, iteration cap, loop
/// detection) fires.
///
/// HOW: Owns the component instances (`ContextProvider`, `ToolCallManager`,
/// `MemoryHierarchy`, `SteeringQueues`, `TokenLedger`, `ErrorPolicy`,
/// `CircuitBreaker`, `LoopDetector`, `ProviderRouter`) and an
/// `AgentLoopState` enum. Each `next_status` call pattern-matches the
/// current state, delegates to the appropriate component, and transitions
/// to the next state. Tool futures are wrapped in `CancellableFutureTask`
/// and driven via `drive_iterator`.
pub struct AgentLoop<D, M> {
    session_id: SessionId,
    context_provider: ContextProvider<D, M>,
    tool_manager: ToolCallManager,
    queues: SteeringQueues,
    memory: MemoryHierarchy<M, D>,
    message_api: MessageApi<D>,
    ledger: TokenLedger,
    detector: LoopDetector,
    policy: ErrorPolicy,
    breaker: CircuitBreaker,
    router: crate::types::ProviderRouter,

    state: AgentLoopState,
    current_model: ModelId,
    config: AgentConfig,
    inner_iteration: usize,
    outer_iteration: usize,
    /// Text of the user message this turn is answering.
    ///
    /// Kept so a bare-number reply can be judged against what was asked — `0`
    /// answering "how many" is correct, `0` answering "hello" is not.
    last_user_prompt: String,
    message_count: u64,
    /// Who the turn runs for, and the provider that decides what they may do
    /// (tool use, spend). Defaults to `AllowAllAccess`; `AgentSession` passes
    /// its own via [`AgentLoop::with_access`].
    access: Arc<dyn SessionAccessProvider>,
    user: UserId,
}

/// The text of a whole turn, as the caller will eventually read it.
///
/// Streaming models emit one `Messages::Assistant` per token, so the turn's
/// answer only exists once the fragments are put back together. Thinking
/// content is excluded: it is the model reasoning to itself, not its answer,
/// and a turn whose only visible output is punctuation is vacuous however much
/// it thought first.
fn assembled_answer(collected: &[Messages]) -> String {
    let chunks: Vec<&str> = collected
        .iter()
        .filter_map(|message| match message {
            Messages::Assistant {
                content: ModelOutput::Text(text),
                ..
            } => Some(text.content.as_str()),
            _ => None,
        })
        .collect();
    join_text_chunks(&chunks)
}

/// Rebuild a turn's full text from its streamed text chunks.
///
/// Backends disagree on what a chunk carries: the local backends stream each
/// new piece (a delta), the HTTP backends re-send the whole text so far (a
/// snapshot). Snapshots are recognisable — every chunk extends the previous
/// one — so in that case the last chunk is the answer; otherwise the chunks
/// are concatenated.
fn join_text_chunks(chunks: &[&str]) -> String {
    let is_snapshots =
        chunks.len() > 1 && chunks.windows(2).all(|pair| pair[1].starts_with(pair[0]));
    if is_snapshots {
        chunks.last().map(|c| (*c).to_string()).unwrap_or_default()
    } else {
        chunks.concat()
    }
}

/// Collapse a turn's streamed chunks into the messages worth keeping.
///
/// Consecutive text chunks become one text message, consecutive thinking
/// chunks one thinking message (see [`join_text_chunks`]); every other output
/// (tool calls, images, embeddings) is kept as is. Each merged message takes
/// the metadata, usage and stop reason of its last chunk.
fn coalesce_turn(collected: &[Messages]) -> Vec<Messages> {
    #[derive(PartialEq)]
    enum Run {
        Text,
        Thinking,
    }

    fn flush(run: &mut Vec<&Messages>, kind: &Run, out: &mut Vec<Messages>) {
        let Some(last) = run.last().copied() else {
            return;
        };
        let Messages::Assistant {
            content: last_content,
            ..
        } = last
        else {
            return;
        };
        let pieces: Vec<&str> = run
            .iter()
            .filter_map(|message| match message {
                Messages::Assistant {
                    content: ModelOutput::Text(text),
                    ..
                } => Some(text.content.as_str()),
                Messages::Assistant {
                    content: ModelOutput::ThinkingContent { thinking, .. },
                    ..
                } => Some(thinking.as_str()),
                _ => None,
            })
            .collect();
        let joined = join_text_chunks(&pieces);
        let content = match (kind, last_content) {
            (Run::Text, ModelOutput::Text(text)) => ModelOutput::Text(TextContent {
                content: joined,
                signature: text.signature.clone(),
            }),
            (Run::Thinking, ModelOutput::ThinkingContent { signature, .. }) => {
                ModelOutput::ThinkingContent {
                    thinking: joined,
                    signature: signature.clone(),
                }
            }
            _ => last_content.clone(),
        };
        let mut merged = last.clone();
        if let Messages::Assistant { content: slot, .. } = &mut merged {
            *slot = content;
        }
        out.push(merged);
        run.clear();
    }

    let mut out = Vec::new();
    let mut run: Vec<&Messages> = Vec::new();
    let mut run_kind = Run::Text;
    for message in collected {
        let kind = match message {
            Messages::Assistant {
                content: ModelOutput::Text(_),
                ..
            } => Some(Run::Text),
            Messages::Assistant {
                content: ModelOutput::ThinkingContent { .. },
                ..
            } => Some(Run::Thinking),
            Messages::Assistant { .. } => None,
            // Only assistant output is persisted from a turn.
            _ => continue,
        };
        if let Some(kind) = kind {
            if !run.is_empty() && kind != run_kind {
                flush(&mut run, &run_kind, &mut out);
            }
            run_kind = kind;
            run.push(message);
        } else {
            flush(&mut run, &run_kind, &mut out);
            out.push(message.clone());
        }
    }
    flush(&mut run, &run_kind, &mut out);
    out
}

/// Turn text-protocol tool calls (`<ToolCall>{..}</ToolCall>`) into real
/// `ModelOutput::ToolCall`s.
///
/// WHY: local backends (llama.cpp, Candle) have no native tool calling. Their
/// prompt tells the model to emit calls in this text format, but nothing ever
/// parsed the output — the call stayed text and the tool never ran.
///
/// Leaves `collected` untouched when the turn already has native tool calls
/// or its text contains no `<ToolCall>` block. Otherwise returns the turn as
/// one assistant text message (the prose around the calls, if any) followed
/// by one assistant message per call, carrying the last chunk's metadata and
/// usage so the ledger still records the turn correctly.
fn with_text_protocol_tool_calls(collected: Vec<Messages>) -> Vec<Messages> {
    let has_native_call = collected.iter().any(|message| {
        matches!(
            message,
            Messages::Assistant {
                content: ModelOutput::ToolCall { .. },
                ..
            }
        )
    });
    if has_native_call {
        return collected;
    }

    let text = assembled_answer(&collected);
    if !text.contains("<ToolCall>") {
        return collected;
    }

    let extracted = match TextBasedFormatter.extract_tool_calls(&text) {
        Ok(extracted) if extracted.has_tool_calls => extracted,
        Ok(_) => return collected,
        Err(err) => {
            tracing::debug!(error = ?err, "agent: could not parse text-protocol tool calls");
            return collected;
        }
    };

    let Some(Messages::Assistant {
        model,
        usage,
        provider,
        metadata,
        ..
    }) = collected
        .iter()
        .rev()
        .find(|message| matches!(message, Messages::Assistant { .. }))
        .cloned()
    else {
        return collected;
    };

    let make = |content: ModelOutput, stop_reason: StopReason| Messages::Assistant {
        id: foundation_compact::ids::new_scru128(),
        model: model.clone(),
        timestamp: foundation_compact::SystemTime::now(),
        usage: usage.clone(),
        content,
        stop_reason,
        provider: provider.clone(),
        error_detail: None,
        signature: None,
        metadata: metadata.clone(),
    };

    let mut turn = Vec::new();
    if let Some(prose) = extracted.remaining_text {
        turn.push(make(
            ModelOutput::Text(TextContent {
                content: prose,
                signature: None,
            }),
            StopReason::Stop,
        ));
    }
    for call in extracted.calls {
        // The parser numbers calls `tool_0`, `tool_1`, … per response; give
        // each a unique id so results from different rounds can't be confused.
        let call = match call {
            ModelOutput::ToolCall {
                name,
                arguments,
                signature,
                depends_on,
                execution_hint,
                ..
            } => ModelOutput::ToolCall {
                id: foundation_compact::ids::new_scru128_string(),
                name,
                arguments,
                signature,
                depends_on,
                execution_hint,
            },
            other => other,
        };
        turn.push(make(call, StopReason::ToolUse));
    }
    turn
}

/// The nudge sent when a turn produced no usable answer.
///
/// Names the actual problem rather than reusing the loop wording — a model told
/// "you are repeating yourself" when it in fact said nothing has been given the
/// wrong correction.
fn vacuous_answer_redirect() -> Messages {
    Messages::User {
        id: foundation_compact::ids::new_scru128(),
        role: MessageRole::System,
        content: UserModelContent::Text(TextContent {
            content: "Your last reply contained no answer - only punctuation or \
                      whitespace. Answer the user's question directly, in plain \
                      words."
                .into(),
            signature: None,
        }),
        signature: None,
    }
}

impl<D: DocumentStore, M: MemoryStore> AgentLoop<D, M> {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    pub fn new(
        session_id: SessionId,
        context_provider: ContextProvider<D, M>,
        tool_manager: ToolCallManager,
        queues: SteeringQueues,
        memory: MemoryHierarchy<M, D>,
        message_api: MessageApi<D>,
        ledger: TokenLedger,
        policy: ErrorPolicy,
        router: crate::types::ProviderRouter,
        config: AgentConfig,
        models: ModelSelection,
    ) -> Self {
        // The memory model is used by the memory hierarchy, not the loop.
        let ModelSelection {
            primary, fallbacks, ..
        } = models;
        let breaker = CircuitBreaker::new(config.circuit_breaker_threshold, fallbacks);
        let current_model = primary;
        Self {
            session_id,
            context_provider,
            tool_manager,
            queues,
            memory,
            message_api,
            ledger,
            detector: LoopDetector::new(LoopDetectorConfig::default()),
            policy,
            breaker,
            router,
            state: AgentLoopState::Initializing,
            current_model,
            config,
            inner_iteration: 0,
            outer_iteration: 0,
            last_user_prompt: String::new(),
            message_count: 0,
            access: Arc::new(AllowAllAccess),
            user: UserId("local".into()),
        }
    }

    /// Run the loop on behalf of `user`, checking `access` before each tool
    /// call (`can_use_tool`) and generation (`can_spend`), and reporting usage
    /// after each generation (`record_usage`).
    #[must_use]
    pub fn with_access(mut self, access: Arc<dyn SessionAccessProvider>, user: UserId) -> Self {
        self.access = access;
        self.user = user;
        self
    }

    /// Persist a user message to session history.
    ///
    /// The message reaches the model through context assembly
    /// (`message_api` -> `ContextProvider` -> `interaction.messages`), so
    /// persisting here is the whole job — an earlier `pending_user_messages`
    /// buffer duplicated it, was never drained (unbounded growth), and was read
    /// only by a debug counter, so it was removed.
    pub fn push_user_message(&mut self, msg: Messages) {
        let _ = self
            .message_api
            .append(SessionRecord::Conversation { message: msg });
    }

    /// Current state label (for diagnostics).
    #[must_use]
    pub fn state_label(&self) -> &'static str {
        match &self.state {
            AgentLoopState::Initializing => "initializing",
            AgentLoopState::OuterBoundary => "outer_boundary",
            AgentLoopState::InnerAssemble => "inner_assemble",
            AgentLoopState::InnerGenerate { .. } => "inner_generate",
            AgentLoopState::InnerToolCalls { .. } => "inner_tool_calls",
            AgentLoopState::InnerExecuting { .. } => "inner_executing",
            AgentLoopState::InnerEmitResults { .. } => "inner_emit_results",
            AgentLoopState::OutputProcessing => "output_processing",
            AgentLoopState::Ending => "ending",
            AgentLoopState::Done => "done",
        }
    }

    /// The model currently being used (may have changed via circuit breaker).
    #[must_use]
    pub fn current_model(&self) -> &ModelId {
        &self.current_model
    }

    // -----------------------------------------------------------------------
    // State transition helpers

    fn transition_outer_boundary(
        &mut self,
    ) -> TaskStatus<SessionRecord, AgentProgress> {
        // A hard abort requested via `AgentSession::abort` (or `steer`'s Abort
        // code) terminates the turn at this boundary. Previously the Abort code
        // existed but nothing set it and the loop never read it — a stubbed
        // cancel path (spec-60 matrix 3.5).
        if self.queues.is_aborted() {
            self.queues.reset_cancel();
            self.state = AgentLoopState::Ending;
            return TaskStatus::Pending(AgentProgress::SessionEnding);
        }

        self.outer_iteration += 1;
        if self.outer_iteration > self.config.max_outer_iterations {
            self.state = AgentLoopState::Ending;
            return TaskStatus::Pending(AgentProgress::SessionEnding);
        }

        // Drain priority queue first.
        let priority_msgs = self.queues.drain_priority();
        if !priority_msgs.is_empty() {
            self.queues.reset_cancel();
            for msg in priority_msgs {
                self.push_user_message(msg);
            }
            self.inner_iteration = 0;
            self.state = AgentLoopState::InnerAssemble;
            return TaskStatus::Pending(AgentProgress::Steering {
                source: std::borrow::Cow::Borrowed("priority_queue"),
            });
        }

        // Drain follow-up queue.
        let follow_up_msgs = self.queues.drain_follow_up();
        tracing::trace!(
            drained = follow_up_msgs.len(),
            outer_iteration = self.outer_iteration,
            "outer_boundary: drained follow_up queue"
        );
        if !follow_up_msgs.is_empty() {
            for msg in follow_up_msgs {
                if let Messages::User {
                    role: MessageRole::User,
                    content: UserModelContent::Text(ref text),
                    ..
                } = msg
                {
                    self.last_user_prompt.clone_from(&text.content);
                }
                self.push_user_message(msg);
            }
            self.inner_iteration = 0;
            self.state = AgentLoopState::InnerAssemble;
            return TaskStatus::Pending(AgentProgress::Steering {
                source: std::borrow::Cow::Borrowed("follow_up_queue"),
            });
        }

        // No more work — end the session.
        self.state = AgentLoopState::Ending;
        TaskStatus::Pending(AgentProgress::SessionEnding)
    }

    fn transition_inner_assemble(
        &mut self,
    ) -> TaskStatus<SessionRecord, AgentProgress> {
        // Honor a hard abort mid-turn (before starting another generation).
        if self.queues.is_aborted() {
            self.queues.reset_cancel();
            self.state = AgentLoopState::Ending;
            return TaskStatus::Pending(AgentProgress::SessionEnding);
        }

        // Check priority queue — front-inject interruption.
        if self.queues.has_priority() {
            let msgs = self.queues.drain_priority();
            self.queues.reset_cancel();
            for msg in msgs {
                self.push_user_message(msg);
            }
            return TaskStatus::Pending(AgentProgress::Steering {
                source: std::borrow::Cow::Borrowed("priority_interrupt"),
            });
        }

        // Check budget exhaustion.
        if self.ledger.is_exhausted() {
            let snapshot = self.ledger.snapshot();
            self.state = AgentLoopState::Ending;
            return TaskStatus::Ready(
                AgenticError::BudgetExhausted { snapshot }.into_failed_action(),
            );
        }

        // Attempt to get the model from the router.
        let model = match self.router.get_model(&self.current_model) {
            Ok(m) => m,
            Err(e) => {
                tracing::error!("router failed to get model: {e:?}");
                let err = AgenticError::from(e);
                return self.handle_error(err);
            }
        };

        // Hydrate memory synchronously and assemble context.
        let memory = self
            .context_provider
            .memory_store()
            .hydrate_sync(&self.session_id)
            .unwrap_or_default();
        let mut ctx = self.context_provider.assemble_from_memory(&memory);

        // Preflight compression: when the assembled context exceeds the
        // compression threshold of the budget, shrink it BEFORE sending — drop
        // the oldest recent messages (keeping the newest) until it fits. This is
        // the heavier counterpart to the context-pressure note (below): pressure
        // warns, compression actually reduces. The threshold field existed but
        // was never applied.
        self.apply_preflight_compression(&mut ctx);

        // Ephemeral context-pressure layer (OD-19-7).
        let system_prompt = self.apply_context_pressure(&ctx);

        // Build the model interaction. The model is offered `shed` plus the
        // tools `shed` has handed out so far — not every registered tool.
        let interaction = ModelInteraction {
            system_prompt: system_prompt.or(ctx.system_prompt),
            soul: None,
            tools_shed: self.tool_manager.offered_tools(),
            messages: ctx.messages,
            chat_template: None,
            tool_choice: None,
        };

        let params = self.config.model_params.clone();
        let effective_max = self.ledger.effective_max_tokens(&params);
        let params = ModelParams {
            max_tokens: effective_max,
            ..params
        };

        // Let the access provider veto the spend before any tokens are used.
        let requested = u64::try_from(effective_max).unwrap_or(u64::MAX);
        match self.access.can_spend(&self.user, requested) {
            Ok(true) => {}
            Ok(false) => {
                self.state = AgentLoopState::Ending;
                return TaskStatus::Ready(
                    AgenticError::Budget { limit: requested }.into_failed_action(),
                );
            }
            Err(err) => {
                self.state = AgentLoopState::Ending;
                return TaskStatus::Ready(AgenticError::Auth(err).into_failed_action());
            }
        }

        // Start streaming generation.
        tracing::trace!(
            messages = interaction.messages.len(),
            has_system = interaction.system_prompt.is_some(),
            "Sending interactions to model for generation"
        );
        match model.stream(interaction, Some(params)) {
            Ok(stream) => {
                self.state = AgentLoopState::InnerGenerate {
                    stream: Box::new(stream),
                    collected: Vec::new(),
                };
                TaskStatus::Pending(AgentProgress::Generating {
                    model: self.current_model.clone(),
                    tokens_so_far: None,
                })
            }
            Err(gen_err) => {
                let err = AgenticError::from_generation(&gen_err, None, 0);
                self.handle_error(err)
            }
        }
    }

    fn transition_inner_generate(
        &mut self,
    ) -> TaskStatus<SessionRecord, AgentProgress> {
        // We need to take ownership of the state to pump the stream.
        let previous = std::mem::replace(&mut self.state, AgentLoopState::Done);
        let actual = previous.variant_name();
        let AgentLoopState::InnerGenerate {
            mut stream,
            mut collected,
        } = previous
        else {
            panic!("transition_inner_generate requires AgentLoopState::InnerGenerate, found {actual}")
        };

        // Pump one item from the stream.
        let Some(item) = stream.next() else {
            // Stream finished — run loop detection, extract tool calls.
            self.breaker.on_success();
            let collected = with_text_protocol_tool_calls(collected);
            return self.on_generation_complete(&collected);
        };

        // Check for mid-generation steering interruption (OD-19-3).
        if self.queues.has_priority() {
            self.queues.reset_cancel();
            let msgs = self.queues.drain_priority();
            for msg in msgs {
                self.push_user_message(msg);
            }
            // Discard current generation, re-assemble with new priority.
            self.state = AgentLoopState::InnerAssemble;
            return TaskStatus::Pending(AgentProgress::Steering {
                source: std::borrow::Cow::Borrowed("mid_gen_priority"),
            });
        }

        let lifted = lift_model_item(item, &self.current_model);
        match lifted {
            Stream::Next(record) => {
                // Collect the message for tool-call extraction + loop detection.
                if let SessionRecord::Conversation { ref message } = record {
                    collected.push(message.clone());
                    self.message_count += 1;
                }
                self.state = AgentLoopState::InnerGenerate { stream, collected };
                TaskStatus::Ready(record)
            }
            Stream::Pending(progress) => {
                self.state = AgentLoopState::InnerGenerate { stream, collected };
                TaskStatus::Pending(progress)
            }
            Stream::Init | Stream::Ignore | Stream::Wait => {
                self.state = AgentLoopState::InnerGenerate { stream, collected };
                TaskStatus::Ignore
            }
            Stream::Delayed(d) => {
                self.state = AgentLoopState::InnerGenerate { stream, collected };
                TaskStatus::Delayed(d)
            }
            Stream::Spread(items) => {
                use foundation_core::valtron::StreamSpread;
                for s in &items {
                    if let StreamSpread::Done(SessionRecord::Conversation { ref message }) = s {
                        collected.push(message.clone());
                        self.message_count += 1;
                    }
                }
                self.state = AgentLoopState::InnerGenerate { stream, collected };
                // Emit the first spread item; rest will be picked up on next poll.
                if let Some(first) = items.into_iter().next() {
                    match first {
                        StreamSpread::Done(rec) => TaskStatus::Ready(rec),
                        StreamSpread::Pending(p) => TaskStatus::Pending(p),
                    }
                } else {
                    TaskStatus::Ignore
                }
            }
        }
    }

    fn on_generation_complete(
        &mut self,
        collected: &[Messages],
    ) -> TaskStatus<SessionRecord, AgentProgress> {
        // Run loop detection (F17) synchronously on the model outputs.
        for msg in collected {
            if let Messages::Assistant { ref content, .. } = msg {
                let detection = self.detector.check(content);
                if detection != LoopDetection::NoLoop {
                    let escalation = self.detector.escalate();
                    match escalation {
                        Escalation::Redirect => {
                            // Inject a system redirect message and re-assemble.
                            let redirect = Messages::User {
                                id: foundation_compact::ids::new_scru128(),
                                role: MessageRole::System,
                                content: UserModelContent::Text(TextContent {
                                    content: "Loop detected. Please try a different approach — \
                                              avoid repeating the same actions or responses."
                                        .into(),
                                    signature: None,
                                }),
                                signature: None,
                            };
                            self.push_user_message(redirect);
                            self.state = AgentLoopState::InnerAssemble;
                            return TaskStatus::Pending(AgentProgress::Steering {
                                source: std::borrow::Cow::Borrowed("loop_redirect"),
                            });
                        }
                        Escalation::SwitchModelOrTemperature { .. } => {
                            if let Some(fallback) = self.breaker.on_failure() {
                                self.current_model = fallback;
                            }
                            let redirect = Messages::User {
                                id: foundation_compact::ids::new_scru128(),
                                role: MessageRole::System,
                                content: UserModelContent::Text(TextContent {
                                    content: "Loop detected after redirect. Switching approach."
                                        .into(),
                                    signature: None,
                                }),
                                signature: None,
                            };
                            self.push_user_message(redirect);
                            self.state = AgentLoopState::InnerAssemble;
                            return TaskStatus::Pending(AgentProgress::Steering {
                                source: std::borrow::Cow::Borrowed("loop_model_switch"),
                            });
                        }
                        Escalation::Terminate => {
                            // A model repeating the SAME empty answer is the
                            // vacuous case wearing a loop's clothes, and the
                            // agreed remedy there is to hand the weak answer
                            // over, not to replace it with an error. Failing
                            // here would turn `.` into "loop detected", which
                            // is strictly worse for whoever asked.
                            //
                            // A loop of substantive text still terminates —
                            // that is real token burn and stopping is the point.
                            if is_vacuous_answer(&assembled_answer(collected)) {
                                tracing::debug!(
                                    "agent: repeated empty answer, passing it \
                                     through rather than failing the turn"
                                );
                                break;
                            }

                            // redirect_count is small (bounded by max_redirects).
                            #[allow(clippy::cast_possible_truncation)]
                            let occurrences = self.detector.redirect_count() as u32;
                            let err = AgenticError::LoopDetected(
                                crate::agentic::errors::LoopDetectedInfo {
                                    kind: format!("{detection:?}"),
                                    occurrences,
                                });
                            self.state = AgentLoopState::Ending;
                            return TaskStatus::Ready(err.into_failed_action());
                        }
                    }
                }
            }
        }

        // A turn can finish having said nothing usable — a lone `.` or `,` and
        // little else. That is not a loop, but it is just as useless to the
        // caller, so it earns the same remedy: say what was wrong and let the
        // model have another go.
        //
        // Checked on the ASSEMBLED turn, not per message: a streaming model
        // emits one `Messages::Assistant` per token, and almost every single
        // token looks vacuous on its own.
        // A turn that called a tool is exempt: it legitimately produces no text,
        // and the tool result is the progress. Everything else — including a
        // turn that emitted nothing at all — is judged on its text, because an
        // empty answer is exactly as useless as a bare `.`.
        let called_a_tool = collected.iter().any(|message| {
            matches!(
                message,
                Messages::Assistant {
                    content: ModelOutput::ToolCall { .. },
                    ..
                }
            )
        });
        // Set when the ladder ran out on a vacuous answer, so the reset below
        // can tell "this turn was fine" from "this turn was junk we gave up on".
        let mut gave_up_on_a_bad_answer = false;

        if !called_a_tool {
            let answer = assembled_answer(collected);
            if self.detector.check_answer(&answer, &self.last_user_prompt) != LoopDetection::NoLoop
            {
                match self.detector.escalate() {
                    Escalation::Redirect | Escalation::SwitchModelOrTemperature { .. } => {
                        tracing::debug!(
                            answer = %answer,
                            attempt = self.detector.redirect_count(),
                            "agent: turn produced no usable answer, asking again"
                        );
                        self.push_user_message(vacuous_answer_redirect());
                        self.state = AgentLoopState::InnerAssemble;
                        // Streaming already handed the caller every token of the
                        // turn being thrown away, so tell it to drop them —
                        // otherwise the retry's answer is appended to the junk
                        // it was meant to replace.
                        return TaskStatus::Ready(SessionRecord::Retracted {
                            id: foundation_compact::ids::new_scru128(),
                            reason: format!(
                                "turn produced no usable answer ({answer:?}), retrying"
                            ),
                            timestamp: std::time::SystemTime::now(),
                        });
                    }
                    // Deliberately NOT a failure. Out of retries, the best thing
                    // left is the weak answer itself — terminating would turn a
                    // poor reply into no reply, which is strictly worse for the
                    // caller. A real loop still terminates, because there the
                    // point is to stop burning tokens.
                    Escalation::Terminate => {
                        gave_up_on_a_bad_answer = true;
                        tracing::debug!(
                            answer = %answer,
                            "agent: still no usable answer after retries, passing it through"
                        );
                    }
                }
            }
        }

        // A turn that came back good earns a fresh allowance: one bad patch
        // early in a session must not leave it one hiccup from giving up hours
        // later, which is what happened when nothing ever reset this.
        //
        // Giving up on a bad answer is NOT that. Resetting there hands the next
        // outer pass a full ladder to spend on the same junk, so a model stuck
        // producing `0` burns max_redirects retries per outer iteration instead
        // of max_redirects in total. The count stands until something works.
        if !gave_up_on_a_bad_answer {
            self.detector.reset();
        }

        // Persist the accepted assistant turn to session history.
        //
        // The streaming path emits each message to the caller via
        // `Stream::Next` but never wrote it to `message_api` — only user
        // messages and tool results were persisted. So a resumed session (or
        // `message_api.recent()` on the next turn) saw the user's side of the
        // conversation but not the assistant's, silently losing multi-turn
        // context. Persist here — once per turn with the complete `collected`
        // set, NOT per `Stream::Next`, so token-streaming models do not write a
        // fragment per token. Loop redirect/terminate return above, so only an
        // accepted generation reaches this point.
        // One message per output, not per streamed chunk: a token-streaming
        // backend yields a message per token and the HTTP backends re-send the
        // text so far on every chunk, and either way persisting each chunk
        // filled the history (and the next turn's context) with fragments.
        for msg in coalesce_turn(collected) {
            let _ = self
                .message_api
                .append(SessionRecord::Conversation { message: msg });
        }

        // Record the model's reported usage into the session ledger.
        // `TokenLedger::record` existed but the loop never called it, so budget
        // tracking, usage snapshots and cost accounting stayed at zero
        // regardless of real token consumption. Streaming models report
        // CUMULATIVE usage on each token message, so record only the LAST
        // assistant message's usage (recording every one would multiply-count).
        if let Some(Messages::Assistant { usage, .. }) = collected
            .iter()
            .rev()
            .find(|m| matches!(m, Messages::Assistant { .. }))
        {
            self.ledger.record(usage);
            // Streaming usage is cumulative, so `total_tokens` of the last
            // message is this generation's total.
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let tokens = usage.total_tokens.max(0.0) as u64;
            if let Err(err) = self.access.record_usage(&self.user, tokens) {
                tracing::warn!(
                    user = %self.user.0,
                    reason = %err.reason,
                    "access provider failed to record usage"
                );
            }
        }

        // Extract tool calls from assistant messages.
        let tool_calls = Self::extract_tool_calls(collected);

        if tool_calls.is_empty() {
            // No tools — go to output processing.
            self.state = AgentLoopState::OutputProcessing;
            TaskStatus::Ignore
        } else {
            let total = tool_calls.len();
            self.state = AgentLoopState::InnerToolCalls { calls: tool_calls };
            TaskStatus::Pending(AgentProgress::ExecutingTools {
                total,
                completed: 0,
            })
        }
    }

    fn extract_tool_calls(messages: &[Messages]) -> Vec<ToolCallRequest> {
        let mut calls = Vec::new();
        for msg in messages {
            if let Messages::Assistant {
                content:
                    ModelOutput::ToolCall {
                        id,
                        name,
                        arguments,
                        depends_on,
                        execution_hint,
                        ..
                    },
                ..
            } = msg
            {
                calls.push(ToolCallRequest {
                    id: id.clone(),
                    name: name.clone(),
                    arguments: arguments.clone().unwrap_or_default(),
                    depends_on: depends_on.clone(),
                    execution_hint: *execution_hint,
                });
            }
        }
        calls
    }

    fn transition_inner_tool_calls(
        &mut self,
    ) -> TaskStatus<SessionRecord, AgentProgress> {
        let previous = std::mem::replace(&mut self.state, AgentLoopState::Done);
        let actual = previous.variant_name();
        let AgentLoopState::InnerToolCalls { calls } = previous else {
            panic!(
                "transition_inner_tool_calls requires AgentLoopState::InnerToolCalls, found {actual}"
            )
        };

        // Build the workflow (topological sort by depends_on).
        let workflow = match self.tool_manager.build_workflow(&calls) {
            Ok(w) => w,
            Err(e) => {
                let err = AgenticError::ToolCall {
                    tool_name: "workflow".into(),
                    reason: e.to_string(),
                };
                self.state = AgentLoopState::OutputProcessing;
                return TaskStatus::Ready(err.into_failed_action());
            }
        };

        // Flatten the workflow stages into a flat execution order.
        let mut flat_calls = Vec::new();
        for stage in workflow.stages {
            match stage {
                crate::agentic::tool_impl::ToolCallStage::Parallel { calls: sc, .. }
                | crate::agentic::tool_impl::ToolCallStage::Sequential { calls: sc, .. } => {
                    flat_calls.extend(sc);
                }
            }
        }

        if flat_calls.is_empty() {
            self.state = AgentLoopState::OutputProcessing;
            return TaskStatus::Ignore;
        }

        self.state = AgentLoopState::InnerExecuting {
            calls: flat_calls,
            results: Vec::new(),
            idx: 0,
            active: None,
            cancel_signals: Vec::new(),
        };
        TaskStatus::Ignore
    }

    fn transition_inner_executing(
        &mut self,
        ctx: Ctx,
    ) -> TaskStatus<SessionRecord, AgentProgress> {
        let previous = std::mem::replace(&mut self.state, AgentLoopState::Done);
        let actual = previous.variant_name();
        let AgentLoopState::InnerExecuting {
            calls,
            mut results,
            idx,
            mut active,
            mut cancel_signals,
        } = previous
        else {
            panic!(
                "transition_inner_executing requires AgentLoopState::InnerExecuting, found {actual}"
            )
        };

        // Check for steering cancel — abort all in-flight tool futures.
        if self.queues.has_priority() {
            for sig in &cancel_signals {
                sig.store(true, Ordering::Release);
            }
            let msgs = self.queues.drain_priority();
            self.queues.reset_cancel();
            for msg in msgs {
                self.push_user_message(msg);
            }
            self.state = AgentLoopState::InnerAssemble;
            return TaskStatus::Pending(AgentProgress::Steering {
                source: std::borrow::Cow::Borrowed("cancel_executing"),
            });
        }

        if idx >= calls.len() {
            // All tools executed — build result messages and emit them.
            let result_messages: Vec<Messages> = results
                .into_iter()
                .map(|(req, result)| {
                    let (content, error_detail) = match result {
                        Ok(r) => (r.content, r.error_detail),
                        Err(e) => (
                            UserModelContent::Text(TextContent {
                                content: e.to_string(),
                                signature: None,
                            }),
                            Some(e.to_string()),
                        ),
                    };
                    Messages::ToolResult {
                        id: foundation_compact::ids::new_scru128(),
                        tool_call_id: req.id,
                        name: req.name,
                        timestamp: foundation_compact::SystemTime::now(),
                        details: None,
                        content,
                        error_detail,
                        signature: None,
                    }
                })
                .collect();

            if result_messages.is_empty() {
                self.state = AgentLoopState::OutputProcessing;
                return TaskStatus::Ignore;
            }

            self.state = AgentLoopState::InnerEmitResults {
                results: result_messages,
                idx: 0,
            };
            return TaskStatus::Ignore;
        }

        // If no active driven iterator, start one via drive_future with CancellableFutureTask.
        if active.is_none() {
            let call = calls[idx].clone();
            let mgr = self.tool_manager.clone();
            let retry_config = mgr.retry_config(&call.name);
            // Ask the access provider before running anything. A refusal (or a
            // failing check) becomes an error result the model can read, the
            // same as any other tool failure.
            let denied = match self.access.can_use_tool(&self.user, &call.name) {
                Ok(true) => None,
                Ok(false) => Some(ToolError::Execution {
                    tool: call.name.clone(),
                    reason: format!(
                        "user '{}' is not authorized to use tool '{}'",
                        self.user.0, call.name
                    ),
                }),
                Err(err) => Some(ToolError::Execution {
                    tool: call.name.clone(),
                    reason: format!("authorization check failed: {}", err.reason),
                }),
            };
            // The model may only call `shed` and the tools `shed` has
            // returned; anything else gets an error telling it to look first.
            let refused = denied.or_else(|| mgr.check_offered(&call.name).err());
            let fut: core::pin::Pin<
                Box<dyn core::future::Future<Output = Result<ToolCallResult, ToolError>> + Send>,
            > = match refused {
                None => Box::pin(async move { mgr.execute_with_retry(&call, &retry_config).await }),
                Some(err) => Box::pin(async move { Err(err) }),
            };
            let signal = Arc::new(AtomicBool::new(false));
            cancel_signals.push(Arc::clone(&signal));
            let task = CancellableFutureTask::new(fut, signal);
            active = Some(foundation_core::valtron::drive_iterator(task, ctx.clone()));
        }

        // Poll the driven iterator.
        let total = calls.len();
        let driven = active.as_mut().expect("just created");
        match driven.next() {
            Some(TaskStatus::Ready(Ok(result))) => {
                results.push((calls[idx].clone(), result));
                self.state = AgentLoopState::InnerExecuting {
                    calls,
                    results,
                    idx: idx + 1,
                    active: None,
                    cancel_signals,
                };
                TaskStatus::Pending(AgentProgress::ExecutingTools {
                    total,
                    completed: idx + 1,
                })
            }
            Some(TaskStatus::Ready(Err(CancelOutcome::Cancelled))) => {
                let err = ToolError::Cancelled(calls[idx].name.clone());
                results.push((calls[idx].clone(), Err(err)));
                self.state = AgentLoopState::InnerExecuting {
                    calls,
                    results,
                    idx: idx + 1,
                    active: None,
                    cancel_signals,
                };
                TaskStatus::Pending(AgentProgress::ExecutingTools {
                    total,
                    completed: idx + 1,
                })
            }
            Some(TaskStatus::Pending(_)) => {
                self.state = AgentLoopState::InnerExecuting {
                    calls,
                    results,
                    idx,
                    active,
                    cancel_signals,
                };
                TaskStatus::Pending(AgentProgress::ExecutingTools {
                    total,
                    completed: idx,
                })
            }
            None => {
                // Driven iterator exhausted without Ready — treat as error.
                let err = ToolError::Execution {
                    tool: calls[idx].name.clone(),
                    reason: "future completed without result".into(),
                };
                results.push((calls[idx].clone(), Err(err)));
                self.state = AgentLoopState::InnerExecuting {
                    calls,
                    results,
                    idx: idx + 1,
                    active: None,
                    cancel_signals,
                };
                TaskStatus::Ignore
            }
            _ => {
                self.state = AgentLoopState::InnerExecuting {
                    calls,
                    results,
                    idx,
                    active,
                    cancel_signals,
                };
                TaskStatus::Ignore
            }
        }
    }

    fn transition_inner_emit_results(
        &mut self,
    ) -> TaskStatus<SessionRecord, AgentProgress> {
        let previous = std::mem::replace(&mut self.state, AgentLoopState::Done);
        let actual = previous.variant_name();
        let AgentLoopState::InnerEmitResults { results, idx } = previous else {
            panic!(
                "transition_inner_emit_results requires AgentLoopState::InnerEmitResults, found {actual}"
            )
        };

        if idx >= results.len() {
            tracing::trace!(
                "Loop index greater tan results len: idx={}, len={}",
                idx,
                results.len()
            );

            // All results emitted — loop back to InnerAssemble for the LLM
            // to process tool results (guarded by max_inner_iterations).
            self.inner_iteration += 1;
            if self.inner_iteration >= self.config.max_inner_iterations {
                tracing::trace!("Max loop iteration method");
                self.state = AgentLoopState::OutputProcessing;
                return TaskStatus::Pending(AgentProgress::SessionEnding);
            }
            self.state = AgentLoopState::InnerAssemble;
            return TaskStatus::Ignore;
        }

        let msg = results[idx].clone();
        tracing::trace!("Adding new message from model: {:?}", &msg);
        let _ = self.message_api.append(SessionRecord::Conversation {
            message: msg.clone(),
        });
        self.message_count += 1;

        self.state = AgentLoopState::InnerEmitResults {
            results,
            idx: idx + 1,
        };
        TaskStatus::Ready(SessionRecord::Conversation { message: msg })
    }

    fn transition_output_processing(
        &mut self,
    ) -> TaskStatus<SessionRecord, AgentProgress> {
        // Fire memory triggers (F15) — check if observation/reflection needed.
        let action = self.memory.check_triggers();
        self.state = AgentLoopState::OuterBoundary;
        match action {
            MemoryAction::GenerateObservation => {
                TaskStatus::Pending(AgentProgress::ProcessingMemory {
                    kind: MemoryKind::Observation,
                })
            }
            MemoryAction::GenerateReflection => {
                TaskStatus::Pending(AgentProgress::ProcessingMemory {
                    kind: MemoryKind::Reflection,
                })
            }
            MemoryAction::None => TaskStatus::Ignore,
        }
    }

    fn transition_ending(
        &mut self,
    ) -> TaskStatus<SessionRecord, AgentProgress> {
        let snapshot = self.ledger.snapshot();
        let summary = SessionRecord::Summary {
            message_count: self.message_count,
            usage: snapshot,
        };
        self.state = AgentLoopState::Done;
        TaskStatus::Ready(summary)
    }

    // -----------------------------------------------------------------------
    // Error handling (F02)

    fn handle_error(
        &mut self,
        error: AgenticError,
    ) -> TaskStatus<SessionRecord, AgentProgress> {
        let action = self.policy.classify(error.clone());
        match action {
            AgentAction::Continue => TaskStatus::Ignore,
            AgentAction::RetryWithReducedContext => {
                // Stay in InnerAssemble — the context provider will re-pack
                // with reduced budget on the next assemble call.
                self.state = AgentLoopState::InnerAssemble;
                TaskStatus::Pending(AgentProgress::Steering {
                    source: std::borrow::Cow::Borrowed("retry_reduced_context"),
                })
            }
            AgentAction::SwitchModel => {
                if let Some(fallback) = self.breaker.on_failure() {
                    self.current_model = fallback;
                    self.state = AgentLoopState::InnerAssemble;
                    TaskStatus::Pending(AgentProgress::Steering {
                        source: std::borrow::Cow::Borrowed("model_switch"),
                    })
                } else {
                    // All fallbacks exhausted — terminate.
                    self.state = AgentLoopState::Ending;
                    TaskStatus::Ready(error.into_failed_action())
                }
            }
            AgentAction::Terminate(err) => {
                self.state = AgentLoopState::Ending;
                TaskStatus::Ready(err.into_failed_action())
            }
        }
    }

    // -----------------------------------------------------------------------
    // Context pressure (OD-19-7)

    /// Shrink an over-budget context in place by dropping the OLDEST messages
    /// until it fits under `preflight_compression_threshold * budget`.
    ///
    /// WHY: the config threshold existed but nothing applied it. When a context
    /// is assembled that would blow the budget, sending it wastes tokens (or is
    /// rejected by the provider). Truncation-based compression keeps the most
    /// recent turns — the ones that matter most — and drops the oldest.
    ///
    /// A `0.0` threshold (or no budget) disables it. Recomputes `token_estimate`
    /// so downstream (context-pressure) sees the compressed size.
    fn apply_preflight_compression(&self, ctx: &mut AgentContext) {
        if self.config.preflight_compression_threshold <= 0.0 {
            return;
        }
        let Some(budget) = self.ledger.budget() else {
            return; // unlimited budget — nothing to compress against
        };
        if budget == 0 {
            return;
        }

        #[allow(clippy::cast_precision_loss)]
        let limit = f64::from(self.config.preflight_compression_threshold) * budget as f64;

        // Drop oldest messages (front) until under the limit or only one left.
        while ctx.messages.len() > 1 {
            #[allow(clippy::cast_precision_loss)]
            let ratio = ctx.token_estimate as f64;
            if ratio <= limit {
                break;
            }
            let dropped = ctx.messages.remove(0);
            let est = crate::agentic::context::estimate_tokens_pub(&dropped);
            ctx.token_estimate = ctx.token_estimate.saturating_sub(est);
        }
    }

    fn apply_context_pressure(&self, ctx: &AgentContext) -> Option<String> {
        if self.config.context_pressure_threshold <= 0.0 {
            return ctx.system_prompt.clone();
        }

        let budget = self.ledger.budget().unwrap_or(u64::MAX);
        // u64 → f64: precision loss acceptable for ratio computation.
        #[allow(clippy::cast_precision_loss)]
        let usage_ratio = ctx.token_estimate as f64 / budget as f64;

        if usage_ratio >= f64::from(self.config.context_pressure_threshold) {
            // Percentage is in [0, ~100]; truncation/sign loss are safe.
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let pct = (usage_ratio * 100.0) as u32;
            let pressure_note = format!(
                "Context is at {pct}% capacity — prefer concise responses \
                 and avoid requesting large tool outputs."
            );
            let base = ctx.system_prompt.as_deref().unwrap_or("");
            Some(format!("{base}\n\n[{pressure_note}]"))
        } else {
            ctx.system_prompt.clone()
        }
    }
}

// ---------------------------------------------------------------------------
// TaskIterator impl

impl<D, M> TaskIterator for AgentLoop<D, M>
where
    D: DocumentStore + 'static,
    M: MemoryStore + 'static,
{
    type Ready = SessionRecord;
    type Pending = AgentProgress;

    fn next_status(&mut self, ctx: Ctx) -> Option<TaskStatus<Self::Ready, Self::Pending>> {
        match &self.state {
            AgentLoopState::Initializing => {
                self.state = AgentLoopState::OuterBoundary;
                Some(TaskStatus::Init)
            }
            AgentLoopState::OuterBoundary => Some(self.transition_outer_boundary()),
            AgentLoopState::InnerAssemble => Some(self.transition_inner_assemble()),
            AgentLoopState::InnerGenerate { .. } => Some(self.transition_inner_generate()),
            AgentLoopState::InnerToolCalls { .. } => Some(self.transition_inner_tool_calls()),
            AgentLoopState::InnerExecuting { .. } => Some(self.transition_inner_executing(ctx.clone())),
            AgentLoopState::InnerEmitResults { .. } => Some(self.transition_inner_emit_results()),
            AgentLoopState::OutputProcessing => Some(self.transition_output_processing()),
            AgentLoopState::Ending => Some(self.transition_ending()),
            AgentLoopState::Done => None,
        }
    }
}