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
//! Driver-stack tests — the execution stack, config axes, executor
//! dispatch, cancellation, and traces. They exercise the runtime wiring,
//! not the kernel contract.

mod common;

use causa_kernel::{
    ArtifactHint, ArtifactKind, ArtifactRef, ArtifactStore, AttemptNumber, BlockContent,
    CallControl, ContextBlock, DynamicToolSource, ModelInvokeErrorKind, ModelOutput, ModelResponse,
    ModelStopReason, ModelUsage, ReasoningPayload, SourceError, StoreError, TextPayload, Tool,
    ToolCallContext, ToolCallId, ToolCallPayload, ToolDefinition, ToolExecutionError, ToolOutput,
    ToolResultPayload, ToolResultStatus, Truncation,
};
use causa_runtime::{
    ExecutionOptions, FramePolicy, HookCtx, HookOutcome, RetryPolicy, RunControl, ToolExecutor,
    ToolOutputLimits, ToolUseHook, TurnInterruption, TurnPolicy, TurnResult, TurnRunOptions,
    TurnRunner, UnknownOutcomeConfig, UnknownOutcomePolicy, WindowBudget,
};
use common::{
    DropAllCompaction, EchoTool, FailTool, RecordingGateway, UnknownStopTool, ctrl, ctx, draft,
    endturn_output, options_with_limits, runner_with, runner_with_dedup, tooluse_calls_output,
    tooluse_output,
};
use serde_json::json;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

#[tokio::test]
async fn final_assistant_completes_once() {
    let c = ctx("t1");
    let runner = runner_with(
        RecordingGateway::scripted(vec![Ok(endturn_output("final"))]),
        vec![],
    );
    let out = runner.run(c, options_with_limits(5, 10), ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    assert_eq!(out.trace.rounds.len(), 1);
    assert_eq!(out.context.blocks().len(), 1);
}

#[tokio::test]
async fn tool_calls_drive_next_frame_and_causality() {
    let c = ctx("t1");
    let runner = runner_with(
        RecordingGateway::scripted(vec![
            Ok(tooluse_output("call echo", "echo", json!({"a":1}))),
            Ok(endturn_output("done")),
        ]),
        vec![Arc::new(EchoTool)],
    );
    let out = runner.run(c, options_with_limits(5, 10), ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    // blocks: assistant tool call + tool result + final assistant (with optional assistant text blocks)
    // Should have at least 3 blocks, causality: tool.result follows tool.call
    let blocks = out.context.blocks();
    let pos_call = blocks
        .iter()
        .position(|b| matches!(b.content, BlockContent::ToolCall(_)))
        .unwrap();
    let pos_result = blocks
        .iter()
        .position(|b| matches!(b.content, BlockContent::ToolResult(_)))
        .unwrap();
    assert!(pos_result > pos_call);
}

#[tokio::test]
async fn retry_same_frame_only_attempt_increments_and_no_block_on_failure() {
    let c = ctx("t1");
    let gw = RecordingGateway::scripted(vec![
        Err(ModelInvokeErrorKind::Transient),
        Ok(endturn_output("ok")),
    ]);
    let runner = runner_with(gw.clone(), vec![]);
    let mut cfg = options_with_limits(5, 10);
    cfg.policy.retry = RetryPolicy {
        max_retries: 1,
        retry_timeouts: false,
        backoff_base_ms: 0,
        backoff_max_ms: 0,
    };
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    // Recorded 2 attempts with same invocation and frame
    let rec = gw.recorded();
    assert_eq!(rec.len(), 2);
    assert_eq!(rec[0].invocation_id, rec[1].invocation_id);
    assert_eq!(rec[0].frame.frame_id, rec[1].frame.frame_id);
    assert_eq!(rec[0].attempt, AttemptNumber(1));
    assert_eq!(rec[1].attempt, AttemptNumber(2));
    // Only one assistant block (no failed attempt block)
    assert_eq!(out.context.blocks().len(), 1);
}

#[tokio::test]
async fn retry_exhaustion_interrupted_and_counts() {
    let c = ctx("t1");
    let gw = RecordingGateway::scripted(vec![
        Err(ModelInvokeErrorKind::Transient),
        Err(ModelInvokeErrorKind::Transient),
    ]);
    let runner = runner_with(gw.clone(), vec![]);
    let mut cfg = options_with_limits(5, 10);
    cfg.policy.retry = RetryPolicy {
        max_retries: 1,
        retry_timeouts: false,
        backoff_base_ms: 0,
        backoff_max_ms: 0,
    };
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(
        out.result,
        TurnResult::Interrupted {
            cause: TurnInterruption::RetryExhausted { .. }
        }
    ));
    let rec = gw.recorded();
    assert_eq!(rec.len(), 2);
}

#[tokio::test]
async fn tool_failure_is_observation_not_terminal_and_next_round() {
    let c = ctx("t1");
    let runner = runner_with(
        RecordingGateway::scripted(vec![
            Ok(tooluse_output("call fail", "fail", json!({}))),
            Ok(endturn_output("done after fail")),
        ]),
        vec![Arc::new(FailTool)],
    );
    let cfg = options_with_limits(5, 10);
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    assert_eq!(out.trace.rounds.len(), 2);
}

#[tokio::test]
async fn dedup_same_batch_rejected_and_parallel_single_failure_not_abort() {
    let c = ctx("t1");
    // Two identical echo calls in same batch => one rejected. This is a
    // test-only dedup hook — TurnRunner::new defaults to passthrough
    // (no opinion); the host composes filters via the framework layer.
    let runner = runner_with_dedup(
        RecordingGateway::scripted(vec![
            Ok(tooluse_calls_output(
                "dup",
                vec![draft("echo", json!({"x":1})), draft("echo", json!({"x":1}))],
            )),
            Ok(endturn_output("done")),
        ]),
        vec![Arc::new(EchoTool)],
    );
    let cfg = options_with_limits(5, 10);
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    // Should have 2 tool calls blocks + 2 results (one rejected) + final assistant?
    // At least check trace shows rejected handling via tool result status
    let last_round = &out.trace.rounds[0];
    assert!(last_round.tool_batch.is_some());
    let batch = last_round.tool_batch.as_ref().unwrap();
    // completion_order should have 1 (only non-rejected executed)
    assert_eq!(batch.completion_order.len(), 1);
    assert_eq!(batch.calls.len(), 2);
}

#[tokio::test]
async fn unknown_outcome_stop_interrupts() {
    let c = ctx("t1");
    let runner = runner_with(
        RecordingGateway::scripted(vec![Ok(tooluse_output("call unk", "unk", json!({})))]),
        vec![Arc::new(UnknownStopTool)],
    );
    let cfg = options_with_limits(5, 10);
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(
        out.result,
        TurnResult::Interrupted {
            cause: TurnInterruption::UnsafeUnknownOutcome { .. }
        }
    ));
}

#[tokio::test]
async fn same_input_same_fake_output_same_snapshot() {
    async fn run_once() -> Vec<ContextBlock> {
        let c = ctx("t1");
        let runner = runner_with(
            RecordingGateway::scripted(vec![
                Ok(tooluse_output("hi", "echo", json!({"k":1}))),
                Ok(endturn_output("bye")),
            ]),
            vec![Arc::new(EchoTool)],
        );
        let out = runner.run(c, options_with_limits(5, 10), ctrl()).await;
        out.context.snapshot_blocks()
    }
    let a = run_once().await;
    let b = run_once().await;
    assert_eq!(
        serde_json::to_string(&a).unwrap(),
        serde_json::to_string(&b).unwrap()
    );
}

#[tokio::test]
async fn token_limits_and_artifact_truncation() {
    struct BigTool;
    #[async_trait::async_trait]
    impl Tool for BigTool {
        fn definition(&self) -> ToolDefinition {
            ToolDefinition {
                name: "big".into(),
                description: "big".into(),
                parameters: json!({"type":"object"}),
            }
        }
        async fn execute(&self, ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
            let big = "a".repeat(1000);
            ToolResultPayload {
                call_id: ctx.call_id.clone(),
                status: ToolResultStatus::Succeeded,
                output: ToolOutput::new(json!(big)),
                media: Vec::new(),
            }
        }
    }
    let c = ctx("t1");
    let gw = RecordingGateway::scripted(vec![
        Ok(tooluse_output("call big", "big", json!({}))),
        Ok(endturn_output("done")),
    ]);
    struct MemStore;
    #[async_trait::async_trait]
    impl ArtifactStore for MemStore {
        async fn persist(
            &self,
            data: &[u8],
            _hint: ArtifactHint,
        ) -> Result<ArtifactRef, StoreError> {
            Ok(ArtifactRef {
                id: blake3::hash(data).to_hex().to_string()[..8].into(),
                size_bytes: data.len(),
                kind: ArtifactKind::FullOutput,
                persisted: true,
            })
        }
        async fn read(
            &self,
            _id: &str,
            _range: Option<std::ops::Range<u64>>,
        ) -> Result<Vec<u8>, StoreError> {
            Ok(vec![])
        }
    }
    let runner = runner_with(gw, vec![Arc::new(BigTool)]);
    let mut cfg = options_with_limits(5, 10);
    cfg.execution.tool_output_limits = ToolOutputLimits { max_tokens: 10 };
    cfg.execution.artifact_store = Some(Arc::new(MemStore));
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    // Find truncated output
    let result_block = out
        .context
        .blocks()
        .iter()
        .find(|b| {
            matches!(&b.content, BlockContent::ToolResult(r) if r.output.truncation == Truncation::Middle)
        })
        .expect("truncated");
    if let BlockContent::ToolResult(r) = &result_block.content {
        assert!(r.output.artifact.is_some());
    } else {
        panic!()
    }
}

#[tokio::test]
async fn parent_cancellation_interrupted() {
    let c = ctx("t1");
    let token = tokio_util::sync::CancellationToken::new();
    token.cancel();
    let gw = RecordingGateway::scripted(vec![Ok(endturn_output("should not"))]);
    let runner = runner_with(gw, vec![]);
    let out = runner
        .run(c, options_with_limits(5, 10), RunControl::new(token, None))
        .await;
    assert!(matches!(
        out.result,
        TurnResult::Interrupted {
            cause: TurnInterruption::ExplicitCancellation
        }
    ));
}

// ---------------------------------------------------------------------------
// Alignment coverage: acceptance gaps + regressions

// max_retries = 0 → initial attempt only

#[tokio::test]
async fn max_retries_zero_does_single_attempt() {
    let c = ctx("t1");
    let gw = RecordingGateway::scripted(vec![Err(ModelInvokeErrorKind::Transient)]);
    let runner = runner_with(gw.clone(), vec![]);
    let mut cfg = options_with_limits(5, 10);
    cfg.policy.retry = RetryPolicy {
        max_retries: 0,
        retry_timeouts: false,
        backoff_base_ms: 0,
        backoff_max_ms: 0,
    };
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(
        out.result,
        TurnResult::Interrupted {
            cause: TurnInterruption::RetryExhausted {
                last_kind: ModelInvokeErrorKind::Transient,
                ..
            }
        }
    ));
    assert_eq!(gw.recorded().len(), 1);
}

// turn deadline exceeded → TurnDeadlineExceeded

#[tokio::test]
async fn turn_deadline_yields_deadline_exceeded() {
    let c = ctx("t1");
    let gw = RecordingGateway::scripted(vec![]);
    let runner = runner_with(gw.clone(), vec![]);
    let cfg = TurnRunOptions::default();
    let ctrl = RunControl::new(
        tokio_util::sync::CancellationToken::new(),
        Some(std::time::Instant::now() - std::time::Duration::from_secs(1)),
    );
    let out = runner.run(c, cfg, ctrl).await;
    assert!(matches!(
        out.result,
        TurnResult::Interrupted {
            cause: TurnInterruption::TurnDeadlineExceeded
        }
    ));
    assert_eq!(gw.recorded().len(), 0);
}

// non-retryable model failure → Interrupted with round trace

#[tokio::test]
async fn non_retryable_error_records_round_trace() {
    let c = ctx("t1");
    let gw = RecordingGateway::scripted(vec![Err(ModelInvokeErrorKind::Permanent)]);
    let runner = runner_with(gw, vec![]);
    let cfg = TurnRunOptions::default();
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(
        out.result,
        TurnResult::Interrupted {
            cause: TurnInterruption::RetryExhausted {
                last_kind: ModelInvokeErrorKind::Permanent,
                ..
            }
        }
    ));
    assert_eq!(out.trace.rounds.len(), 1);
    assert_eq!(out.trace.rounds[0].attempts.len(), 1);
    assert!(!out.trace.rounds[0].attempts[0].is_retryable);
    assert!(out.trace.rounds[0].attempts[0].kind.is_some());
    assert_eq!(out.trace.tool_calls_total, 0);
    assert!(out.context.is_sealed());
}

// cross-batch identical call must not collide

#[tokio::test]
async fn cross_batch_identical_call_does_not_collide() {
    let c = ctx("t1");
    let same_call = || tooluse_output("retry read", "echo", json!({"path": "A"}));
    let gw = RecordingGateway::scripted(vec![
        Ok(same_call()),
        Ok(same_call()),
        Ok(endturn_output("done")),
    ]);
    let runner = runner_with(gw, vec![Arc::new(EchoTool)]);
    let cfg = TurnRunOptions::default();
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(
        matches!(out.result, TurnResult::Completed { .. }),
        "expected completion, got {:?}",
        out.result
    );
    let call_ids: Vec<_> = out
        .context
        .blocks()
        .iter()
        .filter_map(|b| match &b.content {
            BlockContent::ToolCall(tc) => Some(tc.call_id.clone()),
            _ => None,
        })
        .collect();
    assert_eq!(call_ids.len(), 2);
    assert_ne!(call_ids[0], call_ids[1], "round-salted ids must differ");
}

// MaxTokens / Refusal reach their dedicated interruption causes

#[tokio::test]
async fn max_tokens_and_refusal_yield_dedicated_causes_without_blocks() {
    for (stop, expect) in [
        (ModelStopReason::MaxTokens, "max_tokens"),
        (ModelStopReason::Refusal, "refusal"),
    ] {
        let c = ctx("t1");
        let gw = RecordingGateway::scripted(vec![Ok(ModelOutput {
            response: ModelResponse {
                text: TextPayload::new("cut"),
                tool_calls: vec![],
            },
            usage: None,
            stop_reason: stop,
            reasoning: None,
        })]);
        let runner = runner_with(gw, vec![]);
        let cfg = TurnRunOptions::default();
        let out = runner.run(c, cfg, ctrl()).await;
        match (&out.result, expect) {
            (TurnResult::Interrupted { cause }, "max_tokens") => {
                assert!(matches!(cause, TurnInterruption::ModelMaxTokens))
            }
            (TurnResult::Interrupted { cause }, "refusal") => {
                assert!(matches!(cause, TurnInterruption::ModelRefusal))
            }
            _ => panic!("unexpected outcome for {expect}"),
        }
        // MaxTokens/Refusal never persist blocks
        assert_eq!(out.context.blocks().len(), 0);
        assert!(out.context.is_sealed());
        assert_eq!(out.trace.rounds.len(), 1);
        assert!(out.trace.rounds[0].output_summary.is_some());
    }
}

// UnknownOutcomePolicy::Continue → append result and continue

#[tokio::test]
async fn unknown_outcome_continue_continues_turn() {
    struct UnknownContinueTool;
    #[async_trait::async_trait]
    impl Tool for UnknownContinueTool {
        fn definition(&self) -> ToolDefinition {
            ToolDefinition {
                name: "unkc".into(),
                description: "unkc".into(),
                parameters: json!({"type":"object"}),
            }
        }
        async fn execute(&self, ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
            ToolResultPayload {
                call_id: ctx.call_id.clone(),
                status: ToolResultStatus::UnknownOutcome,
                output: ToolOutput::new(json!({"unk": true})),
                media: Vec::new(),
            }
        }
    }
    let c = ctx("t1");
    let gw = RecordingGateway::scripted(vec![
        Ok(tooluse_output("call unkc", "unkc", json!({}))),
        Ok(endturn_output("done")),
    ]);
    let runner = runner_with(gw, vec![Arc::new(UnknownContinueTool)]);
    // The Continue action is host configuration, keyed by the executed
    // tool name — not a tool declaration.
    let mut unknown_outcome = UnknownOutcomeConfig::default();
    unknown_outcome
        .overrides
        .insert("unkc".into(), UnknownOutcomePolicy::Continue);
    let cfg = TurnRunOptions {
        policy: TurnPolicy {
            unknown_outcome,
            ..Default::default()
        },
        ..Default::default()
    };
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    assert!(out.context.blocks().iter().any(
        |b| matches!(&b.content, BlockContent::ToolResult(r) if r.status == ToolResultStatus::UnknownOutcome)
    ));
}

// hung tool: executor call-deadline backstop yields UnknownOutcome;
// Stop policy interrupts the turn.

#[tokio::test]
async fn hung_tool_stop_policy_interrupts_with_unknown_outcome() {
    struct HungTool;
    #[async_trait::async_trait]
    impl Tool for HungTool {
        fn definition(&self) -> ToolDefinition {
            ToolDefinition {
                name: "hung".into(),
                description: "hung".into(),
                parameters: json!({"type":"object"}),
            }
        }
        async fn execute(&self, _ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
            std::future::pending::<()>().await;
            unreachable!()
        }
    }
    let c = ctx("t1");
    let gw = RecordingGateway::scripted(vec![Ok(tooluse_output("call hung", "hung", json!({})))]);
    let runner = runner_with(gw, vec![Arc::new(HungTool)]);
    let cfg = TurnRunOptions {
        execution: ExecutionOptions {
            call_timeout: Some(std::time::Duration::from_millis(50)),
            ..Default::default()
        },
        ..Default::default()
    };
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(
        out.result,
        TurnResult::Interrupted {
            cause: TurnInterruption::UnsafeUnknownOutcome { .. }
        }
    ));
    let batch = out.trace.rounds[0].tool_batch.as_ref().unwrap();
    assert_eq!(batch.calls[0].status, ToolResultStatus::UnknownOutcome);
}

// hung tool with Continue policy → backstop UnknownOutcome is
// committed and the turn proceeds to the next round.

#[tokio::test]
async fn hung_tool_continue_policy_still_completes() {
    struct HungContinueTool;
    #[async_trait::async_trait]
    impl Tool for HungContinueTool {
        fn definition(&self) -> ToolDefinition {
            ToolDefinition {
                name: "hungc".into(),
                description: "hungc".into(),
                parameters: json!({"type":"object"}),
            }
        }
        async fn execute(&self, _ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
            std::future::pending::<()>().await;
            unreachable!()
        }
    }
    let c = ctx("t1");
    let gw = RecordingGateway::scripted(vec![
        Ok(tooluse_output("call hungc", "hungc", json!({}))),
        Ok(endturn_output("done")),
    ]);
    let runner = runner_with(gw, vec![Arc::new(HungContinueTool)]);
    let mut unknown_outcome = UnknownOutcomeConfig::default();
    unknown_outcome
        .overrides
        .insert("hungc".into(), UnknownOutcomePolicy::Continue);
    let cfg = TurnRunOptions {
        policy: TurnPolicy {
            unknown_outcome,
            ..Default::default()
        },
        execution: ExecutionOptions {
            call_timeout: Some(std::time::Duration::from_millis(50)),
            ..Default::default()
        },
        ..Default::default()
    };
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    assert_eq!(out.trace.rounds.len(), 2);
}

// parallel batch: one failing call does not abort the others

#[tokio::test]
async fn parallel_batch_partial_failure_does_not_abort() {
    let c = ctx("t1");
    let gw = RecordingGateway::scripted(vec![
        Ok(tooluse_calls_output(
            "two calls",
            vec![draft("echo", json!({"a": 1})), draft("fail", json!({}))],
        )),
        Ok(endturn_output("done")),
    ]);
    let runner = runner_with(gw, vec![Arc::new(EchoTool), Arc::new(FailTool)]);
    let cfg = TurnRunOptions::default();
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    let statuses: Vec<_> = out
        .context
        .blocks()
        .iter()
        .filter_map(|b| match &b.content {
            BlockContent::ToolResult(r) => Some(r.status.clone()),
            _ => None,
        })
        .collect();
    assert!(statuses.contains(&ToolResultStatus::Succeeded));
    assert!(statuses.contains(&ToolResultStatus::Failed));
}

// completion_order reflects real completion, not submission order

#[tokio::test]
async fn completion_order_reflects_real_completion() {
    struct SlowTool;
    #[async_trait::async_trait]
    impl Tool for SlowTool {
        fn definition(&self) -> ToolDefinition {
            ToolDefinition {
                name: "slow".into(),
                description: "slow".into(),
                parameters: json!({"type":"object"}),
            }
        }
        async fn execute(&self, ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            ToolResultPayload {
                call_id: ctx.call_id.clone(),
                status: ToolResultStatus::Succeeded,
                output: ToolOutput::new(json!("slow")),
                media: Vec::new(),
            }
        }
    }
    let c = ctx("t1");
    // slow is dispatched first (position 0) but completes last
    let gw = RecordingGateway::scripted(vec![
        Ok(tooluse_calls_output(
            "mixed",
            vec![draft("slow", json!({})), draft("echo", json!({}))],
        )),
        Ok(endturn_output("done")),
    ]);
    let runner = runner_with(gw, vec![Arc::new(SlowTool), Arc::new(EchoTool)]);
    let cfg = TurnRunOptions::default();
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    let batch = out.trace.rounds[0].tool_batch.as_ref().unwrap();
    assert_eq!(batch.calls.len(), 2);
    assert_eq!(batch.completion_order.len(), 2);
    // results are committed in original order (slow first)…
    assert_eq!(batch.calls[0].tool_name, "slow");
    assert_eq!(batch.calls[1].tool_name, "echo");
    // …but completion_order starts with the fast echo call
    let fast_id = &batch.calls[1].call_id;
    assert_eq!(&batch.completion_order[0], fast_id);
    assert!(batch.calls[1].duration_ms < batch.calls[0].duration_ms);
}

// append_model_output validation branches

#[tokio::test]
async fn max_tool_calls_interrupt_records_total() {
    let c = ctx("t1");
    let two_calls = tooluse_calls_output(
        "two",
        vec![
            draft("echo", json!({"a": 1})),
            draft("echo", json!({"a": 1})),
        ],
    );
    let gw = RecordingGateway::scripted(vec![Ok(two_calls)]);
    let runner = runner_with(gw, vec![Arc::new(EchoTool)]);
    let cfg = options_with_limits(5, 1);
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(
        out.result,
        TurnResult::Interrupted {
            cause: TurnInterruption::MaxToolCalls { limit: 1 }
        }
    ));
    // raw count (incl. the duplicate) is recorded even on the interrupt path
    assert_eq!(out.trace.tool_calls_total, 2);
    assert_eq!(out.trace.rounds.len(), 1);
    assert!(out.trace.rounds[0].tool_batch.is_none());
}

// ---- frame policy is driver-owned; evaluation stays canonical ----

#[tokio::test]
async fn frame_policy_from_options_shapes_projection_without_touching_facts() {
    let mut c = ctx("t1");
    c.append_input(TextPayload::new("hello"), "user").unwrap();
    // any non-empty content trips the trigger when the host
    // wires a real `TokenCounter` -- an absent counter estimates 0
    // and never trips the budget.
    struct CountPlusOne;
    impl causa_runtime::TokenCounter for CountPlusOne {
        fn estimate(&self, blocks: &[ContextBlock]) -> usize {
            blocks.len() + 100
        }
        fn estimate_value(&self, _value: &serde_json::Value) -> usize {
            1
        }
    }
    let frame_policy = FramePolicy {
        window_budget: WindowBudget {
            model_window_limit: 100,
            compaction_trigger: 1,
        },
        compaction: Some(Arc::new(DropAllCompaction)),
        token_counter: Some(Arc::new(CountPlusOne)),
    };
    let gw = RecordingGateway::scripted(vec![Ok(endturn_output("done"))]);
    let runner = runner_with(gw.clone(), vec![]);
    let cfg = TurnRunOptions {
        frame: frame_policy,
        ..Default::default()
    };
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    // the gateway saw the COMPACTED projection (empty blocks)
    let recorded = gw.recorded();
    assert_eq!(recorded.len(), 1);
    assert!(recorded[0].frame.model_context.blocks.is_empty());
    drop(recorded);
    // the fact state is untouched — compaction is frame-local, never writes
    // back; blocks are still [input text, response text]
    assert_eq!(out.context.blocks().len(), 2);
    assert!(matches!(
        out.context.blocks()[0].content,
        BlockContent::Parts(_)
    ));
}

// ---- artifact failure and loss-free fidelity ----

struct FailingStore;
#[async_trait::async_trait]
impl ArtifactStore for FailingStore {
    async fn persist(&self, _data: &[u8], _hint: ArtifactHint) -> Result<ArtifactRef, StoreError> {
        Err(StoreError::Persist("disk full".into()))
    }
    async fn read(
        &self,
        _id: &str,
        _range: Option<std::ops::Range<u64>>,
    ) -> Result<Vec<u8>, StoreError> {
        Err(StoreError::Read("missing".into()))
    }
}

#[tokio::test]
async fn artifact_store_failure_still_truncates_without_artifact() {
    let c = ctx("t1");
    let big = "x".repeat(400);
    let gw = RecordingGateway::scripted(vec![
        Ok(tooluse_output("big", "echo", json!({"pad": big}))),
        Ok(endturn_output("done")),
    ]);
    let runner = runner_with(gw, vec![Arc::new(EchoTool)]);
    let mut cfg = options_with_limits(5, 10);
    cfg.execution.tool_output_limits = ToolOutputLimits { max_tokens: 10 };
    cfg.execution.artifact_store = Some(Arc::new(FailingStore));
    let out = runner.run(c, cfg, ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    let result_block = out
        .context
        .blocks()
        .iter()
        .find(|b| {
            matches!(
                &b.content,
                BlockContent::ToolResult(r) if r.output.truncation == Truncation::Middle
            )
        })
        .expect("truncated");
    if let BlockContent::ToolResult(r) = &result_block.content {
        // persist failed -> observation degrades to head+tail, no artifact ref
        assert!(r.output.artifact.is_none());
        assert!(r.output.is_truncated());
    } else {
        panic!()
    }
}

// ---- truncation budget -----------------------------------------------------------
//
// The retained head+tail must be sized against the DECLARED limit — notice
// and JSON-string wrapping included — so the committed content re-estimates
// at or under `max_tokens`; a limit smaller than the notice itself leaves
// the notice as the defined floor.

struct RecordingStore;
#[async_trait::async_trait]
impl ArtifactStore for RecordingStore {
    async fn persist(&self, data: &[u8], _hint: ArtifactHint) -> Result<ArtifactRef, StoreError> {
        Ok(ArtifactRef {
            id: blake3::hash(data).to_hex().to_string()[..8].into(),
            size_bytes: data.len(),
            kind: ArtifactKind::FullOutput,
            persisted: true,
        })
    }
    async fn read(
        &self,
        _id: &str,
        _range: Option<std::ops::Range<u64>>,
    ) -> Result<Vec<u8>, StoreError> {
        Ok(vec![])
    }
}

/// Echo a payload straight through the executor under the given output
/// limit; returns the result fact.
async fn truncated_echo(
    arguments: serde_json::Value,
    max_tokens: usize,
    store: Option<Arc<dyn ArtifactStore>>,
) -> ToolResultPayload {
    let executor = ToolExecutor::from_vec(vec![Arc::new(EchoTool)]);
    executor
        .execute_with_limits(
            ToolCallPayload {
                call_id: ToolCallId("probe".into()),
                tool_name: "echo".into(),
                arguments,
            },
            CallControl::new(tokio_util::sync::CancellationToken::new(), None),
            store,
            None,
            ToolOutputLimits { max_tokens },
        )
        .await
}

/// Test mirror of the driver's documented fallback opinion (serialized JSON
/// length / 4, single library home in `defaults`) — used to assert what the
/// `None`-counter fallback would estimate, without reaching into a private
/// module.
fn fallback_estimate(value: &serde_json::Value) -> usize {
    serde_json::to_string(value)
        .map(|s| s.len() / 4)
        .unwrap_or(0)
}

#[tokio::test]
async fn truncation_reduces_output_and_reestimates_within_the_limit() {
    // A 4k-byte observation under a small limit must shrink, not grow;
    // head+tail covering the whole original would grow it.
    let original = json!({"echo": {"text": "a".repeat(4000)}});
    let before = serde_json::to_string(&original).unwrap().len();
    let result = truncated_echo(json!({"text": "a".repeat(4000)}), 100, None).await;
    assert_eq!(result.output.truncation, Truncation::Middle);
    let after = serde_json::to_string(&result.output.content).unwrap().len();
    assert!(
        after < before,
        "truncation grew output: {before} -> {after} bytes"
    );
    assert!(
        fallback_estimate(&result.output.content) <= 100,
        "truncated output re-estimates above the declared limit"
    );
}

#[tokio::test]
async fn truncation_holds_for_utf8_and_artifact_spill() {
    // Multibyte payload: the head/tail cuts must respect char boundaries
    // (no panic), and the budget must hold with the artifact notice too.
    let result = truncated_echo(
        json!({"text": "中文内容".repeat(500)}),
        100,
        Some(Arc::new(RecordingStore)),
    )
    .await;
    assert_eq!(result.output.truncation, Truncation::Middle);
    assert!(result.output.artifact.is_some());
    let text = result
        .output
        .content
        .as_str()
        .expect("truncated content is a JSON string");
    assert!(text.contains("中文"), "kept text is not split mid-char");
    assert!(fallback_estimate(&result.output.content) <= 100);
}

#[tokio::test]
async fn tiny_budget_leaves_the_notice_as_the_floor() {
    // 10 tokens cannot even hold the notice: the defined floor is the
    // notice alone — never the untruncated payload.
    let result = truncated_echo(json!({"text": "a".repeat(4000)}), 10, None).await;
    let text = result.output.content.as_str().unwrap();
    assert!(text.starts_with("\n...[truncated:"));
    assert!(
        !text.contains("aaaa"),
        "tiny budget still leaked the payload: {text}"
    );
}

#[tokio::test]
async fn completed_output_carries_reasoning_and_usage_unchanged() {
    // reasoning signature + rich usage survive the driver losslessly
    let final_output = ModelOutput {
        response: ModelResponse {
            text: TextPayload::new("final"),
            tool_calls: vec![],
        },
        usage: Some(ModelUsage {
            input_tokens: 42,
            output_tokens: 7,
            cache_read_tokens: Some(11),
            cache_write_tokens: Some(3),
            reasoning_tokens: Some(5),
        }),
        stop_reason: ModelStopReason::EndTurn,
        reasoning: Some(ReasoningPayload {
            text: "thinking".into(),
            signature: Some("sig-xyz".into()),
        }),
    };
    let gw = RecordingGateway::scripted(vec![Ok(final_output.clone())]);
    let runner = runner_with(gw, vec![]);
    let cfg = TurnRunOptions::default();
    let out = runner.run(ctx("t1"), cfg, ctrl()).await;
    let completed = match out.result {
        TurnResult::Completed { final_output } => final_output,
        other => panic!("expected completion, got {other:?}"),
    };
    assert_eq!(
        serde_json::to_string(&completed).unwrap(),
        serde_json::to_string(&final_output).unwrap()
    );
}

#[tokio::test]
async fn hook_that_drops_a_call_interrupts_as_invariant_violation() {
    // Batch completeness is runner policy in the normal dispatch path too:
    // a hook that silently drops a call (neither executes nor rejects it)
    // would leave the committed call block unanswered forever.
    struct DropEverything;
    #[async_trait::async_trait]
    impl ToolUseHook for DropEverything {
        async fn apply(&self, _calls: Vec<ToolCallPayload>, _ctx: &HookCtx<'_>) -> HookOutcome {
            HookOutcome {
                to_execute: vec![],
                rejected: vec![],
                unknown_decisions: Vec::new(),
            }
        }
    }
    let gateway = RecordingGateway::scripted(vec![
        Ok(tooluse_output("call echo", "echo", json!({"a": 1}))),
        Ok(endturn_output("done")),
    ]);
    let runner = TurnRunner::with_hook(
        gateway,
        Arc::new(ToolExecutor::from_vec(vec![Arc::new(EchoTool)])),
        Arc::new(DropEverything),
    );
    let out = runner
        .run(ctx("t1"), options_with_limits(5, 10), ctrl())
        .await;
    assert!(matches!(
        out.result,
        TurnResult::Interrupted {
            cause: TurnInterruption::RunnerInvariantViolation { .. }
        }
    ));
    assert!(
        !out.context
            .blocks()
            .iter()
            .any(|b| matches!(b.content, BlockContent::ToolResult(_))),
        "the dropped call must not produce a result"
    );
}

// ---- per-round tool-surface refresh ------------------------------------------------

#[tokio::test]
async fn dynamic_catalog_refreshes_between_model_rounds() {
    // A dynamic source whose listing changes when one of its tools runs
    // must reach the NEXT round's model request through the driver — the
    // run-start snapshot alone is not the catalog.
    struct Catalog {
        version: AtomicU64,
    }
    #[async_trait::async_trait]
    impl DynamicToolSource for Catalog {
        fn id(&self) -> &str {
            "catalog"
        }
        fn version(&self) -> u64 {
            self.version.load(Ordering::SeqCst)
        }
        async fn list(&self) -> Result<Vec<ToolDefinition>, SourceError> {
            Ok(vec![ToolDefinition {
                name: format!("tool_v{}", self.version()),
                description: String::new(),
                parameters: json!({"type": "object"}),
            }])
        }
        async fn invoke(
            &self,
            call: &ToolCallPayload,
            _control: &CallControl,
        ) -> Result<ToolResultPayload, ToolExecutionError> {
            self.version.store(1, Ordering::SeqCst);
            Ok(ToolResultPayload {
                call_id: call.call_id.clone(),
                status: ToolResultStatus::Succeeded,
                output: ToolOutput::new(json!("updated")),
                media: Vec::new(),
            })
        }
    }
    let source = Arc::new(Catalog {
        version: AtomicU64::new(0),
    });
    let executor = Arc::new(ToolExecutor::from_vec(vec![]));
    executor.register_dynamic(source).unwrap();
    let mut options = options_with_limits(5, 10);
    options.invocation.tool_surface = executor.tool_surface().await;
    let gateway = RecordingGateway::scripted(vec![
        Ok(tooluse_output("", "tool_v0", json!({}))),
        Ok(endturn_output("done")),
    ]);
    let runner = TurnRunner::new(gateway.clone(), executor);
    let out = runner.run(ctx("catalog"), options, ctrl()).await;
    assert!(matches!(out.result, TurnResult::Completed { .. }));
    let recorded = gateway.recorded();
    assert_eq!(recorded[0].tool_surface.definitions[0].name, "tool_v0");
    assert_eq!(
        recorded[1].tool_surface.definitions[0].name, "tool_v1",
        "second round ran on a stale catalog"
    );
}

#[tokio::test]
async fn truncation_never_touches_result_media_references() {
    // media travels beside the output content; the textual truncator
    // shrinks the content and must leave the references alone.
    struct ImagingTool;
    #[async_trait::async_trait]
    impl Tool for ImagingTool {
        fn definition(&self) -> ToolDefinition {
            ToolDefinition {
                name: "imaging".into(),
                description: "imaging".into(),
                parameters: json!({"type": "object"}),
            }
        }
        async fn execute(&self, ctx: &ToolCallContext, _c: &CallControl) -> ToolResultPayload {
            ToolResultPayload {
                call_id: ctx.call_id.clone(),
                status: ToolResultStatus::Succeeded,
                output: ToolOutput::new(json!({"chart": "x".repeat(4000)})),
                media: vec![causa_kernel::MediaRef::new("image/png", "asset-1")],
            }
        }
    }
    let executor = ToolExecutor::from_vec(vec![Arc::new(ImagingTool)]);
    let outcome = executor
        .execute_with_limits(
            ToolCallPayload {
                call_id: ToolCallId("probe".into()),
                tool_name: "imaging".into(),
                arguments: json!({}),
            },
            CallControl::new(tokio_util::sync::CancellationToken::new(), None),
            None,
            None,
            ToolOutputLimits { max_tokens: 50 },
        )
        .await;
    assert_eq!(outcome.output.truncation, Truncation::Middle);
    assert!(
        outcome.output.content.to_string().len() < 4000,
        "content must shrink"
    );
    assert_eq!(
        outcome.media,
        vec![causa_kernel::MediaRef::new("image/png", "asset-1")],
        "media references survive truncation untouched"
    );
}