chunk-your-tools 2.0.3

MCP tool schema decomposition and recomposition
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
//! System vs MCP tool policies for catalog pruning (rerank / llm).
//! Port of `src/clear-your-tools/pruners/policies.py`.

use crate::build::CatalogIndex;
use crate::json_util::value_to_string;
use crate::paths::{
    collect_enums, decomposed_prefix, decomposed_root, get_root_tool_key, json_ext,
    to_decomposed_key, tool_id_from_decomposed_rel,
};
use crate::runtime_config;
use serde_json::{Map, Value, json};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::str::FromStr;

const ALWAYS_INCLUDE: &str = "always_include";
const PRUNE_OPTIONAL: &str = "prune_optional";
const PRUNE_ALL: &str = "prune_all";
const PRUNE_OPTIONAL_DESCRIPTIONS: &str = "prune_optional_descriptions";
const PRUNE_ALL_DESCRIPTIONS: &str = "prune_all_descriptions";

const PARTITION_METADATA_KEYS: &[&str] = &[
    "json",
    "md",
    "system_required_enum_values",
    "mcp_required_enum_values",
    "required_enum_values_by_tool",
];

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ToolPolicy {
    AlwaysInclude,
    #[default]
    PruneOptional,
    PruneAll,
    PruneOptionalDescriptions,
    PruneAllDescriptions,
}

/// Canonical policy string literals (for host language typing / validation).
#[must_use]
pub const fn tool_policy_strings() -> [&'static str; 5] {
    [
        ALWAYS_INCLUDE,
        PRUNE_OPTIONAL,
        PRUNE_ALL,
        PRUNE_OPTIONAL_DESCRIPTIONS,
        PRUNE_ALL_DESCRIPTIONS,
    ]
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseToolPolicyError;

impl std::fmt::Display for ParseToolPolicyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("unknown tool policy")
    }
}

impl std::error::Error for ParseToolPolicyError {}

impl FromStr for ToolPolicy {
    type Err = ParseToolPolicyError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            ALWAYS_INCLUDE => Ok(Self::AlwaysInclude),
            PRUNE_OPTIONAL => Ok(Self::PruneOptional),
            PRUNE_ALL => Ok(Self::PruneAll),
            PRUNE_OPTIONAL_DESCRIPTIONS => Ok(Self::PruneOptionalDescriptions),
            PRUNE_ALL_DESCRIPTIONS => Ok(Self::PruneAllDescriptions),
            _ => Err(ParseToolPolicyError),
        }
    }
}

#[must_use]
pub fn parse_tool_policy(s: &str) -> Option<ToolPolicy> {
    s.parse().ok()
}

impl ToolPolicy {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::AlwaysInclude => ALWAYS_INCLUDE,
            Self::PruneOptional => PRUNE_OPTIONAL,
            Self::PruneAll => PRUNE_ALL,
            Self::PruneOptionalDescriptions => PRUNE_OPTIONAL_DESCRIPTIONS,
            Self::PruneAllDescriptions => PRUNE_ALL_DESCRIPTIONS,
        }
    }
}

#[must_use]
pub const fn is_description_policy(policy: ToolPolicy) -> bool {
    matches!(
        policy,
        ToolPolicy::PruneOptionalDescriptions | ToolPolicy::PruneAllDescriptions
    )
}

/// Map description variants to base scoring policies (`prune_optional` / `prune_all`).
#[must_use]
pub const fn scoring_policy(policy: ToolPolicy) -> ToolPolicy {
    match policy {
        ToolPolicy::PruneOptionalDescriptions => ToolPolicy::PruneOptional,
        ToolPolicy::PruneAllDescriptions => ToolPolicy::PruneAll,
        other => other,
    }
}

#[must_use]
pub fn needs_description_reinstate(ctx: &PolicyContext) -> bool {
    if is_description_policy(ctx.system_policy) || is_description_policy(ctx.mcp_policy) {
        return true;
    }
    ctx.per_tool.values().any(|p| is_description_policy(*p))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolKind {
    System,
    Mcp,
}

#[derive(Debug, Clone, Copy)]
pub struct ParseToolKindError;

impl std::fmt::Display for ParseToolKindError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("unknown tool kind")
    }
}

impl std::error::Error for ParseToolKindError {}

impl FromStr for ToolKind {
    type Err = ParseToolKindError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "system" => Ok(Self::System),
            "mcp" => Ok(Self::Mcp),
            _ => Err(ParseToolKindError),
        }
    }
}

#[must_use]
pub fn parse_tool_kind(s: &str) -> Option<ToolKind> {
    s.parse().ok()
}

impl ToolKind {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::System => "system",
            Self::Mcp => "mcp",
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct PolicyContext {
    pub system_policy: ToolPolicy,
    pub mcp_policy: ToolPolicy,
    pub per_tool: HashMap<String, ToolPolicy>,
    /// When set, all tools in this prune session use MCP or system classification
    /// instead of inferring from the `mcp__` name prefix.
    pub tool_kind_override: Option<ToolKind>,
}

impl PolicyContext {
    /// Defaults from [`runtime_config`] (overridable by the host app before use).
    #[must_use]
    pub fn new() -> Self {
        let system = runtime_config::default_system_policy();
        let mcp = runtime_config::default_mcp_policy();
        Self {
            system_policy: parse_tool_policy(&system).unwrap_or(ToolPolicy::PruneOptional),
            mcp_policy: parse_tool_policy(&mcp).unwrap_or(ToolPolicy::PruneAll),
            per_tool: HashMap::new(),
            tool_kind_override: None,
        }
    }

    /// Start from [`Self::new`] and apply optional overrides (used by Python/Node bindings).
    #[must_use]
    pub fn with_overrides(
        system_policy: Option<ToolPolicy>,
        mcp_policy: Option<ToolPolicy>,
        per_tool: HashMap<String, ToolPolicy>,
    ) -> Self {
        let mut ctx = Self::new();
        if let Some(s) = system_policy {
            ctx.system_policy = s;
        }
        if let Some(m) = mcp_policy {
            ctx.mcp_policy = m;
        }
        ctx.per_tool = per_tool;
        ctx
    }
}

/// Apply pruning policies from config JSON.
///
/// Reads `pruning.tools.policy.system_tool`, `mcp_tool`, and `per_tool`.
pub fn policy_context_from_values(config: &Value) -> PolicyContext {
    let mut ctx = PolicyContext::new();

    if let Some(policy) = config
        .get("pruning")
        .and_then(Value::as_object)
        .and_then(|p| p.get("tools"))
        .and_then(Value::as_object)
        .and_then(|t| t.get("policy"))
        .and_then(Value::as_object)
    {
        if let Some(s) = policy
            .get("system_tool")
            .and_then(Value::as_str)
            .and_then(parse_tool_policy)
        {
            ctx.system_policy = s;
        }
        if let Some(m) = policy
            .get("mcp_tool")
            .and_then(Value::as_str)
            .and_then(parse_tool_policy)
        {
            ctx.mcp_policy = m;
        }
        if let Some(per_tool) = policy.get("per_tool").and_then(Value::as_object) {
            for (tool_id, policy) in per_tool {
                if let Some(p) = policy.as_str().and_then(parse_tool_policy) {
                    ctx.per_tool.insert(tool_id.clone(), p);
                }
            }
        }
    }
    ctx
}

/// Parse `TOOL=POLICY` (e.g. `Agent=always_include`).
///
/// # Errors
///
/// Returns an error when the input is not `TOOL=POLICY` or the policy name is unknown.
pub fn parse_tool_policy_pair(s: &str) -> Result<(String, ToolPolicy), String> {
    let (tool_id, policy_str) = s
        .split_once('=')
        .ok_or_else(|| format!("expected TOOL=POLICY, got: {s}"))?;
    let tool_id = tool_id.trim();
    if tool_id.is_empty() {
        return Err(format!("expected TOOL=POLICY, got: {s}"));
    }
    let policy = parse_tool_policy(policy_str.trim())
        .ok_or_else(|| format!("invalid policy for {tool_id}: {policy_str}"))?;
    Ok((tool_id.to_string(), policy))
}

/// Load per-tool overrides from a JSON object (`{"Agent": "always_include", ...}`).
///
/// # Errors
///
/// Returns an error when `val` is not a JSON object, a policy value is not a string,
/// or a policy name is unknown.
pub fn per_tool_policies_from_value(val: &Value) -> Result<HashMap<String, ToolPolicy>, String> {
    let Some(map) = val.as_object() else {
        return Err("per-tool policies must be a JSON object".into());
    };
    let mut out = HashMap::new();
    for (tool_id, policy_val) in map {
        let Some(policy_str) = policy_val.as_str() else {
            return Err(format!("policy for {tool_id} must be a string"));
        };
        let policy = parse_tool_policy(policy_str)
            .ok_or_else(|| format!("invalid policy for {tool_id}: {policy_str}"))?;
        out.insert(tool_id.clone(), policy);
    }
    Ok(out)
}

/// Apply per-tool overrides; later entries win for duplicate tool ids.
pub fn apply_per_tool_overrides<S: std::hash::BuildHasher>(
    ctx: &mut PolicyContext,
    overrides: HashMap<String, ToolPolicy, S>,
) {
    ctx.per_tool.extend(overrides);
}

fn item_object(item: &Value) -> Option<&Map<String, Value>> {
    item.as_object()
}

fn str_field(obj: &Map<String, Value>, key: &str) -> String {
    obj.get(key).map(value_to_string).unwrap_or_default()
}

fn copy_dict_list(items: &Value) -> Vec<Value> {
    let Some(arr) = items.as_array() else {
        return Vec::new();
    };
    arr.iter().filter(|x| x.is_object()).cloned().collect()
}

/// Python `not schema.get("properties")` (missing, null, or empty object).
fn properties_field_empty(schema: &Map<String, Value>) -> bool {
    match schema.get("properties") {
        None | Some(Value::Null) => true,
        Some(Value::Object(o)) => o.is_empty(),
        _ => false,
    }
}

#[must_use]
pub fn is_non_system_tool_id(tool_id: &str) -> bool {
    tool_id.starts_with("mcp__")
}

#[must_use]
pub fn is_system_tool_id(tool_id: &str) -> bool {
    !is_non_system_tool_id(tool_id)
}

/// Classify a tool id using batch override when present, else `mcp__` prefix.
#[must_use]
pub fn tool_is_mcp(tool_id: &str, ctx: &PolicyContext) -> bool {
    match ctx.tool_kind_override {
        Some(ToolKind::Mcp) => true,
        Some(ToolKind::System) => false,
        None => is_non_system_tool_id(tool_id),
    }
}

/// Classify a tool id using batch override when present, else `mcp__` prefix.
#[must_use]
pub fn tool_is_system(tool_id: &str, ctx: &PolicyContext) -> bool {
    !tool_is_mcp(tool_id, ctx)
}

#[must_use]
pub fn chunk_tool_id(item: &Value) -> String {
    let Some(obj) = item_object(item) else {
        return String::new();
    };
    if let Some(id) = obj.get("id") {
        return value_to_string(id);
    }
    if let Some(name) = obj.get("name") {
        return value_to_string(name);
    }
    String::new()
}

#[must_use]
pub fn effective_policy(ctx: &PolicyContext, tool_id: &str) -> ToolPolicy {
    if let Some(p) = ctx.per_tool.get(tool_id) {
        return *p;
    }
    if tool_is_system(tool_id, ctx) {
        ctx.system_policy
    } else {
        ctx.mcp_policy
    }
}

#[must_use]
pub fn tool_pass_through(ctx: &PolicyContext, tool_id: &str) -> bool {
    effective_policy(ctx, tool_id) == ToolPolicy::AlwaysInclude
}

#[must_use]
pub fn batch_tool_pass_through(ctx: &PolicyContext, tool_ids: &[&str]) -> Vec<bool> {
    tool_ids
        .iter()
        .map(|id| tool_pass_through(ctx, id))
        .collect()
}

#[must_use]
pub fn root_tool_id_from_chunk(item: &Value) -> String {
    let Some(obj) = item_object(item) else {
        return chunk_tool_id(item);
    };
    let file_path = str_field(obj, "file_path");
    if let Some(root_key) = get_root_tool_key(&file_path) {
        return tool_id_from_decomposed_rel(&root_key);
    }
    chunk_tool_id(item)
}

pub fn request_pass_through(ctx: &PolicyContext, tools: &[Value]) -> bool {
    let named: Vec<_> = tools
        .iter()
        .filter_map(item_object)
        .filter(|obj| !str_field(obj, "name").is_empty())
        .collect();
    if named.is_empty() {
        return true;
    }
    named
        .iter()
        .all(|obj| tool_pass_through(ctx, &str_field(obj, "name")))
}

#[must_use]
pub fn is_non_system_chunk(item: &Value) -> bool {
    is_non_system_tool_id(&chunk_tool_id(item))
}

#[must_use]
pub fn is_system_chunk(item: &Value) -> bool {
    is_system_tool_id(&chunk_tool_id(item))
}

#[must_use]
pub fn is_decomposed_tool_root_chunk(item: &Value) -> bool {
    let Some(obj) = item_object(item) else {
        return false;
    };
    let file_path = str_field(obj, "file_path");
    if file_path.is_empty() {
        return false;
    }
    let Some(root_key) = get_root_tool_key(&file_path) else {
        return false;
    };
    let Some(decomposed_key) = to_decomposed_key(&file_path) else {
        return false;
    };
    root_key == decomposed_key
}

#[must_use]
pub fn is_decomposed_optional_property_chunk(item: &Value) -> bool {
    let Some(obj) = item_object(item) else {
        return false;
    };
    let file_path = str_field(obj, "file_path");
    if file_path.is_empty() {
        return false;
    }
    let Some(decomposed_key) = to_decomposed_key(&file_path) else {
        return false;
    };
    let Some(root_key) = get_root_tool_key(&file_path) else {
        return false;
    };
    root_key != decomposed_key
}

#[must_use]
pub fn is_system_root_chunk(item: &Value) -> bool {
    is_system_chunk(item) && is_decomposed_tool_root_chunk(item)
}

#[must_use]
pub fn is_mcp_root_chunk(item: &Value) -> bool {
    is_non_system_chunk(item) && is_decomposed_tool_root_chunk(item)
}

#[must_use]
pub fn is_system_optional_chunk(item: &Value) -> bool {
    is_system_chunk(item) && is_decomposed_optional_property_chunk(item)
}

#[must_use]
pub fn is_mcp_optional_chunk(item: &Value) -> bool {
    is_non_system_chunk(item) && is_decomposed_optional_property_chunk(item)
}

fn chunk_is_system_with_ctx(item: &Value, ctx: &PolicyContext) -> bool {
    tool_is_system(&root_tool_id_from_chunk(item), ctx)
}

fn chunk_is_mcp_with_ctx(item: &Value, ctx: &PolicyContext) -> bool {
    tool_is_mcp(&root_tool_id_from_chunk(item), ctx)
}

fn is_system_optional_chunk_with_ctx(item: &Value, ctx: &PolicyContext) -> bool {
    chunk_is_system_with_ctx(item, ctx) && is_decomposed_optional_property_chunk(item)
}

fn is_mcp_optional_chunk_with_ctx(item: &Value, ctx: &PolicyContext) -> bool {
    chunk_is_mcp_with_ctx(item, ctx) && is_decomposed_optional_property_chunk(item)
}

/// Classify optional chunks for many catalog items in one pass.
#[must_use]
pub fn classify_optional_chunks_batch(items: &[Value]) -> (Vec<bool>, Vec<bool>) {
    (
        items.iter().map(is_system_optional_chunk).collect(),
        items.iter().map(is_mcp_optional_chunk).collect(),
    )
}

/// Classify optional chunks using [`PolicyContext`] tool-kind override when set.
#[must_use]
pub fn classify_optional_chunks_batch_with_ctx(
    items: &[Value],
    ctx: &PolicyContext,
) -> (Vec<bool>, Vec<bool>) {
    (
        items
            .iter()
            .map(|item| is_system_optional_chunk_with_ctx(item, ctx))
            .collect(),
        items
            .iter()
            .map(|item| is_mcp_optional_chunk_with_ctx(item, ctx))
            .collect(),
    )
}

#[must_use]
pub fn needs_partition(ctx: &PolicyContext) -> bool {
    scoring_policy(ctx.system_policy) == ToolPolicy::PruneOptional
        || scoring_policy(ctx.mcp_policy) == ToolPolicy::PruneOptional
}

#[must_use]
pub const fn uses_pruned_recompose(policy: ToolPolicy) -> bool {
    matches!(
        policy,
        ToolPolicy::PruneOptional
            | ToolPolicy::PruneAll
            | ToolPolicy::PruneOptionalDescriptions
            | ToolPolicy::PruneAllDescriptions
    )
}

#[must_use]
pub const fn needs_pruned_recompose(ctx: &PolicyContext) -> bool {
    uses_pruned_recompose(ctx.system_policy) || uses_pruned_recompose(ctx.mcp_policy)
}

#[must_use]
pub fn chunk_policy(item: &Value, ctx: &PolicyContext) -> Option<ToolPolicy> {
    if chunk_is_system_with_ctx(item, ctx) {
        Some(ctx.system_policy)
    } else if chunk_is_mcp_with_ctx(item, ctx) {
        Some(ctx.mcp_policy)
    } else {
        None
    }
}

#[must_use]
pub fn system_tools_pass_through(ctx: &PolicyContext) -> bool {
    ctx.system_policy == ToolPolicy::AlwaysInclude
}

#[must_use]
pub fn mcp_tools_pass_through(ctx: &PolicyContext) -> bool {
    ctx.mcp_policy == ToolPolicy::AlwaysInclude
}

#[must_use]
pub fn full_pass_through(ctx: &PolicyContext) -> bool {
    ctx.system_policy == ToolPolicy::AlwaysInclude && ctx.mcp_policy == ToolPolicy::AlwaysInclude
}

#[must_use]
pub fn collect_enum_values_from_chunks(chunks: &[Value]) -> HashSet<String> {
    let mut values = HashSet::new();
    for item in chunks {
        if let Some(content) = item_object(item).and_then(|o| o.get("content")) {
            for val in collect_enums(content) {
                values.insert(value_to_string(&val));
            }
        }
    }
    values
}

fn enum_md_matches_values(md_item: &Value, enum_values: &HashSet<String>) -> bool {
    if enum_values.is_empty() {
        return false;
    }
    let Some(content) = item_object(md_item).and_then(|o| o.get("content")) else {
        return false;
    };
    enum_values.contains(&value_to_string(content))
}

fn should_pin_json_chunk(ctx: &PolicyContext, item: &Value) -> bool {
    if !is_decomposed_tool_root_chunk(item) {
        return false;
    }
    scoring_policy(effective_policy(ctx, &root_tool_id_from_chunk(item)))
        == ToolPolicy::PruneOptional
}

pub fn catalog_needs_partition(data: &Value, ctx: &PolicyContext) -> bool {
    if needs_partition(ctx) {
        return true;
    }
    let Some(json_items) = data.get("json").and_then(Value::as_array) else {
        return false;
    };
    let mut seen = HashSet::new();
    for item in json_items {
        if !item.is_object() {
            continue;
        }
        let tool_id = root_tool_id_from_chunk(item);
        if !seen.insert(tool_id.clone()) {
            continue;
        }
        if scoring_policy(effective_policy(ctx, &tool_id)) == ToolPolicy::PruneOptional {
            return true;
        }
    }
    false
}

pub fn catalog_needs_pruned_recompose(data: &Value, ctx: &PolicyContext) -> bool {
    if needs_pruned_recompose(ctx) {
        return true;
    }
    let Some(json_items) = data.get("json").and_then(Value::as_array) else {
        return false;
    };
    let mut seen = HashSet::new();
    for item in json_items {
        if !item.is_object() {
            continue;
        }
        let tool_id = root_tool_id_from_chunk(item);
        if !seen.insert(tool_id.clone()) {
            continue;
        }
        if uses_pruned_recompose(effective_policy(ctx, &tool_id)) {
            return true;
        }
    }
    false
}

struct JsonPartition {
    pinned_json: Vec<Value>,
    processable_json: Vec<Value>,
    system_required_enums: HashSet<String>,
    mcp_required_enums: HashSet<String>,
    required_enums_by_tool: HashMap<String, HashSet<String>>,
}

fn partition_json_items(ctx: &PolicyContext, json_list: &[Value]) -> JsonPartition {
    let mut pinned_json = Vec::new();
    let mut processable_json = Vec::new();
    let mut system_required_enums = HashSet::new();
    let mut mcp_required_enums = HashSet::new();
    let mut required_enums_by_tool: HashMap<String, HashSet<String>> = HashMap::new();

    for item in json_list {
        if !item.is_object() {
            continue;
        }
        if should_pin_json_chunk(ctx, item) {
            let copy_item = item.clone();
            pinned_json.push(copy_item.clone());
            let tool_id = root_tool_id_from_chunk(item);
            let enum_vals = collect_enum_values_from_chunks(std::slice::from_ref(&copy_item));
            required_enums_by_tool
                .entry(tool_id.clone())
                .or_default()
                .extend(enum_vals.iter().cloned());
            if chunk_is_system_with_ctx(item, ctx) {
                system_required_enums.extend(enum_vals.iter().cloned());
            } else if chunk_is_mcp_with_ctx(item, ctx) {
                mcp_required_enums.extend(enum_vals.iter().cloned());
            }
        } else {
            processable_json.push(item.clone());
        }
    }

    JsonPartition {
        pinned_json,
        processable_json,
        system_required_enums,
        mcp_required_enums,
        required_enums_by_tool,
    }
}

fn partition_md_items(
    md_list: &[Value],
    pinned_enum_values: &HashSet<String>,
) -> (Vec<Value>, Vec<Value>) {
    let mut processable_md = Vec::new();
    let mut pinned_md = Vec::new();

    for md_item in md_list {
        if !md_item.is_object() {
            continue;
        }
        let copy_item = md_item.clone();
        if enum_md_matches_values(&copy_item, pinned_enum_values) {
            pinned_md.push(copy_item);
        } else {
            processable_md.push(copy_item);
        }
    }

    (processable_md, pinned_md)
}

pub fn partition_catalog(data: &Value, ctx: &PolicyContext) -> (Value, Value) {
    if !catalog_needs_partition(data, ctx) {
        return (data.clone(), json!({}));
    }

    let json_list = data.get("json").and_then(Value::as_array);
    let md_list = data.get("md").and_then(Value::as_array);
    let json_list = json_list.map_or(&[] as &[Value], std::vec::Vec::as_slice);
    let md_list = md_list.map_or(&[] as &[Value], std::vec::Vec::as_slice);

    let mut processable = Map::new();
    if let Some(obj) = data.as_object() {
        for (k, v) in obj {
            if !PARTITION_METADATA_KEYS.contains(&k.as_str()) {
                processable.insert(k.clone(), v.clone());
            }
        }
    }

    let mut pinned = Map::new();
    pinned.insert("json".into(), Value::Array(Vec::new()));
    pinned.insert("md".into(), Value::Array(Vec::new()));
    pinned.insert(
        "system_required_enum_values".into(),
        Value::Array(Vec::new()),
    );
    pinned.insert("mcp_required_enum_values".into(), Value::Array(Vec::new()));
    pinned.insert(
        "required_enum_values_by_tool".into(),
        Value::Object(Map::new()),
    );

    let JsonPartition {
        pinned_json,
        processable_json,
        system_required_enums,
        mcp_required_enums,
        required_enums_by_tool,
    } = partition_json_items(ctx, json_list);

    let mut pinned_enum_values = HashSet::new();
    for vals in required_enums_by_tool.values() {
        pinned_enum_values.extend(vals.iter().cloned());
    }

    let (processable_md, pinned_md) = partition_md_items(md_list, &pinned_enum_values);

    processable.insert("json".into(), Value::Array(processable_json));
    processable.insert("md".into(), Value::Array(processable_md));
    pinned.insert("json".into(), Value::Array(pinned_json));
    pinned.insert("md".into(), Value::Array(pinned_md));

    let mut system_sorted: Vec<_> = system_required_enums.into_iter().collect();
    system_sorted.sort();
    let mut mcp_sorted: Vec<_> = mcp_required_enums.into_iter().collect();
    mcp_sorted.sort();
    pinned.insert(
        "system_required_enum_values".into(),
        Value::Array(system_sorted.into_iter().map(Value::String).collect()),
    );
    pinned.insert(
        "mcp_required_enum_values".into(),
        Value::Array(mcp_sorted.into_iter().map(Value::String).collect()),
    );

    let mut by_tool = Map::new();
    for (tool_id, mut vals) in required_enums_by_tool {
        let mut sorted: Vec<_> = vals.drain().collect();
        sorted.sort();
        by_tool.insert(
            tool_id,
            Value::Array(sorted.into_iter().map(Value::String).collect()),
        );
    }
    pinned.insert(
        "required_enum_values_by_tool".into(),
        Value::Object(by_tool),
    );

    (Value::Object(processable), Value::Object(pinned))
}

pub fn merge_catalog(processed: &Value, pinned: &Value) -> Value {
    let mut merged = processed.clone();
    let Some(merged_obj) = merged.as_object_mut() else {
        return merged;
    };

    if let Some(pinned_json) = pinned.get("json").and_then(Value::as_array) {
        let arr = merged_obj
            .entry("json".to_string())
            .or_insert_with(|| Value::Array(Vec::new()));
        if let Some(merged_json) = arr.as_array_mut() {
            merged_json.extend(pinned_json.iter().cloned());
        }
    }
    if let Some(pinned_md) = pinned.get("md").and_then(Value::as_array) {
        let arr = merged_obj
            .entry("md".to_string())
            .or_insert_with(|| Value::Array(Vec::new()));
        if let Some(merged_md) = arr.as_array_mut() {
            merged_md.extend(pinned_md.iter().cloned());
        }
    }
    if pinned.get("system_required_enum_values").is_some()
        && let Some(v) = pinned.get("system_required_enum_values")
    {
        merged_obj.insert("system_required_enum_values".into(), v.clone());
    }
    if pinned.get("mcp_required_enum_values").is_some()
        && let Some(v) = pinned.get("mcp_required_enum_values")
    {
        merged_obj.insert("mcp_required_enum_values".into(), v.clone());
    }
    if pinned.get("required_enum_values_by_tool").is_some()
        && let Some(v) = pinned.get("required_enum_values_by_tool")
    {
        merged_obj.insert("required_enum_values_by_tool".into(), v.clone());
    }
    merged
}

#[must_use]
pub fn stash_system_tools(tools: &[Value]) -> Vec<Value> {
    tools
        .iter()
        .filter(|t| item_object(t).is_some_and(|o| is_system_tool_id(&str_field(o, "name"))))
        .cloned()
        .collect()
}

#[must_use]
pub fn restore_system_tools(stash: &[Value]) -> Vec<Value> {
    stash.to_vec()
}

#[must_use]
pub fn stash_mcp_tools(tools: &[Value]) -> Vec<Value> {
    tools
        .iter()
        .filter(|t| item_object(t).is_some_and(|o| is_non_system_tool_id(&str_field(o, "name"))))
        .cloned()
        .collect()
}

#[must_use]
pub fn restore_mcp_tools(stash: &[Value]) -> Vec<Value> {
    stash.to_vec()
}

#[must_use]
pub fn merge_tools_preserving_order<S: std::hash::BuildHasher>(
    original: &[Value],
    pruned_by_name: &HashMap<String, Value, S>,
    stashed_by_name: &HashMap<String, Value, S>,
) -> Vec<Value> {
    let mut result = Vec::new();
    for tool in original {
        let Some(obj) = item_object(tool) else {
            continue;
        };
        let name = str_field(obj, "name");
        if name.is_empty() {
            continue;
        }
        if let Some(t) = stashed_by_name.get(&name) {
            result.push(t.clone());
        } else if let Some(t) = pruned_by_name.get(&name) {
            result.push(t.clone());
        }
    }
    result
}

#[must_use]
pub fn anthropic_tool_is_system(tool: &Value) -> bool {
    item_object(tool).is_some_and(|o| is_system_tool_id(&str_field(o, "name")))
}

#[must_use]
pub fn anthropic_tool_is_mcp(tool: &Value) -> bool {
    item_object(tool).is_some_and(|o| is_non_system_tool_id(&str_field(o, "name")))
}

#[must_use]
pub fn split_anthropic_tools(tools: &[Value]) -> (Vec<Value>, Vec<Value>) {
    let mut non_system = Vec::new();
    let mut system = Vec::new();
    for tool in tools {
        if anthropic_tool_is_system(tool) {
            system.push(tool.clone());
        } else {
            non_system.push(tool.clone());
        }
    }
    (non_system, system)
}

#[must_use]
pub fn entries_for_policy(ctx: &PolicyContext, all_entries: &[Value]) -> Vec<Value> {
    let mut result = Vec::new();
    for entry in all_entries {
        let tool_id = item_object(entry)
            .map(|o| str_field(o, "id"))
            .unwrap_or_default();
        if !tool_id.is_empty() && tool_pass_through(ctx, &tool_id) {
            continue;
        }
        result.push(entry.clone());
    }
    result
}

#[must_use]
pub fn tools_for_catalog(ctx: &PolicyContext, tools: &[Value]) -> Vec<Value> {
    let mut result = Vec::new();
    for tool in tools {
        let name = item_object(tool)
            .map(|o| str_field(o, "name"))
            .unwrap_or_default();
        if !name.is_empty() && tool_pass_through(ctx, &name) {
            continue;
        }
        result.push(tool.clone());
    }
    result
}

pub fn system_required_enum_values(data: &Value) -> HashSet<String> {
    data.get("system_required_enum_values")
        .and_then(Value::as_array)
        .map(|arr| arr.iter().map(value_to_string).collect())
        .unwrap_or_default()
}

pub fn mcp_required_enum_values(data: &Value) -> HashSet<String> {
    data.get("mcp_required_enum_values")
        .and_then(Value::as_array)
        .map(|arr| arr.iter().map(value_to_string).collect())
        .unwrap_or_default()
}

pub fn required_enum_values_by_tool(data: &Value) -> HashMap<String, HashSet<String>> {
    let Some(raw) = data
        .get("required_enum_values_by_tool")
        .and_then(Value::as_object)
    else {
        return HashMap::new();
    };
    raw.iter()
        .filter_map(|(tool_id, values)| {
            let set: HashSet<String> = values.as_array()?.iter().map(value_to_string).collect();
            Some((tool_id.clone(), set))
        })
        .collect()
}

pub fn optional_leaf_survived_rerank<S: std::hash::BuildHasher>(
    ctx: &PolicyContext,
    item: &Value,
    rerank_score: f64,
    llm_selected_paths: Option<&HashSet<String, S>>,
) -> bool {
    if !is_decomposed_optional_property_chunk(item) {
        return false;
    }
    let file_path = item_object(item)
        .map(|o| str_field(o, "file_path"))
        .unwrap_or_default();
    if let Some(paths) = llm_selected_paths
        && paths.contains(&file_path)
    {
        return true;
    }
    let policy = scoring_policy(effective_policy(ctx, &root_tool_id_from_chunk(item)));
    match policy {
        ToolPolicy::PruneAll => true,
        ToolPolicy::PruneOptional => {
            item_object(item)
                .and_then(|o| o.get("score"))
                .and_then(Value::as_f64)
                .unwrap_or(0.0)
                >= rerank_score
        }
        ToolPolicy::AlwaysInclude
        | ToolPolicy::PruneOptionalDescriptions
        | ToolPolicy::PruneAllDescriptions => false,
    }
}

#[must_use]
pub fn filter_recompose_json_entries<S: std::hash::BuildHasher>(
    ctx: &PolicyContext,
    json_list: &[Value],
    rerank_score: f64,
    llm_selected_paths: Option<&HashSet<String, S>>,
) -> Vec<Value> {
    let mut filtered = Vec::new();
    for item in json_list {
        if is_decomposed_tool_root_chunk(item)
            || optional_leaf_survived_rerank(ctx, item, rerank_score, llm_selected_paths)
        {
            filtered.push(item.clone());
        }
    }
    filtered
}

#[must_use]
pub fn is_direct_root_optional_property_chunk(item: &Value) -> bool {
    if !is_decomposed_optional_property_chunk(item) {
        return false;
    }
    let file_path = item_object(item)
        .map(|o| str_field(o, "file_path"))
        .unwrap_or_default();
    let Some(key) = to_decomposed_key(&file_path) else {
        return false;
    };
    let root = decomposed_root();
    let Ok(rel) = Path::new(&key).strip_prefix(&root) else {
        return false;
    };
    let parts: Vec<_> = rel.components().collect();
    parts.len() == 2
        && parts[1]
            .as_os_str()
            .to_string_lossy()
            .ends_with(&json_ext())
}

fn chunk_input_schema(item: &Value) -> Map<String, Value> {
    let Some(content) = item_object(item)
        .and_then(|o| o.get("content"))
        .and_then(Value::as_object)
    else {
        return Map::new();
    };
    if let Some(schema) = content
        .get("inputSchema")
        .or_else(|| content.get("input_schema"))
        .and_then(Value::as_object)
    {
        return schema.clone();
    }
    Map::new()
}

#[must_use]
pub fn root_chunk_properties_empty(item: &Value) -> bool {
    if !is_decomposed_tool_root_chunk(item) {
        return false;
    }
    properties_field_empty(&chunk_input_schema(item))
}

pub fn tool_id_has_empty_decomposed_root(catalog_index: &CatalogIndex, tool_id: &str) -> bool {
    let rel = format!("{}{tool_id}{}", decomposed_prefix(), json_ext());
    let Some(raw) = catalog_index.files.get(&rel) else {
        return false;
    };
    let parsed: Value = serde_json::from_str(raw).unwrap_or(Value::Null);
    let schema = parsed
        .get("inputSchema")
        .or_else(|| parsed.get("input_schema"))
        .and_then(Value::as_object);
    let Some(schema) = schema else {
        return true;
    };
    properties_field_empty(schema)
}

fn original_tool_input_schema(catalog_index: &CatalogIndex, tool_id: &str) -> Map<String, Value> {
    let full_rel = format!("schemas/full/{tool_id}{}", json_ext());
    if let Some(raw) = catalog_index.files.get(&full_rel)
        && let Ok(parsed) = serde_json::from_str::<Value>(raw)
        && let Some(schema) = parsed
            .get("inputSchema")
            .or_else(|| parsed.get("input_schema"))
            .and_then(Value::as_object)
    {
        return schema.clone();
    }
    for entry in &catalog_index.tools {
        if item_object(entry).map(|o| str_field(o, "id")).as_deref() != Some(tool_id) {
            continue;
        }
        if let Some(full_schema) = entry.get("full_schema").and_then(Value::as_object)
            && let Some(schema) = full_schema
                .get("inputSchema")
                .or_else(|| full_schema.get("input_schema"))
                .and_then(Value::as_object)
        {
            return schema.clone();
        }
    }
    Map::new()
}

#[must_use]
pub fn tool_id_had_empty_original_root_properties(
    catalog_index: &CatalogIndex,
    tool_id: &str,
) -> bool {
    properties_field_empty(&original_tool_input_schema(catalog_index, tool_id))
}

#[must_use]
pub fn needs_empty_optional_mitigation(catalog_index: &CatalogIndex, tool_id: &str) -> bool {
    tool_id_has_empty_decomposed_root(catalog_index, tool_id)
        && !tool_id_had_empty_original_root_properties(catalog_index, tool_id)
}

#[must_use]
pub fn optional_chunks_for_tool(items: &[Value], tool_id: &str) -> Vec<Value> {
    items
        .iter()
        .filter(|item| {
            item.is_object()
                && is_decomposed_optional_property_chunk(item)
                && root_tool_id_from_chunk(item) == tool_id
        })
        .cloned()
        .collect()
}

pub fn direct_root_optional_chunks_for_tool(items: &[Value], tool_id: &str) -> Vec<Value> {
    optional_chunks_for_tool(items, tool_id)
        .into_iter()
        .filter(is_direct_root_optional_property_chunk)
        .collect()
}

fn scored_json_entries(post_rerank_scored: Option<&Value>) -> Vec<Value> {
    let Some(data) = post_rerank_scored.and_then(Value::as_object) else {
        return Vec::new();
    };
    copy_dict_list(data.get("json").unwrap_or(&Value::Null))
}

fn should_mitigate_empty_root(
    ctx: &PolicyContext,
    tool_id: &str,
    root_item: &Value,
    entries: &[Value],
    catalog_index: &CatalogIndex,
) -> bool {
    if !uses_pruned_recompose(effective_policy(ctx, tool_id)) {
        return false;
    }
    if !needs_empty_optional_mitigation(catalog_index, tool_id) {
        return false;
    }
    if !root_chunk_properties_empty(root_item) {
        return false;
    }
    optional_chunks_for_tool(entries, tool_id).is_empty()
}

fn append_rerank_fallback_chunks(
    tool_id: &str,
    result: &mut Vec<Value>,
    seen_paths: &mut HashSet<String>,
    scored_json: &[Value],
) {
    let mut candidates = optional_chunks_for_tool(scored_json, tool_id);
    candidates.sort_by(|a, b| {
        let sa = item_object(a)
            .and_then(|o| o.get("score"))
            .and_then(Value::as_f64)
            .unwrap_or(0.0);
        let sb = item_object(b)
            .and_then(|o| o.get("score"))
            .and_then(Value::as_f64)
            .unwrap_or(0.0);
        sb.partial_cmp(&sa).unwrap_or(std::cmp::Ordering::Equal)
    });
    for chunk in candidates
        .into_iter()
        .take(runtime_config::empty_optional_fallback_k())
    {
        let file_path = item_object(&chunk)
            .and_then(|o| o.get("file_path"))
            .map(value_to_string)
            .unwrap_or_default();
        if file_path.is_empty() || !seen_paths.insert(file_path) {
            continue;
        }
        result.push(chunk);
    }
}

fn tool_roots_from_entries(entries: &[Value]) -> HashMap<String, Value> {
    let mut roots_by_tool = HashMap::new();
    for item in entries {
        if item.is_object() && is_decomposed_tool_root_chunk(item) {
            roots_by_tool.insert(root_tool_id_from_chunk(item), item.clone());
        }
    }
    roots_by_tool
}

fn drop_tools_from_entries(entries: &[Value], tools_to_drop: &HashSet<String>) -> Vec<Value> {
    if tools_to_drop.is_empty() {
        return entries.to_vec();
    }
    entries
        .iter()
        .filter(|item| item.is_object() && !tools_to_drop.contains(&root_tool_id_from_chunk(item)))
        .cloned()
        .collect()
}

pub fn mitigate_empty_optional_properties(
    ctx: &PolicyContext,
    entries: &[Value],
    catalog_index: &CatalogIndex,
    post_rerank_scored: Option<&Value>,
    pipeline: &[String],
) -> Vec<Value> {
    if pipeline.is_empty() || entries.is_empty() {
        return entries.to_vec();
    }
    let last_stage = pipeline.last().map_or("", String::as_str);
    if !matches!(last_stage, "rerank" | "llm" | "bm25") {
        return entries.to_vec();
    }

    let roots_by_tool = tool_roots_from_entries(entries);
    if roots_by_tool.is_empty() {
        return entries.to_vec();
    }

    let scored_json = scored_json_entries(post_rerank_scored);
    let mut result: Vec<Value> = entries.to_vec();
    let mut seen_paths: HashSet<String> = result
        .iter()
        .filter_map(|item| {
            item_object(item)
                .and_then(|o| o.get("file_path"))
                .map(value_to_string)
        })
        .collect();
    let mut tools_to_drop = HashSet::new();

    for (tool_id, root_item) in &roots_by_tool {
        if !should_mitigate_empty_root(ctx, tool_id, root_item, &result, catalog_index) {
            continue;
        }
        if last_stage == "llm" {
            if is_description_policy(effective_policy(ctx, tool_id)) {
                continue;
            }
            tools_to_drop.insert(tool_id.clone());
            continue;
        }
        if matches!(last_stage, "rerank" | "bm25") && !scored_json.is_empty() {
            append_rerank_fallback_chunks(tool_id, &mut result, &mut seen_paths, &scored_json);
        }
    }

    drop_tools_from_entries(&result, &tools_to_drop)
}

pub fn drop_recomposed_tools_with_empty_properties(
    ctx: &PolicyContext,
    tools: &[Value],
    catalog_index: &CatalogIndex,
) -> Vec<Value> {
    let mut kept = Vec::new();
    for tool in tools {
        let name = item_object(tool)
            .map(|o| str_field(o, "name"))
            .unwrap_or_default();
        let schema = item_object(tool)
            .and_then(|o| o.get("inputSchema").or_else(|| o.get("input_schema")))
            .and_then(Value::as_object);
        let has_props = schema.is_some_and(|s| !properties_field_empty(s));
        if has_props {
            kept.push(tool.clone());
            continue;
        }
        if !name.is_empty() && is_description_policy(effective_policy(ctx, &name)) {
            kept.push(tool.clone());
            continue;
        }
        if !name.is_empty()
            && uses_pruned_recompose(effective_policy(ctx, &name))
            && needs_empty_optional_mitigation(catalog_index, &name)
        {
            continue;
        }
        kept.push(tool.clone());
    }
    kept
}

fn chunk_survivor_key_from_entry(entry: &Value) -> Option<String> {
    let fp = item_object(entry).and_then(|o| o.get("file_path"))?;
    let fp_str = value_to_string(fp);
    to_decomposed_key(&fp_str).or(Some(fp_str))
}

fn survivor_keys_from_entries(entries: &[Value]) -> HashSet<String> {
    entries
        .iter()
        .filter_map(chunk_survivor_key_from_entry)
        .collect()
}

fn strip_description_key(value: &mut Value) {
    match value {
        Value::Object(map) => {
            map.remove("description");
            for v in map.values_mut() {
                strip_description_key(v);
            }
        }
        Value::Array(arr) => {
            for v in arr.iter_mut() {
                strip_description_key(v);
            }
        }
        _ => {}
    }
}

fn strip_descriptions_in_chunk_content(chunk: &mut Value) {
    if let Some(content) = item_object(chunk).and_then(|o| o.get("content")).cloned() {
        let mut content = content;
        strip_description_key(&mut content);
        if let Some(obj) = chunk.as_object_mut() {
            obj.insert("content".into(), content);
        }
    }
}

fn root_chunk_survived_for_tool(entries: &[Value], tool_id: &str) -> bool {
    entries
        .iter()
        .any(|item| is_decomposed_tool_root_chunk(item) && root_tool_id_from_chunk(item) == tool_id)
}

fn build_root_chunk_from_catalog(build_catalog: &Value, tool_id: &str) -> Option<Value> {
    let json_arr = build_catalog.get("json")?.as_array()?;
    json_arr
        .iter()
        .find(|item| {
            is_decomposed_tool_root_chunk(item) && root_tool_id_from_chunk(item) == tool_id
        })
        .cloned()
}

fn build_synthetic_required_root_chunk(build_catalog: &Value, tool_id: &str) -> Option<Value> {
    let mut synthetic = build_root_chunk_from_catalog(build_catalog, tool_id)?;
    strip_descriptions_in_chunk_content(&mut synthetic);
    Some(synthetic)
}

fn removed_optional_chunks_for_tool(
    build_catalog: &Value,
    surviving_entries: &[Value],
    tool_id: &str,
) -> Vec<Value> {
    let survivor_keys = survivor_keys_from_entries(surviving_entries);
    let Some(json_arr) = build_catalog.get("json").and_then(Value::as_array) else {
        return Vec::new();
    };
    json_arr
        .iter()
        .filter(|entry| {
            if !is_decomposed_optional_property_chunk(entry) {
                return false;
            }
            if root_tool_id_from_chunk(entry) != tool_id {
                return false;
            }
            let key = chunk_survivor_key_from_entry(entry);
            key.is_some_and(|k| !survivor_keys.contains(&k))
        })
        .cloned()
        .collect()
}

/// Augment recompose json entries with description-policy reinstatement.
pub fn append_description_reinstate_entries(
    ctx: &PolicyContext,
    entries: &[Value],
    build_catalog: &Value,
    _catalog_index: &CatalogIndex,
) -> Vec<Value> {
    if !needs_description_reinstate(ctx) {
        return entries.to_vec();
    }

    let mut result = entries.to_vec();
    let mut seen_paths: HashSet<String> = result
        .iter()
        .filter_map(|item| {
            item_object(item)
                .and_then(|o| o.get("file_path"))
                .map(value_to_string)
        })
        .collect();

    let mut tool_ids = HashSet::new();
    if let Some(json_arr) = build_catalog.get("json").and_then(Value::as_array) {
        for item in json_arr {
            if is_decomposed_tool_root_chunk(item) {
                tool_ids.insert(root_tool_id_from_chunk(item));
            }
        }
    }

    for tool_id in tool_ids {
        let output_policy = effective_policy(ctx, &tool_id);
        if !is_description_policy(output_policy) {
            continue;
        }

        let root_survived = root_chunk_survived_for_tool(entries, &tool_id);

        if !root_survived {
            let root_chunk = if output_policy == ToolPolicy::PruneAllDescriptions {
                build_synthetic_required_root_chunk(build_catalog, &tool_id)
            } else if output_policy == ToolPolicy::PruneOptionalDescriptions {
                build_root_chunk_from_catalog(build_catalog, &tool_id)
            } else {
                None
            };
            if let Some(root) = root_chunk {
                let file_path = item_object(&root)
                    .map(|o| str_field(o, "file_path"))
                    .unwrap_or_default();
                if !file_path.is_empty() && seen_paths.insert(file_path) {
                    result.push(root);
                }
            }
            if output_policy == ToolPolicy::PruneAllDescriptions {
                // Case #1: root pruned — drop optional chunks that leaked through
                // prune_all scoring in filter_recompose (they must not appear in output).
                result.retain(|item| {
                    !(is_decomposed_optional_property_chunk(item)
                        && root_tool_id_from_chunk(item) == tool_id)
                });
                continue;
            }
        }

        for mut chunk in removed_optional_chunks_for_tool(build_catalog, entries, &tool_id) {
            strip_descriptions_in_chunk_content(&mut chunk);
            let file_path = item_object(&chunk)
                .map(|o| str_field(o, "file_path"))
                .unwrap_or_default();
            if !file_path.is_empty() && seen_paths.insert(file_path) {
                result.push(chunk);
            }
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tool_policy_roundtrip() {
        for s in [
            ALWAYS_INCLUDE,
            PRUNE_OPTIONAL,
            PRUNE_ALL,
            PRUNE_OPTIONAL_DESCRIPTIONS,
            PRUNE_ALL_DESCRIPTIONS,
        ] {
            assert_eq!(parse_tool_policy(s).map(ToolPolicy::as_str), Some(s));
        }
    }

    #[test]
    fn scoring_policy_maps_description_variants() {
        assert_eq!(
            scoring_policy(ToolPolicy::PruneOptionalDescriptions),
            ToolPolicy::PruneOptional
        );
        assert_eq!(
            scoring_policy(ToolPolicy::PruneAllDescriptions),
            ToolPolicy::PruneAll
        );
    }

    #[test]
    fn mcp_tool_id_detection() {
        assert!(is_non_system_tool_id("mcp__foo"));
        assert!(!is_system_tool_id("mcp__foo"));
    }

    #[test]
    fn parse_tool_policy_pair_valid() {
        assert!(matches!(
            parse_tool_policy_pair("Agent=always_include"),
            Ok((ref tool, ToolPolicy::AlwaysInclude)) if tool == "Agent"
        ));
    }

    #[test]
    fn per_tool_policies_from_value_parses_object() {
        let val = json!({
            "Agent": "prune_optional",
            "mcp__fff__grep": "always_include"
        });
        assert!(matches!(
            per_tool_policies_from_value(&val),
            Ok(ref map)
                if map.get("Agent") == Some(&ToolPolicy::PruneOptional)
                    && map.get("mcp__fff__grep") == Some(&ToolPolicy::AlwaysInclude)
        ));
    }

    #[test]
    fn policy_context_reads_tools_policy() {
        let config = json!({
            "pruning": {
                "tools": {
                    "policy": {
                        "system_tool": "always_include",
                        "mcp_tool": "prune_optional"
                    }
                }
            }
        });
        let ctx = policy_context_from_values(&config);
        assert_eq!(ctx.system_policy, ToolPolicy::AlwaysInclude);
        assert_eq!(ctx.mcp_policy, ToolPolicy::PruneOptional);
    }

    #[test]
    fn policy_context_ignores_legacy_config_paths() {
        let config = json!({
            "pruning": {
                "policy": {
                    "system_tool": "always_include",
                    "mcp_tool": "prune_optional"
                },
                "per_tool": {
                    "Agent": "prune_all"
                }
            },
            "defaults": {
                "system_tool_policy": "prune_all",
                "mcp_tool_policy": "always_include"
            }
        });
        let ctx = policy_context_from_values(&config);
        assert_eq!(ctx.system_policy, ToolPolicy::PruneOptional);
        assert_eq!(ctx.mcp_policy, ToolPolicy::PruneAll);
        assert!(ctx.per_tool.is_empty());
    }

    #[test]
    fn policy_context_uses_defaults_without_config() {
        let config = json!({});
        let ctx = policy_context_from_values(&config);
        assert_eq!(ctx.system_policy, ToolPolicy::PruneOptional);
        assert_eq!(ctx.mcp_policy, ToolPolicy::PruneAll);
    }

    #[test]
    fn effective_policy_uses_prefix_without_tool_kind_override() {
        let ctx = PolicyContext::new();
        let tool_id = "tools.demo.org.search";
        assert_eq!(effective_policy(&ctx, tool_id), ToolPolicy::PruneOptional);
    }

    #[test]
    fn effective_policy_uses_mcp_policy_with_tool_kind_override() {
        let mut ctx = PolicyContext::new();
        ctx.tool_kind_override = Some(ToolKind::Mcp);
        let tool_id = "tools.demo.org.search";
        assert_eq!(effective_policy(&ctx, tool_id), ToolPolicy::PruneAll);
    }

    #[test]
    fn should_pin_json_chunk_false_when_tool_kind_mcp() {
        let mut ctx = PolicyContext::new();
        ctx.tool_kind_override = Some(ToolKind::Mcp);
        let item = json!({
            "file_path": "schemas/decomposed/tools.demo.org.search.json",
            "content": {"inputSchema": {"properties": {"q": {"type": "string"}}}}
        });
        assert!(!should_pin_json_chunk(&ctx, &item));
    }

    #[test]
    fn should_pin_json_chunk_true_for_system_tool_without_override() {
        let ctx = PolicyContext::new();
        let item = json!({
            "file_path": "schemas/decomposed/tools.demo.org.search.json",
            "content": {"inputSchema": {"properties": {"q": {"type": "string"}}}}
        });
        assert!(should_pin_json_chunk(&ctx, &item));
    }
}