kaish-kernel 0.8.1

Core kernel for kaish: lexer, parser, interpreter, and runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
//! Configurable output size limits for agent safety.
//!
//! When output exceeds the threshold the result is capped and `ExecResult.out`
//! is replaced with a head+tail preview. Two strategies, selected at runtime by
//! [`SpillMode`]:
//! - [`SpillMode::Disk`] (default): the full output is written to a spill file
//!   on the real filesystem and the preview points at it. The agent can then
//!   selectively read the file.
//! - [`SpillMode::Memory`]: the output is truncated in memory only — no disk
//!   I/O, no recoverable file. For runtime read-only kernels (e.g. kaibo) that
//!   must not touch the host filesystem even when `localfs` is compiled in.
//!   Memory stays bounded regardless of how much the command produces.
//!
//! Either way the exit code is remapped to 3 (`did_spill`) so callers can tell
//! the output was capped.
//!
//! Per-mode defaults: MCP kernels get an 8KB limit, REPL/test kernels
//! are unlimited. Runtime-switchable via the `kaish-output-limit` builtin.

use std::path::PathBuf;

use crate::interpreter::ExecResult;
#[cfg(feature = "localfs")]
use crate::paths;

/// Default output limit for MCP mode (8KB).
const DEFAULT_MCP_LIMIT: usize = 8 * 1024;

/// Default head preview size (bytes of output start to keep).
const DEFAULT_HEAD_BYTES: usize = 1024;

/// Default tail preview size (bytes of output end to keep).
const DEFAULT_TAIL_BYTES: usize = 512;

/// Where overflow output goes when it exceeds the limit.
///
/// This is a *runtime* choice, distinct from the compile-time `localfs`
/// feature: a `localfs`-built kernel can still be told to truncate in memory.
/// A build without `localfs` always behaves as [`SpillMode::Memory`] regardless
/// of this setting, since disk I/O is unavailable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SpillMode {
    /// Write overflow to a disk spill file under `paths::spill_dir()` and keep a
    /// head+tail preview in the result (the message carries the file path).
    /// Requires the `localfs` feature. This is the default.
    ///
    /// Auto-overridden to [`Memory`](Self::Memory) at kernel construction when
    /// the VFS mount is `NoLocal` (memory-only) — such a kernel has no host
    /// filesystem to spill to. See `Kernel::assemble`.
    #[default]
    Disk,
    /// Truncate in memory to head+tail only — no disk I/O, no recoverable file.
    /// For runtime read-only kernels (e.g. kaibo) that must never touch the host
    /// filesystem even when `localfs` is compiled in.
    Memory,
}

/// Configurable output size limit.
///
/// Threaded through `KernelConfig` → `ExecContext` → kernel pipeline execution.
/// Runtime-mutable via the `kaish-output-limit` builtin.
#[derive(Debug, Clone)]
pub struct OutputLimitConfig {
    max_bytes: Option<usize>,
    head_bytes: usize,
    tail_bytes: usize,
    spill_mode: SpillMode,
}

impl OutputLimitConfig {
    /// No limiting — REPL/embedded/test default.
    pub fn none() -> Self {
        Self {
            max_bytes: None,
            head_bytes: DEFAULT_HEAD_BYTES,
            tail_bytes: DEFAULT_TAIL_BYTES,
            spill_mode: SpillMode::Disk,
        }
    }

    /// Default limit used by `on` subcommand and `set -o output-limit`.
    pub fn default_limit() -> usize {
        DEFAULT_MCP_LIMIT
    }

    /// MCP-safe defaults: 8KB limit, 1KB head, 512B tail, disk spill.
    pub fn mcp() -> Self {
        Self {
            max_bytes: Some(DEFAULT_MCP_LIMIT),
            head_bytes: DEFAULT_HEAD_BYTES,
            tail_bytes: DEFAULT_TAIL_BYTES,
            spill_mode: SpillMode::Disk,
        }
    }

    /// Switch to in-memory truncation — no disk spill, no host filesystem
    /// writes. For runtime read-only kernels (e.g. kaibo). Builder form of
    /// [`set_spill_mode`](Self::set_spill_mode).
    ///
    /// Note: a `NoLocal` VFS mount forces this mode automatically at kernel
    /// construction, so an embedder only needs this for a `localfs`-mounted
    /// kernel it nonetheless wants to keep off the host disk.
    pub fn in_memory(mut self) -> Self {
        self.spill_mode = SpillMode::Memory;
        self
    }

    /// Whether output limiting is enabled.
    pub fn is_enabled(&self) -> bool {
        self.max_bytes.is_some()
    }

    /// The spill mode (disk vs in-memory truncation).
    pub fn spill_mode(&self) -> SpillMode {
        self.spill_mode
    }

    /// Set the spill mode.
    pub fn set_spill_mode(&mut self, mode: SpillMode) {
        self.spill_mode = mode;
    }

    /// The maximum output size in bytes, if set.
    pub fn max_bytes(&self) -> Option<usize> {
        self.max_bytes
    }

    /// Bytes of output head to preserve in truncated result.
    pub fn head_bytes(&self) -> usize {
        self.head_bytes
    }

    /// Bytes of output tail to preserve in truncated result.
    pub fn tail_bytes(&self) -> usize {
        self.tail_bytes
    }

    /// Set the output limit. `None` disables limiting.
    pub fn set_limit(&mut self, max: Option<usize>) {
        self.max_bytes = max;
    }

    /// Set the head preview size.
    pub fn set_head_bytes(&mut self, bytes: usize) {
        self.head_bytes = bytes;
    }

    /// Set the tail preview size.
    pub fn set_tail_bytes(&mut self, bytes: usize) {
        self.tail_bytes = bytes;
    }
}

/// Result of a spill operation.
pub struct SpillResult {
    pub path: PathBuf,
    pub total_bytes: usize,
}

/// Check if the result output exceeds the limit and spill to disk if so.
///
/// Mutates `result.out` in place: replaces with head+tail+pointer message.
/// Returns `Some(SpillResult)` if a spill file was written, `None` otherwise.
///
/// If the filesystem write fails, the result is replaced with an error.
/// Fail fast: truncating output silently could corrupt structured data
/// that an agent acts on. An explicit error is safer.
///
/// In [`SpillMode::Memory`], or in any build without the `localfs` feature,
/// performs in-memory head+tail truncation (no disk I/O) instead.
pub async fn spill_if_needed(
    result: &mut ExecResult,
    config: &OutputLimitConfig,
) -> Option<SpillResult> {
    let max = config.max_bytes?;

    // Disk spill requires `localfs` AND the caller selecting it. Memory mode
    // (or a build without `localfs`) falls through to in-memory truncation.
    #[cfg(feature = "localfs")]
    if config.spill_mode == SpillMode::Disk {
        // If result.out is already populated (external commands), check it directly
        if !result.text_out().is_empty() && !result.has_output() {
            let total = result.text_out().len();
            if total <= max {
                return None;
            }
            return spill_string(result, config, max).await;
        }

        // If we have structured OutputData, estimate size before materializing
        if let Some(output) = result.output() {
            let estimate = output.estimated_byte_size();
            if estimate <= max {
                // Small enough — materialize normally
                result.materialize();
                // Re-check actual size (estimate is a lower bound)
                if result.text_out().len() <= max {
                    return None;
                }
                return spill_string(result, config, max).await;
            }

            // Large — stream directly to spill file, never holding full String
            return spill_output_data(result, config, max).await;
        }

        return None;
    }

    // In-memory head+tail truncation (Memory mode or no `localfs`): no disk I/O.
    truncate_in_memory(result, config, max)
}

/// Truncate output in memory to head+tail, with no disk I/O.
///
/// Sets `did_spill = true` so the kernel remaps the exit code to 3 — the same
/// "output was capped" signal as a disk spill — but the message carries no file
/// path because there is no recoverable file. Returns `None` (no `SpillResult`,
/// since nothing was written); the caller distinguishes truncation via
/// `result.did_spill`.
///
/// Memory is bounded: large structured `OutputData` is streamed through a byte
/// budget rather than materialized into a full `String`, so a builtin emitting
/// a huge tree (e.g. a recursive `ls` of a giant directory) cannot OOM a
/// read-only kernel.
fn truncate_in_memory(
    result: &mut ExecResult,
    config: &OutputLimitConfig,
    max: usize,
) -> Option<SpillResult> {
    // Structured OutputData: estimate first. If it would clearly overflow,
    // render only a bounded head prefix via `write_canonical` rather than
    // materializing the whole thing.
    if let Some(output) = result.output() {
        let estimate = output.estimated_byte_size();
        if estimate > max {
            // Render a bounded head prefix only — no full materialization.
            let mut buf = Vec::with_capacity(config.head_bytes + 64);
            // write_canonical stops shortly after the budget; ignore the count.
            let _ = output.write_canonical(&mut buf, Some(config.head_bytes));
            let s = String::from_utf8_lossy(&buf);
            let head = truncate_to_char_boundary(&s, config.head_bytes);
            let truncated = format!(
                "{}\n...\n[output truncated in memory: ~{} bytes (exceeds {} byte limit) — head only, no spill file]",
                head, estimate, max
            );
            result.set_out(truncated);
            result.did_spill = true;
            return None;
        }
        // Small enough to materialize safely.
        result.materialize();
    }

    let total = result.text_out().len();
    if total <= max {
        return None;
    }

    // Already-materialized text fits in memory (it was produced into RAM
    // regardless) — give a precise head+tail+total.
    let text = result.text_out().into_owned();
    let head = truncate_to_char_boundary(&text, config.head_bytes);
    let tail = tail_from_str(&text, config.tail_bytes);
    let truncated = format!(
        "{}\n...\n{}\n[output truncated in memory: {} bytes total — no spill file]",
        head, tail, total
    );
    result.set_out(truncated);
    result.did_spill = true;
    None
}

/// Spill an already-materialized string in result.out.
#[cfg(feature = "localfs")]
async fn spill_string(
    result: &mut ExecResult,
    config: &OutputLimitConfig,
    max: usize,
) -> Option<SpillResult> {
    let total = result.text_out().len();
    match write_spill_file(result.text_out().as_bytes()).await {
        Ok((path, written)) => {
            let truncated = build_truncated_output(&result.text_out(), config, &path, total);
            result.set_out(truncated);
            result.did_spill = true;
            Some(SpillResult {
                path,
                total_bytes: written,
            })
        }
        Err(e) => {
            tracing::error!("output spill failed: {}", e);
            *result = ExecResult::failure(1, format!(
                "output exceeded {} byte limit ({} bytes) and spill to disk failed: {}",
                max, total, e
            ));
            None
        }
    }
}

/// Stream OutputData directly to a spill file without materializing the full String.
#[cfg(feature = "localfs")]
async fn spill_output_data(
    result: &mut ExecResult,
    config: &OutputLimitConfig,
    max: usize,
) -> Option<SpillResult> {
    let output = result.output()?;

    let dir = paths::spill_dir();
    if let Err(e) = tokio::fs::create_dir_all(&dir).await {
        tracing::error!("output spill dir creation failed: {}", e);
        *result = ExecResult::failure(1, format!(
            "output exceeded {} byte limit and spill dir creation failed: {}", max, e
        ));
        return None;
    }

    let filename = generate_spill_filename();
    let path = dir.join(&filename);

    // Write OutputData directly to file via write_canonical
    let total = match std::fs::File::create(&path) {
        Ok(mut file) => {
            match output.write_canonical(&mut file, None) {
                Ok(n) => n,
                Err(e) => {
                    tracing::error!("output spill write failed: {}", e);
                    *result = ExecResult::failure(1, format!(
                        "output exceeded {} byte limit and spill to disk failed: {}", max, e
                    ));
                    return None;
                }
            }
        }
        Err(e) => {
            tracing::error!("output spill file creation failed: {}", e);
            *result = ExecResult::failure(1, format!(
                "output exceeded {} byte limit and spill to disk failed: {}", max, e
            ));
            return None;
        }
    };

    // Read head and tail from the spill file for the truncated preview
    let head = read_head_from_file(&path, config.head_bytes).await.unwrap_or_default();
    let tail = read_tail_from_file(&path, config.tail_bytes).await.unwrap_or_default();
    let path_str = path.to_string_lossy();

    result.set_out(format!(
        "{}\n...\n{}\n[output truncated: {} bytes total — full output at {}]",
        head, tail, total, path_str
    ));
    result.did_spill = true;

    Some(SpillResult {
        path,
        total_bytes: total,
    })
}

/// Collect stdout from a child process with spill-aware size limiting.
///
/// Two-phase approach:
/// 1. Detection window (up to 1s): accumulate in memory
/// 2. If still running after 1s and over limit: stream to spill file
///
/// Returns `(stdout_string, stderr_string, did_spill)`.
///
/// Handles child-process stdio, so it lives on the `subprocess` axis (which
/// implies `localfs`); the pure disk-spill helpers below stay on `localfs`.
#[cfg(feature = "subprocess")]
pub async fn spill_aware_collect(
    mut stdout: tokio::process::ChildStdout,
    mut stderr_reader: tokio::process::ChildStderr,
    stderr_stream: Option<crate::scheduler::StderrStream>,
    config: &OutputLimitConfig,
) -> (String, String, bool) {
    let max = config.max_bytes.unwrap_or(usize::MAX);

    // Spawn stderr collection
    let stderr_task = tokio::spawn(async move {
        collect_stderr(&mut stderr_reader, stderr_stream.as_ref()).await
    });

    let (stdout_result, did_spill) = collect_stdout_with_spill(&mut stdout, max, config).await;

    let stderr = stderr_task.await.unwrap_or_default();
    (stdout_result, stderr, did_spill)
}

/// Collect stderr (same pattern as existing dispatch code).
#[cfg(feature = "subprocess")]
async fn collect_stderr(
    reader: &mut tokio::process::ChildStderr,
    stream: Option<&crate::scheduler::StderrStream>,
) -> String {
    use tokio::io::AsyncReadExt;

    let mut buf = Vec::new();
    let mut chunk = [0u8; 8192];
    loop {
        match reader.read(&mut chunk).await {
            Ok(0) => break,
            Ok(n) => {
                if let Some(s) = stream {
                    s.write(&chunk[..n]);
                } else {
                    buf.extend_from_slice(&chunk[..n]);
                }
            }
            Err(_) => break,
        }
    }
    if stream.is_some() {
        String::new()
    } else {
        String::from_utf8_lossy(&buf).into_owned()
    }
}

/// Collect stdout with two-phase spill detection.
///
/// Generic over `AsyncRead + Unpin` — works with `ChildStdout` in production
/// and `DuplexStream` in tests.
///
/// Returns `(stdout_string, did_spill)`.
#[cfg(feature = "subprocess")]
async fn collect_stdout_with_spill<R: tokio::io::AsyncRead + Unpin>(
    stdout: &mut R,
    max_bytes: usize,
    config: &OutputLimitConfig,
) -> (String, bool) {
    use tokio::io::AsyncReadExt;
    use tokio::time::{sleep, Duration};

    let mut buffer = Vec::new();
    let mut chunk = [0u8; 8192];
    let deadline = sleep(Duration::from_secs(1));
    tokio::pin!(deadline);

    // Phase 1: Detection window (up to 1s)
    loop {
        tokio::select! {
            biased;
            result = stdout.read(&mut chunk) => {
                match result {
                    Ok(0) => {
                        // EOF — command finished within detection window.
                        // Post-hoc spill check happens in the caller.
                        return (String::from_utf8_lossy(&buffer).into_owned(), false);
                    }
                    Ok(n) => {
                        buffer.extend_from_slice(&chunk[..n]);
                        // Break early if already over limit — don't OOM during detection window
                        if buffer.len() > max_bytes {
                            break;
                        }
                    }
                    Err(_) => {
                        return (String::from_utf8_lossy(&buffer).into_owned(), false);
                    }
                }
            }
            () = &mut deadline => {
                // 1s elapsed, command still running
                break;
            }
        }
    }

    // Phase 2: Check if we should switch to spill mode
    if buffer.len() > max_bytes {
        // Already over limit — hand off to the disk-spill or in-memory-drain path
        return handle_overflow(&buffer, stdout, config, max_bytes).await;
    }

    // Continue collecting (under limit so far)
    // Check size after each chunk
    loop {
        match stdout.read(&mut chunk).await {
            Ok(0) => break,
            Ok(n) => {
                buffer.extend_from_slice(&chunk[..n]);
                // Check if we've exceeded limit mid-stream
                if buffer.len() > max_bytes {
                    return handle_overflow(&buffer, stdout, config, max_bytes).await;
                }
            }
            Err(_) => break,
        }
    }

    (String::from_utf8_lossy(&buffer).into_owned(), false)
}

/// Decide how to handle stdout that has overflowed the limit: spill the rest to
/// a disk file ([`SpillMode::Disk`]) or drain it with a bounded in-memory
/// head+tail buffer ([`SpillMode::Memory`]). Returns `(message, did_spill)`.
#[cfg(feature = "subprocess")]
async fn handle_overflow<R: tokio::io::AsyncRead + Unpin>(
    buffer: &[u8],
    stdout: &mut R,
    config: &OutputLimitConfig,
    max_bytes: usize,
) -> (String, bool) {
    // Memory mode: never touch disk. Drain with a bounded head+tail buffer so
    // an unbounded child cannot OOM us.
    if config.spill_mode == SpillMode::Memory {
        return (drain_in_memory(buffer, stdout, config).await, true);
    }

    match stream_to_spill(buffer, stdout, config).await {
        Ok(result) => (result, true),
        Err(e) => {
            // Spill failed — return error. Don't continue accumulating.
            // Dropping stdout closes the pipe, which sends SIGPIPE to the child.
            tracing::error!("streaming spill failed: {}", e);
            (
                format!(
                    "ERROR: output exceeded {} byte limit ({} bytes buffered) and spill to disk failed: {}",
                    max_bytes,
                    buffer.len(),
                    e
                ),
                false,
            )
        }
    }
}

/// Drain stdout to EOF keeping only a bounded head+tail in memory, discarding
/// the middle. Memory use is capped at `head_bytes + tail_bytes + one chunk`
/// regardless of how much the child produces. Counts the true total so the
/// truncation marker is honest about how much was dropped.
#[cfg(feature = "subprocess")]
async fn drain_in_memory<R: tokio::io::AsyncRead + Unpin>(
    buffer: &[u8],
    stdout: &mut R,
    config: &OutputLimitConfig,
) -> String {
    use tokio::io::AsyncReadExt;

    // Head is fixed from the prefix we have already buffered.
    let head = {
        let s = String::from_utf8_lossy(buffer);
        truncate_to_char_boundary(&s, config.head_bytes).to_string()
    };

    // Tail ring over the entire stream, bounded to tail_bytes.
    let cap = config.tail_bytes;
    let mut tail: std::collections::VecDeque<u8> = std::collections::VecDeque::with_capacity(cap + 1);
    extend_ring(&mut tail, buffer, cap);
    let mut total = buffer.len();

    let mut chunk = [0u8; 8192];
    loop {
        match stdout.read(&mut chunk).await {
            Ok(0) => break,
            Ok(n) => {
                total += n;
                extend_ring(&mut tail, &chunk[..n], cap);
            }
            Err(_) => break,
        }
    }

    let tail_bytes: Vec<u8> = tail.into_iter().collect();
    let tail_str = String::from_utf8_lossy(&tail_bytes);
    let dropped = total.saturating_sub(head.len() + tail_bytes.len());
    format!(
        "{}\n...\n{}\n[output truncated in memory: {} bytes total, {} discarded — no spill file]",
        head, tail_str, total, dropped
    )
}

/// Append `bytes` to a tail ring buffer bounded to `cap` bytes, evicting from
/// the front. If `bytes` alone exceeds `cap`, only its last `cap` bytes are kept.
#[cfg(feature = "subprocess")]
fn extend_ring(ring: &mut std::collections::VecDeque<u8>, bytes: &[u8], cap: usize) {
    if cap == 0 {
        return;
    }
    let start = bytes.len().saturating_sub(cap);
    for &b in &bytes[start..] {
        if ring.len() == cap {
            ring.pop_front();
        }
        ring.push_back(b);
    }
}

/// Write buffered data + remaining stdout to a spill file, return truncated result.
///
/// Generic over `AsyncRead + Unpin` for testability.
#[cfg(feature = "subprocess")]
async fn stream_to_spill<R: tokio::io::AsyncRead + Unpin>(
    buffer: &[u8],
    stdout: &mut R,
    config: &OutputLimitConfig,
) -> Result<String, std::io::Error> {
    use tokio::io::AsyncReadExt;

    let spill_dir = paths::spill_dir();
    tokio::fs::create_dir_all(&spill_dir).await?;

    let filename = generate_spill_filename();
    let path = spill_dir.join(&filename);
    let mut file = tokio::fs::File::create(&path).await?;

    // Write buffered data
    use tokio::io::AsyncWriteExt;
    file.write_all(buffer).await?;
    let mut total = buffer.len();

    // Stream remaining chunks directly to file
    let mut chunk = [0u8; 8192];
    loop {
        match stdout.read(&mut chunk).await {
            Ok(0) => break,
            Ok(n) => {
                file.write_all(&chunk[..n]).await?;
                total += n;
            }
            Err(_) => break,
        }
    }
    file.flush().await?;

    // Read head + tail for the truncated message
    let full = String::from_utf8_lossy(buffer);
    let head = truncate_to_char_boundary(&full, config.head_bytes);

    // For tail, read from the spill file if buffer doesn't cover the end
    let tail: String = if total <= buffer.len() {
        let full_str = String::from_utf8_lossy(buffer);
        tail_from_str(&full_str, config.tail_bytes).to_string()
    } else {
        read_tail_from_file(&path, config.tail_bytes).await.unwrap_or_default()
    };

    let path_str = path.to_string_lossy();
    Ok(format!(
        "{}\n...\n{}\n[output truncated: {} bytes total — full output at {}]",
        head, tail, total, path_str
    ))
}

/// Write output bytes to a new spill file. Returns (path, bytes_written).
#[cfg(feature = "localfs")]
async fn write_spill_file(data: &[u8]) -> Result<(PathBuf, usize), std::io::Error> {
    let dir = paths::spill_dir();
    tokio::fs::create_dir_all(&dir).await?;

    let filename = generate_spill_filename();
    let path = dir.join(filename);
    tokio::fs::write(&path, data).await?;
    Ok((path, data.len()))
}

/// Build the truncated output string with head, tail, and pointer.
#[cfg(feature = "localfs")]
fn build_truncated_output(
    full: &str,
    config: &OutputLimitConfig,
    spill_path: &std::path::Path,
    total_bytes: usize,
) -> String {
    let head = truncate_to_char_boundary(full, config.head_bytes);
    let tail = tail_from_str(full, config.tail_bytes);
    let path_str = spill_path.to_string_lossy();
    format!(
        "{}\n...\n{}\n[output truncated: {} bytes total — full output at {}]",
        head, tail, total_bytes, path_str
    )
}

/// Truncate a string to at most `max_bytes`, respecting UTF-8 char boundaries.
fn truncate_to_char_boundary(s: &str, max_bytes: usize) -> &str {
    if s.len() <= max_bytes {
        return s;
    }
    // Find the last char boundary at or before max_bytes
    let mut end = max_bytes;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

/// Get the last `max_bytes` of a string, respecting UTF-8 char boundaries.
fn tail_from_str(s: &str, max_bytes: usize) -> &str {
    if s.len() <= max_bytes {
        return s;
    }
    let start = s.len() - max_bytes;
    let mut adjusted = start;
    while adjusted < s.len() && !s.is_char_boundary(adjusted) {
        adjusted += 1;
    }
    &s[adjusted..]
}

/// Read the first N bytes from a file for head preview.
#[cfg(feature = "localfs")]
async fn read_head_from_file(path: &std::path::Path, max_bytes: usize) -> Result<String, std::io::Error> {
    use tokio::io::AsyncReadExt;

    let mut file = tokio::fs::File::open(path).await?;
    let mut buf = vec![0u8; max_bytes];
    let n = file.read(&mut buf).await?;
    buf.truncate(n);

    let s = String::from_utf8_lossy(&buf);
    // Truncate to char boundary
    let result = truncate_to_char_boundary(&s, max_bytes);
    Ok(result.to_string())
}

/// Read the last N bytes from a file for tail preview.
#[cfg(feature = "localfs")]
async fn read_tail_from_file(path: &std::path::Path, max_bytes: usize) -> Result<String, std::io::Error> {
    use tokio::io::{AsyncReadExt, AsyncSeekExt};

    let mut file = tokio::fs::File::open(path).await?;
    let metadata = file.metadata().await?;
    let len = metadata.len() as usize;

    if len <= max_bytes {
        let mut buf = Vec::new();
        file.read_to_end(&mut buf).await?;
        return Ok(String::from_utf8_lossy(&buf).into_owned());
    }

    let offset = len - max_bytes;
    file.seek(std::io::SeekFrom::Start(offset as u64)).await?;
    let mut buf = vec![0u8; max_bytes];
    let n = file.read(&mut buf).await?;
    buf.truncate(n);

    // Adjust to char boundary
    let s = String::from_utf8_lossy(&buf);
    Ok(s.into_owned())
}

/// Generate a unique spill filename using timestamp, PID, and monotonic counter.
#[cfg(feature = "localfs")]
fn generate_spill_filename() -> String {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::SystemTime;

    static COUNTER: AtomicUsize = AtomicUsize::new(0);
    let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
    let ts = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default();
    let pid = std::process::id();
    format!("spill-{}.{}-{}-{}.txt", ts.as_secs(), ts.subsec_nanos(), pid, seq)
}

/// Parse a size string with optional K/M suffix into bytes.
///
/// Accepts: "64K", "64k", "1M", "1m", "65536" (raw bytes).
pub fn parse_size(s: &str) -> Result<usize, String> {
    let s = s.trim();
    if s.is_empty() {
        return Err("empty size string".to_string());
    }

    let (num_str, multiplier) = if let Some(n) = s.strip_suffix('K').or_else(|| s.strip_suffix('k')) {
        (n, 1024)
    } else if let Some(n) = s.strip_suffix('M').or_else(|| s.strip_suffix('m')) {
        (n, 1024 * 1024)
    } else {
        (s, 1)
    };

    let num: usize = num_str
        .parse()
        .map_err(|_| format!("invalid size: {}", s))?;

    Ok(num * multiplier)
}

#[cfg(all(test, feature = "localfs"))]
mod tests {
    use super::*;

    #[test]
    fn test_none_is_disabled() {
        let config = OutputLimitConfig::none();
        assert!(!config.is_enabled());
        assert_eq!(config.max_bytes(), None);
    }

    #[test]
    fn test_mcp_is_enabled() {
        let config = OutputLimitConfig::mcp();
        assert!(config.is_enabled());
        assert_eq!(config.max_bytes(), Some(8 * 1024));
        assert_eq!(config.head_bytes(), 1024);
        assert_eq!(config.tail_bytes(), 512);
    }

    #[test]
    fn test_set_limit() {
        let mut config = OutputLimitConfig::none();
        assert!(!config.is_enabled());

        config.set_limit(Some(1024));
        assert!(config.is_enabled());
        assert_eq!(config.max_bytes(), Some(1024));

        config.set_limit(None);
        assert!(!config.is_enabled());
    }

    #[test]
    fn test_set_head_tail() {
        let mut config = OutputLimitConfig::mcp();
        config.set_head_bytes(2048);
        config.set_tail_bytes(1024);
        assert_eq!(config.head_bytes(), 2048);
        assert_eq!(config.tail_bytes(), 1024);
    }

    #[test]
    fn test_parse_size() {
        assert_eq!(parse_size("64K").unwrap(), 64 * 1024);
        assert_eq!(parse_size("64k").unwrap(), 64 * 1024);
        assert_eq!(parse_size("1M").unwrap(), 1024 * 1024);
        assert_eq!(parse_size("1m").unwrap(), 1024 * 1024);
        assert_eq!(parse_size("65536").unwrap(), 65536);
        assert!(parse_size("").is_err());
        assert!(parse_size("abc").is_err());
    }

    #[test]
    fn test_truncate_to_char_boundary() {
        assert_eq!(truncate_to_char_boundary("hello", 10), "hello");
        assert_eq!(truncate_to_char_boundary("hello", 3), "hel");
        // Multi-byte: "æ—¥" is 3 bytes
        assert_eq!(truncate_to_char_boundary("日本語", 3), "日");
        assert_eq!(truncate_to_char_boundary("日本語", 4), "日");
        assert_eq!(truncate_to_char_boundary("日本語", 6), "日本");
    }

    #[test]
    fn test_tail_from_str() {
        assert_eq!(tail_from_str("hello", 10), "hello");
        assert_eq!(tail_from_str("hello", 3), "llo");
        // Multi-byte
        assert_eq!(tail_from_str("日本語", 3), "語");
        assert_eq!(tail_from_str("日本語", 6), "本語");
    }

    #[test]
    fn test_generate_spill_filename() {
        let name = generate_spill_filename();
        assert!(name.starts_with("spill-"));
        assert!(name.ends_with(".txt"));
    }

    #[tokio::test]
    async fn test_spill_if_needed_under_limit() {
        let config = OutputLimitConfig::mcp();
        let mut result = ExecResult::success("short output");
        let spill = spill_if_needed(&mut result, &config).await;
        assert!(spill.is_none());
        assert_eq!(&*result.text_out(), "short output");
        assert!(!result.did_spill);
    }

    #[tokio::test]
    async fn test_spill_if_needed_over_limit() {
        let config = OutputLimitConfig {
            max_bytes: Some(100),
            head_bytes: 20,
            tail_bytes: 10,
            spill_mode: SpillMode::Disk,
        };
        let big_output = "x".repeat(200);
        let mut result = ExecResult::success(big_output);
        let spill = spill_if_needed(&mut result, &config).await;
        assert!(spill.is_some());
        assert!(result.did_spill);

        let spill = spill.unwrap();
        assert_eq!(spill.total_bytes, 200);
        assert!(spill.path.exists());

        // Verify truncated output
        assert!(result.text_out().contains("..."));
        assert!(result.text_out().contains("[output truncated: 200 bytes total"));
        assert!(result.text_out().contains(&spill.path.to_string_lossy().to_string()));

        // Verify head (first 20 bytes)
        assert!(result.text_out().starts_with(&"x".repeat(20)));

        // Verify spill file has full content
        let spill_content = tokio::fs::read_to_string(&spill.path).await.unwrap();
        assert_eq!(spill_content.len(), 200);

        // Clean up
        let _ = tokio::fs::remove_file(&spill.path).await;
    }

    #[tokio::test]
    async fn test_spill_if_needed_disabled() {
        let config = OutputLimitConfig::none();
        let big_output = "x".repeat(200);
        let mut result = ExecResult::success(big_output.clone());
        let spill = spill_if_needed(&mut result, &config).await;
        assert!(spill.is_none());
        assert_eq!(&*result.text_out(), big_output);
        assert!(!result.did_spill);
    }

    #[test]
    fn test_build_truncated_output() {
        let config = OutputLimitConfig {
            max_bytes: Some(100),
            head_bytes: 5,
            tail_bytes: 3,
            spill_mode: SpillMode::Disk,
        };
        let full = "abcdefghijklmnop";
        let path = PathBuf::from("/tmp/test-spill.txt");
        let result = build_truncated_output(full, &config, &path, 16);
        assert!(result.starts_with("abcde"));
        assert!(result.contains("..."));
        assert!(result.contains("nop"));
        assert!(result.contains("[output truncated: 16 bytes total — full output at /tmp/test-spill.txt]"));
    }

    #[tokio::test]
    async fn test_kernel_mcp_truncates_large_output() {
        use crate::kernel::{Kernel, KernelConfig};

        // MCP config has 8K limit by default — use a smaller limit for testing
        let config = KernelConfig::mcp()
            .with_output_limit(OutputLimitConfig {
                max_bytes: Some(200),
                head_bytes: 50,
                tail_bytes: 30,
                spill_mode: SpillMode::Disk,
            });
        let kernel = Kernel::new(config).expect("kernel creation");

        // seq 1 10000 produces lots of output
        let result = kernel.execute("seq 1 10000").await.expect("execute");
        assert!(result.text_out().contains("[output truncated:"));
        assert!(result.text_out().contains("full output at"));
        // Head should contain the first numbers
        assert!(result.text_out().starts_with("1\n"));
    }

    #[tokio::test]
    async fn test_spill_exits_3() {
        use crate::kernel::{Kernel, KernelConfig};

        let config = KernelConfig::mcp()
            .with_output_limit(OutputLimitConfig {
                max_bytes: Some(100),
                head_bytes: 30,
                tail_bytes: 20,
                spill_mode: SpillMode::Disk,
            });
        let kernel = Kernel::new(config).expect("kernel creation");

        let big = "x".repeat(200);
        let result = kernel.execute(&format!("echo '{}'", big)).await.expect("execute");
        assert_eq!(result.code, 3, "spill should always exit 3");
        assert_eq!(result.original_code, Some(0), "original command exit code preserved");
        assert!(result.text_out().contains("[output truncated:"));
    }

    #[tokio::test]
    async fn test_kernel_repl_no_truncation() {
        use crate::kernel::{Kernel, KernelConfig};

        // REPL has no limit
        let config = KernelConfig::repl();
        let kernel = Kernel::new(config).expect("kernel creation");

        let result = kernel.execute("seq 1 100").await.expect("execute");
        assert!(!result.text_out().contains("[output truncated:"));
        assert!(result.text_out().contains("100"));
    }

    #[tokio::test]
    async fn test_kernel_builtin_truncation() {
        use crate::kernel::{Kernel, KernelConfig};

        // Builtins go through post-hoc spill check
        let config = KernelConfig::mcp()
            .with_output_limit(OutputLimitConfig {
                max_bytes: Some(100),
                head_bytes: 30,
                tail_bytes: 20,
                spill_mode: SpillMode::Disk,
            });
        let kernel = Kernel::new(config).expect("kernel creation");

        // echo with a large string
        let big = "x".repeat(200);
        let result = kernel.execute(&format!("echo '{}'", big)).await.expect("execute");
        assert!(result.text_out().contains("[output truncated:"));
    }

    // ── OutputData estimation and streaming tests ──

    #[test]
    fn test_estimated_byte_size_text() {
        use crate::interpreter::OutputData;
        let data = OutputData::text("hello world");
        assert_eq!(data.estimated_byte_size(), 11);
    }

    #[test]
    fn test_estimated_byte_size_table() {
        use crate::interpreter::{OutputData, OutputNode};
        let data = OutputData::table(
            vec!["NAME".into(), "SIZE".into()],
            vec![
                OutputNode::new("foo").with_cells(vec!["123".into()]),
                OutputNode::new("bar").with_cells(vec!["456".into()]),
            ],
        );
        // "foo\t123\nbar\t456" = 3+1+3 + 1 + 3+1+3 = 15
        assert_eq!(data.estimated_byte_size(), 15);
    }

    #[test]
    fn test_estimated_byte_size_tree() {
        use crate::interpreter::{OutputData, OutputNode};
        let data = OutputData::nodes(vec![
            OutputNode::new("src").with_children(vec![
                OutputNode::new("main.rs"),
                OutputNode::new("lib.rs"),
            ]),
        ]);
        // "src/{main.rs,lib.rs}" = 3 + 2 + 7 + 1 + 6 + 1 = 20
        assert_eq!(data.estimated_byte_size(), 20);
    }

    #[test]
    fn test_write_canonical_matches_to_canonical_string() {
        use crate::interpreter::{OutputData, OutputNode};

        let cases: Vec<OutputData> = vec![
            OutputData::text("hello world"),
            OutputData::nodes(vec![
                OutputNode::new("file1"),
                OutputNode::new("file2"),
            ]),
            OutputData::table(
                vec!["NAME".into(), "SIZE".into()],
                vec![
                    OutputNode::new("foo").with_cells(vec!["123".into()]),
                    OutputNode::new("bar").with_cells(vec!["456".into()]),
                ],
            ),
            OutputData::nodes(vec![
                OutputNode::new("src").with_children(vec![
                    OutputNode::new("main.rs"),
                    OutputNode::new("lib.rs"),
                ]),
            ]),
        ];

        for data in cases {
            let expected = data.to_canonical_string();
            let mut buf = Vec::new();
            let written = data.write_canonical(&mut buf, None).unwrap();
            let got = String::from_utf8(buf).unwrap();
            assert_eq!(got, expected, "write_canonical mismatch for {:?}", data);
            assert_eq!(written, expected.len(), "byte count mismatch");
        }
    }

    #[test]
    fn test_write_canonical_budget_stops_early() {
        use crate::interpreter::{OutputData, OutputNode};

        let data = OutputData::nodes(
            (0..1000).map(|i| OutputNode::new(format!("file_{:04}", i))).collect()
        );
        let mut buf = Vec::new();
        let written = data.write_canonical(&mut buf, Some(100)).unwrap();
        // Should have stopped shortly after 100 bytes
        assert!(written > 100, "should exceed budget slightly");
        assert!(written < 500, "should stop soon after budget: got {}", written);
    }

    #[tokio::test]
    async fn test_spill_if_needed_large_output_data_no_oom() {
        use crate::interpreter::{OutputData, OutputNode};

        let config = OutputLimitConfig {
            max_bytes: Some(1024),
            head_bytes: 100,
            tail_bytes: 50,
            spill_mode: SpillMode::Disk,
        };

        // 100K nodes — large enough to detect OOM if materialized carelessly,
        // but small enough to not slow down the test
        let nodes: Vec<OutputNode> = (0..100_000)
            .map(|i| OutputNode::new(format!("node_{:06}", i)))
            .collect();
        let data = OutputData::nodes(nodes);
        let mut result = ExecResult::with_output(data);

        let spill = spill_if_needed(&mut result, &config).await;
        assert!(spill.is_some(), "should have spilled");
        assert!(result.did_spill);
        assert!(result.text_out().contains("[output truncated:"));

        // Clean up
        if let Some(s) = spill {
            let _ = tokio::fs::remove_file(&s.path).await;
        }
    }

    // ── Streaming collector tests (using tokio::io::duplex) ──
    // These exercise `collect_stdout_with_spill`, the child-stdout path, so
    // they live on the `subprocess` axis.

    #[cfg(feature = "subprocess")]
    #[tokio::test]
    async fn test_collect_small_output_no_spill() {
        let (mut writer, reader) = tokio::io::duplex(1024);
        let config = OutputLimitConfig {
            max_bytes: Some(1024),
            head_bytes: 100,
            tail_bytes: 50,
            spill_mode: SpillMode::Disk,
        };

        // Write small data and close
        use tokio::io::AsyncWriteExt;
        writer.write_all(b"hello world").await.unwrap();
        drop(writer); // EOF

        let mut reader = reader;
        let (result, did_spill) = collect_stdout_with_spill(&mut reader, 1024, &config).await;
        assert_eq!(result, "hello world");
        assert!(!did_spill);
    }

    #[cfg(feature = "subprocess")]
    #[tokio::test]
    async fn test_collect_large_output_spills() {
        let (mut writer, reader) = tokio::io::duplex(64 * 1024);
        let config = OutputLimitConfig {
            max_bytes: Some(100),
            head_bytes: 20,
            tail_bytes: 10,
            spill_mode: SpillMode::Disk,
        };

        // Write data exceeding limit and close
        use tokio::io::AsyncWriteExt;
        let data = "x".repeat(500);
        writer.write_all(data.as_bytes()).await.unwrap();
        drop(writer); // EOF

        let mut reader = reader;
        let (result, did_spill) = collect_stdout_with_spill(&mut reader, 100, &config).await;
        assert!(did_spill, "should have spilled");
        assert!(result.contains("[output truncated:"));
        assert!(result.contains("full output at"));
    }

    #[cfg(feature = "subprocess")]
    #[tokio::test]
    async fn test_collect_exact_boundary_no_spill() {
        let (mut writer, reader) = tokio::io::duplex(1024);
        let config = OutputLimitConfig {
            max_bytes: Some(100),
            head_bytes: 20,
            tail_bytes: 10,
            spill_mode: SpillMode::Disk,
        };

        // Write exactly max_bytes
        use tokio::io::AsyncWriteExt;
        let data = "x".repeat(100);
        writer.write_all(data.as_bytes()).await.unwrap();
        drop(writer); // EOF

        let mut reader = reader;
        let (result, did_spill) = collect_stdout_with_spill(&mut reader, 100, &config).await;
        // Exactly at limit — should not spill (<=)
        assert!(!did_spill, "exact boundary should not spill");
        assert_eq!(result.len(), 100);
    }

    #[cfg(feature = "subprocess")]
    #[tokio::test]
    async fn test_collect_broken_pipe() {
        let (writer, reader) = tokio::io::duplex(1024);
        let config = OutputLimitConfig {
            max_bytes: Some(1024),
            head_bytes: 100,
            tail_bytes: 50,
            spill_mode: SpillMode::Disk,
        };

        // Write some data, then drop writer mid-stream
        use tokio::io::AsyncWriteExt;
        let mut writer = writer;
        writer.write_all(b"partial data").await.unwrap();
        drop(writer); // Simulate broken pipe

        let mut reader = reader;
        let (result, did_spill) = collect_stdout_with_spill(&mut reader, 1024, &config).await;
        assert_eq!(result, "partial data");
        assert!(!did_spill);
    }

    // ── In-memory spill mode (SpillMode::Memory) ──

    #[test]
    fn test_in_memory_builder_and_default() {
        assert_eq!(OutputLimitConfig::mcp().spill_mode(), SpillMode::Disk);
        assert_eq!(OutputLimitConfig::mcp().in_memory().spill_mode(), SpillMode::Memory);

        let mut config = OutputLimitConfig::none();
        config.set_spill_mode(SpillMode::Memory);
        assert_eq!(config.spill_mode(), SpillMode::Memory);
    }

    #[tokio::test]
    async fn test_memory_mode_truncates_string_without_disk() {
        let config = OutputLimitConfig {
            max_bytes: Some(100),
            head_bytes: 20,
            tail_bytes: 10,
            spill_mode: SpillMode::Memory,
        };
        let mut result = ExecResult::success("x".repeat(200));
        let spill = spill_if_needed(&mut result, &config).await;

        // No SpillResult (no file written) but did_spill flags the truncation.
        assert!(spill.is_none(), "memory mode must not write a spill file");
        assert!(result.did_spill, "memory truncation must set did_spill for the exit-3 remap");

        let out = result.text_out();
        assert!(out.contains("truncated in memory"), "got: {}", out);
        assert!(out.contains("200 bytes total"), "got: {}", out);
        assert!(!out.contains("full output at"), "memory mode must not point at a file: {}", out);
        assert!(out.starts_with(&"x".repeat(20)), "head preserved");
    }

    #[tokio::test]
    async fn test_memory_mode_under_limit_untouched() {
        let config = OutputLimitConfig {
            max_bytes: Some(100),
            head_bytes: 20,
            tail_bytes: 10,
            spill_mode: SpillMode::Memory,
        };
        let mut result = ExecResult::success("short");
        let spill = spill_if_needed(&mut result, &config).await;
        assert!(spill.is_none());
        assert!(!result.did_spill);
        assert_eq!(&*result.text_out(), "short");
    }

    #[tokio::test]
    async fn test_memory_mode_large_output_data_bounded() {
        use crate::interpreter::{OutputData, OutputNode};

        let config = OutputLimitConfig {
            max_bytes: Some(1024),
            head_bytes: 100,
            tail_bytes: 50,
            spill_mode: SpillMode::Memory,
        };

        // 100K nodes — would be a huge String if fully materialized.
        let nodes: Vec<OutputNode> = (0..100_000)
            .map(|i| OutputNode::new(format!("node_{:06}", i)))
            .collect();
        let mut result = ExecResult::with_output(OutputData::nodes(nodes));

        let spill = spill_if_needed(&mut result, &config).await;
        assert!(spill.is_none(), "memory mode writes no file");
        assert!(result.did_spill);
        let out = result.text_out();
        assert!(out.contains("truncated in memory"), "got: {}", out);
        assert!(out.starts_with("node_000000"), "head rendered: {}", out);
        // Head-only path for oversized structured data: no tail section echoed.
        assert!(out.contains("head only"), "got: {}", out);
    }

    #[tokio::test]
    async fn test_kernel_memory_mode_exits_3_preserves_original() {
        use crate::kernel::{Kernel, KernelConfig};

        let config = KernelConfig::mcp().with_output_limit(OutputLimitConfig {
            max_bytes: Some(100),
            head_bytes: 30,
            tail_bytes: 20,
            spill_mode: SpillMode::Memory,
        });
        let kernel = Kernel::new(config).expect("kernel creation");

        let big = "x".repeat(200);
        let result = kernel.execute(&format!("echo '{}'", big)).await.expect("execute");
        assert_eq!(result.code, 3, "memory truncation still signals via exit 3");
        assert_eq!(result.original_code, Some(0), "original exit code preserved");
        assert!(result.text_out().contains("truncated in memory"));
        assert!(!result.text_out().contains("full output at"));
    }

    #[tokio::test]
    async fn test_nolocal_kernel_forces_memory_spill() {
        use crate::kernel::{Kernel, KernelConfig, VfsMountMode};

        // NoLocal mount + an explicit Disk spill mode: the kernel must override
        // to Memory so nothing is written to a host spill file, even though
        // `localfs` is compiled in.
        let config = KernelConfig::mcp()
            .with_vfs_mode(VfsMountMode::NoLocal)
            .with_output_limit(OutputLimitConfig {
                max_bytes: Some(100),
                head_bytes: 30,
                tail_bytes: 20,
                spill_mode: SpillMode::Disk,
            });
        let kernel = Kernel::new(config).expect("kernel creation");

        let big = "x".repeat(200);
        let result = kernel.execute(&format!("echo '{}'", big)).await.expect("execute");
        assert_eq!(result.code, 3, "still signals truncation via exit 3");
        assert!(result.text_out().contains("truncated in memory"), "got: {}", result.text_out());
        assert!(
            !result.text_out().contains("full output at"),
            "NoLocal kernel must not write a host spill file: {}",
            result.text_out()
        );
    }

    #[cfg(feature = "subprocess")]
    #[tokio::test]
    async fn test_collect_memory_mode_drains_without_disk() {
        let (mut writer, reader) = tokio::io::duplex(64 * 1024);
        let config = OutputLimitConfig {
            max_bytes: Some(100),
            head_bytes: 20,
            tail_bytes: 10,
            spill_mode: SpillMode::Memory,
        };

        use tokio::io::AsyncWriteExt;
        // head 'a's, filler 'b's, tail 'c's so we can check head+tail survive.
        let data = format!("{}{}{}", "a".repeat(20), "b".repeat(500), "c".repeat(10));
        writer.write_all(data.as_bytes()).await.unwrap();
        drop(writer);

        let mut reader = reader;
        let (result, did_spill) = collect_stdout_with_spill(&mut reader, 100, &config).await;
        assert!(did_spill, "drain flags truncation for the exit-3 remap");
        assert!(result.contains("truncated in memory"), "got: {}", result);
        assert!(!result.contains("full output at"), "no disk file in memory mode");
        assert!(result.starts_with(&"a".repeat(20)), "head preserved: {}", result);
        assert!(result.contains(&"c".repeat(10)), "tail preserved: {}", result);
        assert!(result.contains("530 bytes total"), "honest total: {}", result);
    }

    #[cfg(feature = "subprocess")]
    #[test]
    fn test_extend_ring_keeps_last_cap_bytes() {
        let mut ring = std::collections::VecDeque::new();
        super::extend_ring(&mut ring, b"abcdef", 3);
        assert_eq!(ring.iter().copied().collect::<Vec<u8>>(), b"def");
        // Subsequent pushes keep evicting from the front.
        super::extend_ring(&mut ring, b"gh", 3);
        assert_eq!(ring.iter().copied().collect::<Vec<u8>>(), b"fgh");
        // cap 0 retains nothing.
        let mut empty = std::collections::VecDeque::new();
        super::extend_ring(&mut empty, b"xyz", 0);
        assert!(empty.is_empty());
    }
}