lean-ctx-engine 3.12.3

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
/// Tokenize a shell command segment respecting single/double quotes and backslash escapes.
/// Returns tokens with outer quotes stripped, matching how the shell would parse them.
/// E.g. `git -C "Program Files" status` → `["git", "-C", "Program Files", "status"]`
pub fn shell_tokenize(input: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut current = String::new();
    let mut chars = input.chars().peekable();
    let mut in_single = false;
    let mut in_double = false;
    let mut parameter_depth: u32 = 0;

    while let Some(c) = chars.next() {
        match c {
            '\'' if !in_double => in_single = !in_single,
            '"' if !in_single => in_double = !in_double,
            '\\' if !in_single => {
                // #1781: inside double quotes a backslash is literal unless it
                // precedes `$`, `` ` ``, `"`, `\` or a newline (POSIX 2.2.3).
                // The old arm consumed it unconditionally, so a quoted Windows
                // path — `Start-Process "C:\Program Files\Docker\Docker Desktop.exe"`
                // — tokenized as `C:Program FilesDockerDocker Desktop.exe`, and
                // the allowlist then refused a fragment that was never a command
                // and asked the user to report it. Outside quotes the escape
                // still applies to any character, which `tokenize_backslash_escape`
                // pins.
                let escapes_next =
                    !in_double || matches!(chars.peek(), Some('$' | '`' | '"' | '\\' | '\n'));
                if escapes_next {
                    if let Some(next) = chars.next() {
                        current.push(next);
                    }
                } else {
                    current.push('\\');
                }
            }
            '$' if !in_single && chars.peek() == Some(&'{') => {
                parameter_depth += 1;
                current.push(c);
            }
            '}' if !in_single && parameter_depth > 0 => {
                parameter_depth -= 1;
                current.push(c);
            }
            c if c.is_whitespace() && !in_single && !in_double && parameter_depth == 0 => {
                if !current.is_empty() {
                    tokens.push(std::mem::take(&mut current));
                }
            }
            _ => current.push(c),
        }
    }
    if !current.is_empty() {
        tokens.push(current);
    }
    tokens
}

/// Returns the byte length of the first shell token in `input`, respecting quotes
/// and `(...)` nesting. Used by `skip_env_assignments` to advance past env
/// assignments with quoted values like `FOO="bar baz"` — and, critically, past
/// assignments whose value is a command substitution like `FOO=$(cmd a b)`
/// (#855): without paren-depth tracking, whitespace *inside* the unclosed
/// `$(...)` looked like the end of the token, splitting `s=$(gh pr view …)`
/// into a bogus token `s=$(gh` plus a leftover `pr` that got misread as the
/// base command.
pub fn quote_aware_token_end(input: &str) -> usize {
    let bytes = input.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    let mut in_single = false;
    let mut in_double = false;
    let mut paren_depth: u32 = 0;
    let mut parameter_depth: u32 = 0;

    while i < len {
        let ch = bytes[i];
        match ch {
            b'\'' if !in_double => {
                in_single = !in_single;
                i += 1;
            }
            b'"' if !in_single => {
                in_double = !in_double;
                i += 1;
            }
            b'\\' if !in_single => {
                i = (i + 2).min(len);
            }
            b'(' if !in_single && !in_double => {
                paren_depth += 1;
                i += 1;
            }
            b')' if !in_single && !in_double && paren_depth > 0 => {
                paren_depth -= 1;
                i += 1;
            }
            b'$' if !in_single && !in_double && bytes.get(i + 1) == Some(&b'{') => {
                parameter_depth += 1;
                i += 1;
            }
            b'}' if !in_single && parameter_depth > 0 => {
                parameter_depth -= 1;
                i += 1;
            }
            b if b.is_ascii_whitespace()
                && !in_single
                && !in_double
                && paren_depth == 0
                && parameter_depth == 0 =>
            {
                return i;
            }
            _ => i += 1,
        }
    }
    len
}
/// Extract ALL command segments from a compound shell command.
/// Splits on: &&, ||, ;, | (pipe), and handles subshell grouping.
pub fn extract_all_commands(command: &str) -> Vec<String> {
    split_on_operators(command)
        .into_iter()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

/// One lexical context.
///
/// A command substitution starts a **fresh** one. POSIX says quoting restarts
/// inside `$( … )`, so in `echo "$(python3 -c "a;b")"` the inner `"…"` is its
/// own string and its `;` separates nothing (GH #1646). Tracking quotes as two
/// flat booleans could not express that: the scanner never noticed `$(` while
/// inside double quotes, so the inner opening quote *closed* the outer one,
/// `a;b` looked unquoted, and the `;` split a bogus command out of a Python
/// source line — which the allowlist then rejected with an unusable suggestion.
///
/// Treating the substitution as one word here loses no enforcement: its real
/// contents are re-split and checked by `substitution::extract_substitution_commands`,
/// which is where commands that a substitution genuinely *runs* are caught.
#[derive(Clone, Copy)]
struct Frame {
    in_single_quote: bool,
    in_double_quote: bool,
    paren_depth: u32,
    /// #939: brace groups (`{ cmd; }`) need the same operator-shielding as
    /// `( cmd )` subshells — otherwise a `}` that closes a `{` opened on an
    /// earlier physical line (e.g. after heredoc-body stripping collapses the
    /// body between them) is misread as its own bare command segment.
    brace_depth: u32,
    /// #1793: `[[ … ]]` is a bash conditional *construct*, not a command, and
    /// the `&&`/`||` inside it join predicates rather than commands. Without
    /// shielding, `[[ -x a && -x b ]]` was split mid-condition into fragments
    /// like `[[ -x a` and `-x b ]]`, none of which resolve to a real command.
    bracket_depth: u32,
    kind: FrameKind,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum FrameKind {
    /// The command line itself. Separators split only at this level.
    Base,
    /// Opened by `$(`, closed by the matching `)`.
    DollarParen,
    /// Opened and closed by a backtick — the older substitution form, same
    /// quoting-restart rule.
    Backtick,
}

impl Frame {
    const fn new(kind: FrameKind) -> Self {
        Self {
            in_single_quote: false,
            in_double_quote: false,
            paren_depth: 0,
            brace_depth: 0,
            bracket_depth: 0,
            kind,
        }
    }

    /// Inside quotes, or inside a group whose closing delimiter is still open.
    const fn shields_operators(&self) -> bool {
        self.in_single_quote
            || self.in_double_quote
            || self.paren_depth > 0
            || self.brace_depth > 0
            || self.bracket_depth > 0
    }
}

/// True when the two bytes at `i` form a standalone `[[` token — the opener of
/// a bash conditional (#1793).
///
/// Bash requires `[[` to be its own word, and so does this: a word boundary
/// before and whitespace after. That distinction is what keeps a glob character
/// class (`ls a[[:alpha:]]`) or a nested array subscript (`${arr[[i]]}`) from
/// opening a depth that would never close and swallow the rest of the line.
fn opens_double_bracket(bytes: &[u8], i: usize) -> bool {
    if bytes.get(i) != Some(&b'[') || bytes.get(i + 1) != Some(&b'[') {
        return false;
    }
    let boundary_before = i == 0
        || matches!(
            bytes[i - 1],
            b' ' | b'\t' | b'\n' | b'\r' | b';' | b'&' | b'|' | b'('
        );
    let space_after = matches!(bytes.get(i + 2), Some(b' ' | b'\t' | b'\n' | b'\r'));
    boundary_before && space_after
}

/// True when the two bytes at `i` form a standalone `]]` token closing a
/// conditional opened by [`opens_double_bracket`]. Mirrors its word-boundary
/// rule: whitespace before, and a separator or end of input after.
fn closes_double_bracket(bytes: &[u8], i: usize) -> bool {
    if bytes.get(i) != Some(&b']') || bytes.get(i + 1) != Some(&b']') {
        return false;
    }
    let space_before = i > 0 && matches!(bytes[i - 1], b' ' | b'\t' | b'\n' | b'\r');
    let separator_after = matches!(
        bytes.get(i + 2),
        None | Some(b' ' | b'\t' | b'\n' | b'\r' | b';' | b'&' | b'|' | b')')
    );
    space_before && separator_after
}

/// Split command string on shell operators: ;, &&, ||, |
/// Respects single/double quotes, parentheses nesting, and backslash escapes
/// outside single quotes (GL #1160): `rg split\.label\|quantityLabel` is ONE
/// command — the escaped pipe is regex data, not an operator. The old scanner
/// split there and blocked the pattern fragment as an unknown command; same
/// for `find … -exec rm {} \;`.
pub fn split_on_operators(command: &str) -> Vec<&str> {
    split_with_separators(command)
        .into_iter()
        .map(|(segment, _)| segment)
        .collect()
}

/// The operator that ends a command segment.
///
/// Where a segment runs can depend on it (#1850): a `cd` followed by `&&`
/// moves the next command, one followed by `||` only runs the next command if
/// it failed, and one in a pipeline or in the background moves nothing at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Separator {
    /// `;`, a newline or a carriage return.
    Sequence,
    /// `&&`
    And,
    /// `||`
    Or,
    /// `|`
    Pipe,
    /// A single `&`.
    Background,
}

/// Every segment together with the separator that ends it; the last segment
/// has none. Same scanner as `split_on_operators`, so the two never disagree
/// about where a command ends.
pub fn segments_with_separators(command: &str) -> Vec<(String, Option<Separator>)> {
    split_with_separators(command)
        .into_iter()
        .map(|(segment, sep)| (segment.trim().to_string(), sep))
        .filter(|(segment, _)| !segment.is_empty())
        .collect()
}

/// Every segment together with the separator that ends the segment before
/// it; the first segment has none. A leading `&` with nothing before it still
/// counts, so a PowerShell call operator (`& 'x'`, which this scanner splits
/// like a background `&`) can be told from a command.
pub(super) fn segments_after_separators(command: &str) -> Vec<(String, Option<Separator>)> {
    let mut previous = None;
    let mut out = Vec::new();
    for (segment, sep) in split_with_separators(command) {
        let segment = segment.trim();
        if !segment.is_empty() {
            out.push((segment.to_string(), previous));
        }
        previous = sep;
    }
    out
}

/// Does an `&` that starts a statement (nothing before it in its segment)
/// meet a line break or `;` before any target? Read as a PowerShell call
/// operator, the text after the break would otherwise pass as a statement of
/// its own.
pub(super) fn has_call_operator_before_break(command: &str) -> bool {
    split_with_separators(command).windows(2).any(|pair| {
        let [(before, amp), (target, after)] = pair else {
            return false;
        };
        before.trim().is_empty()
            && *amp == Some(Separator::Background)
            && target.trim().is_empty()
            && *after == Some(Separator::Sequence)
    })
}

/// The top-level statements of a command line: the original text between
/// `;`/newline separators, each still holding its `&&`, `||`, `|` and `&`
/// verbatim. Same scanner as [`segments_with_separators`].
pub fn sequence_statements(command: &str) -> Vec<&str> {
    let base = command.as_ptr() as usize;
    let mut out = Vec::new();
    let mut start: Option<usize> = None;
    for (segment, sep) in split_with_separators(command) {
        let at = segment.as_ptr() as usize - base;
        let begin = *start.get_or_insert(at);
        if matches!(sep, Some(Separator::Sequence) | None) {
            out.push(&command[begin..at + segment.len()]);
            start = None;
        }
    }
    if let Some(begin) = start {
        out.push(&command[begin..]);
    }
    out.into_iter()
        .map(str::trim)
        .filter(|statement| !statement.is_empty())
        .collect()
}

fn split_with_separators(command: &str) -> Vec<(&str, Option<Separator>)> {
    let mut segments = Vec::new();
    let mut start = 0;
    let bytes = command.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    // Stack, not booleans: see [`Frame`]. Index 0 is always the command line.
    let mut stack: Vec<Frame> = vec![Frame::new(FrameKind::Base)];

    while i < len {
        let ch = bytes[i];
        // `$(` and a backtick open a substitution wherever the shell would
        // expand one: unquoted, or inside double quotes. Single quotes inhibit
        // it entirely, which the single-quote arm below handles by consuming
        // everything to the closing quote.
        let opens_substitution = |i: usize| -> Option<(FrameKind, usize)> {
            match bytes[i] {
                b'$' if i + 1 < len && bytes[i + 1] == b'(' => Some((FrameKind::DollarParen, 2)),
                b'`' => Some((FrameKind::Backtick, 1)),
                _ => None,
            }
        };

        let frame = *stack.last().expect("base frame is never popped");

        if frame.in_single_quote {
            if ch == b'\'' {
                stack.last_mut().expect("frame").in_single_quote = false;
            }
            i += 1;
            continue;
        }

        if frame.in_double_quote {
            match ch {
                // \" stays inside the string; \\ consumes both so `"x\\"` closes.
                b'\\' => i = (i + 2).min(len),
                b'"' => {
                    stack.last_mut().expect("frame").in_double_quote = false;
                    i += 1;
                }
                _ => {
                    if let Some((kind, width)) = opens_substitution(i) {
                        stack.push(Frame::new(kind));
                        i += width;
                    } else {
                        i += 1;
                    }
                }
            }
            continue;
        }

        // Unquoted within the current frame.
        if let Some((kind, width)) = opens_substitution(i) {
            if kind == FrameKind::Backtick && frame.kind == FrameKind::Backtick {
                // The same character closes a backtick substitution.
                stack.pop();
            } else {
                stack.push(Frame::new(kind));
            }
            i += width;
            continue;
        }

        let at_top = stack.len() == 1;
        let unshielded = at_top && !frame.shields_operators();

        // #1793: enter/leave a `[[ … ]]` conditional so its internal `&&`/`||`
        // stay part of the condition. Both delimiters must be standalone words
        // (see the helpers), so a glob class (`ls a[[:alpha:]]`) or an array
        // subscript never opens a depth that would swallow the rest of the line.
        if ch == b'[' && opens_double_bracket(bytes, i) {
            stack.last_mut().expect("frame").bracket_depth += 1;
            i += 2;
            continue;
        }
        if ch == b']' && frame.bracket_depth > 0 && closes_double_bracket(bytes, i) {
            let top = stack.last_mut().expect("frame");
            top.bracket_depth = top.bracket_depth.saturating_sub(1);
            i += 2;
            continue;
        }

        match ch {
            b'\\' => {
                // Escaped char is data (bash semantics outside quotes) — never
                // an operator or quote opener.
                i = (i + 2).min(len);
            }
            b'\'' => {
                stack.last_mut().expect("frame").in_single_quote = true;
                i += 1;
            }
            b'"' => {
                stack.last_mut().expect("frame").in_double_quote = true;
                i += 1;
            }
            b'(' => {
                stack.last_mut().expect("frame").paren_depth += 1;
                i += 1;
            }
            b')' => {
                let top = stack.last_mut().expect("frame");
                if top.kind == FrameKind::DollarParen && top.paren_depth == 0 {
                    // Matching close of `$(` — back to the enclosing context,
                    // whose quoting resumes exactly where it left off.
                    stack.pop();
                } else {
                    top.paren_depth = top.paren_depth.saturating_sub(1);
                }
                i += 1;
            }
            b'{' => {
                stack.last_mut().expect("frame").brace_depth += 1;
                i += 1;
            }
            b'}' => {
                let top = stack.last_mut().expect("frame");
                top.brace_depth = top.brace_depth.saturating_sub(1);
                i += 1;
            }
            // GH #2131: bash allows line breaks between a function head and
            // its body (`run()\n{\n…\n}`). The newline ends no command there,
            // so the definition stays one segment, as on a single line.
            b'\n' | b'\r' if unshielded && is_function_head(&command[start..i]) => {
                i += 1;
            }
            b'\n' | b'\r' | b';' if unshielded => {
                segments.push((&command[start..i], Some(Separator::Sequence)));
                i += 1;
                start = i;
            }
            b'&' if unshielded => {
                if i + 1 < len && bytes[i + 1] == b'&' {
                    // &&
                    segments.push((&command[start..i], Some(Separator::And)));
                    i += 2;
                    start = i;
                } else if (i > 0 && matches!(bytes[i - 1], b'>' | b'<'))
                    || (i + 1 < len && bytes[i + 1] == b'>')
                {
                    // Redirect operator, NOT a separator: `2>&1`, `1>&2`, `>&file`, `<&3`,
                    // `0<&-` (prev is '>' or '<') or `&>file`, `&>>file` (next is '>'). The '&' belongs to the current
                    // command — splitting here would mistake the fd/target (e.g. `1`) for a
                    // standalone command and falsely block it (#334).
                    i += 1;
                } else {
                    // single & (background operator) — still a command separator
                    segments.push((&command[start..i], Some(Separator::Background)));
                    i += 1;
                    start = i;
                }
            }
            b'|' if unshielded => {
                if i + 1 < len && bytes[i + 1] == b'|' {
                    // ||
                    segments.push((&command[start..i], Some(Separator::Or)));
                    i += 2;
                    start = i;
                } else if i > 0 && bytes[i - 1] == b'>' {
                    // `>|` (noclobber redirect), NOT a pipe: the '|' belongs to
                    // the redirect operator and the following token is a file
                    // path, not a command. Splitting here treated the target
                    // (e.g. `out` in `date >| out`) as a command and falsely
                    // blocked it against the allowlist (#387).
                    i += 1;
                } else {
                    // pipe
                    segments.push((&command[start..i], Some(Separator::Pipe)));
                    i += 1;
                    start = i;
                }
            }
            _ => {
                i += 1;
            }
        }
    }

    if start < len {
        segments.push((&command[start..], None));
    }

    segments
}

/// Extract normalized command tokens from a single segment (no operators):
/// skip env assignments, skip a PowerShell assignment, return empty for a
/// PowerShell value expression, skip a leading `{` brace-group token (#939 —
/// lean-ctx's own agent wrapper emits this form), and take the basename of
/// the first token. Shared by `extract_base_from_segment` (which returns just
/// the first token) and the subcommand-scoped allowlist matcher (which needs
/// the rest of the tokens too), so the two normalizations cannot drift
/// (GH #1419 follow-up).
pub fn extract_command_tokens_from_segment(segment: &str) -> Vec<String> {
    let trimmed = segment.trim();
    if trimmed.is_empty() {
        return Vec::new();
    }

    let cmd_part = skip_powershell_assignment(skip_env_assignments(trimmed));
    if cmd_part.is_empty() {
        return Vec::new();
    }
    if is_powershell_value_expression(cmd_part) {
        return Vec::new();
    }

    let tokens = shell_tokenize(cmd_part);
    // #939: a leading `{` brace-group token (e.g. from
    // `agent_wrapper::rebuild`'s `{ <real command>\n} && pwd ...` wrapping)
    // is not itself a command — skip it so the base extracted is the real
    // command inside the group, not the brace.
    let mut token_iter = tokens.into_iter();
    let first_token = match token_iter.next() {
        Some(t) if t == "{" => token_iter.next(),
        other => other,
    };
    let Some(first_token) = first_token else {
        return Vec::new();
    };
    let basename = first_token
        .rsplit('/')
        .next()
        .unwrap_or(&first_token)
        .to_string();
    // `./unset`, `/tmp/x/export` run a file, not the builtin: keep the path so
    // the allowlist sees a program, not a builtin name.
    let basename = if first_token.contains('/') && ENV_SETTING_BUILTINS.contains(&basename.as_str())
    {
        first_token.clone()
    } else {
        basename
    };

    std::iter::once(basename).chain(token_iter).collect()
}

/// The program a command word runs, for the gate's name checks (`env`,
/// `git`, interpreters, wrappers, unconditionally blocked programs): its
/// last path component — on macOS and Windows, whose file systems ignore
/// case by default, lower-cased (and without `.exe` on Windows), so
/// `/usr/bin/ENV` is `env` there.
pub fn exec_name(token: &str) -> String {
    exec_name_for(
        token,
        cfg!(any(target_os = "macos", windows)),
        cfg!(windows),
    )
}

pub fn exec_name_for(token: &str, fold_case: bool, windows: bool) -> String {
    let base = if windows {
        token.rsplit(['/', '\\']).next()
    } else {
        token.rsplit('/').next()
    }
    .unwrap_or(token);
    if !fold_case {
        return base.to_owned();
    }
    let lower = base.to_ascii_lowercase();
    match lower.strip_suffix(".exe") {
        Some(stem) if windows => stem.to_owned(),
        _ => lower,
    }
}

/// Extract the base command name from a single segment (no operators).
pub fn extract_base_from_segment(segment: &str) -> String {
    extract_command_tokens_from_segment(segment)
        .into_iter()
        .next()
        .unwrap_or_default()
}

/// Skip a local PowerShell assignment (`$result = Get-Content …`) so the
/// wrapped cmdlet is validated. Environment/scoped variables contain `:` and
/// intentionally remain unrecognized, preventing `$env:PATH = …` bypasses.
///
/// Only a PowerShell host reads `$name = value` as an assignment. Bash runs
/// `$name` with the arguments `= value`, so under any other shell the line is
/// left whole and its `$` command word is refused as expanding at run time.
pub fn skip_powershell_assignment(segment: &str) -> &str {
    let trimmed = segment.trim_start();
    if super::ps_statements::host_mode() != super::ps_statements::Mode::PowerShell {
        return trimmed;
    }
    let Some(variable_end) = powershell_local_variable_end(trimmed) else {
        return trimmed;
    };
    let after_variable = trimmed[variable_end..].trim_start();
    let Some(after_equals) = after_variable.strip_prefix('=') else {
        return trimmed;
    };
    after_equals.trim_start()
}

fn powershell_local_variable_end(segment: &str) -> Option<usize> {
    let bytes = segment.as_bytes();
    if bytes.first() != Some(&b'$') {
        return None;
    }
    let mut end = 1;
    let first = *bytes.get(end)?;
    if !(first.is_ascii_alphabetic() || first == b'_') {
        return None;
    }
    end += 1;
    while bytes
        .get(end)
        .is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')
    {
        end += 1;
    }
    (bytes.get(end) != Some(&b':')).then_some(end)
}

/// A bare local variable or simple index lookup is pipeline data, not a command.
/// Method calls and scoped variables deliberately fall through to deny-by-default.
fn is_powershell_value_expression(segment: &str) -> bool {
    // Bash runs a bare `$VAR` as the command it expands to.
    if super::ps_statements::host_mode() != super::ps_statements::Mode::PowerShell {
        return false;
    }
    let trimmed = segment.trim();
    let Some(variable_end) = powershell_local_variable_end(trimmed) else {
        return false;
    };
    let suffix = trimmed[variable_end..].trim();
    suffix.is_empty()
        || (suffix.starts_with('[')
            && suffix.ends_with(']')
            && !suffix.contains(['(', ')', ';', '|', '&', '=']))
}

/// #1488: detect whether a segment is a shell function definition.
/// Pattern: `NAME() {`, `function NAME {` or `function NAME() {`; GH #2131
/// adds `NAME(){`, a body on the next line and a `( … )` subshell body.
/// Returns the function name if it is a definition, `None` otherwise.
pub fn detect_function_def(segment: &str) -> Option<String> {
    function_def_parts(segment).map(|(name, _)| name.to_string())
}

/// #1488: the commands of a function definition segment, between the outer
/// `{` and `}` (or `(` and `)`) — `greet() { echo hi; echo bye; }` gives
/// `echo hi; echo bye;`. The allowlist expands it like a top-level command
/// line, so control flow in a body (`for … do … done`, `if … then … fi`) is not
/// mistaken for commands (GH #2002).
pub fn function_body(segment: &str) -> Option<&str> {
    function_def_parts(segment).map(|(_, body)| body)
}

/// Split a function definition into its name and body text.
///
/// The body must be one balanced `{ … }` group or `( … )` subshell that ends
/// the segment (GH #2131). Anything after it, such as a redirect evaluated on
/// every call, makes this `None`, so the segment falls through to base
/// extraction and is blocked rather than half-checked.
fn function_def_parts(segment: &str) -> Option<(&str, &str)> {
    let (name, rest) = function_def_head(segment)?;
    let body = rest.trim();
    if body.starts_with('{') {
        return Some((name, super::compound::balanced_brace_inner(body)?));
    }
    if body.starts_with('(') {
        let (inner, end) = super::compound::balanced_paren_at(body, 0)?;
        return (end == body.len()).then_some((name, inner.trim()));
    }
    None
}

/// GH #2131: is `text` exactly a function head with its body still to come?
/// See [`split_with_separators`].
fn is_function_head(text: &str) -> bool {
    function_def_head(text).is_some_and(|(_, rest)| rest.trim().is_empty())
}

/// Parse a function head — `NAME()`, `NAME ()`, `function NAME` or
/// `function NAME()` — and return the name and the text after the head. Bash
/// accepts any whitespace, line breaks included, before the body, and
/// `NAME(){` needs none. `function NAME` without `()` needs whitespace, as
/// `function f{` names a function `f{`.
fn function_def_head(segment: &str) -> Option<(&str, &str)> {
    let cmd_part = skip_env_assignments(segment.trim());
    let keyword_rest = cmd_part
        .strip_prefix("function")
        .filter(|rest| rest.starts_with(|c: char| c.is_whitespace()));
    let (name, after_name) = match keyword_rest {
        Some(rest) => split_function_name(rest.trim_start())?,
        None => split_function_name(cmd_part)?,
    };
    match strip_empty_parens(after_name) {
        Some(rest) => Some((name, rest)),
        None if keyword_rest.is_some()
            && (after_name.is_empty() || after_name.starts_with(|c: char| c.is_whitespace())) =>
        {
            Some((name, after_name))
        }
        None => None,
    }
}

fn split_function_name(text: &str) -> Option<(&str, &str)> {
    let end = text
        .find(|c: char| !(c.is_alphanumeric() || c == '_'))
        .unwrap_or(text.len());
    (end > 0).then(|| text.split_at(end))
}

/// `()` with optional blanks before and inside it; returns what follows.
fn strip_empty_parens(text: &str) -> Option<&str> {
    let rest = text.trim_start_matches([' ', '\t']).strip_prefix('(')?;
    rest.trim_start_matches([' ', '\t']).strip_prefix(')')
}

/// Shell builtins that legitimately export or mutate environment variables.
/// A segment beginning with one of these (`export PATH=…`, `readonly FOO=bar`)
/// is not a bare inline `PATH=… cmd` hijack — skip the builtin and any
/// following `VAR=value` tokens so export-only segments contribute no leaf
/// command and `export PATH=… ; python3 …` resolves to `python3`.
const ENV_SETTING_BUILTINS: &[&str] = &[
    "export", "unset", "readonly", "local", "declare", "typeset", "umask",
];

/// A builtin whose operands the gate may step over (see [`accepts_operand`]).
#[derive(Clone, Copy, PartialEq)]
enum OperandKind {
    /// `export`, `readonly`, `declare`, `local`, `typeset`: names, `NAME=value`.
    Declaration,
    /// `unset`: plain names only.
    Unset,
    /// `umask`: a mode.
    Umask,
}

fn operand_kind_of(unquoted: &str) -> Option<OperandKind> {
    match unquoted {
        "umask" => Some(OperandKind::Umask),
        "unset" => Some(OperandKind::Unset),
        n if ENV_SETTING_BUILTINS.contains(&n) => Some(OperandKind::Declaration),
        _ => None,
    }
}

fn is_identifier(s: &str) -> bool {
    let mut bytes = s.bytes();
    bytes
        .next()
        .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_')
        && bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
}

/// A flag cluster from a fixed whitelist. Everything else stays a leaf, and
/// so blocked: `-f` (exports a function), `-i` (arithmetic on every later
/// assignment, which runs `a[$(cmd)]` subscripts), `-a`/`-A` (a quoted word
/// is re-parsed as a compound assignment), `-n` (namerefs).
fn is_safe_flag(token: &str, allowed: &str) -> bool {
    token == "--"
        || token
            .strip_prefix('-')
            .is_some_and(|f| !f.is_empty() && f.chars().all(|c| allowed.contains(c)))
}

fn is_umask_mode(token: &str) -> bool {
    if matches!(token, "-S" | "-p") {
        return true;
    }
    if (1..=4).contains(&token.len()) && token.bytes().all(|b| (b'0'..=b'7').contains(&b)) {
        return true;
    }
    !token.is_empty()
        && token.split(',').all(|clause| {
            let rest = clause.trim_start_matches(['u', 'g', 'o', 'a']);
            rest.strip_prefix(['-', '+', '='])
                .is_some_and(|perm| perm.chars().all(|c| "rwxXst".contains(c)))
        })
}

/// Whether `unquoted` may be consumed as an operand of the builtin `kind`:
/// a variable name, a plain assignment, or a umask mode, never a program.
/// Anything else (an array subscript, `=(`, a flag outside the whitelist, a
/// redirection, a backtick) is not consumed and reaches the allowlist as the
/// leaf command.
fn accepts_operand(kind: OperandKind, raw: &str, unquoted: &str) -> bool {
    match kind {
        OperandKind::Umask => is_umask_mode(unquoted),
        OperandKind::Unset => is_identifier(unquoted) || is_safe_flag(unquoted, "v"),
        OperandKind::Declaration => {
            if is_identifier(unquoted) || is_safe_flag(unquoted, "rxgplutv") {
                return true;
            }
            // The raw token, not the unquoted one: what is quoted or escaped
            // decides what bash expands and re-parses.
            raw.split_once('=').is_some_and(|(name, value)| {
                is_identifier(name)
                    && !EVALUATED_SPECIAL_VARS.contains(&name)
                    && is_safe_declaration_value(value)
            })
        }
    }
}

/// Whether the raw value of a `declare`-family assignment is one of three
/// plain forms. `declare` re-parses a value that expands to `(…)` as a
/// compound assignment when the target is an array, and that runs a `$(cmd)`
/// nobody scans; bash can produce the `(` through `$'…'`, `${X:-(}`, braces or
/// a variable, so the value is whitelisted rather than searched:
/// - a bare word of `[A-Za-z0-9_./:,@%+=-]` and plain `$NAME` / `${NAME}`;
/// - a single-quoted string without `(`, `$` or a backtick;
/// - a double-quoted string whose only expansions are `$NAME` / `${NAME}`,
///   without `(`, `[`, a backtick, a backslash or `$(`.
fn is_safe_declaration_value(value: &str) -> bool {
    const BARE: &str = "_./:,@%+=-";
    if let Some(inner) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) {
        return !inner.contains(['\'', '(', '$', '`']);
    }
    if let Some(inner) = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
        return !inner.contains(['"', '(', '[', '`', '\\'])
            && only_plain_expansions(inner, |_| true);
    }
    only_plain_expansions(value, |c| c.is_ascii_alphanumeric() || BARE.contains(c))
}

/// Every `$` in `s` starts `$NAME` or `${NAME}`, and every other character
/// satisfies `literal`.
fn only_plain_expansions(s: &str, literal: impl Fn(char) -> bool) -> bool {
    let mut rest = s;
    while let Some(c) = rest.chars().next() {
        if c != '$' {
            if !literal(c) {
                return false;
            }
            rest = &rest[c.len_utf8()..];
            continue;
        }
        rest = &rest[1..];
        let name = if let Some(braced) = rest.strip_prefix('{') {
            let Some((name, after)) = braced.split_once('}') else {
                return false;
            };
            rest = after;
            name
        } else {
            let end = rest
                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
                .unwrap_or(rest.len());
            let (name, after) = rest.split_at(end);
            rest = after;
            name
        };
        if !is_identifier(name) {
            return false;
        }
    }
    true
}

/// Variables bash keeps integer-attributed: assigning one evaluates the value
/// arithmetically (`a[$(cmd)]` runs `cmd`) without any `-i`. No assignment to
/// them is stepped over, whatever the value, because arithmetic resolves
/// names recursively. The list comes from a full `compgen -v` sweep (plus a
/// further set of well-known special variables) of bash, trying each name as
/// `NAME='a[$(cmd)]'`; only these run `cmd`.
pub const EVALUATED_SPECIAL_VARS: &[&str] = &[
    "SECONDS",
    "RANDOM",
    "SRANDOM",
    "OPTIND",
    "HISTCMD",
    "BASH_XTRACEFD",
    "BASH_COMPAT",
];

/// Whether `token` (`NAME=…`, `NAME+=…`) assigns one of [`EVALUATED_SPECIAL_VARS`].
pub fn assigns_evaluated_special(token: &str) -> bool {
    token.split_once('=').is_some_and(|(name, _)| {
        EVALUATED_SPECIAL_VARS.contains(&name.strip_suffix('+').unwrap_or(name))
    })
}

/// What stands in for the command of a segment whose builtin operand was
/// refused: no allowlist entry can ever match it, and the NUL cannot be typed,
/// so it cannot be approved either.
const REFUSED_OPERAND_SENTINEL: &str = "\0refused-builtin-operand";

/// The operand or assignment of a leading `export`/`unset`/… prefix that the
/// gate does not step over, if any. `skip_env_assignments` fails closed on it;
/// this names it for the refusal message.
pub fn refused_builtin_operand(segment: &str) -> Option<String> {
    skip_env_prefix(segment.trim()).err()
}

/// Skip leading KEY=VALUE environment variable assignments.
/// Uses quote-aware scanning so `FOO="bar baz" git status` correctly
/// skips the entire `FOO="bar baz"` token. A refused operand of an
/// env-setting builtin, or an assignment to an evaluated special variable,
/// makes the whole segment unmatchable instead: bash never runs an operand
/// as a program, so it must not become a leaf an allowlisted name can unlock.
pub fn skip_env_assignments(segment: &str) -> &str {
    skip_env_prefix(segment).unwrap_or(REFUSED_OPERAND_SENTINEL)
}

fn skip_env_prefix(segment: &str) -> Result<&str, String> {
    let mut rest = segment;
    let mut operand_kind: Option<OperandKind> = None;
    loop {
        let rest_trimmed = rest.trim_start();
        if rest_trimmed.is_empty() {
            return Ok(rest_trimmed);
        }
        let end = quote_aware_token_end(rest_trimmed);
        if end == 0 {
            return Ok(rest_trimmed);
        }
        let raw_token = &rest_trimmed[..end];
        let unquoted: String = raw_token
            .chars()
            .filter(|c| *c != '"' && *c != '\'')
            .collect();
        if let Some(kind) = operand_kind {
            if accepts_operand(kind, raw_token, &unquoted) {
                rest = &rest_trimmed[end..];
                continue;
            }
            return Err(raw_token.to_string());
        }
        // Bash removes backslashes and quotes from the command word, so
        // `\declare`, `decl\are` and `'export'` all run the builtin. Only the
        // bare spelling is checked by the operand whitelist; any other
        // spelling of a builtin name, or a `$'..'` / `$".."` word that bash
        // may expand into one, fails closed.
        let dequoted: String = unquoted.chars().filter(|c| *c != '\\').collect();
        if raw_token != dequoted && operand_kind_of(&dequoted).is_some() {
            return Err(raw_token.to_string());
        }
        // Only the bare builtin name counts: `./unset` and `/tmp/x/export`
        // are programs and must reach the allowlist as such.
        if let Some(kind) = operand_kind_of(&unquoted) {
            operand_kind = Some(kind);
            rest = &rest_trimmed[end..];
            continue;
        }
        let is_posix_assignment = unquoted.split_once('=').is_some_and(|(name, _)| {
            let mut bytes = name.bytes();
            bytes
                .next()
                .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
                && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
        });
        if is_posix_assignment {
            if assigns_evaluated_special(&unquoted) {
                return Err(raw_token.to_string());
            }
            rest = &rest_trimmed[end..];
        } else if raw_token.contains("$'") || raw_token.contains("$\"") {
            // A command word bash may build from `$'..'` / `$".."` (not a
            // leading assignment, whose value may use them freely).
            return Err(raw_token.to_string());
        } else {
            return Ok(rest_trimmed);
        }
    }
}
/// Public accessor for extracting all command segments.
pub fn extract_all_commands_pub(command: &str) -> Vec<String> {
    extract_all_commands(command)
}
// Legacy compat: single-segment extraction (used by other callers)
pub fn extract_base_command(command: &str) -> String {
    let first_seg = split_on_operators(command)
        .into_iter()
        .next()
        .unwrap_or(command);
    extract_base_from_segment(first_seg)
}