tokensave 7.9.0

Code intelligence tool that builds a semantic knowledge graph from Rust, Go, Java, Scala, TypeScript, Python, C, C++, Kotlin, C#, Swift, and many more codebases
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
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
use std::path::{Path, PathBuf};

use tokensave::hooks::{
    evaluate_claude_pre_tool_use_with_env, evaluate_droid_pre_tool_use_with_env,
    evaluate_hook_decision_with_env, evaluate_kiro_pre_tool_use_with_env, HookEnv,
};

fn env_indexed() -> HookEnv {
    HookEnv {
        in_tokensave_project: true,
        disable_grep_hook: false,
        project_root: None,
    }
}

fn env_not_indexed() -> HookEnv {
    HookEnv {
        in_tokensave_project: false,
        disable_grep_hook: false,
        project_root: None,
    }
}

fn env_disabled() -> HookEnv {
    HookEnv {
        in_tokensave_project: true,
        disable_grep_hook: true,
        project_root: None,
    }
}

/// An indexed project on disk, so absolute targets can be canonicalized.
/// The returned `TempDir` must stay alive for the whole test.
fn indexed_project() -> (tempfile::TempDir, PathBuf) {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().join("project");
    std::fs::create_dir_all(root.join(".tokensave")).expect("create .tokensave");
    std::fs::write(root.join(".tokensave").join("tokensave.db"), b"").expect("write db");
    (tmp, root)
}

fn env_rooted_at(root: &Path) -> HookEnv {
    HookEnv {
        in_tokensave_project: true,
        disable_grep_hook: false,
        project_root: Some(root.to_path_buf()),
    }
}

fn is_blocked(json: &str) -> bool {
    let v: serde_json::Value = serde_json::from_str(json).unwrap();
    v["hookSpecificOutput"]["permissionDecision"].as_str() == Some("deny")
}

fn get_block_reason(json: &str) -> String {
    let v: serde_json::Value = serde_json::from_str(json).unwrap();
    v["hookSpecificOutput"]["permissionDecisionReason"]
        .as_str()
        .unwrap_or("")
        .to_string()
}

#[test]
fn test_blocks_explore_agent() {
    let input = r#"{"subagent_type": "Explore", "prompt": "find files"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_allows_non_explore_agent() {
    let input = r#"{"subagent_type": "general-purpose", "prompt": "write a function"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "allow should produce no output");
}

#[test]
fn test_allows_typed_non_explore_agent_even_with_research_prompt() {
    // An explicitly typed non-Explore agent is a deliberate delegation (an
    // implementer, a custom agent, another harness's task type). Prompt
    // keywords must not turn it into a hard block, even when the prompt reads
    // like research — the caller chose a specific worker on purpose.
    let input = r#"{"subagent_type": "general-purpose", "prompt": "explore the codebase and find all callers of handle_request, then implement the fix"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "a typed non-Explore agent must not be blocked on prompt text, got: {result}"
    );
}

#[test]
fn test_blank_subagent_type_is_treated_as_untyped() {
    // A caller that sets subagent_type to "" is not a deliberate typed
    // delegation; a research-shaped prompt must still be steered, and it must
    // not slip past both branches.
    let research = r#"{"subagent_type": "", "prompt": "explore the codebase and map every caller of handle_request"}"#;
    assert!(is_blocked(&evaluate_hook_decision_with_env(
        research,
        &env_indexed()
    )));
    // ...while a blank type with a non-research prompt is allowed, same as any
    // untyped call.
    let impl_task = r#"{"subagent_type": "", "prompt": "write a unit test for the parser"}"#;
    assert!(evaluate_hook_decision_with_env(impl_task, &env_indexed()).is_empty());
}

#[test]
fn test_still_blocks_untyped_research_task() {
    // With no subagent_type the call is ambiguous and may be an Explore-style
    // fan-out, so the prompt heuristic still steers it to the MCP tools.
    let input = r#"{"prompt": "explore the codebase and map the call graph"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_explore_agent_respects_opt_out() {
    // The opt-out that suppresses Grep/Bash redirection now also suppresses
    // agent redirection, so an explicit "continue" override exists.
    let input = r#"{"subagent_type": "Explore", "prompt": "find files"}"#;
    assert!(is_blocked(&evaluate_hook_decision_with_env(
        input,
        &env_indexed()
    )));
    assert!(
        evaluate_hook_decision_with_env(input, &env_disabled()).is_empty(),
        "the disable opt-out must let an Explore agent through"
    );
}

#[test]
fn test_agent_block_requires_index() {
    // Like the Grep/Bash paths, the agent redirection is pointless without a
    // .tokensave index: there are no MCP tools to redirect to, so both the
    // Explore deny and the untyped-prompt deny must no-op.
    let explore = r#"{"subagent_type": "Explore", "prompt": "find files"}"#;
    assert!(
        evaluate_hook_decision_with_env(explore, &env_not_indexed()).is_empty(),
        "Explore agent must pass through when no index exists"
    );
    let untyped = r#"{"prompt": "explore the codebase and map the call graph"}"#;
    assert!(
        evaluate_hook_decision_with_env(untyped, &env_not_indexed()).is_empty(),
        "untyped research task must pass through when no index exists"
    );
}

#[test]
fn test_kiro_delegation_block_requires_index_and_honors_opt_out() {
    let input = r#"{
        "hook_event_name": "preToolUse",
        "tool_name": "delegate",
        "tool_input": {"task": "Explore the codebase architecture and call graph"}
    }"#;
    assert!(evaluate_kiro_pre_tool_use_with_env(input, &env_indexed()).is_some());
    assert!(evaluate_kiro_pre_tool_use_with_env(input, &env_not_indexed()).is_none());
    assert!(evaluate_kiro_pre_tool_use_with_env(input, &env_disabled()).is_none());
}

#[test]
fn test_blocks_exploration_prompt_explore() {
    let input = r#"{"prompt": "Explore the codebase and find all API endpoints"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_blocks_codebase_structure_prompt() {
    let input = r#"{"prompt": "Understand the codebase structure"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_blocks_call_graph_prompt() {
    let input = r#"{"prompt": "Show me the call graph for this function"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_blocks_who_calls_prompt() {
    let input = r#"{"prompt": "who calls the process_data function?"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_blocks_callers_of_prompt() {
    let input = r#"{"prompt": "find callers of handle_request"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_blocks_callees_of_prompt() {
    let input = r#"{"prompt": "what are the callees of main?"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_blocks_symbol_lookup_prompt() {
    let input = r#"{"prompt": "do a symbol lookup for TokenSave"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_blocks_read_every_prompt() {
    let input = r#"{"prompt": "read every file in src/"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_blocks_entire_codebase_prompt() {
    let input = r#"{"prompt": "scan the entire codebase for patterns"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_allows_normal_prompt() {
    let input = r#"{"prompt": "write a unit test for the parse function"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "allow should produce no output");
}

#[test]
fn test_allows_empty_input() {
    let result = evaluate_hook_decision_with_env("", &env_indexed());
    assert!(result.is_empty(), "allow should produce no output");
}

#[test]
fn test_allows_invalid_json() {
    let result = evaluate_hook_decision_with_env("not json at all", &env_indexed());
    assert!(result.is_empty(), "allow should produce no output");
}

#[test]
fn test_allows_no_prompt_no_subagent() {
    let input = r#"{"foo": "bar"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "allow should produce no output");
}

#[test]
fn test_case_insensitive_blocking() {
    let input = r#"{"prompt": "EXPLORE the Codebase Architecture"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_block_response_has_reason() {
    let input = r#"{"subagent_type": "Explore"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    let reason = get_block_reason(&result);
    assert!(reason.contains("tokensave MCP tools"));
}

#[test]
fn test_block_response_uses_correct_hook_schema() {
    let input = r#"{"subagent_type": "Explore"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    let v: serde_json::Value = serde_json::from_str(&result).unwrap();
    assert_eq!(
        v["hookSpecificOutput"]["hookEventName"].as_str(),
        Some("PreToolUse")
    );
    assert_eq!(
        v["hookSpecificOutput"]["permissionDecision"].as_str(),
        Some("deny")
    );
    assert!(v["hookSpecificOutput"]["permissionDecisionReason"]
        .as_str()
        .is_some());
}

#[test]
fn test_kiro_blocks_delegate_code_research_task() {
    let input = r#"{
        "hook_event_name": "preToolUse",
        "tool_name": "delegate",
        "tool_input": {
            "task": "Explore the codebase architecture and call graph"
        }
    }"#;
    let reason = evaluate_kiro_pre_tool_use_with_env(input, &env_indexed()).unwrap();
    assert!(reason.contains("tokensave MCP tools"));
}

#[test]
fn test_kiro_blocks_subagent_research_prompt() {
    let input = r#"{
        "hook_event_name": "preToolUse",
        "tool_name": "subagent",
        "tool_input": {
            "prompt": "who calls the process_data function?"
        }
    }"#;
    assert!(evaluate_kiro_pre_tool_use_with_env(input, &env_indexed()).is_some());
}

#[test]
fn test_kiro_allows_delegate_execution_task() {
    let input = r#"{
        "hook_event_name": "preToolUse",
        "tool_name": "delegate",
        "tool_input": {
            "task": "Run the full test suite and report failures"
        }
    }"#;
    assert!(evaluate_kiro_pre_tool_use_with_env(input, &env_indexed()).is_none());
}

#[test]
fn test_kiro_allows_non_delegation_tool() {
    let input = r#"{
        "hook_event_name": "preToolUse",
        "tool_name": "read",
        "tool_input": {
            "prompt": "Explore the entire codebase"
        }
    }"#;
    assert!(evaluate_kiro_pre_tool_use_with_env(input, &env_indexed()).is_none());
}

#[test]
fn test_kiro_allows_invalid_json() {
    assert!(evaluate_kiro_pre_tool_use_with_env("not json", &env_indexed()).is_none());
}

// ============================================================================
// Grep tool redirect — symbol-shaped patterns against code files should
// redirect to tokensave_search / _signature_search / _callers.
// ============================================================================

#[test]
fn test_grep_blocks_bare_symbol_on_rust_file() {
    let input = r#"{"pattern": "FooBar", "path": "src/main.rs", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result), "bare symbol on .rs should redirect");
}

#[test]
fn test_grep_allows_omitted_output_mode() {
    let input = r#"{"pattern": "FooBar", "path": "src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "the harness default is path-only, so only explicit content mode should redirect"
    );
}

#[test]
fn test_grep_blocks_alternation_on_rust_file() {
    let input =
        r#"{"pattern": "Foo\\|Bar\\|Baz", "path": "src/main.rs", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "alternation of identifiers should redirect"
    );
}

#[test]
fn test_grep_blocks_word_boundary_symbol() {
    let input =
        r#"{"pattern": "\\bhandle_request\\b", "path": "src/main.rs", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result), "\\bsymbol\\b should redirect");
}

#[test]
fn test_grep_allows_regex_metachar_pattern() {
    // dot-paren — a real regex sweep, not a symbol search
    let input = r#"{"pattern": "\\.split_at\\(", "path": "src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "regex metachars should pass through");
}

#[test]
fn test_grep_allows_character_class() {
    let input = r#"{"pattern": "[A-Z][a-z]+", "path": "src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "char class should pass through");
}

#[test]
fn test_grep_allows_non_code_extension() {
    let input = r#"{"pattern": "FooBar", "path": "README.md"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "non-code file should pass through");
}

#[test]
fn test_grep_allows_files_with_matches_mode() {
    let input = r#"{"pattern": "FooBar", "path": "src/", "output_mode": "files_with_matches"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "files_with_matches is file discovery, not symbol search"
    );
}

#[test]
fn test_grep_allows_count_mode() {
    let input = r#"{"pattern": "FooBar", "path": "src/", "output_mode": "count"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "count mode should pass through");
}

#[test]
fn test_grep_blocks_on_directory_path_when_indexed() {
    let input = r#"{"pattern": "FooBar", "path": "src/", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "symbol search in src/ dir should redirect"
    );
}

#[test]
fn test_grep_blocks_when_only_glob_set() {
    let input = r#"{"pattern": "FooBar", "glob": "**/*.rs", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result), "glob over .rs should redirect");
}

#[test]
fn test_grep_allows_glob_for_non_code() {
    let input = r#"{"pattern": "FooBar", "glob": "**/*.md", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "glob over .md should pass through");
}

#[test]
fn test_grep_non_code_glob_overrides_project_root_path() {
    let input =
        r#"{"pattern": "FooBar", "path": ".", "glob": "**/*.md", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "an explicit Markdown glob should narrow a broad project-root path"
    );
}

#[test]
fn test_grep_non_code_glob_overrides_code_directory_path() {
    let input =
        r#"{"pattern": "FooBar", "path": "src", "glob": "**/*.md", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "an explicit Markdown glob should narrow a code-directory path"
    );
}

#[test]
fn test_grep_code_glob_overrides_non_code_path() {
    let input =
        r#"{"pattern": "FooBar", "path": "docs", "glob": "**/*.rs", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        !result.is_empty(),
        "an explicit Rust glob should classify the effective target as code"
    );
    assert!(is_blocked(&result));
}

#[test]
fn test_grep_mixed_code_and_non_code_glob_passes() {
    let input =
        r#"{"pattern": "FooBar", "path": ".", "glob": "**/*.{rs,md}", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "a mixed glob can return documentation and must pass through"
    );
}

#[test]
fn test_grep_terminal_non_code_suffix_after_brace_passes() {
    let input = r#"{"pattern": "FooBar", "path": ".", "glob": "**/*.{ts,js}.bak", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "the terminal .bak suffix determines the effective file type"
    );
}

#[test]
fn test_grep_terminal_code_suffix_after_brace_blocks() {
    let input = r#"{"pattern": "FooBar", "path": ".", "glob": "**/*.{spec,test}.ts", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        !result.is_empty(),
        "the terminal .ts suffix determines the effective file type"
    );
    assert!(is_blocked(&result));
}

#[test]
fn test_grep_ignores_directory_brace_when_final_file_glob_is_code() {
    let input = r#"{"pattern": "FooBar", "path": ".", "glob": "dir.{a,b}/**/*.rs", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        !result.is_empty(),
        "a brace in an earlier path segment must not hide the final Rust extension"
    );
    assert!(is_blocked(&result));
}

#[test]
fn test_grep_unclassifiable_glob_falls_back_to_path() {
    let input = r#"{"pattern": "FooBar", "path": "src", "glob": "**/generated/**", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "a glob without an extension should preserve the existing path classification"
    );
}

#[test]
fn test_grep_unclassifiable_glob_without_path_preserves_pass_through() {
    let input = r#"{"pattern": "FooBar", "glob": "**/generated/**", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "an extensionless glob without a path should preserve the conservative pass-through"
    );
}

#[test]
fn test_grep_type_filter_has_priority_over_non_code_glob() {
    let input = r#"{"pattern": "FooBar", "path": ".", "glob": "**/*.md", "type": "rust", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "an explicit code type remains the highest-priority filter"
    );
}

#[test]
fn test_grep_blocks_with_type_filter_rust() {
    let input = r#"{"pattern": "FooBar", "type": "rust", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result), "type=rust should redirect");
}

#[test]
fn test_grep_block_message_names_tokensave_tool() {
    let input = r#"{"pattern": "FooBar", "path": "src/main.rs", "output_mode": "content"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    let reason = get_block_reason(&result);
    assert!(
        reason.contains("tokensave_"),
        "block message must name a tokensave tool"
    );
}

// ============================================================================
// Bash with embedded grep/rg/ag — same redirect logic, parsing the command.
// ============================================================================

#[test]
fn test_bash_blocks_grep_on_rust_file() {
    let input = r#"{"command": "grep -n \"FooBar\" src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result), "grep -n symbol .rs should redirect");
}

#[test]
fn test_bash_blocks_rg_on_src_dir() {
    let input = r#"{"command": "rg -n FooBar src/"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result), "rg symbol src/ should redirect");
}

#[test]
fn test_bash_blocks_grep_rn_recursive() {
    let input = r#"{"command": "grep -rn handle_request /Users/me/proj/src/"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "grep -rn callers search should redirect"
    );
}

#[test]
fn test_bash_blocks_alternation_command() {
    let input = r#"{"command": "grep -n \"Foo\\|Bar\" src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "alternation in grep command should redirect"
    );
}

#[test]
fn test_bash_blocks_rtk_grep_prefix() {
    let input = r#"{"command": "rtk grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result), "rtk grep prefix should be unwrapped");
}

#[test]
fn test_bash_allows_git_grep() {
    let input = r#"{"command": "git grep -n FooBar"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "git grep searches history — pass through"
    );
}

#[test]
fn test_bash_redirects_find_by_name() {
    // This asserted pass-through until #294, when `find -name` gained a policy
    // of its own: `tokensave_files` can answer discovery by path now that it
    // also tracks non-code artifacts (#323). See `hook_find_glob_test.rs` for
    // the boundaries — unmodelled predicates and non-code extensions still
    // pass through.
    let input = r#"{"command": "find . -name \"*.rs\" -type f"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result), "find -name should redirect");
    assert!(get_block_reason(&result).contains("tokensave_files"));
}

#[test]
fn test_bash_allows_grep_regex_metachars() {
    let input = r#"{"command": "rg -n \"\\.split_at\\(\" src/"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "regex sweep should pass through");
}

#[test]
fn test_bash_allows_grep_on_markdown() {
    let input = r#"{"command": "grep -n FooBar README.md"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "grep on .md should pass through");
}

#[test]
fn test_bash_allows_grep_in_pipe_after_other_cmd() {
    // Heuristic: only intercept commands that START with grep/rg/ag (after rtk/sudo).
    // Piping ls output through grep is not a code search.
    let input = r#"{"command": "ls src/ | grep FooBar"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "piped grep should pass through (safety)");
}

#[test]
fn test_bash_allows_non_grep_command() {
    let input = r#"{"command": "cargo test"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "non-grep bash should pass through");
}

#[test]
fn test_bash_blocks_grep_after_env_prefix() {
    let input = r#"{"command": "FOO=bar grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "a leading env assignment should not hide the grep"
    );
}

#[test]
fn test_bash_blocks_grep_after_cd_prefix() {
    let input = r#"{"command": "cd src && grep -n FooBar main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "a leading `cd … &&` should not hide the grep"
    );
}

#[test]
fn test_bash_inline_disable_env_is_honored() {
    // An explicit inline TOKENSAVE_DISABLE_GREP_HOOK=<truthy> is a deliberate
    // opt-out and must be honored, not stripped and then blocked. This mirrors
    // the exported opt-out; an ordinary FOO=bar prefix is still stripped.
    let input = r#"{"command": "TOKENSAVE_DISABLE_GREP_HOOK=1 grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "inline TOKENSAVE_DISABLE_GREP_HOOK=1 should opt out like the exported one"
    );
}

#[test]
fn test_bash_inline_disable_env_falsey_still_blocks() {
    // A falsey value is not an opt-out (same truthiness as HookEnv::from_runtime),
    // so the grep is still redirected.
    let input = r#"{"command": "TOKENSAVE_DISABLE_GREP_HOOK=0 grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "TOKENSAVE_DISABLE_GREP_HOOK=0 is falsey and should still redirect"
    );
}

#[test]
fn test_bash_inline_disable_after_cd_is_honored() {
    // The opt-out must be recognized wherever it sits in the leading noise, not
    // only as the very first token, so a conscious `cd … && DISABLE=1 grep …`
    // is honored rather than redirected.
    let input = r#"{"command": "cd src && TOKENSAVE_DISABLE_GREP_HOOK=1 grep -n FooBar main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "an inline opt-out after a cd prefix should still opt out"
    );
}

#[test]
fn test_bash_inline_disable_after_sudo_is_honored() {
    let input = r#"{"command": "sudo TOKENSAVE_DISABLE_GREP_HOOK=1 grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "an inline opt-out after a sudo wrapper should still opt out"
    );
}

#[test]
fn test_bash_inline_disable_after_other_env_is_honored() {
    let input = r#"{"command": "FOO=1 TOKENSAVE_DISABLE_GREP_HOOK=1 grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "an inline opt-out after another assignment should still opt out"
    );
}

#[test]
fn test_bash_inline_disable_before_other_env_is_honored() {
    let input =
        r#"{"command": "TOKENSAVE_DISABLE_GREP_HOOK=1 FOO=bar grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "an inline opt-out before another assignment should still opt out"
    );
}

#[test]
fn test_bash_inline_disable_nested_cd_and_env_is_honored() {
    let input =
        r#"{"command": "cd src && FOO=1 TOKENSAVE_DISABLE_GREP_HOOK=1 grep -n FooBar main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "a deeply nested inline opt-out (cd + env + disable) should still opt out"
    );
}

#[test]
fn test_bash_inline_disable_quoted_is_honored() {
    let input = r#"{"command": "TOKENSAVE_DISABLE_GREP_HOOK=\"1\" grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "a quoted truthy opt-out value should still opt out"
    );
}

#[test]
fn test_bash_inline_disable_true_word_is_honored() {
    let input = r#"{"command": "TOKENSAVE_DISABLE_GREP_HOOK=true grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "value `true` should opt out");
}

#[test]
fn test_bash_inline_disable_false_word_still_blocks() {
    // Case-insensitive `false` is falsey, matching HookEnv::from_runtime.
    let input = r#"{"command": "TOKENSAVE_DISABLE_GREP_HOOK=FALSE grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "value `FALSE` is not an opt-out and should still redirect"
    );
}

#[test]
fn test_bash_inline_disable_empty_value_still_blocks() {
    // An empty value is not set, so it is stripped like ordinary noise and the
    // grep is still redirected.
    let input = r#"{"command": "TOKENSAVE_DISABLE_GREP_HOOK= grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "an empty opt-out value is not an opt-out and should still redirect"
    );
}

#[test]
fn test_bash_inline_disable_last_assignment_wins_falsey_blocks() {
    // Shell "last assignment wins": a trailing falsey reassignment overrides an
    // earlier truthy one, so the grep is still redirected.
    let input = r#"{"command": "TOKENSAVE_DISABLE_GREP_HOOK=1 TOKENSAVE_DISABLE_GREP_HOOK=0 grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "a trailing falsey reassignment should win and still redirect"
    );
}

#[test]
fn test_bash_inline_disable_last_assignment_wins_truthy_allows() {
    let input = r#"{"command": "TOKENSAVE_DISABLE_GREP_HOOK=0 TOKENSAVE_DISABLE_GREP_HOOK=1 grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "a trailing truthy reassignment should win and opt out"
    );
}

#[test]
fn test_bash_blocks_grep_after_cd_and_env_prefix() {
    // Nested non-opt-out prefixes still unwrap to reveal the grep.
    let input = r#"{"command": "cd src && FOO=bar grep -n FooBar main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        is_blocked(&result),
        "cd + ordinary env prefix should not hide the grep"
    );
}

#[test]
fn test_bash_allows_pipe_after_cd_prefix() {
    let input = r#"{"command": "cd src && ls | grep FooBar"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "piped grep after a cd should still pass through"
    );
}

#[test]
fn test_bash_blocks_grep_on_python_file() {
    let input = r#"{"command": "grep -n FooBar src/app.py"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result), "grep on .py should redirect");
}

#[test]
fn test_bash_blocks_grep_on_typescript_file() {
    let input = r#"{"command": "grep -n FooBar src/index.tsx"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result), "grep on .tsx should redirect");
}

// ============================================================================
// Safety guards
// ============================================================================

#[test]
fn test_grep_allows_when_not_indexed() {
    let input = r#"{"pattern": "FooBar", "path": "src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_not_indexed());
    assert!(
        result.is_empty(),
        "no .tokensave/tokensave.db → pass through"
    );
}

#[test]
fn test_grep_allows_when_env_override() {
    let input = r#"{"pattern": "FooBar", "path": "src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_disabled());
    assert!(
        result.is_empty(),
        "TOKENSAVE_DISABLE_GREP_HOOK=1 → pass through"
    );
}

#[test]
fn test_bash_allows_when_env_override() {
    let input = r#"{"command": "grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_disabled());
    assert!(
        result.is_empty(),
        "TOKENSAVE_DISABLE_GREP_HOOK=1 → bash grep passes through"
    );
}

/// Regression for #248: `TOKENSAVE_DISABLE_GREP_HOOK` must be a *complete*
/// bypass for the binary hook, across every redirect path — Grep, Bash, a
/// typed `Explore` agent, and an untyped research-shaped prompt. This is the
/// documented escape hatch for headless / subagent (`claude -p`) dispatch,
/// where a child that legitimately needs raw search must be able to opt out
/// without stripping all hooks. `HookEnv::from_runtime` maps the env var onto
/// `disable_grep_hook`, so exercising the flag here covers the runtime path.
#[test]
fn test_disable_env_bypasses_every_redirect_path() {
    let cases = [
        r#"{"pattern": "FooBar", "path": "src/main.rs", "output_mode": "content"}"#,
        r#"{"command": "grep -n FooBar src/main.rs"}"#,
        r#"{"subagent_type": "Explore", "prompt": "find all API endpoints"}"#,
        r#"{"prompt": "explore the codebase and map the call graph"}"#,
    ];
    for input in cases {
        // Sanity: each case IS redirected with the guardrail active...
        assert!(
            is_blocked(&evaluate_hook_decision_with_env(input, &env_indexed())),
            "expected redirect with guardrail active: {input}"
        );
        // ...and the opt-out lets every one of them through.
        assert!(
            evaluate_hook_decision_with_env(input, &env_disabled()).is_empty(),
            "TOKENSAVE_DISABLE_GREP_HOOK must fully bypass this path: {input}"
        );
    }
}

#[test]
fn test_bash_allows_when_not_indexed() {
    let input = r#"{"command": "grep -n FooBar src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_not_indexed());
    assert!(result.is_empty(), "bash redirect requires indexed project");
}

#[test]
fn test_grep_allows_long_pattern() {
    // Very long patterns are unlikely to be simple symbol searches
    let huge = "A".repeat(300);
    let input = format!(r#"{{"pattern": "{huge}", "path": "src/main.rs"}}"#);
    let result = evaluate_hook_decision_with_env(&input, &env_indexed());
    assert!(result.is_empty(), "pattern over 200 chars should pass");
}

#[test]
fn test_grep_allows_empty_pattern() {
    let input = r#"{"pattern": "", "path": "src/main.rs"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(result.is_empty(), "empty pattern should pass");
}

#[test]
fn test_grep_existing_evaluate_hook_decision_still_works_for_agent() {
    // Sanity: the legacy entrypoint should still handle Agent
    let input = r#"{"subagent_type": "Explore"}"#;
    let result = evaluate_hook_decision_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

// ============================================================================
// Claude Code PreToolUse stdin contract — event arrives as JSON on stdin with
// the tool arguments nested under `tool_input` (no TOOL_INPUT env var).
// ============================================================================

#[test]
fn test_claude_blocks_explore_agent_nested_stdin() {
    let input = r#"{
        "hook_event_name": "PreToolUse",
        "tool_name": "Agent",
        "tool_input": {"subagent_type": "Explore", "prompt": "find files"}
    }"#;
    let result = evaluate_claude_pre_tool_use_with_env(input, &env_indexed());
    assert!(is_blocked(&result), "nested Explore agent should redirect");
}

#[test]
fn test_claude_lowercase_explorer_subagent_passes() {
    let input = r#"{
        "hook_event_name": "PreToolUse",
        "tool_name": "Agent",
        "tool_input": {"subagent_type": "explorer", "prompt": "find files"}
    }"#;
    let result = evaluate_claude_pre_tool_use_with_env(input, &env_indexed());
    assert!(
        result.is_empty(),
        "Claude behavior must remain exact-case Explore only"
    );
}

#[test]
fn test_claude_blocks_research_prompt_nested_stdin() {
    let input = r#"{
        "hook_event_name": "PreToolUse",
        "tool_name": "Agent",
        "tool_input": {"prompt": "who calls the process_data function?"}
    }"#;
    let result = evaluate_claude_pre_tool_use_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
    assert!(get_block_reason(&result).contains("tokensave MCP tools"));
}

#[test]
fn test_claude_allows_normal_tool_nested_stdin() {
    let input = r#"{
        "hook_event_name": "PreToolUse",
        "tool_name": "Bash",
        "tool_input": {"command": "cargo test"}
    }"#;
    let result = evaluate_claude_pre_tool_use_with_env(input, &env_indexed());
    assert!(result.is_empty(), "normal tool call should pass through");
}

#[test]
fn test_claude_falls_back_to_flat_tool_input() {
    // If the wrapper is absent, treat the payload as a flat tool_input object.
    let input = r#"{"subagent_type": "Explore"}"#;
    let result = evaluate_claude_pre_tool_use_with_env(input, &env_indexed());
    assert!(is_blocked(&result));
}

#[test]
fn test_claude_allows_invalid_json() {
    assert!(evaluate_claude_pre_tool_use_with_env("not json", &env_indexed()).is_empty());
}

// ============================================================================
// Factory Droid PreToolUse stdin contract — event arrives as JSON on stdin
// with the tool payload nested under `tool_input` (the Claude/Kiro shape),
// but the block is signaled via the raw reason text (`hook_droid_pre_tool_use`
// prints it to stderr and exits 2 — the Kiro mechanism), not a stdout JSON
// object. The `^(Execute|Grep|Task)$` matcher is installed, so grep/bash-shaped
// `command` payloads, Droid's native `Grep` `pattern`, and typed subagent
// payloads all reach this handler.
// ============================================================================

#[test]
fn test_droid_blocks_grep_shaped_execute_command_on_rust_file() {
    let input = r#"{
        "tool_name": "Execute",
        "tool_input": {"command": "grep -rn FooBar src/main.rs"}
    }"#;
    let reason = evaluate_droid_pre_tool_use_with_env(input, &env_indexed());
    assert!(
        reason.is_some(),
        "a symbol-shaped grep on a Rust file should redirect"
    );
    assert!(reason.unwrap().contains("tokensave"));
}

#[test]
fn test_droid_allows_terminal_launched_tools() {
    // Regression: tools the owner runs via a shell (Plannotator, builds, git)
    // are ordinary Execute commands that don't start with grep/rg/ag and must
    // pass untouched.
    let plannotator = r#"{
        "tool_name": "Execute",
        "tool_input": {"command": "npx plannotator review"}
    }"#;
    assert!(evaluate_droid_pre_tool_use_with_env(plannotator, &env_indexed()).is_none());

    let build = r#"{
        "tool_name": "Execute",
        "tool_input": {"command": "cargo build --release"}
    }"#;
    assert!(evaluate_droid_pre_tool_use_with_env(build, &env_indexed()).is_none());

    let git_commit = r#"{
        "tool_name": "Execute",
        "tool_input": {"command": "git commit -am \"fix bug\""}
    }"#;
    assert!(evaluate_droid_pre_tool_use_with_env(git_commit, &env_indexed()).is_none());
}

#[test]
fn test_droid_allows_git_grep() {
    // git grep searches history, which tokensave does not index.
    let input = r#"{
        "tool_name": "Execute",
        "tool_input": {"command": "git grep FooBar"}
    }"#;
    assert!(evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_none());
}

#[test]
fn test_droid_allows_when_not_indexed() {
    let input = r#"{
        "tool_name": "Execute",
        "tool_input": {"command": "grep -rn FooBar src/main.rs"}
    }"#;
    assert!(evaluate_droid_pre_tool_use_with_env(input, &env_not_indexed()).is_none());
}

#[test]
fn test_droid_respects_disable_grep_hook_escape_hatch() {
    let input = r#"{
        "tool_name": "Execute",
        "tool_input": {"command": "grep -rn FooBar src/main.rs"}
    }"#;
    assert!(evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_some());
    assert!(
        evaluate_droid_pre_tool_use_with_env(input, &env_disabled()).is_none(),
        "TOKENSAVE_DISABLE_GREP_HOOK=1 must let the grep call through"
    );
}

#[test]
fn test_droid_specialized_subagent_with_normal_task_passes() {
    // A specialized sub-agent given a normal (non-research) task must not be
    // blocked. The installed Task matcher routes this through the shared core,
    // but an exact non-research type is still a deliberate delegation.
    let input = r#"{
        "tool_name": "Task",
        "tool_input": {
            "subagent_type": "worker",
            "prompt": "Implement the retry logic for the sync client and add tests"
        }
    }"#;
    assert!(evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_none());
}

#[test]
fn test_droid_explorer_subagent_blocks_with_tokensave_context_hint() {
    let input = r#"{
        "tool_name": "Task",
        "tool_input": {
            "subagent_type": "explorer",
            "description": "Map request flow",
            "prompt": "Find every caller of handle_request"
        }
    }"#;
    let reason = evaluate_droid_pre_tool_use_with_env(input, &env_indexed())
        .expect("Droid explorer should redirect to tokensave");
    assert!(reason.contains("tokensave_context"));
}

#[test]
fn test_droid_explorer_subagent_requires_index_and_honors_opt_out() {
    let input = r#"{
        "tool_name": "Task",
        "tool_input": {
            "subagent_type": "explorer",
            "prompt": "Map the codebase"
        }
    }"#;
    assert!(evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_some());
    assert!(evaluate_droid_pre_tool_use_with_env(input, &env_not_indexed()).is_none());
    assert!(evaluate_droid_pre_tool_use_with_env(input, &env_disabled()).is_none());
}

#[test]
fn test_droid_custom_explorer_named_subagent_passes() {
    let input = r#"{
        "tool_name": "Task",
        "tool_input": {
            "subagent_type": "explorer-writer",
            "prompt": "Inspect and update the documentation"
        }
    }"#;
    assert!(evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_none());
}

#[test]
fn test_droid_untyped_research_task_passes() {
    let input = r#"{
        "tool_name": "Task",
        "tool_input": {
            "prompt": "who calls the process_data function?"
        }
    }"#;
    assert!(
        evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_none(),
        "Droid Task blocking must be limited to exact lowercase explorer"
    );
}

#[test]
fn test_droid_falls_back_to_flat_tool_input() {
    // If the wrapper is absent, treat the payload as a flat tool_input object
    // (matches the Claude adapter's fallback for the same reason).
    let input = r#"{"command": "grep -rn FooBar src/main.rs"}"#;
    assert!(evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_some());
}

#[test]
fn test_droid_allows_empty_input() {
    assert!(evaluate_droid_pre_tool_use_with_env("", &env_indexed()).is_none());
}

#[test]
fn test_droid_allows_invalid_json() {
    assert!(evaluate_droid_pre_tool_use_with_env("not json", &env_indexed()).is_none());
}

#[test]
fn test_droid_block_reason_documents_escape_hatch() {
    let input = r#"{
        "tool_name": "Execute",
        "tool_input": {"command": "grep -rn FooBar src/main.rs"}
    }"#;
    let reason = evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).unwrap();
    assert!(reason.contains("TOKENSAVE_DISABLE_GREP_HOOK"));
}

// ---------------------------------------------------------------------------
// Droid native `Grep` tool payloads. The `Grep` matcher routes these through
// the same shared decision core as the Claude `Grep` tool, but Droid names two
// fields differently (`glob_pattern` not `glob`; `file_paths` not
// `files_with_matches`), so these guard that the classifier reads both shapes.
// ---------------------------------------------------------------------------

#[test]
fn test_droid_native_grep_omitted_output_mode_passes() {
    let input = r#"{
        "tool_name": "Grep",
        "tool_input": {"pattern": "handle_request", "path": "src"}
    }"#;
    let reason = evaluate_droid_pre_tool_use_with_env(input, &env_indexed());
    assert!(
        reason.is_none(),
        "omitted output_mode uses Droid's path-only default and should pass"
    );
}

#[test]
fn test_droid_native_grep_uses_glob_pattern_field() {
    // Droid's Grep field is `glob_pattern`, not Claude's `glob`.
    let on_code = r#"{
        "tool_name": "Grep",
        "tool_input": {"pattern": "FooBar", "glob_pattern": "**/*.rs", "output_mode": "content"}
    }"#;
    assert!(
        evaluate_droid_pre_tool_use_with_env(on_code, &env_indexed()).is_some(),
        "glob_pattern over .rs should redirect"
    );

    let on_docs = r#"{
        "tool_name": "Grep",
        "tool_input": {"pattern": "FooBar", "glob_pattern": "**/*.md", "output_mode": "content"}
    }"#;
    assert!(
        evaluate_droid_pre_tool_use_with_env(on_docs, &env_indexed()).is_none(),
        "glob_pattern over .md should pass through"
    );
}

#[test]
fn test_droid_native_grep_non_code_glob_overrides_project_root_path() {
    let input = r#"{
        "tool_name": "Grep",
        "tool_input": {
            "pattern": "FooBar",
            "path": ".",
            "glob_pattern": "**/*.md",
            "output_mode": "content"
        }
    }"#;
    assert!(
        evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_none(),
        "Droid's explicit Markdown glob should narrow its broad path"
    );
}

#[test]
fn test_droid_native_grep_unclassifiable_glob_without_path_passes() {
    let input = r#"{
        "tool_name": "Grep",
        "tool_input": {
            "pattern": "FooBar",
            "glob_pattern": "**/generated/**",
            "output_mode": "content"
        }
    }"#;
    assert!(
        evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_none(),
        "Droid's extensionless glob should preserve the conservative pass-through"
    );
}

#[test]
fn test_droid_native_grep_file_paths_mode_passes() {
    // `file_paths` returns only names (Droid's cheap mode) — nothing to save.
    let input = r#"{
        "tool_name": "Grep",
        "tool_input": {"pattern": "handle_request", "path": "src", "output_mode": "file_paths"}
    }"#;
    assert!(
        evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_none(),
        "file_paths output mode should pass through"
    );
}

#[test]
fn test_droid_native_grep_content_mode_blocks() {
    let input = r#"{
        "tool_name": "Grep",
        "tool_input": {"pattern": "handle_request", "path": "src", "output_mode": "content"}
    }"#;
    assert!(
        evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_some(),
        "content output mode over code should redirect"
    );
}

#[test]
fn test_droid_native_grep_non_code_target_passes() {
    let input = r#"{
        "tool_name": "Grep",
        "tool_input": {"pattern": "TODO", "glob_pattern": "**/*.md", "output_mode": "content"}
    }"#;
    assert!(evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_none());
}

#[test]
fn test_droid_native_grep_respects_escape_hatch() {
    let input = r#"{
        "tool_name": "Grep",
        "tool_input": {"pattern": "handle_request", "path": "src", "output_mode": "content"}
    }"#;
    assert!(evaluate_droid_pre_tool_use_with_env(input, &env_indexed()).is_some());
    assert!(
        evaluate_droid_pre_tool_use_with_env(input, &env_disabled()).is_none(),
        "TOKENSAVE_DISABLE_GREP_HOOK=1 must let the native Grep call through"
    );
}

// --- absolute / home-rooted project-root targets -------------------------

#[test]
fn test_bash_blocks_grep_on_absolute_project_root() {
    let (_tmp, root) = indexed_project();
    let input =
        serde_json::json!({"command": format!("grep -rn handle_request {}", root.display())})
            .to_string();
    let result = evaluate_hook_decision_with_env(&input, &env_rooted_at(&root));
    assert!(
        is_blocked(&result),
        "an absolute spelling of the indexed root is the same whole-project search as `.`"
    );
}

#[test]
fn test_bash_blocks_grep_on_absolute_project_root_with_trailing_slash() {
    let (_tmp, root) = indexed_project();
    let input = serde_json::json!({"command": format!("rg -n handle_request {}/", root.display())})
        .to_string();
    assert!(
        is_blocked(&evaluate_hook_decision_with_env(
            &input,
            &env_rooted_at(&root)
        )),
        "a trailing slash must not change the classification"
    );
}

#[test]
fn test_bash_allows_grep_on_sibling_sharing_root_prefix() {
    let (tmp, root) = indexed_project();
    let sibling = tmp.path().join("project-old");
    std::fs::create_dir_all(&sibling).expect("create sibling");
    let input =
        serde_json::json!({"command": format!("grep -rn handle_request {}", sibling.display())})
            .to_string();
    assert!(
        evaluate_hook_decision_with_env(&input, &env_rooted_at(&root)).is_empty(),
        "a sibling sharing the root's string prefix is a different tree"
    );
}

#[test]
fn test_bash_allows_grep_on_absolute_non_code_subdirectory() {
    let (_tmp, root) = indexed_project();
    let docs = root.join("docs");
    std::fs::create_dir_all(&docs).expect("create docs");
    let input =
        serde_json::json!({"command": format!("grep -rn handle_request {}", docs.display())})
            .to_string();
    assert!(
        evaluate_hook_decision_with_env(&input, &env_rooted_at(&root)).is_empty(),
        "only the root itself is the whole-project bucket, not every path inside it"
    );
}

#[test]
fn test_grep_blocks_absolute_project_root_path() {
    let (_tmp, root) = indexed_project();
    let input = serde_json::json!({
        "pattern": "handle_request",
        "path": root.to_string_lossy(),
        "output_mode": "content",
    })
    .to_string();
    assert!(
        is_blocked(&evaluate_hook_decision_with_env(
            &input,
            &env_rooted_at(&root)
        )),
        "structured Grep with an absolute root path should redirect"
    );
}

#[test]
fn test_grep_non_code_glob_overrides_absolute_project_root_path() {
    let (_tmp, root) = indexed_project();
    let input = serde_json::json!({
        "pattern": "handle_request",
        "path": root.to_string_lossy(),
        "glob": "**/*.md",
        "output_mode": "content",
    })
    .to_string();
    assert!(
        evaluate_hook_decision_with_env(&input, &env_rooted_at(&root)).is_empty(),
        "an explicit Markdown glob still narrows an absolute project-root path"
    );
}

#[test]
fn test_bash_allows_absolute_root_when_root_is_unknown() {
    let (_tmp, root) = indexed_project();
    let input =
        serde_json::json!({"command": format!("grep -rn handle_request {}", root.display())})
            .to_string();
    assert!(
        evaluate_hook_decision_with_env(&input, &env_indexed()).is_empty(),
        "without a known root the classifier must fail open"
    );
}

#[test]
fn test_bash_allows_absolute_root_when_root_does_not_exist() {
    let (tmp, _root) = indexed_project();
    let missing = tmp.path().join("gone");
    let input =
        serde_json::json!({"command": format!("grep -rn handle_request {}", missing.display())})
            .to_string();
    assert!(
        evaluate_hook_decision_with_env(&input, &env_rooted_at(&missing)).is_empty(),
        "a root that cannot be canonicalized must fail open"
    );
}

#[test]
fn test_bash_absolute_project_root_respects_opt_out() {
    let (_tmp, root) = indexed_project();
    let input =
        serde_json::json!({"command": format!("grep -rn handle_request {}", root.display())})
            .to_string();
    let disabled = HookEnv {
        in_tokensave_project: true,
        disable_grep_hook: true,
        project_root: Some(root.clone()),
    };
    assert!(
        evaluate_hook_decision_with_env(&input, &disabled).is_empty(),
        "TOKENSAVE_DISABLE_GREP_HOOK=1 must bypass the root-target redirect too"
    );
}

#[test]
fn test_droid_execute_blocks_absolute_project_root() {
    let (_tmp, root) = indexed_project();
    let input = serde_json::json!({
        "tool_name": "Execute",
        "tool_input": {"command": format!("rg -n handle_request {}", root.display())},
    })
    .to_string();
    assert!(
        evaluate_droid_pre_tool_use_with_env(&input, &env_rooted_at(&root)).is_some(),
        "the Droid adapter shares the classifier, so the root target redirects there too"
    );
}

#[test]
fn test_droid_native_grep_blocks_absolute_project_root_path() {
    let (_tmp, root) = indexed_project();
    let input = serde_json::json!({
        "tool_name": "Grep",
        "tool_input": {
            "pattern": "handle_request",
            "path": root.to_string_lossy(),
            "output_mode": "content",
        },
    })
    .to_string();
    assert!(
        evaluate_droid_pre_tool_use_with_env(&input, &env_rooted_at(&root)).is_some(),
        "Droid's native Grep takes the same absolute-root path as its Execute tool"
    );
}

#[test]
fn test_bash_blocks_grep_on_root_reached_through_parent_segments() {
    let (_tmp, root) = indexed_project();
    let docs = root.join("docs");
    std::fs::create_dir_all(&docs).expect("create docs");
    let input = serde_json::json!({
        "command": format!("grep -rn handle_request {}/..", docs.display()),
    })
    .to_string();
    assert!(
        is_blocked(&evaluate_hook_decision_with_env(
            &input,
            &env_rooted_at(&root)
        )),
        "canonicalization sees through `..`, so a detour still names the root"
    );
}

#[test]
fn test_bash_allows_grep_on_the_parent_of_the_project_root() {
    let (tmp, root) = indexed_project();
    let input = serde_json::json!({
        "command": format!("grep -rn handle_request {}", tmp.path().display()),
    })
    .to_string();
    assert!(
        evaluate_hook_decision_with_env(&input, &env_rooted_at(&root)).is_empty(),
        "a search wider than the index cannot be served by the graph"
    );
}

#[test]
fn test_bash_classifies_only_the_first_target() {
    let (_tmp, root) = indexed_project();
    let docs = root.join("docs");
    std::fs::create_dir_all(&docs).expect("create docs");
    let input = serde_json::json!({
        "command": format!("grep -rn handle_request {} {}", docs.display(), root.display()),
    })
    .to_string();
    assert!(
        evaluate_hook_decision_with_env(&input, &env_rooted_at(&root)).is_empty(),
        "multi-target commands keep the pre-existing first-target-only classification"
    );
}

// --- activation scope: ancestor discovery and event cwd ------------------

#[test]
fn test_from_runtime_at_discovers_the_root_from_a_subdirectory() {
    let (_tmp, root) = indexed_project();
    let nested = root.join("crates").join("api").join("src");
    std::fs::create_dir_all(&nested).expect("create nested dirs");
    let env = HookEnv::from_runtime_at(Some(&nested));
    assert!(
        env.in_tokensave_project,
        "a subdirectory of an indexed project is still the indexed project"
    );
    assert_eq!(env.project_root.as_deref(), Some(root.as_path()));
}

#[test]
fn test_from_runtime_at_outside_any_project_is_inactive() {
    let (tmp, _root) = indexed_project();
    let outside = tmp.path().join("elsewhere");
    std::fs::create_dir_all(&outside).expect("create outside dir");
    let env = HookEnv::from_runtime_at(Some(&outside));
    assert!(!env.in_tokensave_project);
    assert!(env.project_root.is_none());
}

#[test]
fn test_droid_event_cwd_activates_the_guardrail() {
    let (_tmp, root) = indexed_project();
    let input = serde_json::json!({
        "cwd": root.to_string_lossy(),
        "tool_name": "Execute",
        "tool_input": {"command": "rg -n handle_request src/"},
    })
    .to_string();
    assert!(
        evaluate_droid_pre_tool_use_with_env(&input, &env_not_indexed()).is_some(),
        "the event's own cwd must decide the project, not the hook process cwd"
    );
}

#[test]
fn test_droid_event_cwd_below_the_root_activates_the_guardrail() {
    let (_tmp, root) = indexed_project();
    let nested = root.join("crates").join("api");
    std::fs::create_dir_all(&nested).expect("create nested dirs");
    let input = serde_json::json!({
        "cwd": nested.to_string_lossy(),
        "tool_name": "Execute",
        "tool_input": {"command": "rg -n handle_request src/"},
    })
    .to_string();
    assert!(
        evaluate_droid_pre_tool_use_with_env(&input, &env_not_indexed()).is_some(),
        "a session started in a subdirectory is still inside the indexed project"
    );
}

#[test]
fn test_droid_event_cwd_outside_a_project_deactivates_the_guardrail() {
    let (tmp, _root) = indexed_project();
    let outside = tmp.path().join("elsewhere");
    std::fs::create_dir_all(&outside).expect("create outside dir");
    let input = serde_json::json!({
        "cwd": outside.to_string_lossy(),
        "tool_name": "Execute",
        "tool_input": {"command": "rg -n handle_request src/"},
    })
    .to_string();
    assert!(
        evaluate_droid_pre_tool_use_with_env(&input, &env_indexed()).is_none(),
        "an event cwd outside any index has nothing to redirect to"
    );
}

#[test]
fn test_droid_event_cwd_still_honors_the_opt_out() {
    let (_tmp, root) = indexed_project();
    let input = serde_json::json!({
        "cwd": root.to_string_lossy(),
        "tool_name": "Execute",
        "tool_input": {"command": "rg -n handle_request src/"},
    })
    .to_string();
    // Opted out where the hook runs, but the event points at an indexed
    // project: the override must not resurrect the guardrail.
    let disabled_outside = HookEnv {
        in_tokensave_project: false,
        disable_grep_hook: true,
        project_root: None,
    };
    assert!(
        evaluate_droid_pre_tool_use_with_env(&input, &disabled_outside).is_none(),
        "TOKENSAVE_DISABLE_GREP_HOOK=1 outranks any discovered project"
    );
}

#[test]
fn test_droid_explorer_task_with_event_cwd_still_blocks() {
    let (_tmp, root) = indexed_project();
    let input = serde_json::json!({
        "cwd": root.to_string_lossy(),
        "tool_name": "Task",
        "tool_input": {"subagent_type": "explorer", "prompt": "map the codebase"},
    })
    .to_string();
    assert!(
        evaluate_droid_pre_tool_use_with_env(&input, &env_not_indexed()).is_some(),
        "the built-in explorer guard must survive event-cwd resolution"
    );
}

#[test]
fn test_droid_worker_task_with_event_cwd_still_passes() {
    let (_tmp, root) = indexed_project();
    let input = serde_json::json!({
        "cwd": root.to_string_lossy(),
        "tool_name": "Task",
        "tool_input": {"subagent_type": "worker", "prompt": "explore the codebase structure"},
    })
    .to_string();
    assert!(
        evaluate_droid_pre_tool_use_with_env(&input, &env_indexed()).is_none(),
        "a typed non-explorer task stays a deliberate delegation"
    );
}

#[test]
fn test_kiro_event_cwd_activates_the_delegation_block() {
    let (_tmp, root) = indexed_project();
    let input = serde_json::json!({
        "cwd": root.to_string_lossy(),
        "tool_name": "delegate",
        "tool_input": {"task": "explore the codebase and map the call graph"},
    })
    .to_string();
    assert!(
        evaluate_kiro_pre_tool_use_with_env(&input, &env_not_indexed()).is_some(),
        "Kiro's preToolUse hook should resolve the project like its postToolUse hook"
    );
}

#[test]
fn test_kiro_event_cwd_outside_a_project_deactivates_the_delegation_block() {
    let (tmp, _root) = indexed_project();
    let outside = tmp.path().join("elsewhere");
    std::fs::create_dir_all(&outside).expect("create outside dir");
    let input = serde_json::json!({
        "cwd": outside.to_string_lossy(),
        "tool_name": "delegate",
        "tool_input": {"task": "explore the codebase and map the call graph"},
    })
    .to_string();
    assert!(
        evaluate_kiro_pre_tool_use_with_env(&input, &env_indexed()).is_none(),
        "the event cwd decides in both directions, for Kiro too"
    );
}

#[test]
fn test_claude_event_cwd_activates_the_guardrail() {
    let (_tmp, root) = indexed_project();
    let input = serde_json::json!({
        "cwd": root.to_string_lossy(),
        "tool_name": "Grep",
        "tool_input": {"pattern": "handle_request", "path": "src", "output_mode": "content"},
    })
    .to_string();
    assert!(
        is_blocked(&evaluate_claude_pre_tool_use_with_env(
            &input,
            &env_not_indexed()
        )),
        "Claude's event cwd should decide the project too"
    );
}

#[test]
fn test_claude_event_cwd_outside_a_project_deactivates_the_guardrail() {
    let (tmp, _root) = indexed_project();
    let outside = tmp.path().join("elsewhere");
    std::fs::create_dir_all(&outside).expect("create outside dir");
    let input = serde_json::json!({
        "cwd": outside.to_string_lossy(),
        "tool_name": "Grep",
        "tool_input": {"pattern": "handle_request", "path": "src", "output_mode": "content"},
    })
    .to_string();
    assert!(
        evaluate_claude_pre_tool_use_with_env(&input, &env_indexed()).is_empty(),
        "the event cwd decides in both directions, for Claude too"
    );
}

#[test]
fn test_unusable_event_cwd_keeps_the_process_environment() {
    let (tmp, root) = indexed_project();
    let missing = root.join("gone");
    let file = root.join("Cargo.toml");
    std::fs::write(&file, "[package]\n").expect("write file");
    let cases = vec![
        ("no key".to_string(), None),
        ("blank".to_string(), Some(serde_json::json!(""))),
        ("whitespace".to_string(), Some(serde_json::json!("   "))),
        (
            "relative".to_string(),
            Some(serde_json::json!("crates/api")),
        ),
        (
            "non-existent".to_string(),
            Some(serde_json::json!(missing.to_string_lossy())),
        ),
        (
            "a file, not a directory".to_string(),
            Some(serde_json::json!(file.to_string_lossy())),
        ),
        ("null".to_string(), Some(serde_json::Value::Null)),
        ("a number".to_string(), Some(serde_json::json!(7))),
        (
            "an object".to_string(),
            Some(serde_json::json!({"path": tmp.path().to_string_lossy()})),
        ),
    ];

    for (label, cwd) in cases {
        let mut event = serde_json::json!({
            "tool_name": "Execute",
            "tool_input": {"command": "rg -n handle_request src/"},
        });
        if let Some(cwd) = cwd {
            event["cwd"] = cwd;
        }
        let input = event.to_string();
        assert!(
            evaluate_droid_pre_tool_use_with_env(&input, &env_indexed()).is_some(),
            "{label}: an unusable cwd must fall back to the hook process environment"
        );
        assert!(
            evaluate_droid_pre_tool_use_with_env(&input, &env_not_indexed()).is_none(),
            "{label}: the fallback must not invent a project either"
        );
    }
}

#[test]
fn test_absolute_ancestor_root_target_redirects_from_a_subdirectory() {
    let (_tmp, root) = indexed_project();
    let nested = root.join("crates").join("api");
    std::fs::create_dir_all(&nested).expect("create nested dirs");
    let input = serde_json::json!({
        "cwd": nested.to_string_lossy(),
        "tool_name": "Execute",
        "tool_input": {"command": format!("rg -n handle_request {}", root.display())},
    })
    .to_string();
    assert!(
        evaluate_droid_pre_tool_use_with_env(&input, &env_not_indexed()).is_some(),
        "the discovered ancestor root is the whole-project target"
    );
}