supercode-core 0.2.1

A lightweight, fully-customizable AI coding agent SDK in Rust. Talks to any model via OpenRouter or any OpenAI-compatible endpoint.
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
//! Drive the agent loop with a mock provider — no network — to prove the
//! tool-execution cycle and session continuation work end to end.

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

use async_trait::async_trait;
use supercode::session::Session;
use supercode::sidecar::SidecarWriter;
use supercode::{
    Agent, ChatMessage, ChatRequest, Config, FunctionCall, Provider, Role, ToolCall, Usage,
};

/// First turn: ask for a `list_dir` tool call. Second turn: answer with text
/// that echoes back what the tool returned (so we can assert the tool actually
/// ran and its output was fed back into context).
struct ScriptedProvider {
    calls: AtomicUsize,
}

#[async_trait]
impl Provider for ScriptedProvider {
    async fn complete(
        &self,
        req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode::Result<(ChatMessage, Usage)> {
        let n = self.calls.fetch_add(1, Ordering::SeqCst);
        if n == 0 {
            // The tool list must have been advertised.
            assert!(req.tools.iter().any(|t| t.name == "list_dir"));
            let call = ChatMessage {
                role: Role::Assistant,
                content: None,
                content_parts: None,
                tool_calls: Some(vec![ToolCall {
                    id: "call_1".into(),
                    kind: "function".into(),
                    function: FunctionCall {
                        name: "list_dir".into(),
                        arguments: "{}".into(),
                    },
                }]),
                tool_call_id: None,
                name: None,
                metadata: Default::default(),
            };
            Ok((call, Usage::default()))
        } else {
            // The previous message must be the tool result we fed back.
            let last = req.messages.last().unwrap();
            assert_eq!(last.role, Role::Tool);
            let listing = last.content.clone().unwrap_or_default();
            Ok((
                ChatMessage::assistant(format!("saw: {listing}")),
                Usage::default(),
            ))
        }
    }
}

fn temp_dir(tag: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("supercode-{tag}-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

#[tokio::test]
async fn agent_runs_a_tool_then_answers() {
    let dir = temp_dir("agentloop");
    std::fs::write(dir.join("marker.txt"), "hi").unwrap();

    let config = Config::builder().cwd(dir.clone()).build();
    let provider = Box::new(ScriptedProvider {
        calls: AtomicUsize::new(0),
    });
    let mut agent = Agent::with_provider(config, provider);

    let reply = agent.send("what files are here?").await.unwrap();

    // The final answer reflects the tool output, proving the loop ran the tool
    // and fed the result back to the model.
    assert!(reply.contains("marker.txt"), "reply was: {reply}");

    // History shape: system, user, assistant(tool_call), tool, assistant.
    let roles: Vec<Role> = agent.history().iter().map(|m| m.role).collect();
    assert_eq!(
        roles,
        vec![
            Role::System,
            Role::User,
            Role::Assistant,
            Role::Tool,
            Role::Assistant,
        ]
    );

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn disabled_tools_are_not_advertised() {
    use std::sync::{Arc, Mutex};

    let dir = temp_dir("disabled");
    let config = Config::builder()
        .cwd(dir.clone())
        .disable_tool("bash")
        .tool_description("read_file", "Custom read description")
        .build();

    // A provider that records the tool set it was offered into shared handles.
    struct Recorder {
        names: Arc<Mutex<Vec<String>>>,
        read_desc: Arc<Mutex<String>>,
    }
    #[async_trait]
    impl Provider for Recorder {
        async fn complete(
            &self,
            req: &ChatRequest,
            _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
        ) -> supercode::Result<(ChatMessage, Usage)> {
            *self.names.lock().unwrap() = req.tools.iter().map(|t| t.name.clone()).collect();
            for t in &req.tools {
                if t.name == "read_file" {
                    *self.read_desc.lock().unwrap() = t.description.clone();
                }
            }
            Ok((ChatMessage::assistant("ok"), Usage::default()))
        }
    }

    let names = Arc::new(Mutex::new(Vec::new()));
    let read_desc = Arc::new(Mutex::new(String::new()));
    let provider = Box::new(Recorder {
        names: names.clone(),
        read_desc: read_desc.clone(),
    });
    let mut agent = Agent::with_provider(config, provider);
    agent.send("hi").await.unwrap();

    let offered = names.lock().unwrap().clone();
    assert!(
        !offered.contains(&"bash".to_string()),
        "bash should be disabled"
    );
    assert!(offered.contains(&"read_file".to_string()));
    assert_eq!(
        read_desc.lock().unwrap().as_str(),
        "Custom read description"
    );

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn load_session_seeds_history_for_continuation() {
    let fixture =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/codex_session.jsonl");
    let session = Session::load(&fixture).unwrap();
    let loaded = session.messages.len();

    let config = Config::builder().build();
    let provider = Box::new(ScriptedProvider {
        calls: AtomicUsize::new(1), // skip straight to a text answer
    });
    let mut agent = Agent::with_provider(config, provider);
    agent.load_session(session);

    // System prompt + every loaded message.
    assert_eq!(agent.history().len(), 1 + loaded);
    assert_eq!(agent.history()[0].role, Role::System);
}

#[tokio::test]
async fn continued_assistant_persists_actual_generating_model() {
    let dir = temp_dir("assistant-model-provenance");
    let sidecar_path = dir.join("continued.sidecar.jsonl");
    let source = Session::from_claude_code_str(concat!(
        r#"{"type":"user","uuid":"source-user","parentUuid":null,"sessionId":"source","cwd":"/work","timestamp":"2026-07-19T20:00:00.000Z","message":{"role":"user","content":"source question"}}"#,
        "\n",
        r#"{"type":"assistant","uuid":"source-assistant","parentUuid":"source-user","sessionId":"source","cwd":"/work","timestamp":"2026-07-19T20:00:01.000Z","message":{"role":"assistant","model":"claude-source-model","content":[{"type":"text","text":"source answer"}]}}"#,
        "\n",
    ))
    .unwrap();
    let recorder = SidecarWriter::create(&sidecar_path, &source).unwrap();
    let config = Config::builder().model("z-ai/glm-5.2").build();
    let mut agent = Agent::with_provider(config, Box::new(SaysProvider("continued answer".into())));
    agent.load_session(source);
    agent.set_recorder(recorder);

    agent.send("continue through GLM").await.unwrap();
    let assistant = agent.history().last().unwrap();
    assert_eq!(assistant.role, Role::Assistant);
    assert_eq!(
        assistant.metadata.get("model").map(String::as_str),
        Some("z-ai/glm-5.2")
    );
    drop(agent);

    let persisted = std::fs::read_to_string(&sidecar_path).unwrap();
    let reloaded = Session::from_sidecar_str(&persisted).unwrap();
    let assistant = reloaded.messages.last().unwrap();
    assert_eq!(
        assistant.metadata.get("model").map(String::as_str),
        Some("z-ai/glm-5.2")
    );
    let exported = reloaded
        .to_jsonl_spliced(supercode::session::SessionFormat::ClaudeCode, None)
        .unwrap();
    let last: serde_json::Value = serde_json::from_str(exported.lines().last().unwrap()).unwrap();
    assert_eq!(last["message"]["model"], "z-ai/glm-5.2");
    assert_ne!(
        last["uuid"].as_str().unwrap(),
        "00000000-0000-4000-8000-000000000002"
    );

    std::fs::remove_dir_all(&dir).ok();
}

/// Provider that always asks for a `bash` tool call once, then answers.
struct BashOnce {
    calls: AtomicUsize,
}
#[async_trait]
impl Provider for BashOnce {
    async fn complete(
        &self,
        req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode::Result<(ChatMessage, Usage)> {
        let n = self.calls.fetch_add(1, Ordering::SeqCst);
        if n == 0 {
            let call = ChatMessage {
                role: Role::Assistant,
                content: None,
                content_parts: None,
                tool_calls: Some(vec![ToolCall {
                    id: "c1".into(),
                    kind: "function".into(),
                    function: FunctionCall {
                        name: "bash".into(),
                        arguments: "{\"command\":\"echo ran\"}".into(),
                    },
                }]),
                tool_call_id: None,
                name: None,
                metadata: Default::default(),
            };
            Ok((call, Usage::default()))
        } else {
            // Echo what the tool returned so the test can see if it executed.
            let last = req.messages.last().unwrap();
            Ok((
                ChatMessage::assistant(last.content.clone().unwrap_or_default()),
                Usage::default(),
            ))
        }
    }
}

#[tokio::test]
async fn approval_denied_blocks_tool_execution() {
    use supercode::ApprovalPolicy;
    let dir = temp_dir("approval");
    // Untrusted policy + a handler that denies everything.
    let config = Config::builder()
        .cwd(dir.clone())
        .approval(ApprovalPolicy::Untrusted)
        .approval_handler(Box::new(|_call| false))
        .build();
    let mut agent = Agent::with_provider(
        config,
        Box::new(BashOnce {
            calls: AtomicUsize::new(0),
        }),
    );
    let reply = agent.send("run it").await.unwrap();
    // The tool did NOT run; the model saw a "not approved" result.
    assert!(reply.contains("not approved"), "reply: {reply}");
    assert!(
        !reply.contains("ran"),
        "tool must not have executed: {reply}"
    );
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn approval_handler_allows_and_allowlist_skips() {
    use std::sync::{Arc, Mutex};
    use supercode::ApprovalPolicy;
    let dir = temp_dir("approval2");

    // OnRequest + bash on the allowlist => handler is never consulted, tool runs.
    let consulted = Arc::new(Mutex::new(0usize));
    let c2 = consulted.clone();
    let config = Config::builder()
        .cwd(dir.clone())
        .approval(ApprovalPolicy::OnRequest)
        .auto_approve_tool("bash")
        .approval_handler(Box::new(move |_| {
            *c2.lock().unwrap() += 1;
            true
        }))
        .build();
    let mut agent = Agent::with_provider(
        config,
        Box::new(BashOnce {
            calls: AtomicUsize::new(0),
        }),
    );
    let reply = agent.send("run it").await.unwrap();
    assert!(
        reply.contains("ran"),
        "allowlisted tool should run: {reply}"
    );
    assert_eq!(
        *consulted.lock().unwrap(),
        0,
        "handler must not be consulted for allowlisted tool"
    );
    std::fs::remove_dir_all(&dir).ok();
}

/// Always asks for a tool call (never stops on its own), reporting output tokens.
struct AlwaysToolCall {
    calls: AtomicUsize,
}
#[async_trait]
impl Provider for AlwaysToolCall {
    async fn complete(
        &self,
        _req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode::Result<(ChatMessage, Usage)> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        let msg = ChatMessage {
            role: Role::Assistant,
            content: None,
            content_parts: None,
            tool_calls: Some(vec![ToolCall {
                id: "c".into(),
                kind: "function".into(),
                function: FunctionCall {
                    name: "list_dir".into(),
                    arguments: "{}".into(),
                },
            }]),
            tool_call_id: None,
            name: None,
            metadata: Default::default(),
        };
        let usage = Usage {
            prompt_tokens: 0,
            completion_tokens: 100,
            total_tokens: 100,
            ..Default::default()
        };
        Ok((msg, usage))
    }
}

#[tokio::test]
async fn output_token_budget_stops_the_loop() {
    let dir = temp_dir("budget");
    // Budget of 50 output tokens; each turn reports 100 → loop stops after turn 1
    // instead of running to max_iterations (which would be 25 calls).
    let config = Config::builder()
        .cwd(dir.clone())
        .max_iterations(25)
        .max_total_output_tokens(50)
        .build();
    let provider = std::sync::Arc::new(AlwaysToolCall {
        calls: AtomicUsize::new(0),
    });
    // Re-expose call count via a thin wrapper.
    struct Shared(std::sync::Arc<AlwaysToolCall>);
    #[async_trait]
    impl Provider for Shared {
        async fn complete(
            &self,
            req: &ChatRequest,
            d: &(dyn for<'a> Fn(&'a str) + Send + Sync),
        ) -> supercode::Result<(ChatMessage, Usage)> {
            self.0.complete(req, d).await
        }
    }
    let mut agent = Agent::with_provider(config, Box::new(Shared(provider.clone())));
    let res = agent.send("go").await;
    assert!(
        res.is_ok(),
        "budget should stop cleanly, not error: {res:?}"
    );
    assert_eq!(
        provider.calls.load(Ordering::SeqCst),
        1,
        "budget must stop after one model turn"
    );
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn auto_loads_project_context_files() {
    let dir = temp_dir("ctx");
    std::fs::write(dir.join("CLAUDE.md"), "PROJECT_RULE: always be terse").unwrap();
    let extra = temp_dir("ctx-extra");
    std::fs::write(extra.join("AGENTS.md"), "EXTRA_ROOT_NOTE here").unwrap();

    let config = Config::builder()
        .cwd(dir.clone())
        .add_dir(extra.clone())
        .project_context(true)
        .system_prompt("BASE PROMPT")
        .build();
    let agent = Agent::with_provider(
        config,
        Box::new(ScriptedProvider {
            calls: AtomicUsize::new(1),
        }),
    );
    let sys = agent.history()[0].content.clone().unwrap_or_default();
    assert!(sys.contains("BASE PROMPT"));
    assert!(
        sys.contains("PROJECT_RULE: always be terse"),
        "CLAUDE.md not loaded: {sys}"
    );
    assert!(
        sys.contains("EXTRA_ROOT_NOTE here"),
        "extra-root AGENTS.md not loaded: {sys}"
    );

    // Disabled by default: no context files loaded.
    let config = Config::builder()
        .cwd(dir.clone())
        .system_prompt("BASE")
        .build();
    let agent = Agent::with_provider(
        config,
        Box::new(ScriptedProvider {
            calls: AtomicUsize::new(1),
        }),
    );
    assert!(!agent.history()[0]
        .content
        .clone()
        .unwrap_or_default()
        .contains("PROJECT_RULE"));

    std::fs::remove_dir_all(&dir).ok();
    std::fs::remove_dir_all(&extra).ok();
}

#[tokio::test]
async fn transcript_persistence_and_checkpoint_rewind() {
    let dir = temp_dir("persist");
    std::fs::write(dir.join("marker.txt"), "hi").unwrap();
    let config = Config::builder().cwd(dir.clone()).build();
    let mut agent = Agent::with_provider(
        config,
        Box::new(ScriptedProvider {
            calls: AtomicUsize::new(0),
        }),
    );

    let cp = agent.checkpoint(); // before any turn (just the system msg)
    let reply = agent.send("what files?").await.unwrap();
    assert!(reply.contains("marker.txt"));
    let grown = agent.history().len();
    assert!(grown > cp);

    // Persist + reload into a fresh agent → identical history.
    let path = dir.join("session.jsonl");
    agent.save_transcript(&path).unwrap();
    let config2 = Config::builder().cwd(dir.clone()).build();
    let mut agent2 = Agent::with_provider(
        config2,
        Box::new(ScriptedProvider {
            calls: AtomicUsize::new(1),
        }),
    );
    agent2.load_transcript(&path).unwrap();
    assert_eq!(agent2.history().len(), grown);
    assert_eq!(
        agent2.history()[0].content,
        agent.history()[0].content,
        "system message preserved across save/load"
    );

    // Rewind discards everything after the checkpoint.
    agent.rewind_to(cp);
    assert_eq!(agent.history().len(), cp);

    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn session_store_lifecycle() {
    use supercode::SessionStore;
    let dir = temp_dir("store");
    let store = SessionStore::open(&dir).unwrap();

    store
        .save("s1", "First session", "{\"role\":\"user\"}\n")
        .unwrap();
    store.save("s2", "Second", "{\"role\":\"user\"}\n").unwrap();
    let names: Vec<String> = store.list().into_iter().map(|i| i.name).collect();
    assert_eq!(names, vec!["s1", "s2"]);
    assert_eq!(
        store.list().iter().find(|i| i.name == "s1").unwrap().title,
        "First session"
    );

    // Title rename.
    store.set_title("s1", "Renamed").unwrap();
    assert_eq!(
        store.list().iter().find(|i| i.name == "s1").unwrap().title,
        "Renamed"
    );

    // Archive moves it but keeps it listed as archived + still loadable.
    store.archive("s1").unwrap();
    let s1 = store.list().into_iter().find(|i| i.name == "s1").unwrap();
    assert!(s1.archived);
    assert!(store.load("s1").unwrap().contains("user"));

    // Delete removes it entirely.
    store.delete("s2").unwrap();
    assert!(!store.list().iter().any(|i| i.name == "s2"));

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn pre_and_post_tool_hooks() {
    use std::sync::{Arc, Mutex};
    let dir = temp_dir("hooks");
    std::fs::write(dir.join("marker.txt"), "hi").unwrap();

    // post-hook records every (tool, is_error); pre-hook blocks "bash".
    let log = Arc::new(Mutex::new(Vec::<String>::new()));
    let l2 = log.clone();
    let config = Config::builder()
        .cwd(dir.clone())
        .pre_tool_hook(Box::new(|name, _args| {
            if name == "bash" {
                Some("bash disabled by hook".into())
            } else {
                None
            }
        }))
        .post_tool_hook(Box::new(move |name, _out, is_err| {
            l2.lock().unwrap().push(format!("{name}:{is_err}"));
        }))
        .build();
    // ScriptedProvider calls list_dir (allowed) then answers.
    let mut agent = Agent::with_provider(
        config,
        Box::new(ScriptedProvider {
            calls: AtomicUsize::new(0),
        }),
    );
    let reply = agent.send("list").await.unwrap();
    assert!(reply.contains("marker.txt"));
    // post-hook saw the list_dir call (not an error).
    assert!(
        log.lock().unwrap().iter().any(|e| e == "list_dir:false"),
        "{:?}",
        log.lock().unwrap()
    );

    // Now prove the pre-hook blocks bash via BashOnce.
    let log2 = Arc::new(Mutex::new(Vec::<String>::new()));
    let l3 = log2.clone();
    let config = Config::builder()
        .cwd(dir.clone())
        .pre_tool_hook(Box::new(|name, _| {
            if name == "bash" {
                Some("nope".into())
            } else {
                None
            }
        }))
        .post_tool_hook(Box::new(move |n, _, e| {
            l3.lock().unwrap().push(format!("{n}:{e}"))
        }))
        .build();
    let mut agent = Agent::with_provider(
        config,
        Box::new(BashOnce {
            calls: AtomicUsize::new(0),
        }),
    );
    let reply = agent.send("run").await.unwrap();
    assert!(reply.contains("blocked by pre-tool hook"), "{reply}");
    // post-hook should NOT have fired for the blocked bash (it never executed).
    assert!(!log2.lock().unwrap().iter().any(|e| e.starts_with("bash:")));

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn slash_prompt_expansion_and_compaction() {
    let dir = temp_dir("prompts");
    // Custom prompt + built-in code-review.
    let config = Config::builder()
        .cwd(dir.clone())
        .prompt("greet", "Say hello to {args} politely.")
        .build();
    let agent = Agent::with_provider(
        config,
        Box::new(ScriptedProvider {
            calls: AtomicUsize::new(1),
        }),
    );
    assert_eq!(
        agent.expand_prompt("/greet Alice"),
        "Say hello to Alice politely."
    );
    assert!(agent
        .expand_prompt("/code-review the auth module")
        .contains("correctness bugs"));
    assert!(agent
        .expand_prompt("/code-review the auth module")
        .contains("the auth module"));
    assert_eq!(agent.expand_prompt("plain message"), "plain message"); // non-slash untouched
    assert_eq!(agent.expand_prompt("/unknown x"), "/unknown x"); // unknown command untouched

    // Compaction: build a long history via a saved transcript, then compact.
    let mut lines = String::new();
    lines.push_str(&serde_json::to_string(&supercode::ChatMessage::system("SYS")).unwrap());
    lines.push('\n');
    for i in 0..10 {
        lines.push_str(
            &serde_json::to_string(&supercode::ChatMessage::user(format!("msg {i}"))).unwrap(),
        );
        lines.push('\n');
    }
    let tpath = dir.join("hist.jsonl");
    std::fs::write(&tpath, lines).unwrap();
    let config = Config::builder()
        .cwd(dir.clone())
        .compact_after_messages(6)
        .build();
    let mut agent = Agent::with_provider(
        config,
        Box::new(ScriptedProvider {
            calls: AtomicUsize::new(1),
        }),
    );
    agent.load_transcript(&tpath).unwrap();
    let before = agent.history().len();
    let compacted = agent.maybe_compact();
    assert!(
        compacted,
        "should compact when over threshold (had {before})"
    );
    assert!(agent.history().len() < before);
    assert_eq!(agent.history()[0].role, supercode::Role::System); // system preserved
    assert!(agent.history()[1]
        .content
        .as_deref()
        .unwrap_or("")
        .contains("compacted"));
    // Most recent message retained.
    assert!(agent
        .history()
        .last()
        .unwrap()
        .content
        .as_deref()
        .unwrap_or("")
        .contains("msg 9"));
    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn config_profiles_from_file_and_output_format() {
    use supercode::Config;
    let dir = temp_dir("profiles");
    let cfg = r#"{ "profiles": {
        "fast": {"model": "openai/gpt-5", "effort": "low", "sandbox": "read_only", "approval": "untrusted"},
        "careful": {"model": "anthropic/claude-opus-4-8", "effort": "high", "project_context": true}
    }}"#;
    let path = dir.join("supercode.json");
    std::fs::write(&path, cfg).unwrap();

    let fast = Config::from_profile_file(&path, "fast").unwrap().build();
    assert_eq!(fast.model, "openai/gpt-5");
    assert_eq!(fast.effort.as_deref(), Some("low"));
    assert_eq!(fast.sandbox, supercode::SandboxPolicy::ReadOnly);
    assert_eq!(fast.approval, supercode::ApprovalPolicy::Untrusted);

    let careful = Config::from_profile_file(&path, "careful").unwrap().build();
    assert_eq!(careful.model, "anthropic/claude-opus-4-8");
    assert!(careful.load_project_context);
    // Unset fields keep their defaults.
    assert_eq!(careful.sandbox, supercode::SandboxPolicy::DangerFullAccess);

    assert!(Config::from_profile_file(&path, "missing").is_err());

    // Output formatting.
    assert_eq!(supercode::format_reply("hi", false), "hi");
    assert_eq!(supercode::format_reply("hi", true), "{\"result\":\"hi\"}");

    std::fs::remove_dir_all(&dir).ok();
}

/// A trivial provider that just answers with fixed text (no tools).
struct SaysProvider(String);
#[async_trait]
impl Provider for SaysProvider {
    async fn complete(
        &self,
        _req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode::Result<(ChatMessage, Usage)> {
        Ok((ChatMessage::assistant(self.0.clone()), Usage::default()))
    }
}

#[tokio::test]
async fn subagent_shares_transport_and_runs() {
    let dir = temp_dir("subagent");
    let config = Config::builder().cwd(dir.clone()).build();
    let agent = Agent::with_provider(config, Box::new(SaysProvider("PARENT".into())));
    // Subagent shares the same provider (Arc) → same canned answer, fresh convo.
    let out = agent
        .run_subagent("You are a worker.", "do the thing")
        .await
        .unwrap();
    assert_eq!(out, "PARENT");
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn background_task_runs_and_returns_agent() {
    let dir = temp_dir("bg");
    let config = Config::builder().cwd(dir.clone()).build();
    let agent = Agent::with_provider(config, Box::new(SaysProvider("DONE".into())));
    let handle = agent.run_in_background("go do it");
    let (agent, result) = handle.await.unwrap();
    assert_eq!(result.unwrap(), "DONE");
    // The returned agent retains the conversation.
    assert!(agent
        .history()
        .iter()
        .any(|m| m.content.as_deref() == Some("DONE")));
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn send_with_files_injects_contents() {
    let dir = temp_dir("files");
    std::fs::write(dir.join("notes.txt"), "IMPORTANT_NOTE_42").unwrap();
    std::fs::write(dir.join("img.bin"), [0u8, 159, 146, 150]).unwrap(); // invalid utf8
    let config = Config::builder().cwd(dir.clone()).build();
    let mut agent = Agent::with_provider(config, Box::new(SaysProvider("ok".into())));

    agent
        .send_with_files(
            "review these",
            &[dir.join("notes.txt"), dir.join("img.bin")],
        )
        .await
        .unwrap();

    // The user message carries the file contents (text inline; binary noted).
    let user = agent
        .history()
        .iter()
        .find(|m| m.role == supercode::Role::User)
        .unwrap();
    let c = user.content.clone().unwrap();
    assert!(c.contains("review these"));
    assert!(c.contains("IMPORTANT_NOTE_42"), "text file injected: {c}");
    assert!(
        c.contains("binary content omitted"),
        "binary file noted: {c}"
    );
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn send_with_images_builds_multimodal_message() {
    use supercode::ChatMessage;
    // The user message serializes `content` as a multimodal array on the wire.
    let m = ChatMessage::user_with_images(
        "what is in this image?",
        &[
            "https://example.com/a.png".to_string(),
            "data:image/png;base64,AAAA".to_string(),
        ],
    );
    let wire: serde_json::Value = serde_json::to_value(&m).unwrap();
    assert_eq!(wire["role"], "user");
    assert!(
        wire["content"].is_array(),
        "content must be a multimodal array"
    );
    assert_eq!(wire["content"][0]["type"], "text");
    assert_eq!(wire["content"][0]["text"], "what is in this image?");
    assert_eq!(wire["content"][1]["type"], "image_url");
    assert_eq!(
        wire["content"][1]["image_url"]["url"],
        "https://example.com/a.png"
    );
    assert_eq!(
        wire["content"][2]["image_url"]["url"],
        "data:image/png;base64,AAAA"
    );

    // Round-trips through Deserialize (transcript persistence).
    let back: ChatMessage = serde_json::from_value(wire).unwrap();
    assert!(back.content_parts.is_some() && back.content.is_none());

    // A plain text message still serializes content as a string.
    let t = serde_json::to_value(ChatMessage::user("hi")).unwrap();
    assert!(t["content"].is_string());

    // Agent path: the provider receives the multimodal message.
    let dir = temp_dir("vision");
    let config = Config::builder().cwd(dir.clone()).build();
    struct CapturingProvider(std::sync::Arc<std::sync::Mutex<Option<ChatRequest>>>);
    #[async_trait]
    impl Provider for CapturingProvider {
        async fn complete(
            &self,
            req: &ChatRequest,
            _d: &(dyn for<'a> Fn(&'a str) + Send + Sync),
        ) -> supercode::Result<(ChatMessage, Usage)> {
            *self.0.lock().unwrap() = Some(req.clone());
            Ok((ChatMessage::assistant("a cat"), Usage::default()))
        }
    }
    let captured = std::sync::Arc::new(std::sync::Mutex::new(None));
    let mut agent = Agent::with_provider(config, Box::new(CapturingProvider(captured.clone())));
    let reply = agent
        .send_with_images("describe", &["data:image/png;base64,XYZ".into()])
        .await
        .unwrap();
    assert_eq!(reply, "a cat");
    let req = captured.lock().unwrap().clone().unwrap();
    let user = req
        .messages
        .iter()
        .find(|m| m.role == supercode::Role::User)
        .unwrap();
    assert!(
        user.content_parts.is_some(),
        "the user turn carried image parts to the provider"
    );
    std::fs::remove_dir_all(&dir).ok();
}

/// A provider that always returns a plain text reply, reporting a fixed number
/// of completion tokens — to prove the agent accumulates output tokens across
/// sends (the figure the bench reports).
struct TokenReporter(u64);

#[async_trait]
impl Provider for TokenReporter {
    async fn complete(
        &self,
        _req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode::Result<(ChatMessage, Usage)> {
        let usage = Usage {
            prompt_tokens: 0,
            completion_tokens: self.0,
            total_tokens: self.0,
            ..Default::default()
        };
        Ok((ChatMessage::assistant("done"), usage))
    }
}

#[tokio::test]
async fn agent_accumulates_output_tokens_across_sends() {
    let mut agent = Agent::with_provider(Config::builder().build(), Box::new(TokenReporter(7)));
    assert_eq!(agent.total_output_tokens(), 0);
    agent.send("one").await.unwrap();
    assert_eq!(agent.total_output_tokens(), 7);
    agent.send("two").await.unwrap();
    assert_eq!(
        agent.total_output_tokens(),
        14,
        "tokens accumulate across sends"
    );
}

/// A provider that calls a tool whose output is huge, then summarizes — to
/// prove oversized tool output is capped before it re-enters the context.
struct BigToolThenDone {
    calls: AtomicUsize,
}

#[async_trait]
impl Provider for BigToolThenDone {
    async fn complete(
        &self,
        req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode::Result<(ChatMessage, Usage)> {
        let n = self.calls.fetch_add(1, Ordering::SeqCst);
        if n == 0 {
            let mut msg = ChatMessage::assistant("");
            msg.tool_calls = Some(vec![ToolCall {
                id: "c1".into(),
                kind: "function".into(),
                function: FunctionCall {
                    name: "list_dir".into(),
                    arguments: "{}".into(),
                },
            }]);
            Ok((msg, Usage::default()))
        } else {
            // The tool result we got back must have been capped.
            let tool_msg = req
                .messages
                .iter()
                .rev()
                .find(|m| m.role == Role::Tool)
                .unwrap();
            let len = tool_msg.content.as_deref().unwrap_or("").len();
            assert!(len <= 5000, "tool output should be capped, got {len} bytes");
            Ok((ChatMessage::assistant("done"), Usage::default()))
        }
    }
}

#[tokio::test]
async fn oversized_tool_output_is_capped() {
    // A tool that returns a megabyte of text.
    struct Big;
    #[async_trait]
    impl supercode::tools::Tool for Big {
        fn name(&self) -> &str {
            "list_dir"
        }
        fn description(&self) -> &str {
            "x"
        }
        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({"type":"object"})
        }
        async fn execute(
            &self,
            _a: serde_json::Value,
            _c: &supercode::tools::ToolContext,
        ) -> supercode::Result<String> {
            Ok("A".repeat(1_000_000))
        }
    }
    let config = Config::builder().max_tool_output_bytes(4096).build();
    let mut reg = supercode::tools::ToolRegistry::new();
    reg.register(Big);
    let mut agent = Agent::with_parts(
        config,
        Box::new(BigToolThenDone {
            calls: AtomicUsize::new(0),
        }),
        reg,
    );
    let reply = agent.send("go").await.unwrap();
    assert_eq!(reply, "done");
}

/// Provider that asks for a tool call once (name/args configurable), then
/// echoes back whatever the tool result said so the test can inspect it.
struct OneShotToolCall {
    calls: AtomicUsize,
    tool_name: &'static str,
    arguments: &'static str,
}
#[async_trait]
impl Provider for OneShotToolCall {
    async fn complete(
        &self,
        req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode::Result<(ChatMessage, Usage)> {
        let n = self.calls.fetch_add(1, Ordering::SeqCst);
        if n == 0 {
            let call = ChatMessage {
                role: Role::Assistant,
                content: None,
                content_parts: None,
                tool_calls: Some(vec![ToolCall {
                    id: "c1".into(),
                    kind: "function".into(),
                    function: FunctionCall {
                        name: self.tool_name.into(),
                        arguments: self.arguments.into(),
                    },
                }]),
                tool_call_id: None,
                name: None,
                metadata: Default::default(),
            };
            Ok((call, Usage::default()))
        } else {
            // Echo the tool result content back so the test can see it, and
            // stop the loop (no further tool calls).
            let last = req.messages.last().unwrap();
            assert_eq!(last.role, Role::Tool);
            Ok((
                ChatMessage::assistant(last.content.clone().unwrap_or_default()),
                Usage::default(),
            ))
        }
    }
}

#[tokio::test]
async fn unknown_tool_yields_typed_error_string() {
    use std::sync::{Arc, Mutex};

    let events: Arc<Mutex<Vec<(String, bool)>>> = Arc::new(Mutex::new(Vec::new()));
    let events2 = events.clone();
    let config = Config::builder()
        .event_sink(Box::new(move |ev| {
            if let supercode::AgentEvent::ToolCallCompleted { name, is_error, .. } = ev {
                events2.lock().unwrap().push((name, is_error));
            }
        }))
        .build();
    let mut agent = Agent::with_provider(
        config,
        Box::new(OneShotToolCall {
            calls: AtomicUsize::new(0),
            tool_name: "not_a_real_tool",
            arguments: "{}",
        }),
    );

    let reply = agent.send("do it").await.unwrap();

    // Model-facing string still names the missing tool and stays helpful.
    assert!(reply.contains("unknown tool"), "reply was: {reply}");
    assert!(reply.contains("not_a_real_tool"), "reply was: {reply}");
    assert!(reply.starts_with("Error:"), "reply was: {reply}");

    // The dispatch path reported it as an error.
    let seen = events.lock().unwrap().clone();
    assert!(
        seen.iter()
            .any(|(name, is_err)| name == "not_a_real_tool" && *is_err),
        "{seen:?}"
    );
}

#[tokio::test]
async fn invalid_arguments_yields_typed_error_string() {
    let config = Config::builder().build();
    let mut agent = Agent::with_provider(
        config,
        Box::new(OneShotToolCall {
            calls: AtomicUsize::new(0),
            tool_name: "list_dir",
            // Not valid JSON, so `parsed_arguments()` fails on the agent path
            // before the tool itself ever gets a chance to parse it.
            arguments: "not json at all",
        }),
    );

    let reply = agent.send("do it").await.unwrap();

    assert!(
        reply.contains("invalid arguments for tool"),
        "reply was: {reply}"
    );
    assert!(reply.contains("list_dir"), "reply was: {reply}");
    assert!(reply.starts_with("Error:"), "reply was: {reply}");
}

/// SUP-14 end-to-end: a `read_file` call on a file bigger than the tool-layer
/// `MAX_READ_BYTES` cap must not error, and the message the model actually
/// receives (after the agent-level `max_tool_output_bytes` cap runs on top)
/// must still carry a truncation notice — the read-cap notice sits at the
/// *head* of the tool output, so it survives the tail-trimming agent cap.
#[tokio::test]
async fn read_file_oversized_read_is_truncated_not_errored_end_to_end() {
    use std::sync::atomic::AtomicU64;
    static N: AtomicU64 = AtomicU64::new(0);
    let dir = std::env::temp_dir().join(format!(
        "sc-agent-read-{}-{}",
        std::process::id(),
        N.fetch_add(1, Ordering::SeqCst)
    ));
    std::fs::create_dir_all(&dir).unwrap();

    // MAX_READ_BYTES is 400_000; write a file comfortably past it.
    let line = "the quick brown fox jumps over the lazy dog\n";
    let mut content = String::new();
    while content.len() < 450_000 {
        content.push_str(line);
    }
    std::fs::write(dir.join("big.txt"), &content).unwrap();

    // Default config: max_tool_output_bytes defaults to Some(100_000).
    let config = Config::builder().cwd(dir.clone()).build();
    assert_eq!(config.max_tool_output_bytes, Some(100_000));

    let mut agent = Agent::with_provider(
        config,
        Box::new(OneShotToolCall {
            calls: AtomicUsize::new(0),
            tool_name: "read_file",
            arguments: r#"{"path":"big.txt"}"#,
        }),
    );

    // OneShotToolCall's second turn echoes the tool-role message content back
    // as the assistant reply and asserts `last.role == Role::Tool`, i.e. the
    // dispatch did not come back as a tool error.
    let reply = agent.send("read the big file").await.unwrap();

    assert!(
        reply.len() <= 100_000 + 200,
        "delivered content should respect the agent-level cap plus notice overhead, got {} bytes",
        reply.len()
    );
    assert!(
        reply.starts_with("[read_file: file is "),
        "read-cap notice must survive at the head even after the agent cap: {:?}",
        &reply[..reply.len().min(120)]
    );
    assert!(
        reply.contains("450"),
        "notice should state the true (larger) file size: {reply}"
    );

    std::fs::remove_dir_all(&dir).ok();
}

/// A3 acceptance (SPEC.md): a recorder makes the sidecar keep every tool
/// result at FULL fidelity even while `cap_tool_output` keeps shrinking what
/// enters `history` — and a `recorder: None` agent still caps exactly like
/// before (D6 only changes the truncation notice's wording, never the cut
/// point or the absence of the sidecar).
#[tokio::test]
async fn agent_records_full_fidelity_while_capping_view() {
    use supercode::session::Session;
    use supercode::sidecar::SidecarWriter;

    /// A `list_dir`-named tool (matching what `BigToolThenDone` calls) that
    /// returns a fixed 300 KB payload distinguishable from filler.
    struct BigOutput300k;
    #[async_trait]
    impl supercode::tools::Tool for BigOutput300k {
        fn name(&self) -> &str {
            "list_dir"
        }
        fn description(&self) -> &str {
            "x"
        }
        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({"type": "object"})
        }
        async fn execute(
            &self,
            _a: serde_json::Value,
            _c: &supercode::tools::ToolContext,
        ) -> supercode::Result<String> {
            Ok("Q".repeat(300_000))
        }
    }

    let dir = temp_dir("recorded-fullfidelity");
    let sidecar_path = dir.join("sess.sidecar.jsonl");

    // Agent #1: recorder installed via `set_recorder`, seeded from an empty
    // session (no imported prefix) so the sidecar's appended-turn count maps
    // 1:1 onto `history` minus the synthetic system prompt.
    let config = Config::builder().max_tool_output_bytes(4096).build();
    let mut reg = supercode::tools::ToolRegistry::new();
    reg.register(BigOutput300k);
    let mut agent = Agent::with_parts(
        config,
        Box::new(BigToolThenDone {
            calls: AtomicUsize::new(0),
        }),
        reg,
    );
    let empty_session = Session::from_claude_code_str("").unwrap();
    let writer = SidecarWriter::create(&sidecar_path, &empty_session).unwrap();
    agent.set_recorder(writer);

    let reply = agent.send("go").await.unwrap();
    assert_eq!(reply, "done");

    // (i) history's tool message is capped to the configured bound plus the
    // notice's overhead.
    let tool_msg = agent
        .history()
        .iter()
        .rev()
        .find(|m| m.role == Role::Tool)
        .unwrap();
    let capped = tool_msg.content.as_deref().unwrap_or("");
    assert!(
        capped.len() <= 4096 + 200,
        "capped tool message should be ~4KB + marker, got {} bytes",
        capped.len()
    );
    assert!(
        capped.contains("full output in session sidecar"),
        "truncation notice must say the sidecar has the full output when a recorder is installed: {capped:?}"
    );

    // (ii) reloading the sidecar yields the tool message at exactly 300 KB,
    // byte-identical to what the tool actually returned.
    let raw = std::fs::read_to_string(&sidecar_path).unwrap();
    let reloaded = Session::from_native_str(&raw).unwrap();
    let full_tool_msg = reloaded
        .messages
        .iter()
        .rev()
        .find(|m| m.role == Role::Tool)
        .unwrap();
    let full_content = full_tool_msg.content.as_deref().unwrap_or("");
    assert_eq!(
        full_content.len(),
        300_000,
        "sidecar must retain the full 300KB tool output"
    );
    assert_eq!(
        full_content,
        "Q".repeat(300_000),
        "sidecar's tool output must be byte-identical to the original"
    );

    // (iii) message counts match between the reloaded sidecar and the
    // unreduced history: `history[0]` is this agent's own system prompt
    // (never part of any imported session, never written to the sidecar —
    // see `Agent::load_session`/`Agent::resume_recorded`), so everything
    // from `history[1..]` is exactly what was recorded, turn for turn.
    assert_eq!(
        reloaded.messages.len(),
        agent.history().len() - 1,
        "sidecar turn count must equal history minus the synthetic system prompt"
    );

    // (iv) `recorder: None` behaves byte-identically to today: the same
    // tool call, run with no recorder installed, is capped at the exact same
    // byte boundary (only the honest retention label in the notice differs,
    // per D6 — never the cut point, never whether the notice exists).
    let config2 = Config::builder().max_tool_output_bytes(4096).build();
    let mut reg2 = supercode::tools::ToolRegistry::new();
    reg2.register(BigOutput300k);
    let mut agent_no_recorder = Agent::with_parts(
        config2,
        Box::new(BigToolThenDone {
            calls: AtomicUsize::new(0),
        }),
        reg2,
    );
    let reply2 = agent_no_recorder.send("go").await.unwrap();
    assert_eq!(reply2, "done");
    let tool_msg2 = agent_no_recorder
        .history()
        .iter()
        .rev()
        .find(|m| m.role == Role::Tool)
        .unwrap();
    let capped2 = tool_msg2.content.as_deref().unwrap_or("");
    assert!(
        capped2.contains("full output not retained"),
        "truncation notice must be honest about no sidecar existing: {capped2:?}"
    );
    assert_eq!(
        &capped[..4096],
        &capped2[..4096],
        "the kept prefix must be identical whether or not a recorder is installed"
    );

    std::fs::remove_dir_all(&dir).ok();
}