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
//! Bash-command classification for the `tm hook --pm-guard` PreToolUse guard
//! (issue #1977, hardened in PR #1985; sed/awk deny-by-default redesign #2664).
//!
//! Why: Bash is the escape hatch a prompt-only prohibition can't close — a PM
//! can edit a file with `sed -i`, write one with `echo … > f.rs`, apply a diff
//! with `git apply`, or run the suite with `pytest`, all of which side-step the
//! P1–P5 prohibitions. Worse, shell *composition* (`&&`, `||`, `;`, `|`, a bare
//! `&`, a newline) and *substitution* — command (`$(…)`, backticks) and
//! process (`<(…)`, `>(…)`, #2745) alike — are themselves bypasses: a benign
//! leading verb can hide a forbidden one further down the line or inside a
//! substitution body. This module is the quote-unaware,
//! conservatively-over-blocking classifier that closes those seams; it is
//! factored out of `pm_guard.rs` so that file stays under the 500-SLOC cap.
//! What: [`evaluate_bash_command`] splits a command on every composition
//! separator, classifies each segment (first-token verb, two-token
//! `git apply` / `npm test`, and recursively every substitution body), and
//! applies a whole-command file-write redirection check. A missed deny is the
//! dangerous direction, so ambiguous forms (unbalanced substitutions,
//! over-deep nesting) deny. `sed`/`awk`-family verbs are classified by the
//! sibling [`sed_awk`] module, which is deny-by-default: a segment must prove
//! it is narrowly read-only (no in-place flag, no external script load, no
//! write/exec script construct, balanced quotes) to be allowed. The sibling
//! [`persistence`] module runs the one ALLOW-list here — the agent-cost stop's
//! escape hatch (#4837) — and is default-deny in the opposite direction. The
//! sibling [`main_checkout`] module carries the rules `pm_guard` calls
//! directly, ahead of the subagent exemptions: whole-tree-destructive git
//! verbs aimed at a project's main checkout (ADR-0037), `git commit` there,
//! and the HEAD-moving `pull`/`merge`/`rebase` (ADR-0048). The sibling
//! [`heredoc`] module tells the redirection check which bytes are
//! here-document body content, so a `>` inside a `<<'PY'` script is a
//! comparison rather than a file write (#5356). The sibling
//! [`destructive_delete`] module carries the rule `pm_guard` calls directly,
//! ahead of the subagent exemptions, alongside the worktree-add-tmp guard: a
//! target-path denylist for `rm`/`rmdir`/`unlink`/`find … -delete` aimed at a
//! filesystem root, a repository root, a `.git` directory, or a worktree
//! entry (issue #4031). The sibling [`secret_file_copy`] module carries the
//! same ahead-of-subagent-exemptions rule for `cp`/`mv`: a source-basename
//! denylist (`*.tfvars`, `.env*`, `*.pem`, `*.key`, `id_*`,
//! `credentials`/`secrets` names) refused when the destination resolves into
//! a harness worktree (issue #7122). The sibling [`path_tokens`] module turns a path TOKEN
//! a command wrote into the directory every one of those rules decides on, and
//! reports what its expansion could not reach — the question a rule must ask
//! before stating anything about the directory it got back (#7098, #7100).
//! Test: `evaluate_bash_command_*`, `split_shell_segments_*`, and
//! `has_file_write_redirection_*` in this module's `tests` submodule;
//! `sed_awk::tests` for the sed/awk-specific safety analysis.
// #7839, #7744, #7743, #7738: the ONE tokenizer and token classifier the
// sibling rules ask, replacing the per-guard lexing and redirect/program-text
// splitting that disagreed with the shell four different ways.
// #8261: heavy builds rewritten to run under `tm build-lease`.
// #8969: build_lease_cwd carries the build's directory into the lease.
pub
pub
// #9180: `\`-newline continuations the shell removes; judged beside the original.
// #8596, #8248: a credential CLI whose printed value would reach tool output.
// #7497: the disk-usage half of the worktree-add gate, beside the temp-root
// half it shares a target resolver with.
// #8572: an agent's branch switch in a dirty main checkout.
// #9180: the program words of a here-document operator line.
// #8161: HEAD moves into a linked worktree a live agent stands in.
// #8524, #7905: operator-listed runtime and documents checkouts.
pub
// #7648: an unscoped environment dump inside a Kubernetes pod.
// #8756: a launchd or pm2 query that prints a managed job's environment.
// #8439: a read-only dispatch runs only allowlisted command shapes.
// #8567: the `gh` read verbs a read-only dispatch may run.
// #8571: a read-only dispatch's cp/rm inside its session scratchpad.
// #9127: `( … )`, `{ …; }` and reserved words peeled off for the git-verb walker.
// #8756: one substitution scanner for the forbidden-verb and secret rules.
// #9180: the forbidden-verb verdict on substitution and here-document bodies.
use ;
// #8849: the removal guard's ancestry route for a HEAD behind its merged head.
// #8730: the files a command writes — `tee`, substitution and subshell bodies.
// #8878: the trust-anchor floor's reading — the classifier plus copy verbs.
// #8902: the Architect pane floor — no tmux verb aimed at the Architect's pane.
pub use Pane;
pub use ;
pub use LivePanes;
// #9001: the exact-target floor — a tmux target must name an existing object.
pub use TmuxObject;
pub use ;
// #8878: the D4-remainder floor — uploads, disk tools, force-push to the default.
pub use ;
pub use evaluate_credential_print_command;
pub use ;
pub use evaluate_d4_floor;
pub use ;
pub use evaluate_main_checkout_head_switch;
pub use ;
pub use ;
pub use command_is_persistence_only;
pub use evaluate_pod_env_dump_command;
pub use evaluate_process_env_dump_command;
pub use evaluate_read_only_dispatch_command;
pub use ;
// #7266: the secret-read guard frames here-document bodies through the SAME
// scan the write-redirection check uses, rather than growing a second parser.
pub use split_heredoc_bodies;
// #9001: the `$'…'` decoder, and the #6660 refusal that names its token.
pub use unclassifiable_reason;
// #7839, #7738, #7744: the shared classifier the secret-read guard asks which
// argv token is an interpreter's PROGRAM, and whether a word is regex syntax.
// #8723: and which tokens are prose a `printf`/`echo` writes into a file.
pub use ;
// #7743: the argv-side answer to "does this redirect token name a FILE", used
// by the sibling secret-copy rule.
// #8869: and by the secret-read key-consumer rule, with the input-side parser.
pub use ;
pub use input_redirect_operand;
// #7266: everything after the first export is shared with
// `crate::commands::pm_guard_secret_read`, so a READ of a secret-bearing file
// is screened against the same pattern list, the same brace expander and the
// same process-substitution stripper a COPY of one is.
pub use ;
// #7266 round 5: the read rule allowlists `git add`/`rm`/`mv`/`status`, and the
// subcommand behind `git -C <path> …` is already parsed here. One parser, two
// callers, rather than a second global-option table.
pub use git_subcommand;
// #7498 round 3 critic MEDIUM: a caller that needs the subcommand's INDEX as
// well as its name must not re-derive it by string equality — that is a second
// argv parse, the defect `git_argv_at_subcommand`'s own doc says it prevents.
pub use git_argv_at_subcommand;
// #5791: worktree removal is PM-executed, so an agent's `git worktree remove`
// denies. The sibling `worktree add` guard above is a different rule with a
// different scope — that one is about WHERE a tree is provisioned, this one is
// about WHO may destroy one.
// See ADR-0057 — one role's removal is now a grant, so the rule reports three
// answers rather than two and the third must still be earned.
pub use ;
// #7889: the re-checks are reached only through their deadline.
pub use ;
use ;
use crate;
// Reached by the sibling rule modules through `super::…` — one answer to "what
// did not expand" (#7098, #7100), covering a surviving `~` since #7234.
use unresolved_target;
// One definition of "which directory does this token name", crate-visible since
// #7172: the `EnterWorktree` rule is no Bash rule but asks the same question, so
// it reaches this resolver instead of growing a second normalizer.
pub use ;
use QuoteScan;
// #8756: `substitutions` asks the credential rule which programs run their input.
use is_evaluator;
// #8756: the secret rules read substitution bodies through the same scanner.
pub use ;
/// Deny reason for editing files through a shell tool (sed/awk/patch/git apply/redirection).
pub const SHELL_EDIT_REASON: &str = "PM must not edit files via shell tools \
(sed/awk/patch/git apply/redirection) (prohibitions P1/P5). \
Delegate the change to rust-engineer via the Task/Agent tool.";
/// Deny reason for running builds/tests directly (make/pytest/npm test).
pub const BUILD_TEST_REASON: &str = "PM must not run builds or tests directly \
(prohibitions P4–P5). Delegate to rust-engineer / QA via the Task/Agent tool.";
/// Deny reason for fetching over the network from Bash (curl/wget).
pub const NETWORK_REASON: &str = "PM must not fetch over the network from Bash \
(prohibition P-network). Use WebFetch/WebSearch or delegate the task.";
/// Deny reason for a wrapper whose inner command cannot be lexed (#6660).
pub const UNLEXABLE_WRAPPER_REASON: &str = "this command's `sh -c`/`bash -c`/`env -S`/\
`xargs` wrapper carries an inner command with unbalanced quoting, so the guard cannot \
classify what would actually run. Run the command without the wrapper, or fix the quoting.";
/// Deny reason for `$'…'`/`$"…"` quoting the guard cannot decode (#6660 review).
pub const ANSI_C_QUOTING_REASON: &str = "this command uses `$'…'`/`$\"…\"` quoting, which \
the guard's lexer cannot decode — it cannot establish which program would actually run \
(`sh -c $'git worktree remove x'` reads as `$git`, matching no rule). Rewrite the command \
with ordinary `'…'` or `\"…\"` quoting.";
/// Deny reason for a wrapper nested past [`MAX_WRAPPER_DEPTH`] (#6660 review).
pub const WRAPPER_DEPTH_REASON: &str = "this command nests `sh -c`/`bash -c`/`xargs` \
wrappers deeper than the guard will follow, so it cannot classify what would actually run. \
Run the command without the nesting.";
/// How many wrapper layers the guard descends through (#6660).
///
/// Why: `sh -c "bash -c '…'"` is a real shape, and an adversarial one nests
/// without bound. The cap bounds the recursion; exhausting it DENIES rather
/// than falling through, matching [`MAX_SUBSTITUTION_DEPTH`] — the first cut
/// stopped recursing instead, which made a 9-layer wrapper an allow while an
/// 8-layer one denied.
/// What: the budget threaded through [`unclassifiable_command`] and
/// [`expand_shell_segments`].
const MAX_WRAPPER_DEPTH: usize = 8;
/// Whether the guard is unable to establish what `command` would run (#6660).
///
/// Why: the three ABSOLUTE guards a dispatched subagent actually hits —
/// `evaluate_worktree_remove_command`, the main-checkout destructive/commit/
/// HEAD-move rules, and `evaluate_destructive_delete_command` — are reached
/// from `pm_guard` BEFORE `payload_is_subagent_dispatch` short-circuits, and
/// none of them routes through [`evaluate_bash_command`]. A fail-closed check
/// that lived only in [`classify_bash_segment`] was therefore unreachable for
/// exactly the caller #5791/#6660 exist to bind: `sh -c "git worktree remove
/// 'unterminated"` from a subagent was allowed. Making this ONE function the
/// answer, called from `pm_guard`'s ABSOLUTE band ahead of every Bash rule,
/// is what stops a future rule from inheriting the same hole.
/// What: `Some(reason)` when any segment, at any wrapper depth, carries
/// `$'…'`/`$"…"` quoting the lexer mangles ([`shell_lex::has_live_ansi_c_quoting`]),
/// a program word bash builds by brace expansion
/// ([`shell_groups::has_brace_expanded_program`], #9127),
/// a wrapper whose inner command will not lex
/// ([`shell_lex::WrappedCommand::Unlexable`]), or a wrapper nested past
/// [`MAX_WRAPPER_DEPTH`], or a here-document delimiter the body scanner cannot
/// read as the shell does (#9150). #9180: the continuation-joined spelling
/// is checked too, and a command that opens a here-document while it
/// redefines a data reader ([`heredoc_line::heredoc_refusal`]) is refused. `None` — the ordinary case — leaves every
/// rule to classify the command as before.
/// Test: `unclassifiable_command_flags_ansi_c_quoting`,
/// `unclassifiable_command_flags_an_unlexable_wrapper`,
/// `unclassifiable_command_denies_past_the_depth_cap`,
/// `unclassifiable_command_allows_ordinary_commands`, and end to end in
/// `tests/tm_hook_pm_guard.rs` and
/// `a_quoted_heredoc_delimiter_with_a_word_break_denies`.
pub
/// Depth-aware core of [`unclassifiable_command`].
/// Classify a `Bash` command: `Some(reason)` denies, `None` allows.
///
/// Why: see the module docs — Bash composition and substitution are the seams
/// a prompt-only prohibition can't close, so every composed command (not just
/// the first token) must be inspected.
/// What: the depth-0 entry point; delegates to [`evaluate_bash_command_inner`]
/// which threads the substitution recursion budget.
/// Test: `evaluate_bash_command_denies_*`, `evaluate_bash_command_allows_*`,
/// `evaluate_bash_command_denies_composition_*`.
pub
/// Depth-aware core of [`evaluate_bash_command`].
///
/// Why: command substitutions recurse back into this classifier; carrying an
/// explicit [`Walk`] lets [`classify_command_substitutions`] bound that
/// recursion (see [`MAX_SUBSTITUTION_DEPTH`]) instead of trusting the stack,
/// and #9180 bounds its total work across levels.
/// What: splits on the shell composition operators `&&`, `||`, `;`, `|`, a bare
/// `&`, and a newline (see [`split_shell_segments`]), runs
/// [`classify_bash_segment`] on each — denying if ANY segment names a forbidden
/// verb — then applies the whole-command file-write redirection check
/// ([`has_file_write_redirection`], which ignores `2>&1` fd-dups and
/// `/dev/null` discards). Benign pipes whose segments all allow still pass.
/// Empty commands allow. Deliberately quote-unaware: a forbidden verb hidden in
/// a quoted string may over-deny, the safe direction here. #9180: the
/// continuation-joined spelling is judged first, and each `$(…)` or backtick
/// an unquoted here-document body expands — nested ones included — is judged
/// as a substitution body.
/// Test: covered via `evaluate_bash_command_*` (this is its core);
/// `continuation_tests::the_forbidden_verb_guard_reads_heredoc_expansions_9180`,
/// `continuation_tests::a_doubling_heredoc_nest_denies_in_bounded_time_9180`.
/// Split a command into the sub-commands joined by a shell separator.
///
/// Why: a forbidden verb can hide in any composed segment, not just the first;
/// splitting lets [`evaluate_bash_command_inner`] classify each independently.
/// The separator set must be complete — a bare `&` (background/sequence
/// separator) and a newline are separators too, and omitting the `&` let
/// `true & sed -i …` slip through as one segment classified on its benign
/// leading verb (PR #1985).
/// What: a byte scan that cuts at each composition operator — the two-byte
/// `&&`/`||` (checked first so they are never seen as a bare `&`/`|`), a bare
/// `;`/`|`/`&`/newline — and returns the raw (untrimmed) segments;
/// `classify_bash_segment` trims. A bare `&` is NOT a split when it is a
/// redirection fd-dup (`>&`, `&>`, `2>&1`) or when nothing but whitespace
/// follows it (trailing background `foo &`), so those stay one segment.
/// Quote-aware (#2734): an operator that lies inside a quoted string is literal
/// data (`git commit -m 'a | b'`), not a separator, so it never splits — UNLESS
/// the command's quotes are unbalanced, in which case the [`QuoteScan`] map is
/// untrustworthy and we fall back to the original quote-unaware split (the
/// conservative, over-splitting direction that the sed/awk co-process detection
/// still relies on).
/// Test: `split_shell_segments_splits_operators`,
/// `split_shell_segments_splits_bare_ampersand`,
/// `split_shell_segments_single_command`,
/// `split_shell_segments_ignores_quoted_operators`.
///
/// #6660: the returned list also carries the commands hidden inside a leading
/// `sh -c` / `bash -c` / `env -S` / `xargs` wrapper — see
/// [`expand_shell_segments`]. Every rule in this module reads its segments from
/// here, which is what makes one descent reach all of them.
// #7266: `pub(crate)` so the read guard reads its segments from the SAME
// splitter every rule in this module already uses — that is what makes the
// `sh -c` descent above reach it too.
pub
/// Emit each of `command`'s segments, followed by the segments of whatever a
/// leading command wrapper would run (#6660).
///
/// Why: `sh -c "git worktree remove …"` reached every rule as a segment whose
/// program is `sh`, and no rule has an opinion about `sh`. Emitting the inner
/// command as ADDITIONAL segments is additive by construction: every segment
/// the caller saw before is still present, byte-identical and in the same
/// order, so no existing classification changes and the wrapped command is now
/// classified too.
///
/// The `cd`-tracking rules read these segments in order, so a `cd` inside a
/// wrapped string leaks into the segments that follow the wrapper — a subshell
/// `cd` does not really leak. That over-resolves a later relative path against
/// the subshell's directory, which is the over-blocking direction this guard
/// already prefers everywhere else.
/// What: recurses through [`shell_lex::wrapped_command`] up to
/// [`MAX_WRAPPER_DEPTH`] layers. An [`shell_lex::WrappedCommand::Unlexable`]
/// wrapper contributes no inner segments; [`classify_bash_segment`] denies it
/// instead.
/// Test: `wrappers_do_not_hide_the_inner_command_from_the_git_verb_rules`.
/// The composition-operator split itself, without the #6660 wrapper descent.
///
/// Heredoc-aware (#6946): [`QuoteScan`] knows only `'` and `"`, so every bare
/// newline in a here-document body was a cut. `cat <<'EOF' > notes.md` /
/// `git commit -m wip` / `EOF` arrived at the ADR-0049 composed-commit guard as
/// three segments, and the guard denied a call that runs no git at all.
/// [`heredoc::HeredocBodies::suppresses_separator`] marks the body, the newline
/// that opened it, and the terminator line as data, so the whole here-document
/// stays one segment. The operator line keeps its live syntax, an unterminated
/// here-document suppresses nothing, and a body handed to a shell still splits.
/// #9180: a `\`-newline continuation is no separator ([`continuation::joins_at`]).
/// Test: `split_shell_segments_keeps_a_heredoc_body_whole`,
/// `continuation_tests::split_shell_segments_keep_a_continued_command_whole_9180`,
/// `split_shell_segments_still_splits_an_unterminated_heredoc`,
/// `split_shell_segments_still_splits_a_shell_heredoc_body`.
/// Classify a single composition segment: `Some(reason)` denies, `None` allows.
///
/// Why: factored out of [`evaluate_bash_command_inner`] so the same first-token
/// / two-token / substitution deny logic runs uniformly on every segment.
/// What: resolves the effective program via [`first_command_token`] (strips
/// env/`sudo`/path noise) and denies `patch` (shell edit, unconditionally — it
/// has no read-only use case); `sed`/`awk`/`gawk`/`nawk`/`mawk` are
/// deny-by-default and allowed only when [`sed_awk::sed_is_readonly`] /
/// [`sed_awk::awk_is_readonly`] proves the segment narrowly read-only (issue
/// #2664 — the earlier allow-by-default-unless-flagged shape missed
/// `awk 'BEGIN{system(...)}'`, sed `e`/`w`/`W` commands, and `-f`/`--file`
/// external scripts); `curl`/`wget` (network); `make`/`pytest` (build/test);
/// matches the two-token forms `git apply` / `npm test` via
/// [`effective_tool_name`]; and finally inspects any command substitution /
/// subshell in the segment via [`classify_command_substitutions`] (carrying
/// the recursion [`Walk`]). Empty/whitespace segments allow.
/// Test: covered via `evaluate_bash_command_*` (this is its per-segment core).
/// Best-effort target path for a shell command already classified as a
/// [`SHELL_EDIT_REASON`] deny, for content-aware delegation routing (issue
/// #2918).
///
/// Why: `pm_guard`'s denial message used to hardcode "delegate to
/// rust-engineer" no matter what file the shell command actually touched.
/// Routing by content type needs the target path; unlike the Edit/Write tools
/// (which name it directly in `tool_input.file_path`), a Bash command only has
/// its target embedded in the command text itself.
/// What: scans each composition segment ([`split_shell_segments`]) for a real
/// file-write redirect, a `tee` operand, or the file a git write option names
/// ([`write_targets::segment_write_targets`], #7399, #8730), or, for a
/// sed/awk-family/`patch`/`git apply` segment, the command's trailing
/// non-flag token ([`trailing_file_token`]) — the conventional position of the
/// target file for those verbs. Returns the first match found; `None` when no
/// segment yields a plausible target (the caller then falls back to the
/// generic delegation hint). The sed/awk-family half is a best-effort HINT
/// only — its trailing token may name a file the command READS. The positively
/// identified half is [`shell_write_targets`], which the write boundary decides
/// on.
/// Test: `extract_shell_edit_target_*`.
pub
/// Every file a real write redirect in `command` names, in order.
///
/// Why (#7399 review, HIGH): this scan used to exist twice — once returning a
/// bool for [`has_file_write_redirection`] and once returning the token for
/// the write boundary — and only the bool copy learned #5356's heredoc
/// skip. Once the write boundary began deciding a hard, budget-exempt deny on
/// the token copy, that drift meant a `>` in here-document PROSE denied a
/// command that writes nothing. One scanner, two thin callers, so the two
/// cannot re-diverge.
/// What: scans for `>` outside quotes ([`QuoteScan`]) and outside
/// here-document bodies ([`heredoc::HeredocBodies`]); skips a second `>`
/// (append) and any spaces, treats a following `&` as an fd-duplication
/// (`2>&1`, `>&2`) only when [`bash_tokens::is_descriptor_word`] accepts the
/// word after it (#8730: `>&out.rs` opens `out.rs`), treats `/dev/null` as an
/// output discard, and returns the
/// target token of every real file-write redirect — bash opens each one, so
/// `> notes.md > src/lib.rs` writes both (#8730). An empty entry when the
/// redirect is real but names no token (a trailing `>` or `>|`): still a
/// write for the bool caller, no path for the boundary. The target word ends
/// at an unmatched `)` — the close of the subshell or substitution it sits in
/// (#8730) — while a `$(…)` inside the word stays part of it.
/// Test: `has_file_write_redirection_*`,
/// `extract_shell_edit_target_from_redirection`,
/// `shell_write_targets_ignores_a_heredoc_body_redirect`,
/// `write_targets_reads_every_redirect_of_a_segment`.
/// The trailing non-flag whitespace-separated token of `command`.
///
/// Why: `sed -i s/a/b/ file.rs`, `patch -p1 file.diff`, and `git apply
/// my.patch` all conventionally place the target file last; this is the cheap
/// heuristic [`extract_shell_edit_target`] uses for those verbs.
/// What: the last `split_whitespace` token, unless it starts with `-` (an
/// option flag with nothing after it) in which case there is no plausible
/// target.
/// Whether `command` redirects output to a *file* (a filesystem write), as
/// opposed to an fd-duplication like `2>&1` / `>&2`.
///
/// Why: `echo 'code' > src/lib.rs` writes a file just as surely as the `Write`
/// tool does — the enforcement would be trivially bypassable without catching
/// redirection. But blanket-denying every `>` would false-positive on the very
/// common `… 2>&1` / `>&2` fd redirects, which are not file writes, so those
/// must be distinguished.
/// What: `true` when [`scan_file_write_redirects`] — the one scanner this and
/// the write boundary share since #7399 — finds a redirect. It skips a
/// second `>` (append) and any spaces, treats it as an fd-duplication (allow,
/// keep scanning) only when the next non-space byte is `&`, then reads the
/// redirect *target* token and treats `/dev/null` as benign (output discard,
/// e.g. `2>/dev/null` / `>/dev/null` / `&>/dev/null`) — allow, keep scanning.
/// Any other `>` is a file-write redirect → `true`.
/// Quote-aware (#2734): a `>` inside a quoted string is literal argument content
/// (`git commit -m 'spec -> code'` — Bob's live false positive), not a
/// redirection, and is skipped — UNLESS the command's quotes are unbalanced, in
/// which case the [`QuoteScan`] map is untrustworthy and every `>` is scanned
/// (the original conservative, over-blocking behaviour). Shell-level redirects
/// (`echo x > f`) are unquoted and still caught. NOTE: an in-quote `>` that is
/// genuinely dangerous — an `awk 'BEGIN{print > "f"}'` in-program file write —
/// is caught by [`sed_awk::awk_is_readonly`], not here.
/// Heredoc-aware (#5356): [`QuoteScan`] knows only `'` and `"`, so a `>` in a
/// here-document body — a `len(k) > 3` comparison in a `python3 <<'PY'`
/// script, an `->` arrow in `cat <<EOF` prose — read as a redirect and made a
/// pure read consume the PM's file-change budget. [`heredoc::HeredocBodies`]
/// marks those bytes as body content; the operator line itself stays live, so
/// `python3 <<'PY' > out.rs` is still a redirect.
/// Test: `has_file_write_redirection_detects_write`,
/// `has_file_write_redirection_detects_append`,
/// `has_file_write_redirection_ignores_fd_dup`,
/// `has_file_write_redirection_ignores_dev_null`,
/// `has_file_write_redirection_ignores_quoted_gt`,
/// `has_file_write_redirection_ignores_heredoc_body`,
/// `has_file_write_redirection_detects_redirect_on_a_heredoc_operator_line`,
/// `has_file_write_redirection_false_for_plain_command`.
pub
/// Deny reason for `git worktree add` targeting a denylisted temp root.
///
/// Why (issue #3977, filed as the worktree-hygiene follow-up to #3955): a
/// worktree provisioned under `/tmp`/`/private/tmp`/`/var/folders` silently
/// fails unrelated tests (trusty-search's `SENSITIVE_PATH_PREFIXES` denylist,
/// #3955) and has repeatedly caused agents to lose in-flight work when the
/// harness or OS reaps that scratch space out from under a live worktree.
/// The message must be actionable, not a bare refusal, so it names the
/// project-local convention directly.
pub const WORKTREE_TMP_REASON: &str = "`git worktree add` must not target /tmp, \
/private/tmp, /var/folders, $TMPDIR, or the harness scratchpad — worktrees provisioned \
there silently fail unrelated tests and can be reaped mid-task (issue #3955). Use \
`<repo-root>/.claude/worktrees/<name>` (the tm-workflow convention) instead.";
/// Filesystem roots `git worktree add` must never target (issue #3977).
///
/// Why: `/tmp` and `/private/tmp` are the same location on macOS (`/tmp` is a
/// symlink) but both are listed literally because [`resolves_under_denylisted_tmp`]
/// does a lexical prefix match, not a filesystem-resolving one (see that
/// function's doc for why). `/var/folders` is the root `$TMPDIR` resolves
/// under on macOS (e.g. `/var/folders/x1/…/T/`), and `/var` is itself a
/// symlink to `/private/var`, so `/private/var/folders` is the SAME location
/// under its resolved spelling and needs the same paired entry `/tmp` already
/// has. `current_dir()` inside `$TMPDIR` returns that resolved spelling, so
/// without this entry a cwd-relative target resolved from a
/// `/private/var/folders` working directory slipped past the guard (#5924).
/// The harness scratchpad (`/private/tmp/claude-502/…`) is already covered by
/// the `/private/tmp` entry — it is called out separately in the deny message
/// (not here) because agents are told to prefer it "instead of /tmp", making
/// it the subtle case that looks compliant while still landing in a
/// denylisted zone.
const WORKTREE_TMP_DENYLIST_ROOTS: & = &;
/// `git worktree add`'s own flags that consume a following argv token.
///
/// Why: needed so [`worktree_add_target_token`] can skip past `-b <branch>` /
/// `-B <branch>` / `--reason <text>` (used with `--lock`) without mistaking
/// the flag's value for the target path.
const WORKTREE_ADD_FLAGS_WITH_ARG: & = &;
/// Detect a `git worktree add` call whose target resolves under a denylisted
/// temp root, regardless of who dispatches the `Bash` call.
///
/// Why: this is the ONE piece of policy that must be called directly from
/// `pm_guard()` **before** its Guard 4 subagent-exemption early return, NOT
/// routed through [`evaluate_tool`](crate::commands::pm_guard::evaluate_tool)/[`evaluate_bash_command`] like every other
/// Bash rule in this module. `evaluate_bash_command` is the sole callee of
/// `evaluate_tool`, which Guard 4 never reaches for a payload carrying a
/// non-empty `agent_id` — i.e. every native Task/Agent-dispatched subagent,
/// which is exactly who provisions these worktrees in practice. A rule placed
/// inside `evaluate_bash_command`/`classify_bash_segment` would therefore be a
/// silent no-op for that calling pattern. See `pm_guard::pm_guard`'s call site
/// for the enforcement of "before Guard 4", and its comment for why that must
/// never be "simplified" back inside `evaluate_tool`.
/// What: splits `command` into composition segments (reusing
/// [`split_shell_segments`] for consistency with the rest of the module),
/// tracks a running effective working directory across the command line by
/// following `cd <dir>` segments and a leading `git -C <dir>` override (a
/// deliberate, PARTIAL closing of the `cd /tmp && git worktree add wt-foo`
/// bypass — see the "Residual bypasses" note below), resolves each `worktree
/// add` segment's target (skipping `-b`/`-B`/`--reason` flag values) against
/// that directory, lexically normalizes it (collapsing `.`/`..` WITHOUT
/// touching the filesystem — the target usually does not exist yet), expands
/// a leading `~` and any `$TMPDIR`/`${TMPDIR}`/`$TMP`/`${TMP}` occurrence
/// using the guard process's own environment (which a Bash tool call inherits
/// unchanged), and denies when the result lexically starts with one of
/// [`WORKTREE_TMP_DENYLIST_ROOTS`]. Only the exact `worktree add` two-token
/// form denies — `list`/`remove`/`prune`/`lock`/… are left alone, matching
/// git's own subcommand structure (`git worktree <subcmd>`, not
/// `git worktree add <subcmd>`), and no other `git`/shell verb is touched.
///
/// Residual bypasses accepted (documented per the task's explicit instruction
/// to state, not hide, what remains open — a missed instance here fails open
/// to ALLOW, same as every other classifier in this module):
/// - Indirection through an intermediate shell variable
/// (`X=/tmp; git worktree add "$X/foo"`) is not resolved — this module does
/// not implement a shell variable table.
/// - A `cd`/`-C` target that is itself a symlink into a denylisted root
/// (e.g. a project-tree symlink pointing at `/tmp`) is not caught: path
/// resolution here is purely lexical, never touches the filesystem
/// (`fs::canonicalize`), because the worktree target usually does not exist
/// yet and a guard must stay fast and side-effect-free.
/// `resolves_under_denylisted_tmp` therefore cannot see through a symlink
/// the way the OS eventually would.
/// `/tmp` itself being a symlink to `/private/tmp`, and `/var` to
/// `/private/var`, are NOT in this bucket — both spellings of each are
/// literal entries in [`WORKTREE_TMP_DENYLIST_ROOTS`] (#5924), so a literal
/// `/tmp/...` or `/private/var/folders/...` argument is caught without
/// needing to resolve the symlink.
/// - Multiple/cumulative `git -C` flags are collapsed to "the last one
/// present"; real git applies them successively relative to each other.
/// Realistic invocations use at most one `-C`.
/// - A `cd`/`-C` argument built from command substitution
/// (`cd "$(mktemp -d)"`) is not resolved — this module classifies text
/// structurally, it does not execute the shell.
/// - **Largest of this list, tracked separately as
/// [issue #3981](https://github.com/bobmatnyc/trusty-tools/issues/3981):**
/// `pm_guard`'s Guard 2/3 escape hatches
/// (`TRUSTY_MPM_DISABLE_HOOKS`/`TRUSTY_MPM_PM_UNRESTRICTED`) bypass this
/// entire guard when set, and while neither is ever set programmatically
/// in this codebase's Rust source, Claude Code's `settings.json` supports a
/// top-level `env` object applied to every hook invocation (live-reloaded
/// mid-session) — and a `Write`/`Edit` to `.claude/settings.json` is not
/// itself blocked by `pm_guard` today (`.json` is not a source-code
/// extension, so `evaluate_edit_tool` falls through to an unconditional
/// ALLOW). So the PM, or any subagent Guard 4 already exempts, can set
/// either var there and self-exempt from every rule in this module,
/// including this one, in one ordinary already-permitted config write. This
/// is a pre-existing gap (Guard 3 predates this worktree guard by many
/// issues) that this change neither introduces nor widens; it guards
/// against an agent going off-script, not a determined adversary, and is
/// deliberately NOT fixed here — the remedy belongs in the edit-tool
/// classifier, not this Bash classifier, and is the project owner's call.
///
/// Test: `evaluate_worktree_add_command_*` below;
/// `pm_guard_blocks_worktree_add_under_tmp_via_subagent_payload` and siblings
/// in `tests/tm_hook_pm_guard.rs` exercise the end-to-end binary path,
/// including the `agent_id`-present case this function exists for.
pub
/// Both `git worktree add` gates in one call: the temp-root denylist (#3955)
/// and the disk-usage threshold (#7497).
///
/// Why: `pm_guard()` must run both BEFORE its Guard 4 subagent exemption, and
/// two call sites there are two places for the next rule to be added to only
/// one of them. The placement requirement is identical, so the call is too.
/// What: the temp-root reason wins when both apply — it names a location that
/// is wrong regardless of how full the disk is. Returns `None` when the command
/// creates no worktree.
/// Test: `evaluate_worktree_add_command_*` for the first rule, `disk_usage`'s
/// own tests for the second, and `tests/tm_hook_pm_guard.rs` for both end to end.
pub
/// [`evaluate_worktree_add_command`] against an explicit environment.
///
/// Why: see [`PathEnv`] — this is the seam that lets the expansion rules be
/// asserted end-to-end (same segment splitting, same denylist, same return
/// value) without any test touching process-global env.
/// Every path a `git worktree add` in `command` would create.
///
/// Why (#7497): the disk-usage gate asks a DIFFERENT question of the SAME
/// targets — "is the volume this lands on full?" rather than "is it under a
/// denylisted temp root?" — and a second walk of the command line is how the
/// two would drift into resolving `cd`, `git -C`, `~` and `$TMPDIR` differently.
/// One resolver, two rules.
/// What: the resolved, lexically normalised targets, in command order. Empty
/// when the command contains no `worktree add`, which is the fast path every
/// other Bash call takes.
/// Test: `worktree_add_targets_resolves_cd_and_dash_c`, and the disk rule's own
/// cases in `pm_guard_bash::disk_usage`.
pub
/// [`worktree_add_targets`] against an explicit environment — see [`PathEnv`].
/// The `-C <path>` value preceding a resolved `worktree` subcommand token, if
/// any — git's own global working-directory override.
///
/// Why: `git -C /tmp worktree add wt-foo` changes git's effective working
/// directory for the whole invocation exactly as a preceding `cd /tmp &&`
/// would, so it must feed the same resolution base as
/// [`evaluate_worktree_add_command`]'s `cd`-tracking. Scoped to `argv[..worktree_idx]`
/// so a `-C` appearing after `worktree` (not valid git syntax, but shlex would
/// still tokenize it) is never mistaken for the global option.
/// What: the last `-C <value>` pair found before `worktree_idx` (real git
/// applies multiple `-C` flags cumulatively/relative to each other — this
/// collapses to "last wins", a documented simplification; see the residual
/// bypass list on [`evaluate_worktree_add_command`]).
/// The target-path token of a `git worktree add …` argv tail (everything
/// after the `add` token), skipping flags and their values.
///
/// Why: `git worktree add [-f] [--detach] [--checkout] [--lock [--reason
/// <text>]] [--orphan] [(-b | -B) <branch>] <path> [<commit-ish>]` — the path
/// is the first non-flag positional, but `-b`/`-B`/`--reason` each consume a
/// following token that must not be mistaken for it.
/// What: walks `tail`, skipping [`WORKTREE_ADD_FLAGS_WITH_ARG`] pairs and any
/// other `-`-prefixed flag, returning the first remaining token.
/// Whether `path` lexically starts with one of [`WORKTREE_TMP_DENYLIST_ROOTS`].
// #7498, #7479, #7499: reported false positives get their own test file, so
// the allow case and the deny case bounding it sit side by side per issue.
// #9001: case 3's allow beside its deny bound, plus the mysql DENY rows.
// #7839, #7833, #7479, #7744, #7743, #7738, #7728, #7863: one row per issue
// for the shared-tokenizer cluster, beside the still-refused controls that
// bound every relaxation.
// #9127: a rule reading the shell-group walk must refuse what it cannot place.