causa-runtime 0.0.1

Causa runtime — optional components: execution stack (turn loop, dispatch, streaming, pause/resume, session)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
//! The execution stack here — retry scheduling, tool batch dispatch, artifact
//! spill, control plumbing, and trace construction. The canonical consumer
//! of the kernel's contracts lives here, one layer up.
use crate::budget::FramePolicy;
use crate::config::TurnRunOptions;
use crate::config::UnknownOutcomePolicy;
use crate::control::RunControl;
use crate::conversation::{ConversationError, ConversationState, SealedResult};
use crate::executor::ToolExecutor;
use crate::hook::UnknownDecision;
use crate::interaction::BatchDecision;
use causa_kernel::AttemptNumber;
use causa_kernel::ModelGateway;
use causa_kernel::ModelRequest;
use causa_kernel::ModelStopReason;
use causa_kernel::TextPayload;
use causa_kernel::ToolCallPayload;
use causa_kernel::ToolResultPayload;
use causa_kernel::{ArtifactRef, ToolCallId, ToolResultStatus, Truncation};
use causa_kernel::{AttemptControl, ModelUsage, StreamDelta};
use causa_kernel::{BlockContent, merged_frame};
use causa_kernel::{BlockId, ConversationId, FrameScope, InvocationId, RoundId};
use causa_kernel::{ModelInvokeError, ModelInvokeErrorKind, ModelOutput};
use causa_kernel::{TurnContext, TurnSnapshot};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};

use tracing::Instrument;

use crate::hook::{HookCtx, HookOutcome, PassthroughHook, ToolUseHook};
use futures_util::StreamExt;

fn millis_since(t: Instant) -> u64 {
    t.elapsed().as_millis() as u64
}

/// The turn's committed-but-unanswered tool calls, in block order — the
/// model-emitted draft order results pair into. Shared by the resume
/// validation and the approval-resume prologue.
pub(crate) fn unanswered_tool_calls(active: &TurnContext) -> Vec<ToolCallPayload> {
    let mut pending: Vec<ToolCallPayload> = Vec::new();
    for b in active.blocks() {
        match &b.content {
            BlockContent::ToolCall(c) => pending.push(c.clone()),
            BlockContent::ToolResult(r) => pending.retain(|p| p.call_id != r.call_id),
            _ => {}
        }
    }
    pending
}

// Tool-use filtering lives behind `crate::hook::ToolUseHook`.
// `TurnRunner` defaults to `PassthroughHook` (no opinion); concrete
// filter policies live in `crate::filter` or the host layer.

/// Why a turn terminated in `TurnResult::Interrupted`. The serde shape
/// (`kind` / `detail`) is part of the event wire contract; see the
/// wire-contract note on [`TurnOutcome`].
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", content = "detail")]
pub enum TurnInterruption {
    /// The host cancelled the turn through the shared `RunControl` token
    /// (including cancellation observed mid-call, mid-stream, or during
    /// retry backoff).
    ExplicitCancellation,
    /// The turn deadline carried by `RunControl` passed (checked at every
    /// loop top; retry backoff caps its wait at the remaining deadline and
    /// re-checks before each attempt, and a retry loop that gives up after
    /// the deadline has passed ends here rather than with the last
    /// attempt's error kind).
    TurnDeadlineExceeded,
    /// Uniform carrier for terminal model-call failures: retry exhaustion
    /// and non-retryable kinds (Permanent / InvalidRequest / UnknownOutcome)
    /// all land here, discriminated by `last_kind`; a parent-caused
    /// `Cancelled` maps to `ExplicitCancellation` instead.
    RetryExhausted {
        /// Error kind of the final failed attempt — retry exhaustion and
        /// non-retryable kinds alike.
        last_kind: ModelInvokeErrorKind,
        /// Error message of the final failed attempt.
        last_error: String,
    },
    /// The kernel refused the model response —
    /// `TurnContext::append_model_output` rejected it.
    InvalidModelOutput {
        /// The kernel's rejection message.
        reason: String,
    },
    /// The loop reached `TurnLimits::max_model_rounds` before the model
    /// ended the turn.
    MaxModelRounds {
        /// The configured limit that was reached.
        limit: u32,
    },
    /// The turn emitted more than `TurnLimits::max_tool_calls` tool calls
    /// (counted at dispatch time, including a batch paused pending
    /// approval).
    MaxToolCalls {
        /// The configured limit that was exceeded.
        limit: u32,
    },
    /// A tool call ended `UnknownOutcome` while its trusted declaration
    /// demands `Stop` — the call's result is unknowable, so continuing
    /// is unsafe.
    UnsafeUnknownOutcome {
        /// The offending call.
        call_id: ToolCallId,
    },
    /// Turn-scope frame materialization failed — `FramePolicy::materialize`
    /// returned an error.
    CompactionFailed {
        /// The materialization error message.
        reason: String,
    },
    /// A driver invariant broke (e.g. the fact machine refused an append)
    /// — a caller bug, not a model or tool failure.
    RunnerInvariantViolation {
        /// The invariant failure message.
        reason: String,
    },
    /// The model stopped on the token ceiling; the driver dispatches this
    /// before applying, so no blocks persist.
    ModelMaxTokens,
    /// The model refused; the driver dispatches this before applying, so
    /// no blocks persist.
    ModelRefusal,
}

/// One model attempt inside a round — an entry of the retry ledger.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AttemptTrace {
    /// 1-based attempt number within the round's invocation.
    pub attempt: AttemptNumber,
    /// `None` = successful attempt; `Some(kind)` = the failure classification.
    pub kind: Option<ModelInvokeErrorKind>,
    /// Whether the failure was classified retryable (it may still not have
    /// been retried once `RetryPolicy::max_retries` was spent).
    pub is_retryable: bool,
    /// Wall-clock duration of the attempt, in milliseconds.
    pub duration_ms: u64,
}
/// Summary of the model output that closed a round, recorded before any
/// tool dispatch.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OutputSummary {
    /// The model's stop reason (`EndTurn`, `ToolUse`, `MaxTokens`, `Refusal`).
    pub stop_reason: ModelStopReason,
    /// Token usage reported by the gateway, when the provider supplied it.
    pub usage: Option<causa_kernel::ModelUsage>,
    /// Number of tool calls in the model's response payload.
    pub tool_call_count: usize,
    /// Byte length of the response text.
    pub response_text_bytes: usize,
}
/// One dispatched tool call, as observed by the executor.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ToolCallTrace {
    /// Id pairing this entry with the committed tool-call block.
    pub call_id: ToolCallId,
    /// Tool name from the draft payload (resolved by `call_id`).
    pub tool_name: String,
    /// The call's index in the model-emitted draft order.
    pub position: usize,
    /// Final result status of the call.
    pub status: ToolResultStatus,
    /// Output truncation marker (`Truncation::None` unless truncated).
    pub truncation: Truncation,
    /// Reference to the spilled full output, when truncation used an
    /// `ArtifactStore`.
    pub artifact: Option<ArtifactRef>,
    /// Executor-measured wall-clock duration in milliseconds (`0` for
    /// host-precomputed outcomes).
    pub duration_ms: u64,
}
/// One dispatched tool batch, as observed by the executor.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ToolBatchTrace {
    /// Per-call traces in canonical (model draft) order — executor
    /// results, hook rejections, and host-precomputed outcomes alike.
    pub calls: Vec<ToolCallTrace>,
    /// Actual completion order (recorded as the executor returns), not submission order.
    pub completion_order: Vec<ToolCallId>,
}
/// One model round: framing, attempts, output, applied blocks, and its
/// tool batch (when any).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ModelRoundTrace {
    /// 0-based round index within the turn.
    pub round_id: RoundId,
    /// Turn + round identity every attempt of the round shares (a retry
    /// bumps only the attempt number).
    pub invocation_id: InvocationId,
    /// The `source_version` at frame materialization (the version before apply).
    pub frame_version: causa_kernel::ContextVersion,
    /// One entry per model attempt, in order.
    pub attempts: Vec<AttemptTrace>,
    /// `None` when no output was produced (every attempt failed).
    pub output_summary: Option<OutputSummary>,
    /// Ids of the blocks the model door committed this round (optional
    /// text first, then one tool call per draft).
    pub applied_block_ids: Vec<BlockId>,
    /// The dispatched batch, when the round dispatched tools.
    pub tool_batch: Option<ToolBatchTrace>,
}
/// The turn's trace: one record per model round plus totals.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TurnTrace {
    /// Rounds in execution order — including rounds whose invocation
    /// never produced output.
    pub rounds: Vec<ModelRoundTrace>,
    /// Total tool calls emitted, counted at dispatch time (a paused batch
    /// counts once, at emission — the resume does not re-count).
    pub tool_calls_total: usize,
    /// Wall-clock duration of this run in milliseconds (a resumed
    /// continuation measures only the continuation).
    pub total_duration_ms: u64,
}
impl TurnTrace {
    /// An empty trace — no rounds, zero totals; the fresh-drive starting
    /// point.
    pub fn new() -> Self {
        Self {
            rounds: vec![],
            tool_calls_total: 0,
            total_duration_ms: 0,
        }
    }
}
impl Default for TurnTrace {
    fn default() -> Self {
        Self::new()
    }
}

/// How a turn ended: completed, interrupted, or paused mid-turn. The
/// serde shapes are a load-bearing wire contract (embedded in
/// `ContextEvent`); `tests/serialization.rs` pins them.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum TurnResult {
    /// The model ended the turn (`EndTurn`) — no pending work remains.
    Completed {
        /// The final model output.
        final_output: ModelOutput,
    },
    /// The turn stopped early; `cause` discriminates why.
    Interrupted {
        /// Why the turn was interrupted.
        cause: TurnInterruption,
    },
    /// Resumable suspension — not a terminal state: the turn's facts stay
    /// open in the outcome's `context` / `state` (the single fact source),
    /// the prepared batch is neither executed nor rejected, and
    /// `resume_turn` / `TurnRunner::resume` continue the same turn from
    /// the [`Continuation`].
    Paused {
        /// The single continuation: pause position, control counts,
        /// prepared work, and queued inputs.
        continuation: Continuation,
    },
}

/// The hook-prepared work an approval pause checkpoints: the hook has
/// already filtered / rejected / rewritten the model-emitted batch, and
/// those decisions cannot be re-derived on resume — they are saved, not
/// re-run. The original payloads remain derivable from the committed
/// tool-call blocks (fact identity); the independent rewrite and rejections
/// live here as serializable data.
///
/// The checkpoint stores recorded results plus the unknown-outcome actions
/// fixed at pause time, not result envelopes: a tool's recorded result is
/// a fact, and what an `UnknownOutcome` result does next is harness
/// configuration. [`unknown_decisions`](Self::unknown_decisions)
/// must exactly cover the saved results whose status is `UnknownOutcome`
/// — no extra, missing, or duplicate entries — and a resume may never
/// recompute them through new configuration.
///
/// # Wire compatibility
///
/// `rejected` is written as `[{result, policy}]` through a private runtime
/// DTO — the policy is the fixed decision for `UnknownOutcome` entries and
/// the canonical `Stop` for every other status (whose policy never
/// participated in execution). Deserialization reads the same shape (both
/// fields required), drops the policy of non-unknown entries, and rejects
/// any decision set that does not exactly cover the saved `UnknownOutcome`
/// results; earlier formats without prepared work still fail loudly.
pub struct PreparedApproval {
    /// Calls the hook admitted — arguments possibly rewritten — in model
    /// draft order. These are what still await the host's decision at
    /// resume; the resume decision must cover them exactly once.
    pub awaiting: Vec<ToolCallPayload>,
    /// Calls the hook rejected. The stored results commit verbatim at
    /// resume (with their original call ids) and can never be re-decided —
    /// a resume decision touching them is rejected before anything
    /// executes.
    pub rejected: Vec<ToolResultPayload>,
    /// The unknown-outcome actions fixed when the turn paused: exactly one
    /// entry per saved `UnknownOutcome` result, no more, no fewer. New
    /// configuration never overrides these on resume.
    pub unknown_decisions: Vec<UnknownDecision>,
}
impl std::fmt::Debug for PreparedApproval {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PreparedApproval")
            .field("awaiting", &self.awaiting.len())
            .field("rejected", &self.rejected.len())
            .field("unknown_decisions", &self.unknown_decisions.len())
            .finish()
    }
}
impl Clone for PreparedApproval {
    fn clone(&self) -> Self {
        Self {
            awaiting: self.awaiting.clone(),
            rejected: self.rejected.clone(),
            unknown_decisions: self.unknown_decisions.clone(),
        }
    }
}

/// Private wire shape for one checkpointed rejection: the `{result, policy}`
/// envelope. Not part of the public API — the public in-memory structure
/// separates the recorded result from the saved action.
#[derive(serde::Serialize, serde::Deserialize)]
struct RejectedWire {
    result: ToolResultPayload,
    policy: UnknownOutcomePolicy,
}

impl serde::Serialize for PreparedApproval {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let rejected: Vec<RejectedWire> = self
            .rejected
            .iter()
            .map(|result| RejectedWire {
                result: result.clone(),
                policy: if result.status == ToolResultStatus::UnknownOutcome {
                    // Exact cover is an invariant; fall back to the default
                    // action only to keep serialization total.
                    self.unknown_decisions
                        .iter()
                        .find(|d| d.call_id == result.call_id)
                        .map(|d| d.policy)
                        .unwrap_or_default()
                } else {
                    // The policy of a decided result never participated in
                    // execution; the canonical Stop keeps the old shape.
                    UnknownOutcomePolicy::Stop
                },
            })
            .collect();
        #[derive(serde::Serialize)]
        struct Wire<'a> {
            awaiting: &'a Vec<ToolCallPayload>,
            rejected: Vec<RejectedWire>,
        }
        Wire {
            awaiting: &self.awaiting,
            rejected,
        }
        .serialize(serializer)
    }
}

impl<'de> serde::Deserialize<'de> for PreparedApproval {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(serde::Deserialize)]
        struct Wire {
            awaiting: Vec<ToolCallPayload>,
            rejected: Vec<RejectedWire>,
        }
        let wire = Wire::deserialize(deserializer)?;
        let mut rejected = Vec::with_capacity(wire.rejected.len());
        let mut unknown_decisions: Vec<UnknownDecision> = Vec::new();
        for entry in wire.rejected {
            if entry.result.status == ToolResultStatus::UnknownOutcome {
                // The saved action rides the old policy field; a missing
                // one is a hard deserialize error, never a silent Stop.
                unknown_decisions.push(UnknownDecision {
                    call_id: entry.result.call_id.clone(),
                    policy: entry.policy,
                });
            }
            // Non-unknown entries' policy was never consumed by the
            // execution stack; it is dropped on load and re-canonicalized
            // to Stop on write.
            rejected.push(entry.result);
        }
        // Exact cover: every saved UnknownOutcome has exactly one decision,
        // and no decision points at a decided (non-unknown) result.
        let unknown_ids: std::collections::HashSet<&ToolCallId> = rejected
            .iter()
            .filter(|r| r.status == ToolResultStatus::UnknownOutcome)
            .map(|r| &r.call_id)
            .collect();
        let mut seen = std::collections::HashSet::new();
        for d in &unknown_decisions {
            if !unknown_ids.contains(&d.call_id) {
                return Err(serde::de::Error::custom(format!(
                    "checkpoint decision for call {:?} does not match a saved UnknownOutcome result",
                    d.call_id.0
                )));
            }
            if !seen.insert(&d.call_id) {
                return Err(serde::de::Error::custom(format!(
                    "checkpoint has conflicting decisions for call {:?}",
                    d.call_id.0
                )));
            }
        }
        if seen.len() != unknown_ids.len() {
            return Err(serde::de::Error::custom(
                "checkpoint is missing the unknown-outcome decision for a saved result",
            ));
        }
        // A call id appearing twice among the results would already be a
        // fact-pairing error downstream; reject it here where the wire is
        // at fault.
        let mut ids = std::collections::HashSet::new();
        for r in &rejected {
            if !ids.insert(&r.call_id) {
                return Err(serde::de::Error::custom(format!(
                    "checkpoint saves call {:?} twice",
                    r.call_id.0
                )));
            }
        }
        Ok(Self {
            awaiting: wire.awaiting,
            rejected,
            unknown_decisions,
        })
    }
}

/// Where a turn paused. The execution stack currently emits only the
/// approval position; the steering position exists so hosts that suspend
/// before a model round produce a continuation the same resume machinery
/// consumes (the pause point and the round together define the next step —
/// never free-floating `Option`s).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", content = "detail", rename_all = "snake_case")]
pub enum PausePoint {
    /// The approval gate paused behind a hook-prepared batch.
    AwaitingApproval {
        /// The hook's prepared work awaiting the host's decision.
        prepared: PreparedApproval,
        /// Advisory decision budget the host granted itself, as *remaining*
        /// time so the variant stays serde-friendly (a host anchors
        /// `Instant::now() + d`). Carried for information only — the resume
        /// never derives a deadline from it.
        deadline: Option<Duration>,
    },
    /// Paused before a model round so the host can steer; no batch awaits
    /// (a steering continuation over a turn with unanswered tool calls is
    /// rejected at resume — the batch could never be answered).
    PausedForSteering,
}

/// The single continuation of a paused turn: everything
/// resuming needs beyond the paused outcome's fact state, the runner, the
/// new options, and the new control. Rounds and quotas are read from here
/// — never from the trace, which is observational and may be trimmed
/// freely without changing where a resume continues or what it may spend.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Continuation {
    /// Where and why the turn paused.
    pub pause_point: PausePoint,
    /// The round the continuation sits at: for an approval pause, the
    /// paused round whose batch executes first at resume (the loop then
    /// continues at round+1); for a steering pause, the first round whose
    /// model phase has not run yet.
    pub round: u32,
    /// Tool calls already counted against the turn's quota at emission
    /// time (a paused batch was counted once, at emission — the resume
    /// never re-counts it). The authoritative control count across
    /// resumes.
    pub accounted_tool_calls: usize,
    /// Inputs received but not yet committed. A resume commits them first
    /// (`user.steering` label), before the resume request's own inject —
    /// "queued → injected → pulled" order; identical texts are independent
    /// inputs and are never deduped.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub queued_inputs: Vec<TextPayload>,
}

/// A bare-turn entry's result: the turn context (sealed unless the turn
/// paused), the outcome, and the trace.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TurnOutcome {
    /// The sealed active turn at handoff. Serialized through the
    /// `turn_context_as_snapshot` adapter (see `causa_kernel::turn_context_as_snapshot`):
    /// the in-memory `TurnContext` is the mutable fact machine, but
    /// once sealed its snapshot projection is the canonical wire shape.
    /// On reload we rebuild a sealed `TurnContext` via
    /// `from_validated_blocks` + `seal()`.
    #[serde(with = "causa_kernel::turn_context_as_snapshot")]
    pub context: TurnContext,
    /// Terminal result or pause — see [`TurnResult`].
    pub result: TurnResult,
    /// What happened during the run — see [`TurnTrace`].
    pub trace: TurnTrace,
}

// Wire-contract note: `TurnResult`, `TurnOutcome`, `ConversationOutcome`
// and the `TurnTrace` family are embedded in `causa_runtime::event::ContextEvent`
// and delivered over IPC. Their Rust item paths live in this crate and may
// move between layers without notice — but their serde shapes are a
// load-bearing external contract and must not change without a breaking
// migration of the event wire format. `tests/serialization.rs` pins the
// shapes.

/// The conversation entry's counterpart to [`TurnOutcome`]: consume/return —
/// the state comes back with the active turn sealed inside and its outcome
/// stamped; the host then calls `commit` (Completed) or `abort_turn`
/// (Interrupted).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConversationOutcome {
    /// The state back from the run, its active turn sealed and
    /// outcome-stamped; the host then calls `commit` (Completed),
    /// `abort_turn` (Interrupted), or `resume_turn` (Paused).
    pub state: ConversationState,
    /// The active turn's outcome.
    pub result: TurnResult,
    /// The active turn's trace (a resumed continuation appends to the
    /// paused phase's trace).
    pub trace: TurnTrace,
}

/// The frame source — the single fork point between the two runner entries.
#[derive(Clone, Copy)]
enum FrameSource<'a> {
    /// Policy-shaped materialization over the active turn (Turn scope).
    Turn(&'a FramePolicy),
    /// Lossless merged view (Conversation scope) — the frame policy is
    /// deliberately inert here.
    Conversation {
        conversation_id: &'a ConversationId,
        history: &'a [TurnSnapshot],
    },
}

/// The model-phase fork point: a batch `invoke`, or a delta `stream` whose
/// items are forwarded to the interaction seam. Everything downstream of
/// the assembled `ModelOutput` is shared state machine.
#[derive(Clone, Copy)]
pub(crate) enum ModelPhase {
    Batch,
    Stream,
}

/// Continuation payload for a resumed turn: the validated continuation plus
/// the new decision, consumed once by `drive_from`'s prologue. Built by the
/// public resume entries after validation; rounds, counts, prepared work,
/// and queued inputs all come from the [`Continuation`] — the trace rides
/// along as observation only.
pub(crate) struct ResumeState {
    /// The paused turn's continuation (pause position, round, counts,
    /// prepared work, queued inputs).
    pub(crate) continuation: Continuation,
    /// The resume request's new decision for the prepared batch. `Some`
    /// iff the pause point is `AwaitingApproval` (enforced by validation).
    pub(crate) decision: Option<HookOutcome>,
    /// The resume request's new inputs, appended before the next model
    /// round — after the continuation's queued inputs.
    pub(crate) inject: Vec<TextPayload>,
    /// The paused phase's trace — rounds append to it, totals re-derive
    /// from the continuation's count. A trimmed trace changes nothing.
    pub(crate) trace: TurnTrace,
}

/// What a batch dispatch feeds the executor: live payloads, or
/// pre-computed results (hook rejections and the host's
/// `BatchDecision::Reject` copy).
enum BatchWork {
    Execute(Vec<ToolCallPayload>),
    Precomputed(Vec<PrecomputedResult>),
}

/// One pre-computed tool result with its unknown-outcome action when that
/// action is already fixed — a checkpoint entry, an explicit host
/// decision, or an executed `UnknownOutcome` (resolved by the executed
/// name at dispatch time). `None` resolves through the turn's
/// unknown-outcome configuration by the batch's tool name;
/// results with any other status never consume an action.
#[derive(Debug, Clone)]
struct PrecomputedResult {
    result: ToolResultPayload,
    fixed_policy: Option<UnknownOutcomePolicy>,
}

/// Attach explicit host decisions to precomputed results: an
/// `UnknownOutcome` entry picks up its explicit decision if one is given,
/// else stays unfixed (resolved by the batch name later). Entries for
/// non-unknown results are ignored here and rejected by validation.
fn attach_decisions(
    results: Vec<ToolResultPayload>,
    decisions: &[UnknownDecision],
) -> Vec<PrecomputedResult> {
    results
        .into_iter()
        .map(|result| PrecomputedResult {
            fixed_policy: if result.status == ToolResultStatus::UnknownOutcome {
                decisions
                    .iter()
                    .find(|d| d.call_id == result.call_id)
                    .map(|d| d.policy)
            } else {
                None
            },
            result,
        })
        .collect()
}

/// The execution stack over the kernel's ports: frame materialization,
/// bounded model retry, tool batch dispatch through the hook and
/// interaction seams, run control plumbing, and trace construction.
pub struct TurnRunner {
    gateway: Arc<dyn ModelGateway>,
    executor: Arc<ToolExecutor>,
    /// Seam for tool-use filtering. `TurnRunner::new()` defaults to
    /// `PassthroughHook` (no filter applied — the driver carries no
    /// opinion). Custom hooks (e.g. `FilterChain`, which implements
    /// `ToolUseHook`) plug in via `TurnRunner::with_hook`.
    hook: Arc<dyn ToolUseHook>,
}
impl TurnRunner {
    /// A runner with the default [`PassthroughHook`] — no tool-use
    /// filtering (the driver carries no opinion; opt in via
    /// [`TurnRunner::with_hook`]).
    pub fn new(gateway: Arc<dyn ModelGateway>, executor: Arc<ToolExecutor>) -> Self {
        Self {
            gateway,
            executor,
            hook: Arc::new(PassthroughHook),
        }
    }

    /// A runner with a custom [`ToolUseHook`] applied between model
    /// output and tool dispatch (e.g. a
    /// [`FilterChain`](crate::filter::FilterChain)).
    pub fn with_hook(
        gateway: Arc<dyn ModelGateway>,
        executor: Arc<ToolExecutor>,
        hook: Arc<dyn ToolUseHook>,
    ) -> Self {
        Self {
            gateway,
            executor,
            hook,
        }
    }
    /// Frames materialize from the active turn alone (Turn scope,
    /// policy-shaped).
    pub async fn run(
        &self,
        context: TurnContext,
        options: TurnRunOptions,
        ctrl: RunControl,
    ) -> TurnOutcome {
        let span = tracing::info_span!(
            "agent.turn",
            turn_id = %context.turn_id().0,
            scope = "turn"
        );
        self.run_inner(context, options, ctrl, ModelPhase::Batch)
            .instrument(span)
            .await
    }

    async fn run_inner(
        &self,
        mut context: TurnContext,
        options: TurnRunOptions,
        ctrl: RunControl,
        phase: ModelPhase,
    ) -> TurnOutcome {
        let start = Instant::now();
        let (result, mut trace, tool_calls_total) = self
            .drive(
                &mut context,
                FrameSource::Turn(&options.frame),
                &options,
                &ctrl,
                phase,
            )
            .await;
        // Every drive exit is terminal or paused; the entry owns all
        // bookkeeping (totals, duration, sealing — withheld on pause).
        trace.tool_calls_total = tool_calls_total;
        trace.total_duration_ms = millis_since(start);
        if !matches!(result, TurnResult::Paused { .. }) {
            context.seal();
        }
        TurnOutcome {
            context,
            result,
            trace,
        }
    }

    /// The streaming twin of [`TurnRunner::run`]. The model
    /// phase consumes provider deltas — each one forwarded to
    /// `options.interaction.on_delta` — instead of a single batch result;
    /// retry bookkeeping, tool dispatch, traces, and sealing are the same
    /// shared state machine. A retried attempt re-streams the same frame;
    /// deltas already observed are advisory history, and the host decides
    /// how to present the partial-then-reset flow.
    pub async fn run_streaming(
        &self,
        context: TurnContext,
        options: TurnRunOptions,
        ctrl: RunControl,
    ) -> TurnOutcome {
        let span = tracing::info_span!(
            "agent.turn",
            turn_id = %context.turn_id().0,
            scope = "turn.streaming"
        );
        self.run_inner(context, options, ctrl, ModelPhase::Stream)
            .instrument(span)
            .await
    }

    /// Frames materialize as the lossless merged view over committed history
    /// plus the active turn (Conversation scope — the `options.frame` policy
    /// is deliberately inert here). Consume/return: the state comes back
    /// with the active turn sealed and outcome-stamped; the host then calls
    /// `commit` (Completed) or `abort_turn` (Interrupted).
    pub async fn run_in_conversation(
        &self,
        state: ConversationState,
        options: TurnRunOptions,
        ctrl: RunControl,
    ) -> Result<ConversationOutcome, ConversationError> {
        self.drive_conversation(state, options, ctrl, ModelPhase::Batch, None)
            .await
    }

    /// The streaming twin of [`TurnRunner::run_in_conversation`]
    /// — same consume/return contract and entry gates, delta-driven model
    /// phase. `options.frame` stays deliberately inert here.
    pub async fn run_in_conversation_streaming(
        &self,
        state: ConversationState,
        options: TurnRunOptions,
        ctrl: RunControl,
    ) -> Result<ConversationOutcome, ConversationError> {
        self.drive_conversation(state, options, ctrl, ModelPhase::Stream, None)
            .await
    }

    /// Continue a paused conversation turn. The continuation half of
    /// `run_in_conversation` — same
    /// consume/return contract; the free function
    /// `crate::resume::resume_turn` is the public face: it validates the
    /// complete paused outcome (stamp, open turn, continuation-vs-facts,
    /// decision coverage) and builds the [`ResumeState`] from the
    /// outcome's [`Continuation`].
    pub(crate) async fn resume_conversation(
        &self,
        state: ConversationState,
        options: TurnRunOptions,
        ctrl: RunControl,
        resume: ResumeState,
    ) -> Result<ConversationOutcome, ConversationError> {
        // Resumes continue in batch phase: the facts are complete, and a
        // streaming continuation is future work.
        self.drive_conversation(state, options, ctrl, ModelPhase::Batch, Some(resume))
            .await
    }

    /// Continue a paused bare turn — the
    /// continuation half of [`TurnRunner::run`]/[`TurnRunner::run_streaming`].
    /// Consumes the **complete paused outcome** plus the new
    /// [`ResumeRequest`](crate::resume::ResumeRequest) (decision + inject);
    /// the host no longer assembles reason/trace by hand. Validation runs
    /// before anything executes or any fact changes — a rejected request
    /// returns the untouched paused material in the
    /// [`ResumeRejection`](crate::resume::ResumeRejection). Rounds, quota
    /// counts, prepared hook work, and queued inputs all come from the
    /// outcome's [`Continuation`]: a trimmed or empty trace changes
    /// nothing, and lower limits stop the turn before external execution.
    // Rejection returns the complete paused material by value, matching
    // resume_turn and the Session construction contract.
    #[allow(clippy::result_large_err)]
    pub async fn resume(
        &self,
        outcome: TurnOutcome,
        request: crate::resume::ResumeRequest,
        options: TurnRunOptions,
        ctrl: RunControl,
    ) -> Result<TurnOutcome, crate::resume::ResumeRejection<TurnOutcome>> {
        if let Err(reason) =
            crate::resume::validate_resume(&outcome.result, &outcome.context, &request)
        {
            return Err(crate::resume::ResumeRejection { reason, outcome });
        }
        let TurnResult::Paused { continuation } = outcome.result else {
            unreachable!("validated above");
        };
        let TurnOutcome {
            mut context, trace, ..
        } = outcome;
        let start = Instant::now();
        let (result, mut trace, tool_calls_total) = self
            .drive_from(
                &mut context,
                FrameSource::Turn(&options.frame),
                &options,
                &ctrl,
                ModelPhase::Batch,
                Some(ResumeState {
                    continuation,
                    decision: request.decision,
                    inject: request.inject,
                    trace,
                }),
            )
            .await;
        trace.tool_calls_total = tool_calls_total;
        trace.total_duration_ms = millis_since(start);
        if !matches!(result, TurnResult::Paused { .. }) {
            context.seal();
        }
        Ok(TurnOutcome {
            context,
            result,
            trace,
        })
    }

    /// The conversation entry body — entry gates, merged-frame source,
    /// terminal bookkeeping, and outcome-stamped sealing shared by both
    /// conversation entries and the resume path.
    async fn drive_conversation(
        &self,
        state: ConversationState,
        options: TurnRunOptions,
        ctrl: RunControl,
        phase: ModelPhase,
        resume: Option<ResumeState>,
    ) -> Result<ConversationOutcome, ConversationError> {
        // One `agent.turn` span per entry, ids and scope only — never
        // message content. The span is entered per poll via `Instrument`,
        // so the future stays `Send`.
        let scope = if resume.is_some() {
            "conversation.resume"
        } else if matches!(phase, ModelPhase::Stream) {
            "conversation.streaming"
        } else {
            "conversation"
        };
        let turn_id = state
            .active_turn()
            .map(|t| t.turn_id().0)
            .unwrap_or_default();
        let span = tracing::info_span!(
            "agent.turn",
            turn_id = %turn_id,
            conversation_id = %state.conversation_id().0,
            scope = scope,
        );
        self.drive_conversation_inner(state, options, ctrl, phase, resume)
            .instrument(span)
            .await
    }

    /// The conversation entry body — entry gates, merged-frame source,
    /// terminal bookkeeping, and outcome-stamped sealing shared by both
    /// conversation entries and the resume path.
    async fn drive_conversation_inner(
        &self,
        mut state: ConversationState,
        options: TurnRunOptions,
        ctrl: RunControl,
        phase: ModelPhase,
        resume: Option<ResumeState>,
    ) -> Result<ConversationOutcome, ConversationError> {
        // Entry gates — caller bugs fail fast, before the state machine.
        let active_id = match state.active_turn() {
            Some(t) => t.turn_id(),
            None => return Err(ConversationError::NoActiveTurn),
        };
        if state.active_turn().expect("checked above").is_sealed() {
            return Err(ConversationError::TurnAlreadySealed);
        }
        // A paused turn occupies the slot; fresh-driving it would run the
        // same turn twice. Resume (resume_turn) or abort instead.
        if resume.is_none() && state.sealed_result() == Some(SealedResult::Paused) {
            return Err(ConversationError::TurnAlreadyActive);
        }
        // Field-split borrow: read conversation id and history while driving
        // the active turn mutably; stamping happens after the loop through
        // the public `seal_turn`, so no second &mut seam is exposed.
        let (conversation_id, history, active) = state.runner_parts();
        let active = active.expect("NoActiveTurn checked above");
        let start = Instant::now();
        let (result, mut trace, tool_calls_total) = self
            .drive_from(
                active,
                FrameSource::Conversation {
                    conversation_id,
                    history: &history,
                },
                &options,
                &ctrl,
                phase,
                resume,
            )
            .await;
        trace.tool_calls_total = tool_calls_total;
        trace.total_duration_ms = millis_since(start);
        let stamp = match &result {
            TurnResult::Completed { .. } => SealedResult::Completed,
            TurnResult::Interrupted { .. } => SealedResult::Interrupted,
            TurnResult::Paused { .. } => SealedResult::Paused,
        };
        state
            .seal_turn(active_id, stamp)
            .expect("active turn still present");
        Ok(ConversationOutcome {
            state,
            result,
            trace,
        })
    }

    /// One streaming model attempt: forward every delta to the interaction
    /// seam, then return the `Done` output (falling back to a stream-phase
    /// `Usage` delta when `Done` carries none). An `Error` delta maps to the
    /// same error shape the `invoke` path produces, so the shared retry
    /// loop and trace machinery apply unchanged; a stream that ends
    /// without `Done` is `UnknownOutcome`.
    async fn stream_attempt(
        &self,
        req: &ModelRequest,
        attempt_ctrl: &AttemptControl,
        options: &TurnRunOptions,
        round_id: RoundId,
    ) -> Result<ModelOutput, ModelInvokeError> {
        use futures_util::StreamExt;
        let mut stream = self.gateway.stream(req, attempt_ctrl).await?;
        let mut usage_seen: Option<ModelUsage> = None;
        loop {
            let item = tokio::select! {
                biased;
                _ = attempt_ctrl.cancellation_token().cancelled() => {
                    return Err(ModelInvokeError::new(
                        ModelInvokeErrorKind::Cancelled,
                        "cancelled during stream",
                    ));
                }
                next = stream.next() => match next {
                    Some(item) => item,
                    None => {
                        return Err(ModelInvokeError::new(
                            ModelInvokeErrorKind::UnknownOutcome,
                            "stream ended without Done",
                    ));
                    }
                },
            };
            options.interaction.on_delta(round_id, &item).await;
            match item {
                StreamDelta::Done { final_output, .. } => {
                    let mut out = final_output;
                    if out.usage.is_none() {
                        out.usage = usage_seen;
                    }
                    return Ok(out);
                }
                StreamDelta::Usage(u) => usage_seen = Some(u),
                StreamDelta::Error { kind, message } => {
                    return Err(ModelInvokeError::new(kind, message));
                }
                StreamDelta::TextDelta { .. }
                | StreamDelta::ReasoningDelta { .. }
                | StreamDelta::ToolCallDelta { .. } => {}
            }
        }
    }

    /// The shared state machine — every entry runs this loop; the frame
    /// source, the model phase, and the resume prologue are the only
    /// forks. Every exit is terminal or paused; the entries own
    /// sealing/stamping.
    async fn drive(
        &self,
        active: &mut TurnContext,
        frames: FrameSource<'_>,
        options: &TurnRunOptions,
        ctrl: &RunControl,
        phase: ModelPhase,
    ) -> (TurnResult, TurnTrace, usize) {
        self.drive_from(active, frames, options, ctrl, phase, None)
            .await
    }

    async fn drive_from(
        &self,
        active: &mut TurnContext,
        frames: FrameSource<'_>,
        options: &TurnRunOptions,
        ctrl: &RunControl,
        phase: ModelPhase,
        resume: Option<ResumeState>,
    ) -> (TurnResult, TurnTrace, usize) {
        let mut round: u32;
        let mut tool_calls_total: usize;
        let mut trace: TurnTrace;
        let mut pending_inject: Vec<TextPayload>;
        match resume {
            None => {
                round = 0;
                tool_calls_total = 0;
                trace = TurnTrace::new();
                pending_inject = Vec::new();
            }
            Some(r) => {
                let ResumeState {
                    continuation,
                    decision,
                    inject,
                    trace: resumed_trace,
                } = r;
                let Continuation {
                    pause_point,
                    round: paused_round,
                    accounted_tool_calls,
                    queued_inputs,
                } = continuation;
                round = paused_round;
                tool_calls_total = accounted_tool_calls;
                trace = resumed_trace;
                // Queued inputs land before the request's inject ("queued
                // → injected → pulled"); both commit at the loop top with
                // the `user.steering` label.
                pending_inject = queued_inputs;
                pending_inject.extend(inject);
                // A resumed turn whose control is already spent exits
                // before touching facts.
                if ctrl.should_stop() {
                    let cause = if ctrl.is_cancelled() {
                        TurnInterruption::ExplicitCancellation
                    } else {
                        TurnInterruption::TurnDeadlineExceeded
                    };
                    return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
                }
                // Exhausted limits stop the turn BEFORE external
                // execution: a lowered `max_tool_calls` refuses the
                // withheld batch itself, a lowered `max_model_rounds`
                // refuses the paused round's batch (its results would
                // never reach a model call). Steering pauses re-enter the
                // loop instead, where the boundary checks apply before any
                // model call.
                if tool_calls_total as u64 > options.policy.limits.max_tool_calls as u64 {
                    return (
                        TurnResult::Interrupted {
                            cause: TurnInterruption::MaxToolCalls {
                                limit: options.policy.limits.max_tool_calls,
                            },
                        },
                        trace,
                        tool_calls_total,
                    );
                }
                if matches!(pause_point, PausePoint::AwaitingApproval { .. })
                    && round >= options.policy.limits.max_model_rounds
                {
                    return (
                        TurnResult::Interrupted {
                            cause: TurnInterruption::MaxModelRounds {
                                limit: options.policy.limits.max_model_rounds,
                            },
                        },
                        trace,
                        tool_calls_total,
                    );
                }
                // Approval-resume prologue: execute the paused round's
                // batch. The saved hook rejections stay rejected; the new
                // decision covers the remaining awaiting calls exactly
                // once (validated at the entry, re-checked by `run_batch`).
                // The batch was already counted into `accounted_tool_calls`
                // at emission, so the prologue never re-counts it.
                if let Some(decision) = decision {
                    let PausePoint::AwaitingApproval {
                        prepared,
                        deadline: _,
                    } = pause_point
                    else {
                        unreachable!("entry validation pairs a decision with an approval pause");
                    };
                    // The paused batch is exactly the committed-but-
                    // unanswered tool calls of this turn, in block order —
                    // the model-emitted draft order the results pair into.
                    let draft = unanswered_tool_calls(active);
                    // Checkpoint entries commit verbatim with their fixed
                    // actions; only the awaiting calls are
                    // newly decided. New precomputed rejections use the
                    // host's explicit entries, else resolve through the
                    // current configuration by the batch name.
                    let PreparedApproval {
                        rejected: saved_rejected,
                        unknown_decisions: saved_decisions,
                        ..
                    } = prepared;
                    let mut rejected: Vec<PrecomputedResult> = saved_rejected
                        .into_iter()
                        .map(|result| PrecomputedResult {
                            fixed_policy: saved_decisions
                                .iter()
                                .find(|d| d.call_id == result.call_id)
                                .map(|d| d.policy),
                            result,
                        })
                        .collect();
                    rejected.extend(attach_decisions(
                        decision.rejected,
                        &decision.unknown_decisions,
                    ));
                    if let Err(cause) = self
                        .run_batch(
                            active,
                            &draft,
                            BatchWork::Execute(decision.to_execute),
                            rejected,
                            options,
                            ctrl,
                            round,
                            &mut trace,
                        )
                        .await
                    {
                        return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
                    }
                    round += 1;
                }
            }
        }

        // The first model phase of this drive advertises the host-declared
        // surface (the `TurnInvocation` baseline); every later round
        // boundary re-snapshots the runner's executor, so catalog changes
        // — including ones this turn's own tool calls triggered — reach the
        // next request. Retries within one round reuse that round's
        // snapshot.
        let first_model_round = round;

        loop {
            // Steering: resume-time injections first, then the
            // round-boundary pull. Both append with the `user.steering`
            // source label; the next model round sees them.
            if !pending_inject.is_empty() {
                for text in std::mem::take(&mut pending_inject) {
                    if let Err(e) = active.append_input(text, "user.steering") {
                        return (
                            TurnResult::Interrupted {
                                cause: TurnInterruption::RunnerInvariantViolation {
                                    reason: e.to_string(),
                                },
                            },
                            trace,
                            tool_calls_total,
                        );
                    }
                }
            }
            for text in options.interaction.pending_inputs().await {
                if let Err(e) = active.append_input(text, "user.steering") {
                    return (
                        TurnResult::Interrupted {
                            cause: TurnInterruption::RunnerInvariantViolation {
                                reason: e.to_string(),
                            },
                        },
                        trace,
                        tool_calls_total,
                    );
                }
            }
            // boundary checks
            if ctrl.should_stop() {
                let cause = if ctrl.is_cancelled() {
                    TurnInterruption::ExplicitCancellation
                } else {
                    TurnInterruption::TurnDeadlineExceeded
                };
                return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
            }
            if round >= options.policy.limits.max_model_rounds {
                return (
                    TurnResult::Interrupted {
                        cause: TurnInterruption::MaxModelRounds {
                            limit: options.policy.limits.max_model_rounds,
                        },
                    },
                    trace,
                    tool_calls_total,
                );
            }
            // materialize the round's frame — the single fork point between
            // the entries; the fact machine only ever offers the lossless
            // projection, the policy orchestrates anything beyond it
            let frame = match frames {
                FrameSource::Turn(policy) => {
                    match policy.materialize(active, RoundId(round)).await {
                        Ok(f) => f,
                        Err(e) => {
                            return (
                                TurnResult::Interrupted {
                                    cause: TurnInterruption::CompactionFailed {
                                        reason: e.to_string(),
                                    },
                                },
                                trace,
                                tool_calls_total,
                            );
                        }
                    }
                }
                FrameSource::Conversation {
                    conversation_id,
                    history,
                } => merged_frame(conversation_id, history, active, RoundId(round)),
            };
            let frame_version = match &frame.scope {
                FrameScope::Turn { source_version, .. }
                | FrameScope::Conversation { source_version, .. } => *source_version,
            };
            let invocation = InvocationId {
                turn_id: active.turn_id(),
                round_id: RoundId(round),
            };
            // Per-round tool surface (see `first_model_round` above): the
            // host baseline for the first model phase, a fresh executor
            // snapshot at every later round boundary. Retries inside the
            // attempt loop below reuse the same snapshot, so advertising
            // and dispatch routing stay one decision per round.
            let round_surface = if round == first_model_round {
                options.invocation.tool_surface.clone()
            } else {
                self.executor.tool_surface().await
            };
            // The round span covers the bounded retry loop; spans are
            // entered per poll via `Instrument`, so the future stays `Send`.
            // Fields carry ids and names only — never frame content or
            // arguments.
            let round_span = tracing::debug_span!(
                "agent.round",
                turn_id = %invocation.turn_id.0,
                round_id = round
            );
            let (attempts, output) = async {
                // bounded logical retry: same InvocationId / ContextFrame, attempt+1
                let mut attempt: u32 = 1;
                let mut attempts: Vec<AttemptTrace> = Vec::new();
                let output: Result<ModelOutput, ModelInvokeError> = loop {
                    let attempt_started = Instant::now();
                    let attempt_ctrl = ctrl.for_attempt(options.policy.attempt_timeout);
                    let req = ModelRequest {
                        invocation_id: invocation.clone(),
                        attempt: AttemptNumber(attempt),
                        frame: frame.clone(),
                        model: options.invocation.model.clone(),
                        tool_surface: round_surface.clone(),
                        generation: options.invocation.generation.clone(),
                        cache: options.invocation.cache,
                    };
                    let attempt_span = tracing::debug_span!(
                        "agent.attempt",
                        attempt = attempt,
                        model = %options.invocation.model.0
                    );
                    let result = match phase {
                        ModelPhase::Batch => {
                            self.gateway
                                .invoke(&req, &attempt_ctrl)
                                .instrument(attempt_span)
                                .await
                        }
                        ModelPhase::Stream => {
                            self.stream_attempt(&req, &attempt_ctrl, options, RoundId(round))
                                .instrument(attempt_span)
                                .await
                        }
                    };
                    match result {
                        Ok(out) => {
                            attempts.push(AttemptTrace {
                                attempt: AttemptNumber(attempt),
                                kind: None,
                                is_retryable: false,
                                duration_ms: millis_since(attempt_started),
                            });
                            break Ok(out);
                        }
                        Err(e) => {
                            let retryable = options.policy.retry.allows(&e.kind);
                            attempts.push(AttemptTrace {
                                attempt: AttemptNumber(attempt),
                                kind: Some(e.kind.clone()),
                                is_retryable: retryable,
                                duration_ms: millis_since(attempt_started),
                            });
                            if retryable && attempt <= options.policy.retry.max_retries {
                                // Cancellation- and deadline-aware backoff:
                                // sleep between attempts, racing the shared
                                // token so a cancel lands immediately instead
                                // of after the wait, and capping the wait at
                                // the remaining turn deadline so the driver
                                // never holds the turn hostage in its own
                                // backoff.
                                let delay = options.policy.retry.backoff_delay(attempt + 1);
                                let capped = ctrl
                                    .remaining_turn_time()
                                    .map_or(delay, |remaining| delay.min(remaining));
                                if !capped.is_zero() {
                                    tokio::select! {
                                        biased;
                                        _ = attempt_ctrl.cancellation_token().cancelled() => {
                                            break Err(ModelInvokeError::new(
                                                ModelInvokeErrorKind::Cancelled,
                                                "cancelled during retry backoff",
                                            ));
                                        }
                                        _ = tokio::time::sleep(capped) => {}
                                    }
                                }
                                // Stop guard before spending another attempt:
                                // a cancel or a deadline that landed during the
                                // backoff (or the previous attempt) ends the
                                // loop here. The outer mapping attributes the
                                // turn's end to `TurnDeadlineExceeded` whenever
                                // the deadline has passed, so the terminal
                                // reason matches the round-boundary check.
                                if ctrl.should_stop() {
                                    if ctrl.is_cancelled() {
                                        break Err(ModelInvokeError::new(
                                            ModelInvokeErrorKind::Cancelled,
                                            "cancelled during retry backoff",
                                        ));
                                    }
                                    break Err(ModelInvokeError::new(
                                        ModelInvokeErrorKind::TimedOut,
                                        "turn deadline passed during retry backoff",
                                    ));
                                }
                                attempt += 1;
                                continue;
                            }
                            break Err(e);
                        }
                    }
                };
                (attempts, output)
            }
            .instrument(round_span)
            .await;
            let output = match output {
                Ok(o) => o,
                Err(e) => {
                    let cause = if matches!(e.kind, ModelInvokeErrorKind::Cancelled)
                        && ctrl.is_cancelled()
                    {
                        TurnInterruption::ExplicitCancellation
                    } else if ctrl.should_stop() && !ctrl.is_cancelled() {
                        // The turn deadline passed while the retry loop was
                        // still working — mid-attempt or during backoff — so
                        // the turn ends with the same verdict the
                        // round-boundary check would produce, not with the
                        // last attempt's error kind.
                        TurnInterruption::TurnDeadlineExceeded
                    } else {
                        TurnInterruption::RetryExhausted {
                            last_kind: e.kind.clone(),
                            last_error: e.message.clone(),
                        }
                    };
                    trace.rounds.push(ModelRoundTrace {
                        round_id: RoundId(round),
                        invocation_id: invocation,
                        frame_version,
                        attempts,
                        output_summary: None,
                        applied_block_ids: vec![],
                        tool_batch: None,
                    });
                    return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
                }
            };
            let output_summary = Some(OutputSummary {
                stop_reason: output.stop_reason,
                usage: output.usage.clone(),
                tool_call_count: output.response.tool_calls.len(),
                response_text_bytes: output.response.text.0.len(),
            });
            // Every round lands in the trace exactly once, right after the
            // output is summarized — including the paths that never apply a
            // block. Later stages fill their fields through `last_mut`.
            trace.rounds.push(ModelRoundTrace {
                round_id: RoundId(round),
                invocation_id: invocation.clone(),
                frame_version,
                attempts,
                output_summary,
                applied_block_ids: vec![],
                tool_batch: None,
            });
            // MaxTokens / Refusal never persist blocks; they carry their
            // own dedicated interruption causes, so dispatch before apply.
            // This is driver policy: the canonical append_model_output would
            // happily record them as facts.
            if matches!(
                output.stop_reason,
                ModelStopReason::MaxTokens | ModelStopReason::Refusal
            ) {
                let cause = if matches!(output.stop_reason, ModelStopReason::MaxTokens) {
                    TurnInterruption::ModelMaxTokens
                } else {
                    TurnInterruption::ModelRefusal
                };
                return (TurnResult::Interrupted { cause }, trace, tool_calls_total);
            }
            let applied = match active.append_model_output(
                invocation.clone(),
                &output.response,
                output.stop_reason,
            ) {
                Ok(a) => a,
                Err(e) => {
                    return (
                        TurnResult::Interrupted {
                            cause: TurnInterruption::InvalidModelOutput {
                                reason: e.to_string(),
                            },
                        },
                        trace,
                        tool_calls_total,
                    );
                }
            };
            // The receipt carries the prepared tool calls in model draft
            // order — the same payloads the kernel committed, with ids
            // generated exactly once. No re-reading of blocks.
            let call_payloads: Vec<ToolCallPayload> = applied.tool_calls;
            trace
                .rounds
                .last_mut()
                .expect("round trace just pushed")
                .applied_block_ids = applied.block_ids.clone();
            match output.stop_reason {
                ModelStopReason::EndTurn => {
                    // append_model_output guarantees EndTurn has empty tool_calls
                    return (
                        TurnResult::Completed {
                            final_output: output,
                        },
                        trace,
                        tool_calls_total,
                    );
                }
                ModelStopReason::ToolUse => {
                    // Emitted calls count at dispatch time — including the
                    // batch still pending behind a pause (the resume
                    // therefore must not re-count it).
                    tool_calls_total += call_payloads.len();
                    if tool_calls_total as u32 > options.policy.limits.max_tool_calls {
                        return (
                            TurnResult::Interrupted {
                                cause: TurnInterruption::MaxToolCalls {
                                    limit: options.policy.limits.max_tool_calls,
                                },
                            },
                            trace,
                            tool_calls_total,
                        );
                    }
                    // ToolUse hook: the tool-use filter seam. `TurnRunner::new()`
                    // defaults to `PassthroughHook` (no filter applied — opt in
                    // via `with_hook`). `FilterChain` plugs in via `with_hook`,
                    // implementing `ToolUseHook` directly.
                    let (hook_to_exec, hook_rejected, hook_decisions): (
                        Vec<ToolCallPayload>,
                        Vec<ToolResultPayload>,
                        Vec<UnknownDecision>,
                    ) = {
                        let call_control = ctrl
                            .for_attempt(options.policy.attempt_timeout)
                            .for_call(options.execution.call_timeout);
                        let conversation_id = match &frames {
                            FrameSource::Conversation {
                                conversation_id, ..
                            } => Some(*conversation_id),
                            FrameSource::Turn(_) => None,
                        };
                        let hook_ctx = HookCtx {
                            turn_id: &active.turn_id(),
                            conversation_id,
                            round_id: RoundId(round),
                            control: &call_control,
                        };
                        let outcome = self.hook.apply(call_payloads.clone(), &hook_ctx).await;
                        (
                            outcome.to_execute,
                            outcome.rejected,
                            outcome.unknown_decisions,
                        )
                    };
                    // The second gate — the host's batch decision.
                    // Default `Proceed`; `Pause` suspends the turn with the
                    // model-emitted batch as `pending_calls`, before any
                    // execution or rejection lands in the facts.
                    let decision = options.interaction.decide_batch(&hook_to_exec).await;
                    match decision {
                        BatchDecision::Pause { deadline } => {
                            // The checkpoint saves the hook's prepared work
                            // (admitted-with-rewrites + rejections) so the
                            // resume never re-runs the hook and never
                            // re-admits a rejected call. The outcome's
                            // context is the single fact source — no
                            // duplicated snapshot rides on the variant.
                            // The checkpoint fixes the
                            // actual action for every prepared
                            // UnknownOutcome — the explicit hook entry if
                            // given, else the turn's current configuration
                            // resolved by the batch's tool name. A resume
                            // can never recompute these.
                            let draft_names: HashMap<ToolCallId, String> = call_payloads
                                .iter()
                                .map(|p| (p.call_id.clone(), p.tool_name.clone()))
                                .collect();
                            let unknown_decisions = hook_rejected
                                .iter()
                                .filter(|r| r.status == ToolResultStatus::UnknownOutcome)
                                .map(|r| UnknownDecision {
                                    call_id: r.call_id.clone(),
                                    policy: hook_decisions
                                        .iter()
                                        .find(|d| d.call_id == r.call_id)
                                        .map(|d| d.policy)
                                        .unwrap_or_else(|| {
                                            options.policy.unknown_outcome.resolve(
                                                draft_names
                                                    .get(&r.call_id)
                                                    .map(String::as_str)
                                                    .unwrap_or(""),
                                            )
                                        }),
                                })
                                .collect();
                            return (
                                TurnResult::Paused {
                                    continuation: Continuation {
                                        pause_point: PausePoint::AwaitingApproval {
                                            prepared: PreparedApproval {
                                                awaiting: hook_to_exec,
                                                rejected: hook_rejected,
                                                unknown_decisions,
                                            },
                                            deadline,
                                        },
                                        round,
                                        accounted_tool_calls: tool_calls_total,
                                        queued_inputs: Vec::new(),
                                    },
                                },
                                trace,
                                tool_calls_total,
                            );
                        }
                        BatchDecision::Proceed => {
                            if let Err(cause) = self
                                .run_batch(
                                    active,
                                    &call_payloads,
                                    BatchWork::Execute(hook_to_exec),
                                    attach_decisions(hook_rejected, &hook_decisions),
                                    options,
                                    ctrl,
                                    round,
                                    &mut trace,
                                )
                                .await
                            {
                                return (
                                    TurnResult::Interrupted { cause },
                                    trace,
                                    tool_calls_total,
                                );
                            }
                        }
                        BatchDecision::Rewrite(rewritten) => {
                            if let Err(cause) = self
                                .run_batch(
                                    active,
                                    &call_payloads,
                                    BatchWork::Execute(rewritten),
                                    attach_decisions(hook_rejected, &hook_decisions),
                                    options,
                                    ctrl,
                                    round,
                                    &mut trace,
                                )
                                .await
                            {
                                return (
                                    TurnResult::Interrupted { cause },
                                    trace,
                                    tool_calls_total,
                                );
                            }
                        }
                        BatchDecision::Reject {
                            results,
                            unknown_decisions,
                        } => {
                            if let Err(cause) = self
                                .run_batch(
                                    active,
                                    &call_payloads,
                                    BatchWork::Precomputed(attach_decisions(
                                        results,
                                        &unknown_decisions,
                                    )),
                                    attach_decisions(hook_rejected, &hook_decisions),
                                    options,
                                    ctrl,
                                    round,
                                    &mut trace,
                                )
                                .await
                            {
                                return (
                                    TurnResult::Interrupted { cause },
                                    trace,
                                    tool_calls_total,
                                );
                            }
                        }
                    }
                    round += 1;
                }
                ModelStopReason::MaxTokens | ModelStopReason::Refusal => {
                    unreachable!("handled before append_model_output")
                }
            }
        }
    }

    /// Execute a tool batch and commit its results — the shared core of
    /// the normal ToolUse dispatch and the approval-resume prologue.
    // Private shared core; every parameter is a distinct axis (facts,
    // order, work, policy, control, round, trace) — grouping would only
    // obscure it.
    #[allow(clippy::too_many_arguments)]
    /// `draft_order` is the model-emitted payload order; the canonical
    /// result order follows it (host rewrites and pre-computed rejects
    /// still pair by `call_id`). The batch trace attaches to the round's
    /// trace entry before committing, so even a
    /// `RunnerInvariantViolation` keeps the observations.
    async fn run_batch(
        &self,
        active: &mut TurnContext,
        draft_order: &[ToolCallPayload],
        work: BatchWork,
        mut rejected: Vec<PrecomputedResult>,
        options: &TurnRunOptions,
        ctrl: &RunControl,
        round: u32,
        trace: &mut TurnTrace,
    ) -> Result<(), TurnInterruption> {
        // Batch completeness is runner policy (the kernel's tool door
        // intentionally accepts partial commits): every model-emitted call
        // must be covered exactly once by the work + rejected decision —
        // no silent drops, no duplicates, no foreign ids. Validated BEFORE
        // dispatch so a broken decision cannot spend side effects on calls
        // the facts can never pair.
        let expected: HashSet<ToolCallId> = draft_order.iter().map(|p| p.call_id.clone()).collect();
        let mut covered: HashSet<ToolCallId> = HashSet::new();
        let work_ids: Vec<&ToolCallId> = match &work {
            BatchWork::Execute(payloads) => payloads.iter().map(|p| &p.call_id).collect(),
            BatchWork::Precomputed(pre) => pre.iter().map(|o| &o.result.call_id).collect(),
        };
        for call_id in work_ids
            .into_iter()
            .chain(rejected.iter().map(|o| &o.result.call_id))
        {
            if !expected.contains(call_id) {
                return Err(TurnInterruption::RunnerInvariantViolation {
                    reason: format!(
                        "batch decision covers call {:?} which the model did not emit",
                        call_id.0
                    ),
                });
            }
            if !covered.insert(call_id.clone()) {
                return Err(TurnInterruption::RunnerInvariantViolation {
                    reason: format!("batch decision covers call {:?} more than once", call_id.0),
                });
            }
        }
        if covered.len() != expected.len() {
            let missing: Vec<String> = expected
                .difference(&covered)
                .map(|id| id.0.clone())
                .collect();
            return Err(TurnInterruption::RunnerInvariantViolation {
                reason: format!(
                    "batch decision does not cover every emitted call: missing {missing:?}"
                ),
            });
        }
        // parallel dispatch; completion order comes from the
        // stream (each future is yielded as it finishes), so no
        // shared log is needed
        let (mut results, completion_order, call_durations): (
            Vec<PrecomputedResult>,
            Vec<ToolCallId>,
            HashMap<ToolCallId, u64>,
        ) = match work {
            BatchWork::Execute(to_exec) => {
                let futs = to_exec.into_iter().map(|payload| {
                    let unknown_outcome = options.policy.unknown_outcome.clone();
                    let cc = ctrl
                        .for_attempt(options.policy.attempt_timeout)
                        .for_call(options.execution.call_timeout);
                    let store = options.execution.artifact_store.clone();
                    let tc = options.execution.token_counter.clone();
                    // The effective per-call output limit is
                    // resolved by the ACTUAL executed name (post hook /
                    // rewrite / resume decision) before dispatch; the
                    // executor never consults the tool object.
                    let limits = options
                        .execution
                        .tool_output_limits_overrides
                        .get(&payload.tool_name)
                        .copied()
                        .unwrap_or(options.execution.tool_output_limits);
                    // An executed UnknownOutcome's action
                    // resolves by the executed name, not the draft's.
                    let name = payload.tool_name.clone();
                    let exec = self.executor.clone();
                    async move {
                        let t0 = Instant::now();
                        let result = exec
                            .execute_with_limits(payload, cc, store, tc, limits)
                            .await;
                        let fixed_policy = if result.status == ToolResultStatus::UnknownOutcome {
                            Some(unknown_outcome.resolve(&name))
                        } else {
                            None
                        };
                        (
                            PrecomputedResult {
                                result,
                                fixed_policy,
                            },
                            millis_since(t0),
                        )
                    }
                });
                let mut stream = futures_util::stream::FuturesUnordered::from_iter(futs);
                let mut results = Vec::with_capacity(stream.len());
                let mut completion_order = Vec::with_capacity(stream.len());
                let mut call_durations: HashMap<ToolCallId, u64> = HashMap::new();
                while let Some((pre, duration_ms)) = stream.next().await {
                    completion_order.push(pre.result.call_id.clone());
                    call_durations.insert(pre.result.call_id.clone(), duration_ms);
                    results.push(pre);
                }
                (results, completion_order, call_durations)
            }
            BatchWork::Precomputed(precomputed) => (
                precomputed,
                Vec::new(), // host-supplied: no executor completion order
                HashMap::new(),
            ),
        };
        results.append(&mut rejected);
        // Post-execution identity: every returned outcome must answer one
        // of the batch's own calls — a tool fabricating a foreign id fails
        // loudly here instead of as a kernel pairing error after the fact.
        if let Some(foreign) = results
            .iter()
            .find(|r| !expected.contains(&r.result.call_id))
        {
            return Err(TurnInterruption::RunnerInvariantViolation {
                reason: format!(
                    "tool outcome answers foreign call {:?}",
                    foreign.result.call_id.0
                ),
            });
        }
        // Canonical order = model draft order, taken from the
        // receipt's position — not from ToolCallId encoding. The
        // kernel re-derives the same order from call block
        // sequences when committing.
        let order_index: HashMap<ToolCallId, usize> = draft_order
            .iter()
            .enumerate()
            .map(|(i, p)| (p.call_id.clone(), i))
            .collect();
        results.sort_by_key(|r| order_index.get(&r.result.call_id).copied());
        let tool_names: HashMap<ToolCallId, String> = draft_order
            .iter()
            .map(|p| (p.call_id.clone(), p.tool_name.clone()))
            .collect();
        // Resolve every remaining unknown-outcome action through
        // the turn policy, keyed by the batch's tool name for the call
        // (precomputed entries were never executed, so the batch name is
        // their actual name). Explicit / checkpoint-fixed actions win.
        for pre in &mut results {
            if pre.result.status == ToolResultStatus::UnknownOutcome && pre.fixed_policy.is_none() {
                pre.fixed_policy = Some(
                    options.policy.unknown_outcome.resolve(
                        tool_names
                            .get(&pre.result.call_id)
                            .map(String::as_str)
                            .unwrap_or(""),
                    ),
                );
            }
        }
        // Every UnknownOutcome now carries exactly one resolved action.
        debug_assert!(results.iter().all(|pre| {
            pre.result.status != ToolResultStatus::UnknownOutcome || pre.fixed_policy.is_some()
        }));
        // attach batch trace before committing so even a
        // RunnerInvariantViolation keeps the observations
        if let Some(rt) = trace
            .rounds
            .last_mut()
            .filter(|rt| rt.round_id == RoundId(round))
        {
            rt.tool_batch = Some(ToolBatchTrace {
                calls: results
                    .iter()
                    .map(|pre| ToolCallTrace {
                        call_id: pre.result.call_id.clone(),
                        tool_name: tool_names
                            .get(&pre.result.call_id)
                            .cloned()
                            .unwrap_or_default(),
                        position: order_index
                            .get(&pre.result.call_id)
                            .copied()
                            .unwrap_or_default(),
                        status: pre.result.status.clone(),
                        truncation: pre.result.output.truncation,
                        artifact: pre.result.output.artifact.clone(),
                        duration_ms: call_durations
                            .get(&pre.result.call_id)
                            .copied()
                            .unwrap_or(0),
                    })
                    .collect(),
                completion_order,
            });
        }
        if let Err(e) =
            active.append_tool_results(results.iter().map(|pre| pre.result.clone()).collect())
        {
            return Err(TurnInterruption::RunnerInvariantViolation {
                reason: e.to_string(),
            });
        }
        // UnknownOutcome action: Stop interrupts after the real
        // result is committed, Continue proceeds to the next round — it
        // never re-runs the call, rewrites the result into a success, or
        // cancels sibling calls; parent should_stop is checked at the next
        // loop top.
        if let Some(uu) = results.iter().find(|pre| {
            pre.result.status == ToolResultStatus::UnknownOutcome
                && pre.fixed_policy == Some(UnknownOutcomePolicy::Stop)
        }) {
            return Err(TurnInterruption::UnsafeUnknownOutcome {
                call_id: uu.result.call_id.clone(),
            });
        }
        Ok(())
    }
}