trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! `tm hook` `PreToolUse` Bash command-rewrite logic — Option 0 spike (#1956).
//!
//! Why: `docs/specs/tool-output-interception-seam.md` §Option 0 documents a
//! pre-context-insertion compression seam for Bash: rewrite the *command*
//! Claude Code is about to execute so the subprocess's own stdout is already
//! filtered by the time the tool result is captured — the same trick
//! claude-mpm's `ztk` hook uses (`hooks/ztk_hook.py`), but piping through
//! `tm compress` instead of an external Zig binary. That doc's Tradeoffs
//! section calls out the exact incident this must defend against from day
//! one: an earlier orchestrator command (a SAM build) broke when wrapped
//! unconditionally, because appending a pipe can change exit-code semantics
//! (`set -o pipefail` interactions) for build tools that spawn long
//! subprocess chains.
//! What: [`rewrite_bash_command_for_compression`] is the single entry point —
//! it returns `None` (meaning: do not rewrite, forward the command
//! unmodified) for empty commands, day-one orchestrator exclusions
//! (`make`/`sam`/`rake`/`gradle`/`gradlew`/`mvn`/`ant`/`cdk`/`terraform`,
//! mirroring claude-mpm's `_ORCHESTRATOR_EXCLUSIONS`), any command that
//! already contains pipe/chain/redirection/background composition (`|`,
//! `&`, `;`, `>`, `<`) since appending another pipe to those is the same class of
//! risk (redirection in particular: piping `tm compress` after an
//! already-redirected stdout gets it empty input for no benefit — a
//! trusty-review finding, PR #1968), any command a brace group cannot wrap —
//! a `#`, or a trailing unescaped `\` (see [`cannot_be_brace_wrapped`]) —
//! and any command whose derived tool
//! name would embed shell metacharacters (see
//! [`is_safe_tool_name`]). Otherwise it returns `Some(rewritten)`: the command
//! inside a brace group that reports its exit status, with
//! `| tm compress --tool "<effective tool name>"` appended — see
//! [`effective_tool_name`] for why the tool value is derived from the
//! command rather than a hardcoded `"bash"`, and
//! [`crate::commands::compress::wrap_command_reporting_exit`] for the group.
//! [`build_pretooluse_rewrite_response`] builds the
//! `hookSpecificOutput.updatedInput` JSON body `tm hook` prints to stdout so
//! Claude Code substitutes the rewritten command before executing it — this
//! exact shape is confirmed against the live Claude Code hooks reference
//! (<https://code.claude.com/docs/en/hooks>, confirmed 2026-07-03; see that
//! function's doc comment for the citation).
//! Test: `rewrite_*`, `is_orchestrator_command_*`, `first_command_token_*`,
//! `is_safe_tool_name_*`, `build_pretooluse_rewrite_response_*` below.

// #6566: the tool-name coverage predicate lives beside the filter dispatch it
// predicts, in `trusty-agents-common`, so the two cannot drift apart.
use trusty_agents_common::compress::has_filter_for;
// #7120: the #6986 source-read predicate, asked of the whole command.
use trusty_agents_common::compress::tool_output::is_source_file_read;
// #7477: the worktree resolver the `EnterWorktree` guard already uses.
use std::path::{Path, PathBuf};
use trusty_mpm::core::project_aliases::worktree_root;

/// Day-one orchestrator-command exclusion list.
///
/// Why: These tools spawn long, multi-stage subprocess chains where an
/// unconditional `| tm compress --tool bash` wrap has already caused a real
/// incident (a SAM build silently truncated at a later stage — see the
/// design doc's Tradeoffs section and `docs/specs/SPEC-INSTALLER-01.md:150`).
/// Mirrors claude-mpm's `_ORCHESTRATOR_EXCLUSIONS` (`hooks/ztk_hook.py`
/// ~lines 49-69) so this spike inherits the same day-one safety margin
/// rather than rediscovering the failure mode.
/// What: Matched against the command's first whitespace-delimited token
/// (after stripping env-var-assignment prefixes, `sudo`/`env`, and any
/// leading path) by [`is_orchestrator_command`].
/// Test: `is_orchestrator_command_matches_known_exclusions`.
const ORCHESTRATOR_EXCLUSIONS: &[&str] = &[
    "make",
    "sam",
    "rake",
    "gradle",
    "gradlew",
    "mvn",
    "ant",
    "cdk",
    "terraform",
];

/// Decide whether `command` is safe to rewrite, and build the rewrite.
///
/// Why: Centralises the "is this rewrite safe?" decision so `tm hook` can
/// stay a thin caller — better to under-rewrite (skip a compressible
/// command) than to break a working one, per the design doc's explicit
/// tradeoff framing.
/// What: Returns `None` (no-op — forward the original command unmodified)
/// when `command` is empty/whitespace-only, matches
/// [`is_orchestrator_command`], already contains pipe/chain composition
/// (see [`has_unsafe_pipe_composition`]), or derives a tool name containing
/// shell metacharacters (see [`is_safe_tool_name`] — a
/// trusty-review-flagged injection risk, PR #1968: the derived name is
/// embedded verbatim inside a double-quoted shell argument below, and
/// double quotes do not stop POSIX command substitution). Otherwise returns
/// `Some("{ <command>; <exit sentinel>; } | tm compress --tool \"<effective tool name>\"")` —
/// the brace group and its trailing `printf` come from
/// [`crate::commands::compress::wrap_command_reporting_exit`], which is what
/// carries the wrapped command's exit status into a filter the shell started
/// concurrently (#7384). Every guard above runs against the bare command, and
/// [`cannot_be_brace_wrapped`] adds the two the group itself needs: a `#`
/// comments out the group's own `printf` and closing brace, and a trailing `\`
/// escapes its `;`. A command carrying either is forwarded unmodified —
/// the `--tool` value comes from [`effective_tool_name`], **not** a
/// hardcoded `"bash"`: `compress_tool_output`'s dispatch table
/// (`trusty-agents-common::compress::tool_output`) matches filters by
/// substring against the tool name (`"cargo"`, `"diff"`, `"log"`, …), so a
/// literal `"bash"` would never match any filter branch and every rewritten
/// command would silently pass through with 0% compression — defeating the
/// entire point of this spike. Quoted because the derived name may contain
/// a space (e.g. `"cargo test"`).
/// Finally, it returns `None` when no compression filter covers the derived
/// tool name (#6566): the wrap used to be unconditional, so a `git status`,
/// `sed -n`, or `gh pr list` paid a `tm compress` process spawn to get its
/// own bytes back. Over 48h of `~/.trusty-mpm/compression.jsonl`, 3,415 of
/// 3,643 wrapped invocations (93.7%) reduced nothing. The tool-name list
/// stays in `trusty-agents-common` — this module asks
/// `compress::has_filter_for` rather than keeping a second copy that could
/// drift from the dispatch it is meant to predict.
/// It also returns `None` for a read verb applied to a source file (#7120),
/// asked of the whole command rather than the derived name: `cat foo.rs`
/// already fails `has_filter_for`, but `cat -n foo.rs` derives `"cat -n"` and
/// reaches the file-read filter, so the flagged spelling bypass-permissions
/// mode uses paid a compress spawn for its own bytes back.
/// Test: `rewrite_appends_compress_pipe_for_plain_command`,
/// `rewrite_skips_a_flagged_source_read`,
/// `rewrite_appends_compress_pipe_with_subcommand_tool_name`,
/// `rewrite_skips_orchestrator_commands`, `rewrite_skips_piped_commands`,
/// `rewrite_skips_chained_commands`, `rewrite_skips_empty_command`,
/// `rewrite_skips_command_substitution_in_tool_name`,
/// `rewrite_skips_tools_with_no_compression_filter`,
/// `rewrite_still_wraps_tools_with_a_compression_filter`.
pub(crate) fn rewrite_bash_command_for_compression(command: &str) -> Option<String> {
    let trimmed = command.trim();
    if trimmed.is_empty() {
        return None;
    }
    if is_orchestrator_command(trimmed) {
        return None;
    }
    if has_unsafe_pipe_composition(trimmed) {
        return None;
    }
    // #7384: a comment or a trailing `\` would swallow or absorb the brace
    // group's own `printf`, so such a command is never wrapped.
    if cannot_be_brace_wrapped(trimmed) {
        return None;
    }
    // #7120: asked of the WHOLE command, because `effective_tool_name` keeps
    // only the first two tokens and a flag displaces the path out of them —
    // `cat -n <file>.rs` derives `"cat -n"`, which `classify_tool` routes to
    // the file-read filter the #6986 passthrough exists to keep source away
    // from.
    if is_source_file_read(trimmed) {
        return None;
    }
    let tool = effective_tool_name(trimmed);
    if !is_safe_tool_name(&tool) {
        return None;
    }
    // #6566: no filter covers this tool name, so the wrap would spawn a
    // process that returns its input unchanged.
    if !has_filter_for(&tool) {
        return None;
    }
    // #7384: the brace group carries the wrapped command's exit status into the
    // filter, which a pipeline otherwise discards.
    Some(format!(
        "{} | tm compress --tool \"{tool}\"",
        crate::commands::compress::wrap_command_reporting_exit(trimmed)
    ))
}

/// [`rewrite_bash_command_for_compression`], unless the call runs in an
/// isolation worktree.
///
/// Why (#7477): Claude Code's worktree-isolation classifier refuses the
/// rewritten `{ …; printf …; } | tm compress --tool "…"` shape, so a wrapped
/// `git diff`, `ls -la` or `cargo test` never runs in an agent's isolation
/// worktree. The `SUB_AGENT_ENV` gate in `misc::hook` does not cover those
/// agents: only trusty-agents' own spawns set that variable.
/// What: `None` when `hook_cwd` sits in an isolation worktree
/// ([`is_isolation_worktree`]), and also when `hook_cwd` is absent or empty —
/// a cwd the hook cannot read cannot be shown to be outside one, and an
/// unwrapped command never trips the classifier. Otherwise exactly
/// [`rewrite_bash_command_for_compression`].
/// Test: `no_rewrite_inside_an_isolation_worktree`,
/// `rewrite_outside_an_isolation_worktree_is_unchanged`,
/// `no_rewrite_when_the_cwd_is_undecidable`.
pub(crate) fn rewrite_bash_command_unless_isolated(
    command: &str,
    hook_cwd: Option<&Path>,
) -> Option<String> {
    let cwd = hook_cwd.filter(|c| !c.as_os_str().is_empty())?;
    if is_isolation_worktree(cwd) {
        return None;
    }
    rewrite_bash_command_for_compression(command)
}

/// Whether `cwd` sits in a Claude Code isolation worktree (#7477).
///
/// Why: `isolation: "worktree"` provisions trees under `<repo>/.claude/worktrees/`
/// (ADR-0020's harness store). A tm session worktree under `.worktrees/` hosts
/// the PM itself, meets no isolation classifier, and keeps its compression.
/// What: [`worktree_root`] — the resolver the `EnterWorktree` guard reads a
/// caller's pinned tree from — names a tree whose container is
/// `.claude/worktrees`. Purely lexical, like that guard.
/// Test: `no_rewrite_inside_an_isolation_worktree`,
/// `rewrite_outside_an_isolation_worktree_is_unchanged`.
fn is_isolation_worktree(cwd: &Path) -> bool {
    worktree_root(cwd)
        .and_then(|root| root.parent().map(|p| p.ends_with(".claude/worktrees")))
        .unwrap_or(false)
}

/// The directory a hook call runs in: the payload's `cwd`, else the hook's own.
///
/// Why (#7477): the same resolution `pm_guard` applies to its `hook_cwd`, so
/// both hooks agree on which tree a call stands in.
/// What: the payload's string `cwd`, else [`std::env::current_dir`], else
/// `None` — which [`rewrite_bash_command_unless_isolated`] treats as isolated.
/// Test: `hook_stays_silent_for_a_bash_call_in_an_isolation_worktree`.
pub(crate) fn hook_cwd(payload: Option<&serde_json::Value>) -> Option<PathBuf> {
    payload
        .and_then(|v| v.get("cwd"))
        .and_then(|v| v.as_str())
        .map(PathBuf::from)
        .or_else(|| std::env::current_dir().ok())
}

/// Derive the `compress_tool_output` dispatch key from a Bash command.
///
/// Why: The dispatch table in `trusty-agents-common::compress::tool_output`
/// matches per-tool filters by substring against a `tool_name` string shaped
/// like `"cargo test"` / `"git diff"` (see that module's `cargo`/`git`
/// branches) — it has no branch for the literal string `"bash"`. Passing
/// the command's actual program + subcommand lets the existing `cargo
/// test`/`cargo check`/`git diff`/`git log` filters fire for the domains
/// they already cover. Commands outside that coverage (`git status`, `sed`,
/// `gh pr list`, …) are no longer wrapped at all since #6566 — the caller
/// checks the derived name against `compress::has_filter_for` first.
/// What: Strips the same env-assignment/`sudo`/`env`/path noise
/// [`first_command_token`] strips (looping so `env FOO=bar cargo test` and
/// similar multi-prefix combinations resolve correctly — a trusty-review
/// finding, PR #1968: a one-shot `if first == "sudo"` check left the literal
/// `env` command unhandled, e.g. `env FOO=bar cargo test` previously
/// resolved to the wrong tool name `"env FOO=bar"` instead of `"cargo
/// test"`), then returns `"<program> <subcommand>"` when a second
/// whitespace-delimited token follows, else just `<program>`.
/// Test: `effective_tool_name_joins_program_and_subcommand`,
/// `effective_tool_name_single_token_command`,
/// `effective_tool_name_strips_env_and_sudo_noise`,
/// `effective_tool_name_strips_env_command_prefix`.
pub(crate) fn effective_tool_name(command: &str) -> String {
    // #7399 finding (b): the same lexer [`first_command_token`] uses, so the
    // `npm test` matcher in `pm_guard_bash::classify_bash_segment` sees the
    // program bash would exec — `"/opt/My Tools/npm" test` and `n"p"m test`
    // both resolve to `npm test` rather than to a fragment of the path.
    let words = shlex_words(command);
    let mut tokens = words.iter().map(String::as_str);
    let Some(mut first) = tokens.next() else {
        return String::new();
    };
    loop {
        if is_env_assignment(first) {
            let Some(next) = tokens.next() else {
                return String::new();
            };
            first = next;
            continue;
        }
        if first == "sudo" || first == "env" {
            match tokens.next() {
                Some(next) if !next.starts_with('-') => {
                    first = next;
                    continue;
                }
                // Either nothing follows `sudo`/`env`, or the next token is
                // itself a flag (e.g. `sudo -u root make`, `env -i cmd`).
                // Resolving the real program name in that case needs
                // argument-aware parsing this function doesn't do; rather
                // than guess and derive a bogus tool name (trusty-review
                // finding, PR #1968: `sudo -u root make build` previously
                // resolved to `"-u root"` instead of recognising `make`),
                // degrade to "unknown" — `is_safe_tool_name` already
                // rejects an empty string, so the caller safely skips the
                // rewrite.
                _ => return String::new(),
            }
        }
        break;
    }
    let program = first.rsplit('/').next().unwrap_or(first);
    match tokens.next() {
        Some(subcommand) => format!("{program} {subcommand}"),
        None => program.to_string(),
    }
}

/// Whether `tool_name` is safe to embed verbatim inside the double-quoted
/// `--tool "<tool_name>"` argument of the rewritten command.
///
/// Why: [`effective_tool_name`] derives its value from whitespace-delimited
/// tokens of the *user-supplied* Bash command with no further sanitisation.
/// Wrapping the value in double quotes only defeats word-splitting — POSIX
/// shells still perform command substitution (`$(...)`, backticks) and
/// variable expansion (`$VAR`) *inside* double-quoted strings, and an
/// embedded `"` would terminate the quoted argument early and let whatever
/// follows be interpreted as new shell syntax. A command whose first two
/// tokens happen to contain any of those characters — e.g.
/// `echo $(touch /tmp/pwned)` — would therefore have that substitution
/// re-evaluated a second time, in a new shell position, as part of building
/// the `--tool` argument (trusty-review-flagged shell-injection risk, PR
/// #1968; confirmed by an independent `review_diff` pass).
/// What: `true` only when every character is ASCII alphanumeric or one of
/// the small set that legitimately appears in tool names/subcommands/paths
/// (space, `-`, `_`, `.`, `/`, `:`) — exactly what `"cargo test"`,
/// `"git diff"`, or `"./scripts/foo.sh"` need. Anything else (`$`,
/// backticks, `"`, `\`, parens, newlines, …) is rejected, and
/// [`rewrite_bash_command_for_compression`] falls back to its safe
/// no-rewrite default rather than risk embedding it.
/// Test: `is_safe_tool_name_allows_typical_tool_names`,
/// `is_safe_tool_name_rejects_shell_metacharacters`.
fn is_safe_tool_name(tool_name: &str) -> bool {
    !tool_name.is_empty()
        && tool_name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_' | '.' | '/' | ':'))
}

/// Whether `command`'s first token matches a known orchestrator exclusion.
///
/// Why: Split out from [`rewrite_bash_command_for_compression`] for direct
/// unit testing of the matching rule independent of the rewrite string
/// format.
/// What: Delegates token extraction to [`first_command_token`], then does a
/// case-sensitive exact match against [`ORCHESTRATOR_EXCLUSIONS`]. When
/// [`first_command_token`] can't confidently resolve the real program name
/// (returns `None` — e.g. `sudo -u root make`, where the token after `sudo`
/// is itself a flag, not a program), this conservatively returns `true`
/// (treat as orchestrator-like, i.e. don't rewrite) rather than `false`: a
/// trusty-review-flagged fail-open gap (PR #1968) where "can't tell" used
/// to mean "assume it's safe to rewrite" — backwards for a safety check
/// whose entire purpose is avoiding exactly this kind of unrecognised
/// build-orchestrator invocation.
/// Test: `is_orchestrator_command_matches_known_exclusions`,
/// `is_orchestrator_command_ignores_unrelated_commands`,
/// `is_orchestrator_command_conservatively_true_for_sudo_with_flags`.
fn is_orchestrator_command(command: &str) -> bool {
    match first_command_token(command) {
        Some(program) => ORCHESTRATOR_EXCLUSIONS.contains(&program.as_str()),
        None => true,
    }
}

// #8735: the wrapper list moved beside its option grammars, in `program_word`.
pub(crate) use super::program_word::COMMAND_WRAPPERS;

/// Skip a leading run of `KEY=value` env-assignments and [`COMMAND_WRAPPERS`]
/// tokens in `tokens` (a leading `\` on any token stripped before comparison,
/// per the same alias-bypass idiom [`first_command_token`] documents),
/// returning the index of the first token that is neither — the real command
/// — or `None` when a wrapper takes an option (`sudo -u root make`, `env -i
/// cmd`), carries an option or operand the resolver cannot measure, or has
/// nothing after it.
///
/// Why: [`first_command_token`] and `pm_guard_bash::shell_lex::git_subcommand`
/// both need this exact skip — a wrapper reaching either unresolved is a
/// classifier silently seeing a different (wrapped) command than the one
/// that will actually run (issue #4031 review). #8735: the skip is now the
/// shared `program_word` resolver, so `timeout 5 make` resolves to `make`
/// rather than to its duration `5`; the `None` answers are unchanged.
/// What: delegates to `program_word::precommand_index`.
/// Test: `strip_wrapper_prefix_skips_env_assignment`,
/// `strip_wrapper_prefix_skips_every_known_wrapper`,
/// `strip_wrapper_prefix_none_for_wrapper_followed_by_flag`,
/// `strip_wrapper_prefix_skips_backslash_before_a_wrapper`.
pub(crate) fn strip_wrapper_prefix<T: AsRef<str>>(tokens: &[T]) -> Option<usize> {
    super::program_word::precommand_index(tokens)
}

/// Extract the effective first command token, stripping noise prefixes.
///
/// Why: A raw `command.split_whitespace().next()` would miss
/// `FOO=bar make build` (env-var prefix), `sudo make install`, and
/// `/usr/bin/make` (absolute path) — all of which should still match
/// `make` for exclusion purposes. Being permissive here trades a little
/// precision for staying on the safe (under-rewrite) side.
/// What: delegates the prefix-skip to [`strip_wrapper_prefix`], then returns
/// the basename (post-`/`, post-`\`) of whatever token remains.
/// Returns `None` — "can't confidently resolve" — under the same condition
/// [`strip_wrapper_prefix`] does (a wrapper followed by a flag-shaped
/// token): the real program name in that case needs argument-aware parsing
/// this function doesn't do, and [`is_orchestrator_command`] treats `None`
/// as "conservatively assume orchestrator" rather than risk missing a real
/// exclusion (trusty-review finding, PR #1968).
/// Test: `first_command_token_strips_env_assignment`,
/// `first_command_token_strips_sudo`, `first_command_token_strips_path`,
/// `first_command_token_plain_command`,
/// `first_command_token_strips_env_command_prefix`,
/// `first_command_token_none_for_sudo_followed_by_flag`,
/// `first_command_token_strips_leading_backslash`,
/// `first_command_token_strips_command_wrapper`,
/// `first_command_token_strips_builtin_wrapper`,
/// `first_command_token_strips_backslash_after_sudo`,
/// `first_command_token_strips_nice_time_nohup_exec`,
/// `first_command_token_resolves_a_quoted_path_with_spaces`,
/// `first_command_token_resolves_a_quoted_forbidden_verb`,
/// `first_command_token_resolves_split_quoting`,
/// `first_command_token_keeps_the_fallback_answer_on_unbalanced_quoting`.
///
/// #7374/#7399: the name is resolved through [`shlex_words`], the lexer bash
/// agrees with, so `s"e"d`, `'se'"d"` and `/opt/my\ tools/sed` all resolve to
/// `sed`. A `split_whitespace` scan could not: it reads a quote as an ordinary
/// character, so a verb spelled across adjacent quote fragments never matched
/// a rule and `bash -c 's"e"d -i x f'` ran the real `sed`.
pub(crate) fn first_command_token(command: &str) -> Option<String> {
    program_basename(&shlex_words(command))
}

/// The command's words, lexed the way bash lexes them.
///
/// Why (#7374, #7399 finding (b)): quoting is not decoration — bash strips it
/// before deciding which program to exec, so any classifier that reads the
/// command name off a `split_whitespace` scan is reading a different command
/// than the one that will run. `shlex` is already this crate's answer to that
/// question (`pm_guard_bash::shell_lex::git_subcommand` resolves a git
/// subcommand with it), so this routes the command-name decision through the
/// same lexer rather than growing a second, weaker one.
/// What: `shlex::split` when the command lexes. When it does not — unbalanced
/// quoting, a trailing lone backslash — this falls back to the plain
/// whitespace split the callers had before, never to anything wider: a command
/// the lexer cannot read must not gain an allow it did not already have. A
/// command that genuinely cannot be classified is refused upstream by
/// `pm_guard_bash::unclassifiable_command`.
/// Test: `shlex_words_lexes_split_quoting`,
/// `shlex_words_falls_back_on_unbalanced_quoting`.
fn shlex_words(command: &str) -> Vec<String> {
    shlex::split(command).unwrap_or_else(|| {
        command
            .split_whitespace()
            .map(str::to_string)
            .collect::<Vec<_>>()
    })
}

/// The program name `tokens` would run, past env assignments and wrappers.
///
/// What: delegates the prefix-skip to [`strip_wrapper_prefix`], then returns
/// the basename (post-`/`, post-`\`) of the token it stops at. `None` under
/// the one condition [`strip_wrapper_prefix`] reports it — a wrapper followed
/// by a flag-shaped token.
/// Test: every `first_command_token_*` case reaches this.
fn program_basename(tokens: &[String]) -> Option<String> {
    let start = strip_wrapper_prefix(tokens)?;
    let tok = tokens.get(start)?.as_str();
    let tok = tok.strip_prefix('\\').unwrap_or(tok);
    Some(tok.rsplit('/').next().unwrap_or(tok).to_string())
}

/// Whether `token` looks like a `KEY=value` shell environment assignment.
///
/// Why: Shared by [`strip_wrapper_prefix`]; split out so the "what counts as
/// an env assignment" rule has one definition.
/// What: `KEY` must be non-empty, start with a letter or underscore, and
/// contain only alphanumerics/underscores up to the first `=`.
pub(crate) fn is_env_assignment(token: &str) -> bool {
    let Some((key, _value)) = token.split_once('=') else {
        return false;
    };
    !key.is_empty()
        && key
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// Whether `command` already contains pipe/chain/redirection/background
/// composition.
///
/// Why: Appending a second pipe to a command that already pipes/chains
/// (`|`, `&&`, `;`) is the same class of risk the orchestrator exclusion
/// guards against — the design doc explicitly calls out "don't rewrite
/// something that already contains a `|` or `&&`/`;` chain that could break
/// under an additional pipe". Output/input redirection (`>`, `>>`, `<`) is
/// the same class of risk from the opposite direction: a trusty-review
/// finding (PR #1968) noted that `cargo test > out.log`, rewritten to
/// `cargo test > out.log | tm compress --tool "cargo test"`, pipes
/// `tm compress` an *empty* stdin (stdout was already redirected to the
/// file) — the rewrite would silently do nothing useful while altering the
/// command's pipeline/exit-code shape for no benefit. Backgrounding (`&`) is
/// a third variant of the same risk (a further trusty-review finding, PR
/// #1968): `cargo test &` rewritten to `cargo test & | tm compress ...`
/// is invalid shell syntax in most shells, not merely a no-op.
/// What: Simple substring checks — deliberately conservative (a command
/// with `|`/`&`/`;`/`>`/`<` inside a quoted string literal will also be
/// skipped; under-rewriting is the safe failure mode here). A single
/// `contains('&')` check subsumes both the `&&` chain operator and the
/// standalone backgrounding `&` — there's no case where `&` is safe to
/// leave unguarded in this position.
/// Test: `has_unsafe_pipe_composition_detects_pipe`,
/// `has_unsafe_pipe_composition_detects_and_chain`,
/// `has_unsafe_pipe_composition_detects_semicolon`,
/// `has_unsafe_pipe_composition_detects_output_redirection`,
/// `has_unsafe_pipe_composition_detects_input_redirection`,
/// `has_unsafe_pipe_composition_detects_background_operator`,
/// `has_unsafe_pipe_composition_false_for_plain_command`.
fn has_unsafe_pipe_composition(command: &str) -> bool {
    command.contains('|')
        || command.contains('&') // catches both `&&` chaining and background `&`
        || command.contains(';')
        || command.contains('>')
        || command.contains('<')
}

/// Whether wrapping `command` in a brace group would change what runs.
///
/// Why: #7384 puts the command, the exit-status `printf` and the closing `}` on
/// ONE physical line, which two shapes break. An unquoted `#` starts a comment
/// that swallows the rest of that line, so the group never closes — sh, bash
/// and zsh all abort with a syntax error and the command does not run at all. A
/// trailing unescaped `\` escapes the template's `;`, so the `printf`, its
/// format string and `"$?"` become extra arguments to the command — no error,
/// wrong output, status lost. [`has_unsafe_pipe_composition`] catches neither,
/// because neither character composes anything on its own.
/// What: rejects any `#`, and any command whose trailing run of backslashes is
/// odd. `#` is rejected wherever it appears: `grep -c '#include' f` is quoted
/// and would be safe, but telling that from a comment needs a shell parser, and
/// under-rewriting is the safe side here for exactly the reason
/// [`has_unsafe_pipe_composition`] already gives. Such a command is forwarded
/// unmodified and simply goes uncompressed.
/// Test: `rewrite_skips_a_command_a_brace_group_cannot_wrap`,
/// `cannot_be_brace_wrapped_counts_trailing_backslashes`,
/// `every_rewrite_this_module_emits_runs_correctly_in_a_real_shell`.
fn cannot_be_brace_wrapped(command: &str) -> bool {
    let trailing_backslashes = command.chars().rev().take_while(|c| *c == '\\').count();
    command.contains('#') || trailing_backslashes % 2 == 1
}

/// Build the `hookSpecificOutput.updatedInput` JSON body for a `PreToolUse`
/// Bash command rewrite.
///
/// Why: This is the JSON shape `tm hook` prints to stdout so Claude Code
/// substitutes `rewritten_command` for the original before executing it.
/// Originally implemented per the shape sketched in
/// `docs/specs/tool-output-interception-seam.md` §Option 0 (itself derived
/// from claude-mpm's `ztk_hook.py::_build_ztk_response_impl` convention) with
/// no in-repo reference to confirm it. **Confirmed against the live Claude
/// Code hooks reference** (<https://code.claude.com/docs/en/hooks>,
/// confirmed 2026-07-03 while addressing a trusty-review finding on PR
/// #1968): "PreToolUse: `updatedInput` directly under `hookSpecificOutput`
/// replaces a tool's arguments before it runs," with the documented example
/// matching this shape exactly. That same reference also confirms (a) the
/// hook's response is only parsed on `exit 0`, and stdout "must contain only
/// the JSON object" for that parse to succeed — see `misc::hook`'s doc
/// comment for why the caller now returns immediately after printing this
/// — and (b) the stdin payload field names this module's caller
/// (`misc::hook`) reads (`hook_event_name`, `tool_name`,
/// `tool_input.command`) match the live protocol. This function itself has
/// no failure path: parsing failures upstream (in `misc::read_stdin_hook_payload`)
/// already degrade to "no stdin payload" before this is ever called, so an
/// invalid/unrecognised hook payload shape fails safe as a silent no-op, not
/// a malformed response.
/// What: `{"hookSpecificOutput": {"hookEventName": "PreToolUse",
/// "updatedInput": {"command": rewritten_command}}}`.
/// Test: `build_pretooluse_rewrite_response_has_expected_shape`.
pub(crate) fn build_pretooluse_rewrite_response(rewritten_command: &str) -> serde_json::Value {
    serde_json::json!({
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "updatedInput": { "command": rewritten_command }
        }
    })
}

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

    /// The one place the whole rewritten string is spelled out.
    ///
    /// #7384 put the command inside a brace group with a trailing exit-status
    /// `printf`; the producer of that group is `commands::compress`, so every
    /// expectation below is built from it rather than from a second literal
    /// that could drift away from what the filter parses.
    fn expected_rewrite(command: &str, tool: &str) -> String {
        format!(
            "{} | tm compress --tool \"{tool}\"",
            crate::commands::compress::wrap_command_reporting_exit(command)
        )
    }

    #[test]
    fn rewrite_appends_compress_pipe_for_plain_command() {
        let out = rewrite_bash_command_for_compression("cargo test");
        assert_eq!(
            out.as_deref(),
            Some(expected_rewrite("cargo test", "cargo test").as_str())
        );
        // #7384: the command still runs first and the pipe still terminates in
        // the filter — the group only adds the status report.
        let out = out.expect("a covered tool must be wrapped");
        assert!(out.starts_with("{ cargo test; printf "), "{out}");
        assert!(
            out.ends_with("} | tm compress --tool \"cargo test\""),
            "{out}"
        );
    }

    #[test]
    fn rewrite_appends_compress_pipe_with_subcommand_tool_name() {
        // The `--tool` value must be the derived "<program> <subcommand>"
        // pair (matching the compress dispatch table's filter keys), not a
        // hardcoded "bash" — see `effective_tool_name`'s doc comment for why
        // a literal "bash" would never match any filter branch.
        let out = rewrite_bash_command_for_compression("git diff HEAD~1");
        assert_eq!(
            out.as_deref(),
            Some(expected_rewrite("git diff HEAD~1", "git diff").as_str())
        );
    }

    /// The three commands #7477 saw refused, each a covered tool.
    const ISOLATION_REFUSED: [&str; 3] = ["git diff", "ls -la", "cargo test"];

    #[test]
    fn no_rewrite_inside_an_isolation_worktree() {
        // #7477: the harness classifier refuses the wrapped shape here, so the
        // command must reach Claude Code exactly as written.
        for cwd in [
            "/repo/.claude/worktrees/agent-a",
            "/repo/.claude/worktrees/agent-a/crates/trusty-mpm",
            "/repo/.base/.worktrees/session-x/.claude/worktrees/agent-b",
        ] {
            for cmd in ISOLATION_REFUSED {
                assert!(
                    rewrite_bash_command_for_compression(cmd).is_some(),
                    "{cmd} must be a covered tool, or this test proves nothing"
                );
                assert_eq!(
                    rewrite_bash_command_unless_isolated(cmd, Some(Path::new(cwd))),
                    None,
                    "{cmd} in {cwd}"
                );
            }
        }
    }

    #[test]
    fn rewrite_outside_an_isolation_worktree_is_unchanged() {
        // A main checkout, a tm session worktree, and the `.claude/worktrees`
        // container itself (which names no single tree) all keep the wrap.
        for cwd in [
            "/repo",
            "/repo/crates/trusty-mpm",
            "/repo/.base/.worktrees/session-x",
            "/repo/.claude/worktrees",
            "/repo/worktrees/agent-a",
        ] {
            for cmd in ISOLATION_REFUSED {
                assert_eq!(
                    rewrite_bash_command_unless_isolated(cmd, Some(Path::new(cwd))),
                    rewrite_bash_command_for_compression(cmd),
                    "{cmd} in {cwd}"
                );
            }
        }
    }

    #[test]
    fn no_rewrite_when_the_cwd_is_undecidable() {
        // #7477 fail-open arm: no readable cwd means isolation cannot be ruled
        // out, and the unwrapped command is the one the classifier accepts.
        for cmd in ISOLATION_REFUSED {
            assert_eq!(rewrite_bash_command_unless_isolated(cmd, None), None);
            assert_eq!(
                rewrite_bash_command_unless_isolated(cmd, Some(Path::new(""))),
                None
            );
        }
    }

    #[test]
    fn cannot_be_brace_wrapped_counts_trailing_backslashes() {
        // An ODD trailing run escapes the template's `;`; an even run is an
        // escaped backslash and leaves the `;` alone.
        assert!(cannot_be_brace_wrapped("ls -la \\"));
        assert!(!cannot_be_brace_wrapped("ls -la \\\\"));
        assert!(cannot_be_brace_wrapped("ls -la \\\\\\"));
        // A backslash that is not at the end escapes something in the command
        // itself and cannot reach the template's `;`.
        assert!(!cannot_be_brace_wrapped("grep -n hi\\ there f"));
        // `#` anywhere, quoted or not — see the function's doc comment.
        assert!(cannot_be_brace_wrapped("cargo test # explain"));
        assert!(cannot_be_brace_wrapped("grep -c '#include' f"));
        assert!(!cannot_be_brace_wrapped("cargo test -p trusty-mpm"));
    }

    #[test]
    fn rewrite_skips_a_command_a_brace_group_cannot_wrap() {
        // #7384 round 2: both shapes reached the rewrite and both broke it —
        // the comment swallowed the group's own `printf` and closing brace
        // (syntax error, command never ran), the trailing backslash escaped the
        // `;` and turned the `printf` into arguments (silently wrong output).
        // The documented no-op is the safe answer for both.
        for cmd in [
            "cargo test # explain",
            "grep -c '#include' src/lib.rs",
            "cargo test -p x \\",
            "git diff HEAD~1 \\",
        ] {
            assert_eq!(
                rewrite_bash_command_for_compression(cmd),
                None,
                "a brace group cannot wrap this safely: {cmd}"
            );
        }
    }

    /// Whether `shell` can be spawned on this host.
    fn shell_is_available(shell: &str) -> bool {
        std::process::Command::new(shell)
            .arg("-c")
            .arg("exit 0")
            .output()
            .is_ok()
    }

    /// Run `script` under `shell`, returning its exit code, stdout and stderr.
    fn run_script(shell: &str, script: &str) -> (Option<i32>, String, String) {
        let out = std::process::Command::new(shell)
            .arg("-c")
            .arg(script)
            .output()
            .unwrap_or_else(|e| panic!("failed to run {shell}: {e}"));
        (
            out.status.code(),
            String::from_utf8_lossy(&out.stdout).into_owned(),
            String::from_utf8_lossy(&out.stderr).into_owned(),
        )
    }

    /// Execute what this module emits, in a real shell, for the four shapes.
    ///
    /// Why: every other test here asserts the SHAPE of the rewritten string,
    /// which is how #7384 round 1 shipped a string all three shells reject with
    /// `unexpected end of file` — the assertions matched and the command could
    /// never have run. This one runs it.
    /// What: for each shape, either the rewrite exists and its brace group must
    /// run cleanly and preserve both the command's output and the sentinel, or
    /// the rewrite is the documented no-op and the bare command must still do
    /// its own job with nothing from the template leaking into it. The filter
    /// stage is swapped for `cat` — `tm` need not be installed where unit tests
    /// run, and `tm compress`'s own behaviour is proven in `tm_compress_pipe`;
    /// the brace group, which is what this test is about, is untouched.
    /// Test: itself.
    #[test]
    fn every_rewrite_this_module_emits_runs_correctly_in_a_real_shell() {
        let dir = tempfile::tempdir().expect("temp dir");
        let payload = dir.path().join("payload.txt");
        std::fs::write(&payload, "alpha\nhi there\nomega\n").expect("write payload");
        let path = payload.display().to_string();
        let plain = format!("grep -n hi {path}");

        // (command, what its own stdout must contain when it runs bare)
        let cases = [
            (plain.clone(), "2:hi there"),
            (format!("{plain} # explain"), "2:hi there"),
            (format!("grep -c '#include' {path}"), "0"),
            (format!("{plain} \\"), "hi there"),
        ];

        for shell in ["sh", "bash", "zsh"] {
            if !shell_is_available(shell) {
                // Announce the skip: a silently-skipped shell reads as a pass.
                eprintln!(
                    "SKIP every_rewrite_this_module_emits_runs_correctly_in_a_real_shell: no {shell} on this host"
                );
                continue;
            }
            for (command, expected) in &cases {
                let Some(rewritten) = rewrite_bash_command_for_compression(command) else {
                    // The no-op arm: forwarded unmodified, so it must still
                    // work and must carry nothing from the template.
                    let (_code, stdout, stderr) = run_script(shell, command);
                    assert!(
                        stdout.contains(expected),
                        "{shell}: an un-rewritten `{command}` must still run: \
                         stdout={stdout:?} stderr={stderr:?}"
                    );
                    assert!(
                        !stdout.contains("__tm_compress_exit=")
                            && !stderr.contains("__tm_compress_exit="),
                        "{shell}: nothing from the template may reach an \
                         un-rewritten command: stdout={stdout:?} stderr={stderr:?}"
                    );
                    continue;
                };
                let (group, _filter) = rewritten
                    .split_once("| tm compress")
                    .expect("the rewrite always ends in the compress filter stage");
                let script = format!("{group}| cat");
                let (code, stdout, stderr) = run_script(shell, &script);
                assert_eq!(
                    code,
                    Some(0),
                    "{shell}: the rewritten `{command}` must run cleanly: \
                     script={script:?} stdout={stdout:?} stderr={stderr:?}"
                );
                assert!(
                    stdout.starts_with(expected),
                    "{shell}: the command's own output must survive the wrap: \
                     stdout={stdout:?} stderr={stderr:?}"
                );
                assert!(
                    stdout.ends_with("\n__tm_compress_exit=0__\n"),
                    "{shell}: the sentinel must reach the filter intact: \
                     stdout={stdout:?} stderr={stderr:?}"
                );
            }
        }
    }

    #[test]
    fn rewrite_skips_orchestrator_commands() {
        for cmd in [
            "make build",
            "sam deploy",
            "terraform apply",
            "gradlew build",
        ] {
            assert_eq!(
                rewrite_bash_command_for_compression(cmd),
                None,
                "expected no rewrite for orchestrator command: {cmd}"
            );
        }
    }

    #[test]
    fn rewrite_skips_piped_commands() {
        assert_eq!(
            rewrite_bash_command_for_compression("cargo test | tee out.log"),
            None
        );
    }

    #[test]
    fn rewrite_skips_chained_commands() {
        assert_eq!(
            rewrite_bash_command_for_compression("cargo build && cargo test"),
            None
        );
        assert_eq!(rewrite_bash_command_for_compression("cd /tmp; ls"), None);
    }

    #[test]
    fn rewrite_skips_empty_command() {
        assert_eq!(rewrite_bash_command_for_compression(""), None);
        assert_eq!(rewrite_bash_command_for_compression("   "), None);
    }

    #[test]
    fn rewrite_skips_command_substitution_in_tool_name() {
        // `$(...)`, backticks, and embedded quotes in the derived tool name
        // must never reach the `--tool "<name>"` shell argument verbatim —
        // see `is_safe_tool_name`'s doc comment for the injection risk.
        assert_eq!(
            rewrite_bash_command_for_compression("echo $(touch /tmp/pwned)"),
            None
        );
        assert_eq!(rewrite_bash_command_for_compression("echo `whoami`"), None);
        assert_eq!(
            rewrite_bash_command_for_compression("echo \"quoted\" arg"),
            None
        );
    }

    #[test]
    fn rewrite_skips_sudo_with_user_flag() {
        // Regression test (trusty-review finding, PR #1968): `sudo -u root
        // make build` must never be rewritten — before the fix, the token
        // after `sudo` (`-u`) was blindly treated as the program name,
        // producing the bogus tool name `"-u root"` and — critically —
        // causing `is_orchestrator_command` to miss that this is a `make`
        // invocation, defeating the orchestrator-exclusion safety net this
        // whole module exists to provide.
        assert_eq!(
            rewrite_bash_command_for_compression("sudo -u root make build"),
            None
        );
    }

    #[test]
    fn rewrite_skips_tools_with_no_compression_filter() {
        // #6566: these were wrapped unconditionally, each paying a `tm
        // compress` process spawn to get its own bytes back — 93.7% of
        // wrapped invocations over the measured 48h window. `git status`,
        // `sed -n 1p f`, and `gh pr list` are the three highest-volume
        // offenders; none reaches a filter branch in
        // `trusty-agents-common::compress`.
        for cmd in [
            "git status",
            "git add -A",
            "git push",
            "sed -n 1p f",
            "gh pr list",
            "gh issue view 6566",
            "wc -l Cargo.toml",
            "ssh host uptime",
            "tm wait --for run",
            "echo hello",
        ] {
            assert_eq!(
                rewrite_bash_command_for_compression(cmd),
                None,
                "expected no compress wrap for uncovered tool: {cmd}"
            );
        }
    }

    #[test]
    fn rewrite_skips_a_flagged_source_read() {
        // #7120: bypass-permissions mode reads files with `cat -n <path>`.
        // `effective_tool_name` keeps only the first two tokens, so the flag
        // pushed the path out and `"cat -n"` reached the file-read filter —
        // one compress spawn per read, returning every byte it was given. The
        // unflagged spelling was already skipped by #6986's passthrough.
        for cmd in [
            "cat -n crates/trusty-mpm/src/bin/tm/commands/hook_rewrite.rs",
            "cat crates/trusty-mpm/src/bin/tm/commands/hook_rewrite.rs",
            "cat -s src/lib.rs",
            "/bin/cat -n README.md",
        ] {
            assert_eq!(
                rewrite_bash_command_for_compression(cmd),
                None,
                "a source read must never be wrapped for compression: {cmd}"
            );
        }

        // The negative bound: `> /tmp/gate.txt` then `cat` it back is this
        // project's gate-capture pattern, which is real gate output and still
        // reaches the file-read filter.
        let expected = expected_rewrite("cat -n /tmp/gate.txt", "cat -n");
        assert_eq!(
            rewrite_bash_command_for_compression("cat -n /tmp/gate.txt").as_deref(),
            Some(expected.as_str()),
            "a captured gate log is not a source read"
        );
    }

    #[test]
    fn rewrite_still_wraps_tools_with_a_compression_filter() {
        // The other half of #6566's gate: every tool the dispatch does cover
        // must be wrapped exactly as before.
        for (cmd, tool) in [
            ("cargo test -p x", "cargo test"),
            ("cargo clippy --all-targets", "cargo clippy"),
            ("git diff", "git diff"),
            ("git log --oneline", "git log"),
            ("grep -n foo src/", "grep -n"),
            ("ls -la", "ls -la"),
        ] {
            let expected = expected_rewrite(cmd, tool);
            assert_eq!(
                rewrite_bash_command_for_compression(cmd).as_deref(),
                Some(expected.as_str()),
                "expected a compress wrap for covered tool: {cmd}"
            );
        }
    }

    #[test]
    fn is_orchestrator_command_matches_known_exclusions() {
        assert!(is_orchestrator_command("make"));
        assert!(is_orchestrator_command("sudo make install"));
        assert!(is_orchestrator_command("FOO=bar make build"));
        assert!(is_orchestrator_command("/usr/bin/make build"));
    }

    #[test]
    fn is_orchestrator_command_ignores_unrelated_commands() {
        assert!(!is_orchestrator_command("cargo test"));
        assert!(!is_orchestrator_command("git diff"));
    }

    #[test]
    fn is_orchestrator_command_conservatively_true_for_sudo_with_flags() {
        // Fail-safe: when the real program name can't be confidently
        // resolved (`sudo`/`env` followed by a flag rather than a program),
        // treat the command as orchestrator-like rather than risk rewriting
        // an unrecognised `make`/`sam`/etc. invocation.
        assert!(is_orchestrator_command("sudo -u root make build"));
        assert!(is_orchestrator_command("env -i make build"));
    }

    #[test]
    fn first_command_token_strips_env_assignment() {
        assert_eq!(
            first_command_token("FOO=bar make build").as_deref(),
            Some("make")
        );
    }

    #[test]
    fn first_command_token_strips_sudo() {
        assert_eq!(
            first_command_token("sudo make install").as_deref(),
            Some("make")
        );
    }

    #[test]
    fn first_command_token_strips_path() {
        assert_eq!(
            first_command_token("/usr/bin/make build").as_deref(),
            Some("make")
        );
    }

    #[test]
    fn first_command_token_plain_command() {
        assert_eq!(first_command_token("cargo test").as_deref(), Some("cargo"));
    }

    #[test]
    fn first_command_token_strips_env_command_prefix() {
        // `env FOO=bar make build` (the common `env`-prefixed invocation
        // form) must still resolve to `make` for orchestrator-exclusion
        // matching purposes — a trusty-review-flagged gap where only
        // `sudo` was handled, not the literal `env` command.
        assert_eq!(
            first_command_token("env FOO=bar make build").as_deref(),
            Some("make")
        );
    }

    #[test]
    fn first_command_token_none_for_sudo_followed_by_flag() {
        // `sudo -u root make` — the token after `sudo` is itself a flag,
        // not a program name; resolving it correctly needs argument-aware
        // parsing this function doesn't do, so it must degrade to `None`
        // (trusty-review finding, PR #1968) rather than returning the
        // bogus token `"-u"`.
        assert_eq!(
            first_command_token("sudo -u root make build").as_deref(),
            None
        );
        assert_eq!(first_command_token("env -i make build").as_deref(), None);
    }

    #[test]
    fn first_command_token_strips_leading_backslash() {
        // #4031 review, HIGH 3: `\rm` is the standard alias-bypass idiom —
        // Bash itself strips the backslash before exec, so this classifier
        // must too, or a resolved verb like `\rm` never matches `"rm"`.
        assert_eq!(first_command_token("\\rm -rf /root").as_deref(), Some("rm"));
    }

    #[test]
    fn first_command_token_strips_command_wrapper() {
        // #4031 review, HIGH 4: `command rm` runs the real `rm`, bypassing
        // any shell function/alias named `rm` — the same bypass class as a
        // leading backslash, via the POSIX `command` builtin instead.
        assert_eq!(
            first_command_token("command rm -rf /root").as_deref(),
            Some("rm")
        );
    }

    #[test]
    fn first_command_token_strips_builtin_wrapper() {
        assert_eq!(
            first_command_token("builtin rm -rf /root").as_deref(),
            Some("rm")
        );
    }

    #[test]
    fn first_command_token_strips_backslash_after_sudo() {
        // The two bypass idioms compose: `sudo \rm` must resolve the same
        // as `sudo rm` — the backslash strip re-runs on every token the
        // `sudo`/`env`/`command`/`builtin` arm advances to.
        assert_eq!(
            first_command_token("sudo \\rm -rf /root").as_deref(),
            Some("rm")
        );
    }

    #[test]
    fn first_command_token_strips_nice_time_nohup_exec() {
        // #4031 review pass 2: enumerating only sudo/env/command/builtin
        // left process/resource wrappers unresolved — the whole class closes
        // at once via `COMMAND_WRAPPERS`, not one word at a time.
        //
        // `env -i rm -rf /root` is deliberately excluded here: `-i` is env's
        // OWN flag, and this function still degrades to `None` on a wrapper
        // immediately followed by a flag-shaped token, unchanged from
        // `sudo -u root make`. That case is closed instead in
        // `destructive_delete.rs`, which no longer depends on this function
        // for verb detection at all (issue #4031 review, item 1).
        for command in [
            "nice rm -rf /root",
            "time rm -rf /root",
            "nohup rm -rf /root",
            "exec rm -rf /root",
        ] {
            assert_eq!(
                first_command_token(command).as_deref(),
                Some("rm"),
                "expected \"rm\" for: {command}"
            );
        }
    }

    /// #7374: a quoted absolute path with spaces resolves to its own basename.
    ///
    /// Why: every macOS `.app` binary is spelled this way, and
    /// `split_whitespace` cut it at the space, so the command name read as the
    /// fragment `Google`. The unquoted, space-free spelling is the control: the
    /// two must agree on what the program is.
    /// Test: itself.
    #[test]
    fn first_command_token_resolves_a_quoted_path_with_spaces() {
        for command in [
            r#""/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --headless"#,
            r#"'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' --headless"#,
        ] {
            assert_eq!(
                first_command_token(command).as_deref(),
                Some("Google Chrome"),
                "expected the path's own basename for: {command}"
            );
        }
        // The control: no spaces, no quotes, same shape, same kind of answer.
        assert_eq!(
            first_command_token("/Applications/GoogleChrome.app/Contents/MacOS/GoogleChrome -x")
                .as_deref(),
            Some("GoogleChrome")
        );
    }

    /// #7374: no quoting spelling hides a forbidden verb.
    ///
    /// Why: the fix must not degrade to "strip the quotes and allow anything".
    /// Quoted, split-quoted and backslash-escaped spellings all resolve to the
    /// program bash would exec: before, `"/Applications/My Tools/sed" -i x f`
    /// resolved to `My` and slipped the shell-edit deny. The quoted `make` row
    /// is the same misread in the false-DENY direction. Split quoting has its
    /// own case in `first_command_token_resolves_split_quoting`.
    /// Test: itself.
    #[test]
    fn first_command_token_resolves_a_quoted_forbidden_verb() {
        assert_eq!(
            first_command_token(r#""/Applications/My Tools/sed" -i s/a/b/ f"#).as_deref(),
            Some("sed")
        );
        assert_eq!(
            first_command_token(r#"'/Applications/My Tools/patch' -p1 x"#).as_deref(),
            Some("patch")
        );
        // The false-deny direction: the program is `echo`, never `make`.
        assert_eq!(
            first_command_token(r#""/opt/make tools/echo" hi"#).as_deref(),
            Some("echo")
        );
        // A quoted wrapper is still a wrapper.
        assert_eq!(
            first_command_token(r#""sudo" rm -rf /root"#).as_deref(),
            Some("rm")
        );
    }

    /// #7374: a verb split across quote fragments still resolves to the verb.
    ///
    /// Why: this is the shape a byte-scanning splitter cannot see. `s"e"d` is
    /// one word to any whitespace scan and contains no quote pair to unwrap, so
    /// the name read as the literal `s"e"d` and matched no rule — while
    /// `bash -c 's"e"d -i x f'` ran the real `sed`. Backslash-escaped spaces are
    /// the same misread with a different escape.
    /// Test: itself.
    #[test]
    fn first_command_token_resolves_split_quoting() {
        for command in [
            r#"s"e"d -i s/a/b/ f"#,
            r#"'se'"d" -i s/a/b/ f"#,
            r#""se"'d' -i s/a/b/ f"#,
            r"/opt/my\ tools/sed -i x f",
        ] {
            assert_eq!(
                first_command_token(command).as_deref(),
                Some("sed"),
                "split quoting must not hide the verb: {command}"
            );
        }
        assert_eq!(
            first_command_token(r#"c"u"rl http://x"#).as_deref(),
            Some("curl")
        );
    }

    /// #7374: unlexable quoting keeps the pre-fix answer, never a wider one.
    ///
    /// Why: `shlex` returns `None` on an unbalanced quote, and the fallback
    /// must be the plain whitespace split these callers had before — a command
    /// the lexer cannot read must not GAIN an allow. `sed -i "x` keeps its
    /// deny; `"sed -i x` keeps the allow it already had, and is refused
    /// upstream instead when it matters.
    /// Test: itself.
    #[test]
    fn first_command_token_keeps_the_fallback_answer_on_unbalanced_quoting() {
        assert!(shlex::split(r#"sed -i "x"#).is_none());
        assert_eq!(
            first_command_token(r#"sed -i "x"#).as_deref(),
            Some("sed"),
            "an unbalanced quote after the verb must not lose the deny"
        );
        assert_eq!(
            first_command_token(r#""sed -i x"#).as_deref(),
            Some("\"sed"),
            "the fallback answers exactly as split_whitespace did"
        );
    }

    /// #7374: `shlex_words` lexes what bash lexes.
    ///
    /// Test: itself.
    #[test]
    fn shlex_words_lexes_split_quoting() {
        assert_eq!(shlex_words(r#"s"e"d -i f"#), vec!["sed", "-i", "f"]);
        assert_eq!(
            shlex_words(r#""/opt/a b/sed" -i f"#),
            vec!["/opt/a b/sed", "-i", "f"]
        );
        assert_eq!(
            shlex_words("git diff -- docs/"),
            vec!["git", "diff", "--", "docs/"]
        );
    }

    /// #7374: an unlexable command falls back to the whitespace split.
    ///
    /// Test: itself.
    #[test]
    fn shlex_words_falls_back_on_unbalanced_quoting() {
        assert_eq!(shlex_words(r#"sed -i "x"#), vec!["sed", "-i", "\"x"]);
    }

    /// #7399 finding (b): the tool name is lexed, so `npm test` is seen.
    ///
    /// Why: `effective_tool_name` backs the `npm test` deny in
    /// `pm_guard_bash::classify_bash_segment`, and it read the name off a
    /// whitespace scan, so a quoted path or split quoting produced a fragment
    /// and the deny never fired.
    /// Test: itself.
    #[test]
    fn effective_tool_name_lexes_quoted_and_split_spellings() {
        assert_eq!(
            effective_tool_name(r#""/opt/My Tools/npm" test"#),
            "npm test"
        );
        assert_eq!(effective_tool_name(r#"n"p"m test"#), "npm test");
        assert_eq!(effective_tool_name(r"/opt/my\ tools/npm test"), "npm test");
    }

    #[test]
    fn strip_wrapper_prefix_skips_env_assignment() {
        let tokens = ["FOO=bar", "make", "build"];
        assert_eq!(strip_wrapper_prefix(&tokens), Some(1));
    }

    #[test]
    fn strip_wrapper_prefix_skips_every_known_wrapper() {
        for wrapper in COMMAND_WRAPPERS {
            // #8735: `timeout`, `chrt`, `taskset`, `flock` take an operand.
            let operand = crate::commands::program_word::sample_operand(wrapper);
            let (tokens, program) = if operand.is_empty() {
                (vec![*wrapper, "rm", "-rf", "/root"], 1)
            } else {
                (vec![*wrapper, operand, "rm", "-rf", "/root"], 2)
            };
            assert_eq!(
                strip_wrapper_prefix(&tokens),
                Some(program),
                "expected wrapper {wrapper} to be skipped"
            );
        }
    }

    #[test]
    fn strip_wrapper_prefix_none_for_wrapper_followed_by_flag() {
        let tokens = ["sudo", "-u", "root", "make"];
        assert_eq!(strip_wrapper_prefix(&tokens), None);
    }

    #[test]
    fn strip_wrapper_prefix_skips_backslash_before_a_wrapper() {
        let tokens = ["\\nice", "rm", "-rf", "/root"];
        assert_eq!(strip_wrapper_prefix(&tokens), Some(1));
    }

    #[test]
    fn effective_tool_name_joins_program_and_subcommand() {
        assert_eq!(effective_tool_name("cargo test --workspace"), "cargo test");
        assert_eq!(effective_tool_name("git diff HEAD~1"), "git diff");
    }

    #[test]
    fn effective_tool_name_single_token_command() {
        assert_eq!(effective_tool_name("ls"), "ls");
        assert_eq!(effective_tool_name("ls -la"), "ls -la");
    }

    #[test]
    fn effective_tool_name_strips_env_and_sudo_noise() {
        assert_eq!(effective_tool_name("FOO=bar cargo test"), "cargo test");
        assert_eq!(effective_tool_name("sudo cargo test"), "cargo test");
        assert_eq!(effective_tool_name("/usr/bin/cargo test"), "cargo test");
    }

    #[test]
    fn effective_tool_name_strips_env_command_prefix() {
        // `env FOO=bar cargo test` (the literal `env` command, not just a
        // `KEY=value` assignment) must still resolve to `"cargo test"`, not
        // the previously-buggy `"env FOO=bar"` — trusty-review finding,
        // PR #1968.
        assert_eq!(effective_tool_name("env FOO=bar cargo test"), "cargo test");
    }

    #[test]
    fn effective_tool_name_returns_empty_for_sudo_followed_by_flag() {
        // `sudo -u root make build` must NOT resolve to a bogus tool name
        // like `"-u root"` — trusty-review finding, PR #1968. An empty
        // string fails `is_safe_tool_name`, so the caller safely skips the
        // rewrite instead of guessing.
        assert_eq!(effective_tool_name("sudo -u root make build"), "");
        assert_eq!(effective_tool_name("env -i cargo test"), "");
    }

    #[test]
    fn is_safe_tool_name_allows_typical_tool_names() {
        assert!(is_safe_tool_name("cargo test"));
        assert!(is_safe_tool_name("git diff"));
        assert!(is_safe_tool_name("./scripts/foo.sh"));
        assert!(is_safe_tool_name("ls-la_v2"));
    }

    #[test]
    fn is_safe_tool_name_rejects_shell_metacharacters() {
        assert!(!is_safe_tool_name("echo $(touch /tmp/pwned)"));
        assert!(!is_safe_tool_name("echo `whoami`"));
        assert!(!is_safe_tool_name("echo \"quoted\""));
        assert!(!is_safe_tool_name("a;b"));
        assert!(!is_safe_tool_name(""));
    }

    #[test]
    fn has_unsafe_pipe_composition_detects_pipe() {
        assert!(has_unsafe_pipe_composition("cargo test | tee out.log"));
    }

    #[test]
    fn has_unsafe_pipe_composition_detects_and_chain() {
        assert!(has_unsafe_pipe_composition("cargo build && cargo test"));
    }

    #[test]
    fn has_unsafe_pipe_composition_detects_semicolon() {
        assert!(has_unsafe_pipe_composition("cd /tmp; ls"));
    }

    #[test]
    fn has_unsafe_pipe_composition_detects_output_redirection() {
        // Regression test (trusty-review finding, PR #1968): a command that
        // already redirects stdout to a file must not be rewritten — piping
        // `tm compress` after the redirect would receive empty stdin and do
        // nothing useful.
        assert!(has_unsafe_pipe_composition("cargo test > out.log"));
        assert!(has_unsafe_pipe_composition("cargo test >> out.log"));
    }

    #[test]
    fn has_unsafe_pipe_composition_detects_input_redirection() {
        assert!(has_unsafe_pipe_composition("cat < input.txt"));
    }

    #[test]
    fn has_unsafe_pipe_composition_detects_background_operator() {
        // Regression test (trusty-review finding, PR #1968): `cargo test &`
        // rewritten to `cargo test & | tm compress ...` is invalid shell
        // syntax in most shells — must never be rewritten.
        assert!(has_unsafe_pipe_composition("cargo test &"));
    }

    #[test]
    fn has_unsafe_pipe_composition_false_for_plain_command() {
        assert!(!has_unsafe_pipe_composition("cargo test"));
    }

    #[test]
    fn build_pretooluse_rewrite_response_has_expected_shape() {
        let response = build_pretooluse_rewrite_response("cargo test | tm compress --tool bash");
        assert_eq!(
            response["hookSpecificOutput"]["hookEventName"],
            "PreToolUse"
        );
        assert_eq!(
            response["hookSpecificOutput"]["updatedInput"]["command"],
            "cargo test | tm compress --tool bash"
        );
    }
}