bamboo-engine 2026.10.13

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

pub(crate) mod filters;
pub(crate) mod scenarios;
pub(crate) mod tee;

use super::per_call::ToolExecutionOutcome;
use bamboo_agent_core::tools::parse_tool_args_best_effort;

// ── Context Pressure ─────────────────────────────────────────────────────────

/// Current context window pressure, used to adjust compression aggressiveness.
pub(crate) struct ContextPressure {
    /// Current token usage as percentage of compression trigger (0-100).
    pub usage_percent: u8,
    /// Remaining tokens before compression trigger.
    pub remaining_tokens: u32,
}

// ── Compression Tier ────────────────────────────────────────────────────────

/// Tier classification based on output token count.
///
/// Determines which compression strategy to apply:
/// - `Passthrough`: output is small enough to keep as-is
/// - `Light`: ANSI strip + blank collapse + duplicate line collapse
/// - `Standard`: scenario-aware semantic compression
/// - `Aggressive`: Standard + tighter line limits
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CompressionTier {
    Passthrough,
    Light,
    Standard,
    Aggressive,
}

/// Token thresholds for tier classification.
const TIER_LIGHT_TOKENS: u32 = 1_000;
const TIER_STANDARD_TOKENS: u32 = 10_000;
const TIER_AGGRESSIVE_TOKENS: u32 = 25_000;

/// Classify output into a compression tier by token count.
fn classify_tier(text: &str) -> CompressionTier {
    use bamboo_compression::TokenCounter;
    let counter = bamboo_compression::TiktokenTokenCounter::default();
    let tokens = counter.count_text(text);

    if tokens < TIER_LIGHT_TOKENS {
        CompressionTier::Passthrough
    } else if tokens < TIER_STANDARD_TOKENS {
        CompressionTier::Light
    } else if tokens < TIER_AGGRESSIVE_TOKENS {
        CompressionTier::Standard
    } else {
        CompressionTier::Aggressive
    }
}

/// Adjust compression tier based on context pressure.
///
/// - Low pressure (< 50%): only compress Standard and above
/// - Normal pressure (50-80%): compress Light and above
/// - High pressure (> 80%): compress everything, promote Light → Standard
fn adjust_tier_for_pressure(
    tier: CompressionTier,
    pressure: Option<&ContextPressure>,
) -> CompressionTier {
    let Some(p) = pressure else {
        return tier; // no pressure info → use base tier
    };

    match p.usage_percent {
        0..=49 => {
            // Low pressure: skip Light tier (only compress Standard+)
            match tier {
                CompressionTier::Light => CompressionTier::Passthrough,
                other => other,
            }
        }
        50..=80 => {
            // Normal pressure: use base tier as-is
            tier
        }
        _ => {
            // High pressure: promote Light → Standard for more aggressive compression
            match tier {
                CompressionTier::Light => CompressionTier::Standard,
                other => other,
            }
        }
    }
}

/// Apply light-weight compression (ANSI strip + blank collapse + dedup).
fn apply_light_compression(raw_result: &str) -> CompressionResult {
    // For JSON Bash envelopes, apply to stdout/stderr separately
    let parsed: serde_json::Value = match serde_json::from_str(raw_result) {
        Ok(v) => v,
        Err(_) => {
            // Plain text
            let clean = filters::strip_ansi(raw_result);
            let collapsed = filters::collapse_blank_lines(&clean);
            let deduped = filters::collapse_duplicate_lines(&collapsed, 3);
            let was_compressed = deduped.len() != raw_result.len();
            return CompressionResult {
                compressed: deduped,
                was_compressed,
            };
        }
    };

    let stdout = parsed.get("stdout").and_then(|v| v.as_str()).unwrap_or("");
    let stderr = parsed.get("stderr").and_then(|v| v.as_str()).unwrap_or("");

    let clean_stdout = filters::strip_ansi(stdout);
    let clean_stderr = filters::strip_ansi(stderr);
    let collapsed_stdout = filters::collapse_blank_lines(&clean_stdout);
    let collapsed_stderr = filters::collapse_blank_lines(&clean_stderr);
    let deduped_stdout = filters::collapse_duplicate_lines(&collapsed_stdout, 3);
    let deduped_stderr = filters::collapse_duplicate_lines(&collapsed_stderr, 3);

    let was_compressed = deduped_stdout.len() != stdout.len()
        || deduped_stderr.len() != stderr.len()
        || clean_stdout.len() != stdout.len()
        || clean_stderr.len() != stderr.len();

    if !was_compressed {
        return CompressionResult {
            compressed: raw_result.to_string(),
            was_compressed: false,
        };
    }

    // Rebuild JSON
    let mut obj = parsed.clone();
    if let Some(map) = obj.as_object_mut() {
        map.insert(
            "stdout".to_string(),
            serde_json::Value::String(deduped_stdout),
        );
        map.insert(
            "stderr".to_string(),
            serde_json::Value::String(deduped_stderr),
        );
    }
    let compressed = serde_json::to_string(&obj).unwrap_or_else(|_| raw_result.to_string());

    CompressionResult {
        compressed,
        was_compressed: true,
    }
}

// ── Scenario Detection ──────────────────────────────────────────────────────

/// High-level classification of a tool's output so the correct compression
/// strategy can be selected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum OutputScenario {
    /// `cargo test`, `pytest`, `npm test`, `vitest`, `jest`, etc.
    BashTest,
    /// `tsc`, `eslint`, `cargo check`, `cargo clippy`, etc.
    BashBuild,
    /// `git status`, `git diff`, `git log`, etc.
    BashGit,
    /// `npm install`, `cargo build`, `pip install`, etc.
    BashPackage,
    /// Any other Bash command.
    BashGeneric,
    /// `Read` tool output (code files).
    ReadCode,
    /// `Grep` tool output.
    GrepResults,
    /// `WebFetch` tool output.
    WebFetchHtml,
    /// Everything else — no compression applied.
    PassThrough,
}

/// Detect the output scenario from the tool name and (optionally) the command
/// embedded in the Bash JSON arguments.
pub(crate) fn detect_scenario(tool_name: &str, args_json: &str) -> OutputScenario {
    match tool_name {
        "Bash" | "BashOutput" => detect_bash_scenario(args_json),
        "Read" | "read_file" => OutputScenario::ReadCode,
        "Grep" => OutputScenario::GrepResults,
        "WebFetch" => OutputScenario::WebFetchHtml,
        _ => OutputScenario::PassThrough,
    }
}

/// Sub-classifier for Bash / BashOutput tools.
fn detect_bash_scenario(args_json: &str) -> OutputScenario {
    let command = extract_command(args_json);
    let cmd = command.trim();

    if is_test_command(cmd) {
        OutputScenario::BashTest
    } else if is_build_command(cmd) {
        OutputScenario::BashBuild
    } else if is_git_command(cmd) {
        OutputScenario::BashGit
    } else if is_package_command(cmd) {
        OutputScenario::BashPackage
    } else {
        OutputScenario::BashGeneric
    }
}

/// Extract the `command` field from a Bash JSON arguments string.
fn extract_command(args_json: &str) -> String {
    serde_json::from_str::<serde_json::Value>(args_json)
        .ok()
        .and_then(|v| v.get("command").and_then(|c| c.as_str()).map(String::from))
        .unwrap_or_default()
}

fn is_test_command(cmd: &str) -> bool {
    let patterns = [
        "cargo test",
        "cargo nextest",
        "pytest",
        "python -m pytest",
        "npm test",
        "npm run test",
        "npx vitest",
        "npx jest",
        "yarn test",
        "pnpm test",
        "go test",
        "dotnet test",
        "mvn test",
        "gradle test",
        "./gradlew test",
        "phpunit",
        "rspec",
        "bundle exec rspec",
    ];
    patterns.iter().any(|p| cmd_contains(cmd, p))
}

fn is_build_command(cmd: &str) -> bool {
    let patterns = [
        // Rust
        "cargo check",
        "cargo clippy",
        "cargo build",
        // JavaScript / TypeScript
        "tsc",
        "eslint",
        "npm run build",
        "npm run lint",
        "npx tsc",
        // Go
        "go build",
        "go vet",
        // .NET
        "dotnet build",
        "dotnet publish",
        // Maven
        "mvn compile",
        "mvn package",
        "mvn verify",
        "mvn install",
        "mvn clean",
        "mvn deploy",
        "mvn site",
        // Gradle
        "gradle build",
        "gradle assemble",
        "gradle compileJava",
        "gradle compileKotlin",
        "./gradlew build",
        "./gradlew assemble",
        "./gradlew compileJava",
        // Docker
        "docker build",
        "docker compose build",
        "docker-compose build",
        // Terraform
        "terraform plan",
        "terraform apply",
        "terraform init",
    ];
    patterns.iter().any(|p| cmd_contains(cmd, p))
}

fn is_git_command(cmd: &str) -> bool {
    let patterns = [
        "git status",
        "git diff",
        "git log",
        "git show",
        "git branch",
        "git stash",
    ];
    patterns.iter().any(|p| cmd_contains(cmd, p))
}

fn is_package_command(cmd: &str) -> bool {
    let patterns = [
        // JavaScript
        "npm install",
        "npm ci",
        "yarn install",
        "yarn add",
        "pnpm install",
        "pnpm add",
        // Python
        "pip install",
        "pip3 install",
        "poetry install",
        // Rust
        "cargo install",
        // Go
        "go mod download",
        "go mod tidy",
        "go get ",
        // PHP
        "composer install",
        "composer update",
        "composer require",
        // Ruby
        "bundle install",
        "bundler install",
        "gem install",
        // System
        "apt install",
        "apt-get install",
        "brew install",
        // Maven / Gradle deps
        "mvn dependency:",
        "gradle dependencies",
        "./gradlew dependencies",
        // .NET
        "dotnet restore",
        "nuget install",
    ];
    patterns.iter().any(|p| cmd_contains(cmd, p))
}

/// Check whether `cmd` contains the pattern, accounting for leading pipes,
/// `&&`, `||`, `cd dir &&`, etc.
fn cmd_contains(cmd: &str, pattern: &str) -> bool {
    // Simple substring match is sufficient for Phase 1.
    // We match against the full command text which catches piped / chained
    // commands too (e.g. `cd foo && cargo test`).
    cmd.contains(pattern)
}

// ── Main Entry Point ────────────────────────────────────────────────────────

/// Outcome of the compression pipeline.
pub(crate) struct CompressionResult {
    /// The (potentially) compressed result string to replace `ToolResult.result`.
    pub compressed: String,
    /// Whether any compression was actually applied.
    pub was_compressed: bool,
}

/// Terminal handles and final status are protocol fields. A global output cap
/// may shrink captured text, but must never make the next poll impossible.
pub(super) fn truncate_exec_session_output(
    raw_result: &str,
    max_tokens: u32,
    counter: &bamboo_compression::TiktokenTokenCounter,
) -> Option<String> {
    use bamboo_compression::TokenCounter;

    let mut payload = serde_json::from_str::<serde_json::Value>(raw_result).ok()?;
    let object = payload.as_object_mut()?;
    if !matches!(
        object.get("status").and_then(serde_json::Value::as_str),
        Some("running" | "completed" | "killed" | "error")
    ) {
        return None;
    }
    let output = object.get("output")?.as_str()?.to_owned();
    let prior_omitted = object
        .get("output_omitted_bytes")
        .and_then(serde_json::Value::as_u64)
        .unwrap_or(0);
    object.insert("output".into(), serde_json::json!(""));
    object.insert(
        "output_omitted_bytes".into(),
        serde_json::json!(prior_omitted.saturating_add(output.len() as u64)),
    );
    let mut kept = serde_json::to_string(object).expect("terminal result is serializable");
    if counter.count_text(&kept) > max_tokens {
        // Hook context is optional; it cannot acquire the required terminal
        // metadata exception merely by living inside the JSON envelope.
        if let Some(feedback) = object.remove("hook_feedback") {
            let omitted = feedback
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(serde_json::Value::as_str)
                .fold(0_u64, |bytes, text| bytes.saturating_add(text.len() as u64));
            let prior = object
                .get("hook_feedback_omitted_bytes")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(0);
            object.insert(
                "hook_feedback_omitted_bytes".into(),
                serde_json::json!(prior.saturating_add(omitted)),
            );
            kept = serde_json::to_string(object).expect("terminal result is serializable");
        }
    }
    if counter.count_text(&kept) > max_tokens && object.remove("polling").is_some() {
        // Progress/advisory data is optional. It cannot inherit the exception
        // that protects a continuation handle or a real terminal status.
        kept = serde_json::to_string(object).expect("terminal result is serializable");
    }
    if counter.count_text(&kept) > max_tokens {
        // Even a tiny budget must retain fixed metadata, including an error or
        // session handle. The output itself is still reduced to zero bytes.
        return Some(kept);
    }
    let mut render = |end: usize| {
        object.insert("output".into(), serde_json::json!(&output[..end]));
        object.insert(
            "output_omitted_bytes".into(),
            serde_json::json!(prior_omitted.saturating_add((output.len() - end) as u64)),
        );
        serde_json::to_string(object).expect("terminal result is serializable")
    };
    let mut low = 0;
    let mut high = output.len();
    while low <= high {
        let midpoint = low + (high - low) / 2;
        let mut end = midpoint;
        while !output.is_char_boundary(end) {
            end -= 1;
        }
        let candidate = render(end);
        if counter.count_text(&candidate) <= max_tokens {
            kept = candidate;
            low = midpoint + 1;
        } else if midpoint == 0 {
            break;
        } else {
            high = midpoint - 1;
        }
    }
    Some(kept)
}

/// Compress a `ToolExecutionOutcome` in-place.
///
/// Returns the same outcome with the `ToolResult.result` potentially replaced
/// by a compressed version.  If no compression is needed the outcome is
/// returned unchanged.
pub(super) async fn maybe_compress(
    tool_name: &str,
    args_json: &str,
    session_id: &str,
    mut outcome: ToolExecutionOutcome,
    max_tool_output_tokens: u32,
    context_pressure: Option<ContextPressure>,
    task_hint: Option<&TaskCompressionHint>,
) -> ToolExecutionOutcome {
    let execution_name = outcome
        .portable_tool
        .as_ref()
        .map(|tool| tool.execution_name())
        .unwrap_or(tool_name);
    let exec_session = matches!(execution_name, "exec_command" | "write_stdin");
    let result = match outcome.result {
        Ok(ref mut result) => result,
        Err(_) => return outcome, // error path — never compress
    };

    let scenario = detect_scenario(tool_name, args_json);
    if scenario != OutputScenario::PassThrough {
        let original = result.result.clone();
        let base_tier = classify_tier(&original);
        let tier = adjust_tier_for_pressure(base_tier, context_pressure.as_ref());

        let compressed = match tier {
            CompressionTier::Passthrough => CompressionResult {
                compressed: original.clone(),
                was_compressed: false,
            },
            CompressionTier::Light => apply_light_compression(&original),
            CompressionTier::Standard | CompressionTier::Aggressive => {
                compress_by_scenario(scenario, &original, args_json, tier)
            }
        };

        if compressed.was_compressed {
            // Recovery files screen output and never receive command arguments.
            let tee_note =
                tee::tee_save_if_needed(session_id, &original, &compressed.compressed).await;

            // Replace result with compressed version (+ optional tee note).
            result.result = match tee_note {
                Some(note) => format!("{}\n\n{}", compressed.compressed, note),
                None => compressed.compressed,
            };
        }
    }

    // Enforce hard token ceiling if configured.
    if max_tool_output_tokens > 0 {
        use bamboo_compression::TokenCounter;
        let counter = bamboo_compression::TiktokenTokenCounter::default();
        let tokens = counter.count_text(&result.result);
        if tokens > max_tool_output_tokens {
            if exec_session {
                if let Some(truncated) =
                    truncate_exec_session_output(&result.result, max_tool_output_tokens, &counter)
                {
                    result.result = truncated;
                    return outcome;
                }
            }
            let browser_download = tool_name
                .trim()
                .rsplit("::")
                .next()
                .is_some_and(|name| name.eq_ignore_ascii_case("browser"))
                && parse_tool_args_best_effort(args_json)
                    .0
                    .get("action")
                    .and_then(serde_json::Value::as_str)
                    == Some("download");
            if result.success
                && browser_download
                && serde_json::from_str::<serde_json::Value>(&result.result)
                    .ok()
                    .is_some_and(|payload| {
                        payload
                            .get("data_base64")
                            .and_then(serde_json::Value::as_str)
                            .is_some()
                    })
            {
                // A generic textual truncation corrupts the Base64 and can
                // leave a successful download with invalid JSON. The bytes
                // have already been cleaned up by the host, so report a
                // bounded failure and let the model request a smaller file.
                result.success = false;
                result.result = serde_json::json!({
                    "error":"download_result_exceeds_tool_output_budget",
                    "message":"Browser download bytes exceed the configured tool output token budget",
                    "limit_tokens":max_tool_output_tokens,
                })
                .to_string();
                return outcome;
            }
            let truncated = truncate_to_token_budget(
                &result.result,
                max_tool_output_tokens,
                &counter,
                task_hint,
            );
            tracing::info!(
                "[{}] Tool output truncated: {} tokens > {} limit, {} chars → {} chars",
                session_id,
                tokens,
                max_tool_output_tokens,
                result.result.len(),
                truncated.len(),
            );
            result.result = truncated;
        }
    }

    outcome
}

/// Task-aware compression hint: significant terms from the ACTIVE task's
/// completion criteria (+ description). When a tool output must be truncated to
/// fit the token budget, lines matching any term are preferentially preserved so
/// task-relevant evidence (e.g. the criterion the agent is verifying) survives
/// the cut. Built once per round from the `TaskLoopContext`
/// (see `build_task_compression_hint`). This is the Phase-4 "task-aware" masking:
/// truncation is biased toward what the active task needs, not just head/tail.
#[derive(Debug, Clone, Default)]
pub(crate) struct TaskCompressionHint {
    keywords: Vec<String>,
}

impl TaskCompressionHint {
    /// Build from raw phrases (criteria / description): split into lowercased
    /// significant terms (≥4 chars), deduped, capped.
    pub(crate) fn from_phrases<I: IntoIterator<Item = String>>(phrases: I) -> Self {
        let mut keywords: Vec<String> = Vec::new();
        'outer: for phrase in phrases {
            for term in phrase.split(|c: char| !c.is_alphanumeric()) {
                let term = term.trim().to_lowercase();
                if term.len() >= 4 && !keywords.contains(&term) {
                    keywords.push(term);
                }
                if keywords.len() >= 32 {
                    break 'outer;
                }
            }
        }
        Self { keywords }
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.keywords.is_empty()
    }

    fn matches(&self, line: &str) -> bool {
        let lower = line.to_lowercase();
        self.keywords.iter().any(|k| lower.contains(k.as_str()))
    }
}

/// Collect up to `max_tokens` worth of lines from `text` that match the task
/// hint, for preservation when the output is otherwise truncated. Returns `None`
/// when no lines match (or the hint is empty).
fn collect_task_relevant_lines(
    text: &str,
    hint: &TaskCompressionHint,
    max_tokens: u32,
    counter: &bamboo_compression::TiktokenTokenCounter,
) -> Option<String> {
    use bamboo_compression::TokenCounter;
    if hint.is_empty() || max_tokens == 0 {
        return None;
    }
    let mut kept: Vec<&str> = Vec::new();
    let mut used = 0u32;
    for line in text.lines() {
        if !hint.matches(line) {
            continue;
        }
        let cost = counter.count_text(line).saturating_add(1);
        if used.saturating_add(cost) > max_tokens {
            break;
        }
        used += cost;
        kept.push(line);
        if kept.len() >= 50 {
            break;
        }
    }
    if kept.is_empty() {
        None
    } else {
        Some(kept.join("\n"))
    }
}

/// Truncate text to fit within a token budget by keeping head + tail portions.
///
/// When a [`TaskCompressionHint`] is present AND some lines in the dropped middle
/// match it, a slice of the budget is reserved to preserve those task-relevant
/// lines (Phase-4 task-aware masking). With no hint (or no match) the behaviour
/// is the original 70/30 head/tail split, byte-for-byte.
fn truncate_to_token_budget(
    text: &str,
    max_tokens: u32,
    counter: &bamboo_compression::TiktokenTokenCounter,
    task_hint: Option<&TaskCompressionHint>,
) -> String {
    use bamboo_compression::TokenCounter;

    let preserved = task_hint.filter(|hint| !hint.is_empty()).and_then(|hint| {
        collect_task_relevant_lines(text, hint, (max_tokens as f64 * 0.15) as u32, counter)
    });

    if let Some(lines) = preserved {
        // Reserve ~15% of the budget for task-relevant lines and shrink head/tail
        // to 0.5/0.2, leaving ~15% headroom for the truncation marker + role/
        // newline boilerplate so the assembled output stays within `max_tokens`
        // (head + tail are sliced from the full text, so their sum must stay
        // comfortably under budget rather than at it).
        let head_tokens = (max_tokens as f64 * 0.5) as u32;
        let tail_tokens = (max_tokens as f64 * 0.2) as u32;
        let head = find_prefix_within_tokens(text, head_tokens, counter);
        let tail = find_suffix_within_tokens(text, tail_tokens, counter);
        return format!(
            "{}\n\n[... tool output truncated: {} tokens → {} token budget; task-relevant lines preserved ...]\n{}\n\n{}",
            head,
            counter.count_text(text),
            max_tokens,
            lines,
            tail,
        );
    }

    let head_tokens = (max_tokens as f64 * 0.7) as u32;
    let tail_tokens = max_tokens.saturating_sub(head_tokens);

    let head = find_prefix_within_tokens(text, head_tokens, counter);
    let tail = find_suffix_within_tokens(text, tail_tokens, counter);

    format!(
        "{}\n\n[... tool output truncated: {} tokens → {} token budget ...]\n\n{}",
        head,
        counter.count_text(text),
        max_tokens,
        tail,
    )
}

/// Keep the START of `text`, capped at `max_tokens` tokens.
///
/// Delegates to [`TiktokenTokenCounter::truncate_to_token_prefix`], which
/// encodes the text **once** and decodes the first `max_tokens` tokens back to a
/// string — O(N) — instead of the O(N²) char-by-char re-tokenization this used
/// to perform (`count_text(&text[..i])` on every char index). See issue #24.
fn find_prefix_within_tokens(
    text: &str,
    max_tokens: u32,
    counter: &bamboo_compression::TiktokenTokenCounter,
) -> String {
    counter.truncate_to_token_prefix(text, max_tokens)
}

/// Keep the END of `text`, capped at `max_tokens` tokens.
///
/// Delegates to [`TiktokenTokenCounter::truncate_to_token_suffix`] (O(N),
/// encode-once). See [`find_prefix_within_tokens`] and issue #24.
fn find_suffix_within_tokens(
    text: &str,
    max_tokens: u32,
    counter: &bamboo_compression::TiktokenTokenCounter,
) -> String {
    counter.truncate_to_token_suffix(text, max_tokens)
}

/// Dispatch to the appropriate scenario compressor.
fn compress_by_scenario(
    scenario: OutputScenario,
    raw_result: &str,
    _args_json: &str,
    tier: CompressionTier,
) -> CompressionResult {
    match scenario {
        OutputScenario::BashTest => scenarios::bash_test::compress(raw_result, tier),
        OutputScenario::BashBuild => scenarios::bash_build::compress(raw_result, tier),
        OutputScenario::BashGit => scenarios::bash_git::compress(raw_result, tier),
        OutputScenario::BashPackage => scenarios::bash_package::compress(raw_result, tier),
        OutputScenario::BashGeneric => scenarios::bash_generic::compress(raw_result, tier),
        OutputScenario::ReadCode => scenarios::read_code::compress(raw_result, tier),
        OutputScenario::GrepResults => scenarios::grep_results::compress(raw_result, tier),
        OutputScenario::WebFetchHtml => scenarios::web_fetch::compress(raw_result, tier),
        OutputScenario::PassThrough => CompressionResult {
            compressed: raw_result.to_string(),
            was_compressed: false,
        },
    }
}

// ── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::super::policy::{ToolPolicyGuard, ToolPolicyPrecheckViolation};
    use super::*;
    use bamboo_agent_core::tools::{FunctionCall, ToolCall, ToolResult};

    // Declare the identity retained after executor selection, without changing
    // the pre-promotion model catalog or testing admission in this fixture.
    fn selected_tool_identity(
        execution_name: &str,
    ) -> Option<super::super::per_call::PortableToolExecution> {
        Some(
            super::super::per_call::PortableToolExecution::selected_identity_fixture(
                execution_name,
            ),
        )
    }

    #[tokio::test]
    async fn exec_session_caps_preserve_protocol_fields_and_count_omitted_utf8_bytes() {
        use bamboo_compression::{TiktokenTokenCounter, TokenCounter};
        let counter = TiktokenTokenCounter::default();
        let text = "界🦀\n\"\\variable output ".repeat(500);
        for (name, execution_name) in [
            ("exec_command", "exec_command"),
            ("write_stdin", "write_stdin"),
            ("default::exec_command", "exec_command"),
            ("default::write_stdin", "write_stdin"),
        ] {
            for status in ["running", "completed", "killed", "error"] {
                let mut payload = serde_json::json!({
                    "status":status,
                    "output":text,
                    "output_omitted_bytes":7,
                });
                if status == "running" {
                    payload["session_id"] = "retained-exec-handle".into();
                } else if status == "completed" {
                    payload["exit_code"] = 7.into();
                } else if status == "error" {
                    payload["error"] =
                        "Output capture failed; final status remains available".into();
                }
                let raw = payload.to_string();
                let mut expected_control = payload.clone();
                expected_control.as_object_mut().unwrap().remove("output");
                expected_control
                    .as_object_mut()
                    .unwrap()
                    .remove("output_omitted_bytes");
                for cap in [0, 1, 32, 96, 512] {
                    let outcome = ToolExecutionOutcome {
                        output_cap: None,
                        permission_replay_origin: None,
                        result: Ok(ToolResult::text(true, raw.clone())),
                        needs_human: None,
                        portable_tool: selected_tool_identity(execution_name),
                        post_tool_hook_eligible: true,
                        managed_running_violation: false,
                        tool_duration: std::time::Duration::ZERO,
                    };
                    let result = maybe_compress(name, "{}", "exec-cap", outcome, cap, None, None)
                        .await
                        .result
                        .unwrap();
                    assert!(result.success);
                    let mut received: serde_json::Value =
                        serde_json::from_str(&result.result).unwrap();
                    let kept = received["output"].as_str().unwrap();
                    assert!(text.starts_with(kept));
                    assert_eq!(
                        received["output_omitted_bytes"].as_u64().unwrap(),
                        7 + (text.len() - kept.len()) as u64
                    );
                    if cap == 0 {
                        assert_eq!(result.result, raw);
                    } else if counter.count_text(&result.result) > cap {
                        assert!(kept.is_empty(), "only fixed metadata may exceed the cap");
                    } else if cap == 512 {
                        assert!(!kept.is_empty(), "available output budget should be used");
                    }
                    received.as_object_mut().unwrap().remove("output");
                    received
                        .as_object_mut()
                        .unwrap()
                        .remove("output_omitted_bytes");
                    assert_eq!(received, expected_control);
                }
            }
        }
    }

    #[tokio::test]
    async fn exec_session_cap_exception_does_not_apply_to_foreign_names_or_other_json() {
        let terminal = serde_json::json!({"status":"running", "session_id":"foreign", "output":"variable output ".repeat(500)}).to_string();
        let approval = serde_json::json!({"status":"awaiting_permission_approval", "output":"variable output ".repeat(500)}).to_string();
        for (name, raw) in [
            ("vendor::exec_command", &terminal),
            ("vendor::write_stdin", &terminal),
            ("exec_command", &approval),
        ] {
            let outcome = ToolExecutionOutcome {
                output_cap: None,
                permission_replay_origin: None,
                result: Ok(ToolResult::text(true, raw.clone())),
                needs_human: None,
                portable_tool: selected_tool_identity(name),
                post_tool_hook_eligible: true,
                managed_running_violation: false,
                tool_duration: std::time::Duration::ZERO,
            };
            let result = maybe_compress(name, "{}", "other-cap", outcome, 1, None, None)
                .await
                .result
                .unwrap();
            assert!(result.result.contains("tool output truncated"));
        }
    }

    #[test]
    fn exec_session_caps_drop_optional_polling_before_required_metadata_exception() {
        use bamboo_compression::{TiktokenTokenCounter, TokenCounter};

        let counter = TiktokenTokenCounter::default();
        let output = "captured output 界🦀 ".repeat(500);
        let polling = serde_json::json!({
            "elapsed_ms":90_000, "output_idle_ms":90_000,
            "consecutive_empty_readouts":3, "exit_observed":false,
            "advisory":"No new output across repeated polls. Check a command-owned progress signal before polling again; silence does not prove completion.",
        });
        let payload = serde_json::json!({
            "status":"running", "session_id":"retained-handle", "output":output,
            "polling":polling,
        });
        for cap in [1, 32, 128, 512] {
            let compressed =
                truncate_exec_session_output(&payload.to_string(), cap, &counter).unwrap();
            let received: serde_json::Value = serde_json::from_str(&compressed).unwrap();
            assert_eq!(received["status"], "running");
            assert_eq!(received["session_id"], "retained-handle");
            let kept = received["output"].as_str().unwrap();
            assert!(output.starts_with(kept));
            assert_eq!(received["output_omitted_bytes"], output.len() - kept.len());
            if counter.count_text(&compressed) > cap {
                assert!(kept.is_empty());
                assert!(received.get("polling").is_none());
            }
            if cap == 1 {
                assert!(received.get("polling").is_none());
            } else if cap == 512 {
                assert_eq!(received["polling"], polling);
                assert!(counter.count_text(&compressed) <= cap);
            }
        }
    }

    #[test]
    fn exec_session_caps_drop_optional_feedback_before_required_metadata_exception() {
        use bamboo_compression::{TiktokenTokenCounter, TokenCounter};

        let counter = TiktokenTokenCounter::default();
        for feedback in ["review detail".to_owned(), "review 界🦀 ".repeat(1_000)] {
            for cap in [1, 256] {
                let output = "captured output ".repeat(1_000);
                let payload = serde_json::json!({
                    "status":"running", "session_id":"retained-handle", "output":output,
                    "hook_feedback":[feedback], "hook_feedback_omitted_bytes":13,
                });
                let compressed =
                    truncate_exec_session_output(&payload.to_string(), cap, &counter).unwrap();
                let received: serde_json::Value = serde_json::from_str(&compressed).unwrap();
                assert_eq!(received["status"], "running");
                assert_eq!(received["session_id"], "retained-handle");
                let retained = received["hook_feedback"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .map(|text| text.as_str().unwrap().len())
                    .sum::<usize>();
                assert_eq!(
                    received["hook_feedback_omitted_bytes"].as_u64().unwrap() as usize + retained,
                    13 + feedback.len()
                );
                let kept = received["output"].as_str().unwrap();
                assert_eq!(received["output_omitted_bytes"], output.len() - kept.len());
                if cap == 1 {
                    assert!(kept.is_empty());
                    assert!(received.get("hook_feedback").is_none());
                } else {
                    assert!(counter.count_text(&compressed) <= cap);
                    assert_eq!(
                        received.get("hook_feedback").is_some(),
                        feedback.len() < 100
                    );
                }
            }
        }
    }

    #[tokio::test]
    async fn browser_download_over_tool_budget_returns_valid_no_bytes_failure() {
        let raw = serde_json::json!({
            "page_epoch":17,
            "active_tab_id":"tab-1",
            "url":"https://example.test/",
            "filename":"archive.bin",
            "byte_count":12288,
            "sha256":"a".repeat(64),
            "data_base64":"QUJD".repeat(4096),
        })
        .to_string();
        let args = r##"{"action":"download","selector":"#link","expected_epoch":17}"##;
        let outcome = || ToolExecutionOutcome {
            output_cap: None,
            permission_replay_origin: None,
            result: Ok(ToolResult::text(true, raw.clone())),
            needs_human: None,
            portable_tool: None,
            post_tool_hook_eligible: true,
            managed_running_violation: false,
            tool_duration: std::time::Duration::ZERO,
        };
        for tool_name in ["browser", "default::browser"] {
            for arguments in [
                args,
                r##"{"action":"download","selector":"#link","expected_epoch":17"##,
            ] {
                let output = maybe_compress(
                    tool_name,
                    arguments,
                    "test-session",
                    outcome(),
                    128,
                    None,
                    None,
                )
                .await;
                let result = output.result.unwrap();
                assert!(
                    !result.success,
                    "an over-budget download must not look successful"
                );
                let payload: serde_json::Value = serde_json::from_str(&result.result).unwrap();
                assert_eq!(
                    payload["error"],
                    "download_result_exceeds_tool_output_budget"
                );
                assert_eq!(payload["limit_tokens"], 128);
                assert!(payload.get("data_base64").is_none());
            }
        }

        let unlimited = maybe_compress("browser", args, "test-session", outcome(), 0, None, None)
            .await
            .result
            .unwrap();
        assert!(unlimited.success);
        assert_eq!(unlimited.result, raw);

        let other_action = maybe_compress(
            "browser",
            r#"{"action":"snapshot"}"#,
            "test-session",
            outcome(),
            128,
            None,
            None,
        )
        .await
        .result
        .unwrap();
        assert!(other_action.success);
        assert_ne!(other_action.result, raw);
    }

    #[tokio::test]
    async fn over_budget_downloads_open_the_three_failure_circuit() {
        let args = r##"{"action":"download","selector":"#link","expected_epoch":17"##;
        let call = ToolCall {
            id: "download-call".into(),
            tool_type: "function".into(),
            function: FunctionCall {
                name: "default::browser".into(),
                arguments: args.into(),
            },
        };
        let mut guard = ToolPolicyGuard::default();
        for _ in 0..3 {
            guard.check_before_execution(&call, 0).unwrap();
            let raw = serde_json::json!({ "data_base64": "QUJD".repeat(4096) }).to_string();
            let outcome = ToolExecutionOutcome {
                output_cap: None,
                permission_replay_origin: None,
                result: Ok(ToolResult::text(true, raw)),
                needs_human: None,
                portable_tool: None,
                post_tool_hook_eligible: true,
                managed_running_violation: false,
                tool_duration: std::time::Duration::ZERO,
            };
            let compressed = maybe_compress(
                "default::browser",
                args,
                "test-session",
                outcome,
                128,
                None,
                None,
            )
            .await;
            assert!(!compressed.result.as_ref().unwrap().success);
            guard.observe_outcome(&call, &compressed.result);
        }
        assert!(matches!(
            guard.check_before_execution(&call, 0),
            Err(ToolPolicyPrecheckViolation::ToolCircuitOpen {
                consecutive_failures: 3,
                ..
            })
        ));
    }

    #[test]
    fn detect_cargo_test() {
        let args = r#"{"command": "cargo test --workspace"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashTest);
    }

    #[test]
    fn detect_npm_test() {
        let args = r#"{"command": "npm test"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashTest);
    }

    #[test]
    fn detect_pytest() {
        let args = r#"{"command": "cd myproject && pytest -v"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashTest);
    }

    #[test]
    fn detect_cargo_check() {
        let args = r#"{"command": "cargo check"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashBuild);
    }

    #[test]
    fn detect_cargo_clippy() {
        let args = r#"{"command": "cargo clippy -- -D warnings"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashBuild);
    }

    #[test]
    fn detect_git_status() {
        let args = r#"{"command": "git status"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashGit);
    }

    #[test]
    fn detect_git_diff() {
        let args = r#"{"command": "git diff --stat"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashGit);
    }

    #[test]
    fn detect_npm_install() {
        let args = r#"{"command": "npm install"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashPackage);
    }

    #[test]
    fn detect_generic_bash() {
        let args = r#"{"command": "ls -la"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashGeneric);
    }

    #[test]
    fn detect_chained_cargo_test() {
        let args = r#"{"command": "cd bamboo && cargo test --lib"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashTest);
    }

    #[test]
    fn detect_read_tool() {
        assert_eq!(detect_scenario("Read", "{}"), OutputScenario::ReadCode);
        assert_eq!(detect_scenario("read_file", "{}"), OutputScenario::ReadCode);
    }

    #[test]
    fn detect_grep_tool() {
        assert_eq!(detect_scenario("Grep", "{}"), OutputScenario::GrepResults);
    }

    #[test]
    fn detect_webfetch_tool() {
        assert_eq!(
            detect_scenario("WebFetch", "{}"),
            OutputScenario::WebFetchHtml
        );
    }

    #[test]
    fn detect_passthrough_tools() {
        assert_eq!(detect_scenario("Edit", "{}"), OutputScenario::PassThrough);
        assert_eq!(detect_scenario("Write", "{}"), OutputScenario::PassThrough);
        assert_eq!(detect_scenario("Task", "{}"), OutputScenario::PassThrough);
        assert_eq!(
            detect_scenario("conclusion_with_options", "{}"),
            OutputScenario::PassThrough
        );
    }

    #[test]
    fn detect_invalid_args_json() {
        // Invalid JSON should fall through gracefully
        assert_eq!(
            detect_scenario("Bash", "not-json"),
            OutputScenario::BashGeneric
        );
    }

    // ── Maven command detection ──

    #[test]
    fn detect_mvn_compile() {
        let args = r#"{"command": "mvn compile"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashBuild);
    }

    #[test]
    fn detect_mvn_clean_install() {
        let args = r#"{"command": "mvn clean install -DskipTests"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashBuild);
    }

    #[test]
    fn detect_mvn_package() {
        let args = r#"{"command": "mvn package -Dmaven.test.skip=true"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashBuild);
    }

    #[test]
    fn detect_mvn_verify() {
        let args = r#"{"command": "mvn verify"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashBuild);
    }

    #[test]
    fn detect_mvn_test() {
        let args = r#"{"command": "mvn test"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashTest);
    }

    #[test]
    fn detect_mvn_dependency() {
        let args = r#"{"command": "mvn dependency:tree"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashPackage);
    }

    // ── Gradle / Docker / Terraform detection ──

    #[test]
    fn detect_gradle_build() {
        let args = r#"{"command": "gradle build"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashBuild);
    }

    #[test]
    fn detect_gradlew_build() {
        let args = r#"{"command": "./gradlew build"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashBuild);
    }

    #[test]
    fn detect_gradlew_test() {
        let args = r#"{"command": "./gradlew test"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashTest);
    }

    #[test]
    fn detect_docker_build() {
        let args = r#"{"command": "docker build -t myapp ."}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashBuild);
    }

    #[test]
    fn detect_terraform_plan() {
        let args = r#"{"command": "terraform plan"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashBuild);
    }

    #[test]
    fn detect_go_mod_download() {
        let args = r#"{"command": "go mod download"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashPackage);
    }

    #[test]
    fn detect_composer_install() {
        let args = r#"{"command": "composer install"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashPackage);
    }

    #[test]
    fn detect_bundle_install() {
        let args = r#"{"command": "bundle install"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashPackage);
    }

    #[test]
    fn detect_dotnet_restore() {
        let args = r#"{"command": "dotnet restore"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashPackage);
    }

    #[test]
    fn detect_poetry_install() {
        let args = r#"{"command": "poetry install"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashPackage);
    }

    // ── Context pressure tests ──

    #[test]
    fn pressure_low_skips_light_tier() {
        let pressure = ContextPressure {
            usage_percent: 30,
            remaining_tokens: 100_000,
        };
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Light, Some(&pressure)),
            CompressionTier::Passthrough
        );
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Standard, Some(&pressure)),
            CompressionTier::Standard
        );
    }

    #[test]
    fn pressure_normal_uses_base_tier() {
        let pressure = ContextPressure {
            usage_percent: 65,
            remaining_tokens: 50_000,
        };
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Light, Some(&pressure)),
            CompressionTier::Light
        );
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Standard, Some(&pressure)),
            CompressionTier::Standard
        );
    }

    #[test]
    fn pressure_high_promotes_light_to_standard() {
        let pressure = ContextPressure {
            usage_percent: 90,
            remaining_tokens: 5_000,
        };
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Light, Some(&pressure)),
            CompressionTier::Standard
        );
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Passthrough, Some(&pressure)),
            CompressionTier::Passthrough
        );
    }

    #[test]
    fn pressure_none_uses_base_tier() {
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Light, None),
            CompressionTier::Light
        );
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Passthrough, None),
            CompressionTier::Passthrough
        );
    }

    // ── Tier classification edge cases ──

    #[test]
    fn classify_tier_empty_string() {
        assert_eq!(classify_tier(""), CompressionTier::Passthrough);
    }

    #[test]
    fn classify_tier_short_string() {
        assert_eq!(classify_tier("hello world"), CompressionTier::Passthrough);
    }

    #[test]
    fn classify_tier_aggressive_is_reachable() {
        // Use real words for more accurate token count; each word ≈ 1 token
        let words: Vec<String> = (0..30_000).map(|i| format!("word{}", i)).collect();
        let big = words.join(" ");
        let tier = classify_tier(&big);
        assert_eq!(tier, CompressionTier::Aggressive);
    }

    // ── Pressure boundary edge cases ──

    #[test]
    fn pressure_boundary_50_percent() {
        // Exactly 50% → normal range (50-80)
        let pressure = ContextPressure {
            usage_percent: 50,
            remaining_tokens: 50_000,
        };
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Light, Some(&pressure)),
            CompressionTier::Light
        );
    }

    #[test]
    fn pressure_boundary_80_percent() {
        // Exactly 80% → normal range (50-80)
        let pressure = ContextPressure {
            usage_percent: 80,
            remaining_tokens: 20_000,
        };
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Light, Some(&pressure)),
            CompressionTier::Light
        );
    }

    #[test]
    fn pressure_boundary_81_percent() {
        // 81% → high pressure range (>80)
        let pressure = ContextPressure {
            usage_percent: 81,
            remaining_tokens: 19_000,
        };
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Light, Some(&pressure)),
            CompressionTier::Standard
        );
    }

    #[test]
    fn pressure_boundary_49_percent() {
        // 49% → low pressure range (<50)
        let pressure = ContextPressure {
            usage_percent: 49,
            remaining_tokens: 51_000,
        };
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Light, Some(&pressure)),
            CompressionTier::Passthrough
        );
    }

    #[test]
    fn pressure_does_not_change_aggressive() {
        let low = ContextPressure {
            usage_percent: 10,
            remaining_tokens: 90_000,
        };
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Aggressive, Some(&low)),
            CompressionTier::Aggressive
        );
    }

    #[test]
    fn pressure_does_not_change_standard_at_low() {
        let low = ContextPressure {
            usage_percent: 10,
            remaining_tokens: 90_000,
        };
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Standard, Some(&low)),
            CompressionTier::Standard
        );
    }

    #[test]
    fn pressure_zero_percent() {
        let pressure = ContextPressure {
            usage_percent: 0,
            remaining_tokens: 200_000,
        };
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Light, Some(&pressure)),
            CompressionTier::Passthrough
        );
    }

    #[test]
    fn pressure_100_percent() {
        let pressure = ContextPressure {
            usage_percent: 100,
            remaining_tokens: 0,
        };
        assert_eq!(
            adjust_tier_for_pressure(CompressionTier::Light, Some(&pressure)),
            CompressionTier::Standard
        );
    }

    // ── Light compression edge cases ──

    #[test]
    fn light_compression_plain_text_no_changes() {
        let input = "hello\nworld\n";
        let result = apply_light_compression(input);
        assert!(!result.was_compressed);
    }

    #[test]
    fn light_compression_strips_ansi_plain_text() {
        let input = "\x1b[32mgreen text\x1b[0m\n";
        let result = apply_light_compression(input);
        assert!(result.was_compressed);
        assert!(!result.compressed.contains("\x1b["));
    }

    #[test]
    fn light_compression_json_envelope() {
        let json = serde_json::json!({
            "command": "echo",
            "stdout": "\x1b[32mhello\x1b[0m",
            "stderr": "",
            "exit_code": 0,
        })
        .to_string();
        let result = apply_light_compression(&json);
        assert!(result.was_compressed);
        assert!(!result.compressed.contains("\x1b["));
        // Should still be valid JSON
        let parsed: serde_json::Value = serde_json::from_str(&result.compressed).unwrap();
        let stdout_val = parsed["stdout"].as_str().unwrap();
        assert!(stdout_val.starts_with("hello"));
    }

    #[test]
    fn light_compression_json_no_ansi_not_compressed() {
        // Use content with trailing newline so collapse_blank_lines doesn't add one
        let json = serde_json::json!({
            "command": "echo",
            "stdout": "clean output\n",
            "stderr": "no ansi here\n",
            "exit_code": 0,
        })
        .to_string();
        let result = apply_light_compression(&json);
        assert!(!result.was_compressed);
    }

    // ── Scenario detection edge cases ──

    #[test]
    fn detect_piped_cargo_test() {
        let args = r#"{"command": "cargo test 2>&1 | tee output.log"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashTest);
    }

    #[test]
    fn detect_bashoutput_uses_bash_detection() {
        let args = r#"{"command": "git status"}"#;
        assert_eq!(detect_scenario("BashOutput", args), OutputScenario::BashGit);
    }

    #[test]
    fn detect_command_with_env_prefix() {
        let args = r#"{"command": "CI=true cargo test"}"#;
        assert_eq!(detect_scenario("Bash", args), OutputScenario::BashTest);
    }

    // ── Task-aware truncation (Phase 4) ──

    #[test]
    fn truncate_preserves_task_relevant_middle_lines() {
        use bamboo_compression::TokenCounter;
        let counter = bamboo_compression::TiktokenTokenCounter::default();
        let mut lines: Vec<String> = (0..400)
            .map(|i| format!("filler line number {i} with some padding words"))
            .collect();
        lines.insert(
            200,
            "CRITICAL zephyrqux module test FAILED here".to_string(),
        );
        let text = lines.join("\n");
        let max_tokens = 80;
        assert!(
            counter.count_text(&text) > max_tokens,
            "text must exceed budget"
        );

        let hint = TaskCompressionHint::from_phrases(vec!["zephyrqux module passes".to_string()]);
        let out = truncate_to_token_budget(&text, max_tokens, &counter, Some(&hint));
        assert!(
            out.contains("task-relevant lines preserved"),
            "preserved-section marker present"
        );
        assert!(
            out.contains("zephyrqux"),
            "the matching middle line must survive truncation"
        );
    }

    #[test]
    fn truncate_without_hint_keeps_original_format() {
        let counter = bamboo_compression::TiktokenTokenCounter::default();
        let text = (0..400)
            .map(|i| format!("line {i} content"))
            .collect::<Vec<_>>()
            .join("\n");
        let out = truncate_to_token_budget(&text, 50, &counter, None);
        assert!(out.contains("[... tool output truncated:"));
        assert!(!out.contains("task-relevant lines preserved"));
    }

    #[test]
    fn task_hint_extracts_significant_terms_and_matches() {
        let hint =
            TaskCompressionHint::from_phrases(vec!["All tests pass for module X".to_string()]);
        assert!(!hint.is_empty());
        assert!(hint.matches("re-running the module checks"));
        assert!(!hint.matches("xyz qrs unrelated"));
    }

    #[test]
    fn skill_output_utf8_byte_ceiling_bounds_actual_bundled_and_default_counters() {
        use bamboo_compression::{HeuristicTokenCounter, TiktokenTokenCounter, TokenCounter};
        let bundled = TiktokenTokenCounter::default();
        let heuristic = HeuristicTokenCounter::default();
        let ascii = (0..=127).map(char::from).collect::<String>();
        let unicode = [
            "界🦀é",
            "\r\n\0\"\\",
            "<|endoftext|><|endofprompt|>",
            "\u{10ffff}\u{10000}\u{7ff}",
        ];
        let mut cases = vec![String::new(), ascii.clone(), "a".into(), "🦀".into()];
        cases.extend(unicode.iter().map(|s| s.to_string()));
        for byte in 0..=127 {
            cases.push(char::from(byte).to_string());
        }
        let maximal = "界🦀\0\r\n\"\\<|endoftext|>".repeat(30_000);
        let mut end = (512 * 1024).min(maximal.len());
        while !maximal.is_char_boundary(end) {
            end -= 1;
        }
        cases.push(maximal[..end].to_string());
        for text in cases {
            assert!(text.len() <= 512 * 1024);
            for count in [bundled.count_text(&text), heuristic.count_text(&text)] {
                assert!(
                    count as usize <= text.len(),
                    "actual count {count} > {} bytes",
                    text.len()
                );
            }
        }
    }

    #[tokio::test]
    async fn skill_output_byte_sized_json_survives_generic_compression_and_zero_cap() {
        use bamboo_compression::{TiktokenTokenCounter, TokenCounter};
        let raw = serde_json::json!({"contents":"界🦀\0\r\n\"\\<|endoftext|>".repeat(12),"next_cursor":null}).to_string();
        let counter = TiktokenTokenCounter::default();
        assert!(counter.count_text(&raw) as usize <= raw.len());
        for cap in [raw.len() as u32, 0] {
            let outcome = ToolExecutionOutcome {
                output_cap: None,
                permission_replay_origin: None,
                portable_tool: None,
                result: Ok(ToolResult::text(true, raw.clone())),
                needs_human: None,
                post_tool_hook_eligible: true,
                managed_running_violation: false,
                tool_duration: std::time::Duration::ZERO,
            };
            let result =
                maybe_compress("skills_read", "{}", "output-test", outcome, cap, None, None)
                    .await
                    .result
                    .unwrap();
            assert!(result.success);
            assert_eq!(result.result, raw);
            serde_json::from_str::<serde_json::Value>(&result.result).unwrap();
        }
    }

    #[tokio::test]
    async fn skill_output_name_and_failed_ok_result_never_bypass_generic_hard_cap() {
        use bamboo_compression::{TiktokenTokenCounter, TokenCounter};
        let raw = serde_json::json!({"contents":"🦀\"\\ variable content ".repeat(2_000),"next_cursor":"later"}).to_string();
        assert!(TiktokenTokenCounter::default().count_text(&raw) > 128);
        for name in [
            "skills_read",
            "default::skills_read",
            "untrusted::skills_read",
            "unrelated",
        ] {
            for success in [true, false] {
                let outcome = ToolExecutionOutcome {
                    output_cap: None,
                    permission_replay_origin: None,
                    portable_tool: None,
                    result: Ok(ToolResult::text(success, raw.clone())),
                    needs_human: None,
                    post_tool_hook_eligible: true,
                    managed_running_violation: false,
                    tool_duration: std::time::Duration::ZERO,
                };
                let result = maybe_compress(name, "{}", "output-test", outcome, 128, None, None)
                    .await
                    .result
                    .unwrap();
                assert_eq!(result.success, success);
                assert_ne!(result.result, raw);
                assert!(result.result.contains("tool output truncated"));
            }
        }
        let error = "genuine execution error ".repeat(200);
        let outcome = ToolExecutionOutcome {
            output_cap: None,
            permission_replay_origin: None,
            portable_tool: None,
            result: Err(error.clone()),
            needs_human: None,
            post_tool_hook_eligible: true,
            managed_running_violation: false,
            tool_duration: std::time::Duration::ZERO,
        };
        let result = maybe_compress("skills_read", "{}", "output-test", outcome, 1, None, None)
            .await
            .result
            .unwrap_err();
        assert_eq!(result, error);
    }

    #[tokio::test]
    async fn scoped_cap_metadata_never_bypasses_generic_compressor_argument_or_error_path() {
        let raw = "🦀 variable escaped \" \\ ".repeat(1000);
        for observation in [None, Some(None), Some(Some(0)), Some(Some(64))] {
            for name in ["skills_read", "ordinary_custom_tool"] {
                let make_outcome = |result| ToolExecutionOutcome {
                    output_cap: observation,
                    permission_replay_origin: None,
                    portable_tool: None,
                    result,
                    needs_human: None,
                    post_tool_hook_eligible: true,
                    managed_running_violation: false,
                    tool_duration: std::time::Duration::ZERO,
                };
                let compressed = maybe_compress(
                    name,
                    "{}",
                    "scoped-compressor",
                    make_outcome(Ok(ToolResult::text(true, raw.clone()))),
                    64,
                    None,
                    None,
                )
                .await;
                assert_eq!(compressed.output_cap, observation);
                let result = compressed.result.unwrap();
                assert!(result.success);
                assert!(result.result.contains("tool output truncated"));
                assert_ne!(result.result, raw);
                let unbounded = maybe_compress(
                    name,
                    "{}",
                    "scoped-compressor",
                    make_outcome(Ok(ToolResult::text(true, raw.clone()))),
                    0,
                    None,
                    None,
                )
                .await;
                assert_eq!(unbounded.output_cap, observation);
                assert_eq!(unbounded.result.unwrap().result, raw);
                let error = "genuine Reader failure".repeat(100);
                let failed = maybe_compress(
                    name,
                    "{}",
                    "scoped-compressor",
                    make_outcome(Err(error.clone())),
                    1,
                    None,
                    None,
                )
                .await;
                assert_eq!(failed.output_cap, observation);
                assert_eq!(failed.result.unwrap_err(), error);
            }
        }
    }
}