mahbot 0.10.3

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Windows (`cmd.exe`) command model of the transparent grep interception.
//!
//! Compiled on every platform and driven by the runtime platform value
//! ([`crate::tools::shell::SHELL_PLATFORM`], one `if cfg!(windows)` constant every
//! consumer takes as data), the way the read-only guard's `windows` layer is: the parent
//! reads a command string exactly as `cmd.exe /C` would split, quote and dispatch it.
//!
//! `sh -c` and `cmd.exe /C` disagree on nearly every token: `&` separates commands for
//! cmd and backgrounds for sh; `;` separates for sh and is ordinary text for cmd; `^`
//! escapes and `(...)` groups for cmd; only `"` quotes, `""` being a literal quote
//! inside a span, while `'` and `\` are ordinary. No unix reading ever runs on a
//! Windows string, and everything the model cannot read is refused fail-closed.
//!
//! The hand-off: cmd.exe caps its command line at 8191 UTF-16 code units and re-parses
//! it before the program sees argv, so no quoting carries a 64 KiB JSON payload
//! intact — a served member passes its spec through a scratch file under the private
//! temp root ([`scratch_dir`]) named via [`SPEC_FILE_FLAG`], which the parent deletes
//! when the call finishes (the temp cleaner is the backstop). The rewrite reaches
//! cmd.exe as the `/C` argument in the extra quote pair it strips — `raw_arg`, not
//! `arg`, since std's escaping is not cmd.exe's reading. [`cmd_quote`] refuses a `%`,
//! `!` or `"` in a path this process did not choose (install path, scratch root), which
//! cmd.exe rewrites even inside quotes: every search on such a machine then fails
//! loudly. The narrower two-`%`-or-more reading ([`has_percent_expansion`]) covers the
//! agent's own search text, which rides the spec file, never the command line.
//!
//! Tracked and engine cwds both go through [`super::canonical_or_lexical`], so the cwd
//! gate only needs [`same_spelling`]'s case/separator/verbatim-insensitive comparison.
//! `readonly/windows.rs` reads cmd.exe with its own reader and fail-closed policy, so a
//! rule change belongs in both places.
//!
//! The reading: a line ENDS at a bare break (hence the shell's `&` respelling —
//! [`crate::tools::shell::windows_line`]); splits on `&`/`|`; keeps a `>`-family
//! redirect's own `&` (`2>&1`); treats `;`/`'`/`\` as ordinary; reads `""` inside a
//! span as a literal quote; dispatches verbs case- and extension-insensitively; changes
//! nothing on a bare `cd` (`/d` is its only switch); keeps the `pushd`/`popd` stack.
//! Every refusal rests on it. [`fnmatch`] is pinned differentially by
//! `windows_fnmatch_parity`.

use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use crate::tools::shell::scan::{self, CdScan};

use super::GrepWord;

pub(super) const SPEC_FILE_FLAG: &str = "--spec-file";

/// Scratch directory (below the daemon's private temp root) holding served members' specs.
const SPEC_DIR: &str = "grep-engine";

/// True when the `&` at the cursor belongs to the redirect token before it (`2>&1`,
/// `>& file`): a `&` directly after `>` merges descriptors, so it never ends the member.
/// A word-glued redirect meeting the next command (`grep a>&echo done`) is one member
/// here and is then refused as unreadable ([`has_glued_redirect`]).
fn redirect_keeps_amp(before: &str) -> bool {
    before.ends_with('>')
}

/// Push the trimmed member of `current` onto `out` with its connector. `required` marks a
/// member that must not be empty (one before a `&`/`|`/`&&`/`||`), since dropping it
/// silently would turn the line into a valid single command.
fn flush(
    current: &mut String,
    out: &mut Vec<(String, String)>,
    conn: &str,
    required: bool,
) -> bool {
    let text = current.trim().to_string();
    current.clear();
    if text.is_empty() {
        return !required;
    }
    out.push((text, conn.to_string()));
    true
}

/// Split a command line the way `cmd.exe /C` does: on `&`, `&&`, `|`, `||`, returning
/// `(segment, following-connector)` pairs with `""` last. `None` for a reading this model
/// does not have: a `^`, a `(`/`)` or a line break outside double quotes (the caret
/// escapes, the parentheses group, and a break is the same kind of unknown — one that
/// arrives here is a shape the platform itself continues across), an unbalanced `"`, or
/// an empty member before a connector / a trailing connector with no member after it.
/// `;` is ordinary text and never a connector; the caller reads it via [`unquoted_semicolon`].
#[must_use]
pub(in crate::tools::shell) fn segment_command(command: &str) -> Option<Vec<(String, String)>> {
    let chars: Vec<char> = command.chars().collect();
    let mut out: Vec<(String, String)> = Vec::new();
    let mut current = String::new();
    let mut in_double = false;
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c == '"' {
            // `""` inside a quoted span is a literal quote, not a close+open.
            if in_double && chars.get(i + 1) == Some(&'"') {
                current.push_str("\"\"");
                i += 2;
                continue;
            }
            in_double = !in_double;
            current.push('"');
            i += 1;
            continue;
        }
        if in_double {
            current.push(c);
            i += 1;
            continue;
        }
        match c {
            // Unmodellable outside quotes (see the doc comment); a break reaching here is a
            // text this model cannot read.
            '^' | '(' | ')' | '\n' => return None,
            '&' | '|' => {
                if c == '&' && redirect_keeps_amp(&current) {
                    current.push('&');
                    i += 1;
                    continue;
                }
                let doubled = chars.get(i + 1) == Some(&c);
                let conn = match (c, doubled) {
                    ('&', true) => "&&",
                    ('&', false) => "&",
                    ('|', true) => "||",
                    ('|', false) => "|",
                    _ => unreachable!("only `&` and `|` reach this arm"),
                };
                if !flush(&mut current, &mut out, conn, true) {
                    return None;
                }
                i += if doubled { 2 } else { 1 };
            }
            _ => {
                current.push(c);
                i += 1;
            }
        }
    }
    if in_double {
        return None;
    }
    flush(&mut current, &mut out, "", false);
    // A trailing connector leaves cmd.exe nothing after it: the unix segmenter's policy.
    if matches!(
        out.last().map(|(_, c)| c.as_str()),
        Some("&" | "&&" | "|" | "||")
    ) {
        return None;
    }
    Some(out)
}

/// True when a `;` appears outside double quotes: cmd.exe never splits a command on it, so
/// the fragments around one are not separate commands.
#[must_use]
pub(super) fn unquoted_semicolon(command: &str) -> bool {
    let mut in_double = false;
    let mut chars = command.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '"' {
            if in_double && chars.peek() == Some(&'"') {
                chars.next();
                continue;
            }
            in_double = !in_double;
            continue;
        }
        if !in_double && c == ';' {
            return true;
        }
    }
    false
}

/// The delivered text of a word: the inner text of a balanced pair of surrounding double
/// quotes, or the word itself without a quote character. `None` for an interior or
/// unbalanced `"`, which cmd reads differently, so callers fail closed instead.
fn strip_double_quotes(word: &str) -> Option<&str> {
    if let Some(inner) = word
        .strip_prefix('"')
        .and_then(|rest| rest.strip_suffix('"'))
    {
        return (!inner.contains('"')).then_some(inner);
    }
    (!word.contains('"')).then_some(word)
}

/// The key cmd.exe's own dispatch matches a verb word on: its delivered text, lower-cased,
/// with a trailing `.exe` folded away, so `GREP`, `Grep.EXE` and `grep` are one verb.
/// Every verb list in the engine is written in that spelling and read through this key.
/// `None` for a spelling whose delivered text is not the word as written (an interior or
/// unbalanced `"`): the shell would re-read it, so no list may be matched against it.
#[must_use]
pub(in crate::tools::shell) fn verb_key(word: &str) -> Option<String> {
    let word = strip_double_quotes(word)?;
    // Fold a `.exe` suffix in any case (`Grep.EXE`), one ASCII extension only.
    let bytes = word.as_bytes();
    let stem = if bytes.len() >= 4 && bytes[bytes.len() - 4..].eq_ignore_ascii_case(b".exe") {
        &word[..word.len() - 4]
    } else {
        word
    };
    Some(stem.to_ascii_lowercase())
}

/// The grep family a command word names, or `None`. cmd.exe dispatches case-insensitively
/// through `PATHEXT`, so `GREP`, `Grep.EXE` and `grep` run the same program; only `.exe` is
/// folded, since `.com`/`.bat`/`.cmd` name programs of their own. A path-qualified word
/// names a file rather than a dispatch, so it is left to the platform as written — as unix
/// reads `./grep`.
#[must_use]
pub(super) fn grep_verb(word: &str) -> Option<&'static str> {
    let key = verb_key(word)?;
    if key.is_empty() || key.contains(['\\', '/']) {
        return None;
    }
    match key.as_str() {
        "grep" => Some("grep"),
        "egrep" => Some("egrep"),
        "fgrep" => Some("fgrep"),
        _ => None,
    }
}

/// Push the accumulated token onto `out` through the shared redirect classifier.
fn flush_token(raw: &mut String, value: &mut String, out: &mut Vec<GrepWord>) {
    if raw.is_empty() {
        return;
    }
    let (redirect, needs_target) = match scan::classify_shell_token(raw) {
        scan::TokenKind::Regular => (false, false),
        scan::TokenKind::Redirect { needs_target } => (true, needs_target),
    };
    out.push(GrepWord {
        value: std::mem::take(value),
        raw: std::mem::take(raw),
        redirect,
        needs_target,
    });
}

/// cmd.exe's word splitting for one member: whitespace-separated, `"`-quoting with `""` as
/// a literal quote, and — unlike `sh` — no escape character, so `\` is ordinary text and
/// `'` does not quote. `None` on an unbalanced quote. The value keeps `$` and backticks
/// literal (cmd expands neither, and `$` is a common ERE anchor); `%…%` is the caller's to
/// fail closed on ([`has_percent_expansion`]).
#[must_use]
pub(in crate::tools::shell) fn tokenize(segment: &str) -> Option<Vec<GrepWord>> {
    let mut out = Vec::new();
    let mut raw = String::new();
    let mut value = String::new();
    let mut in_double = false;
    let mut chars = segment.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '"' {
            if in_double && chars.peek() == Some(&'"') {
                chars.next();
                raw.push_str("\"\"");
                value.push('"');
                continue;
            }
            in_double = !in_double;
            raw.push('"');
            continue;
        }
        if !in_double && c.is_whitespace() {
            flush_token(&mut raw, &mut value, &mut out);
            continue;
        }
        raw.push(c);
        value.push(c);
    }
    if in_double {
        return None;
    }
    flush_token(&mut raw, &mut value, &mut out);
    Some(out)
}

/// True when `raw` carries an unquoted redirect operator after its first character — the
/// glued spelling cmd.exe splits into an argument plus a redirect (`x>out.txt`). Words that
/// *open* with an operator are [`scan::classify_shell_token`]'s redirects already.
#[must_use]
pub(super) fn has_glued_redirect(raw: &str) -> bool {
    let mut in_quotes = false;
    for (at, c) in raw.char_indices() {
        match c {
            '"' => in_quotes = !in_quotes,
            '<' | '>' if !in_quotes && at > 0 => return true,
            _ => {}
        }
    }
    false
}

/// Unquote one raw word the way cmd.exe delivers it: balanced double quotes removed, `""`
/// inside the span a literal quote, every other character literal; idempotent on [`tokenize`].
#[must_use]
pub(in crate::tools::shell) fn unquote_word(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    let mut in_double = false;
    let mut chars = raw.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '"' {
            if in_double && chars.peek() == Some(&'"') {
                chars.next();
                out.push('"');
                continue;
            }
            in_double = !in_double;
            continue;
        }
        out.push(c);
    }
    out
}

/// Quote one argument for a cmd.exe command line. cmd.exe re-reads the whole line, but
/// stops treating `&`, `|`, `<`, `>`, `^`, `(`, `)`, `;` and `=` as syntax inside a quoted
/// argument — which is what makes `C:\Program Files (x86)\…` servable. What it rewrites
/// even inside quotes is `%` (always) and `!` (where delayed expansion is on), plus the
/// quote itself and a line terminator: those are refused fail-closed. Both callers pass a
/// path this process did not choose, so such a path is the per-machine condition the
/// module header states.
pub(super) fn cmd_quote(text: &str) -> Result<String, String> {
    let forbidden = ['%', '!', '"', '\n', '\r'];
    if let Some(bad) = text.chars().find(|c| forbidden.contains(c)) {
        return Err(format!("argument contains `{bad}`"));
    }
    Ok(format!("\"{text}\""))
}

/// Allocate the scratch path one served member's spec is written to:
/// `<scratch dir>/<pid>-<n>.json`, the counter keeping it unique in the process. Pure path
/// arithmetic: the directory is [`write_spec_file`]'s to create and the file the caller's
/// to remove. The path is quoted and listed for removal before the write, so neither a
/// refused argument nor a failed write leaves a file behind.
pub(super) fn spec_file_path() -> PathBuf {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    scratch_dir().join(format!(
        "{}-{}.json",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    ))
}

/// The directory [`spec_file_path`] allocates in: [`crate::temp::shell_tmpdir`] — the
/// daemon's pinned private root — and under `cfg(test)` the process test root instead (a
/// test run must never touch a root the daemon owns). The lane's fake storage root is that
/// same root, so the scratch files sit in their own `grep-engine` subdirectory.
fn scratch_dir() -> PathBuf {
    #[cfg(test)]
    {
        crate::util::test::test_root().join(SPEC_DIR)
    }
    #[cfg(not(test))]
    {
        PathBuf::from(crate::temp::shell_tmpdir()).join(SPEC_DIR)
    }
}

/// Write one engine spec to its scratch path, creating the scratch directory if needed.
/// `create_new` refuses to follow a planted symlink; a leftover file from an earlier run
/// is removed first so it cannot turn the write into a refusal, though an entry that cannot
/// be removed at all (a directory, an ACL-locked file) does refuse the member. The error is
/// a rendered location, never an errno the caller matches on.
pub(super) fn write_spec_file(path: &Path, json: &str) -> Result<(), String> {
    if let Some(dir) = path.parent() {
        fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
    }
    let _ = fs::remove_file(path);
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map_err(|e| format!("{}: {e}", path.display()))?;
    file.write_all(json.as_bytes())
        .map_err(|e| format!("{}: {e}", path.display()))
}

/// True when `word` is an absolute Windows spelling: a drive root (`C:\`, `C:/`), a UNC
/// server/share (`\\srv\share`, `//srv/share`), or a separator-rooted path. A
/// drive-RELATIVE spelling (`C:x`) is not absolute.
#[must_use]
pub(super) fn is_absolute_word(word: &str) -> bool {
    word.starts_with(['\\', '/']) || drive_anchor(word).is_some()
}

/// Join a display path: with `\` when the prefix carries no trailing separator, directly
/// when it does (as [`split_components`]' prefix always does).
#[must_use]
pub(super) fn join_display(prefix: &str, name: &str) -> String {
    if prefix.is_empty() || prefix.ends_with(['\\', '/']) {
        format!("{prefix}{name}")
    } else {
        format!("{prefix}\\{name}")
    }
}

/// The display path of a walked entry: the operand's own spelling with the entry's relative
/// suffix [`join_display`]ed on. A root that is one separator keeps one; an empty root, none.
#[must_use]
pub(super) fn traversal_display(root_display: &str, rel: &str) -> String {
    let root = root_display.trim_end_matches(['\\', '/']);
    let root = if root.is_empty() {
        root_display.get(..1).unwrap_or("")
    } else {
        root
    };
    join_display(root, rel)
}

/// The `\\server\share\` anchor of a UNC pattern. `None` when the pattern is not UNC or
/// names no server/share (a degenerate anchor has no root to walk).
fn unc_anchor(pattern: &str) -> Option<&str> {
    let rest = pattern
        .strip_prefix("\\\\")
        .or_else(|| pattern.strip_prefix("//"))?;
    let mut parts = rest.splitn(3, ['\\', '/']);
    let server = parts.next().filter(|s| !s.is_empty())?;
    let share = parts.next().filter(|s| !s.is_empty())?;
    parts.next()?; // no component path below the anchor
    // The anchor ends after the separator following the share.
    let len = server.len() + share.len() + 4;
    Some(&pattern[..len])
}

/// The `:` of a leading drive spelling (`C:`, `C:\`, `C:foo`) — the one place the
/// drive-letter test lives. `None` for a word that names no drive.
fn drive_colon(word: &str) -> Option<usize> {
    let bytes = word.as_bytes();
    (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':').then_some(1)
}

/// The `C:\`/`C:/` anchor of a drive-rooted pattern. `None` for a drive-RELATIVE spelling
/// (`C:foo`), which has no root to walk.
fn drive_anchor(pattern: &str) -> Option<&str> {
    let colon = drive_colon(pattern)?;
    if !matches!(pattern.as_bytes().get(colon + 1), Some(b'\\' | b'/')) {
        return None;
    }
    Some(&pattern[..colon + 2])
}

/// True for a drive-relative spelling (`C:foo`): it names the cwd of ANOTHER drive, which
/// nothing here keeps, so a caller must refuse it rather than resolve it against this cwd.
#[must_use]
pub(in crate::tools::shell) fn is_drive_relative(word: &str) -> bool {
    drive_colon(word).is_some() && drive_anchor(word).is_none()
}

/// Split a glob pattern into its walk-root prefix and the components below it, at `\` and
/// `/`. The prefix keeps the anchor Windows resolves first — a drive (`C:\`), a UNC
/// server/share (`\\srv\share\`) or a rooted separator — and ends with the separator it was
/// typed with. `None` for a spelling with no root to walk or no component left to match.
#[must_use]
pub(super) fn split_components(pattern: &str) -> Option<(String, Vec<String>)> {
    // A drive-relative spelling names the cwd of ANOTHER drive: no root to walk.
    if is_drive_relative(pattern) {
        return None;
    }
    let (prefix, rest) = if pattern.starts_with("\\\\") || pattern.starts_with("//") {
        // A `\\`/`//`-leading spelling is UNC (or a device path): without a readable
        // server/share anchor, reading it as a rooted separator resolves a different directory.
        let anchor = unc_anchor(pattern)?;
        (anchor.to_string(), &pattern[anchor.len()..])
    } else if pattern.starts_with(['\\', '/']) {
        (pattern[..1].to_string(), &pattern[1..])
    } else if let Some(anchor) = drive_anchor(pattern) {
        (anchor.to_string(), &pattern[anchor.len()..])
    } else {
        (String::new(), pattern)
    };
    let comps: Vec<String> = rest
        .split(['\\', '/'])
        .filter(|c| !c.is_empty())
        .map(str::to_string)
        .collect();
    if comps.is_empty() {
        return None;
    }
    Some((prefix, comps))
}

/// True when the token carries a glob metacharacter (`*`, `?`, `[`) outside double quotes:
/// cmd.exe expands nothing, so the program reading the operand expands it.
#[must_use]
pub(super) fn has_unquoted_glob(tok: &str) -> bool {
    let mut in_double = false;
    let mut chars = tok.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '"' {
            if in_double && chars.peek() == Some(&'"') {
                chars.next();
                continue;
            }
            in_double = !in_double;
            continue;
        }
        if !in_double && matches!(c, '*' | '?' | '[') {
            return true;
        }
    }
    false
}

/// True when the word holds two or more `%` characters — the per-word approximation of
/// cmd.exe's line-wide `%…%` pairing, so `100%%` is refused too. Enough here because a
/// served member's words ride the spec file, never the command line; a `cd` target does
/// stay verbatim in the rewrite and is refused on the same (over-refusing) approximation.
/// An undefined name expands to nothing. A lone `%` and every `!` are ordinary: `cmd /C`
/// runs with `/V:OFF`, so delayed expansion is off whatever the machine's settings say.
#[must_use]
pub(in crate::tools::shell) fn has_percent_expansion(word: &str) -> bool {
    word.matches('%').count() >= 2
}

/// Windows identity of two paths — the engine's cwd gate reads directories with it and the
/// runner whole file paths ([`plan`]'s `is_own_image_word`), because the key is the entire
/// spelling: case, separator spelling, verbatim prefix and a trailing separator are all
/// insignificant. `cmd.exe` never spells a path the way `fs::canonicalize` does, so byte
/// equality is deliberately not the test.
#[must_use]
pub(in crate::tools::shell) fn same_spelling(a: &Path, b: &Path) -> bool {
    spelling_key(a) == spelling_key(b)
}

/// [`same_spelling`]'s comparison form: verbatim prefix stripped, `/` folded to `\`,
/// trailing separators trimmed, lowercased. A root (`C:\`, `\`) keeps its separator.
fn spelling_key(p: &Path) -> String {
    let stripped = crate::util::strip_verbatim_prefix(p);
    let folded = stripped.to_string_lossy().replace('/', "\\");
    let trimmed = folded.trim_end_matches('\\');
    if trimmed.is_empty() || trimmed.ends_with(':') {
        folded.to_lowercase()
    } else {
        trimmed.to_lowercase()
    }
}

/// Scan a `cd` member's words under cmd.exe's grammar: `/d` (its only switch, changing the
/// drive too) is recognised case-insensitively only right after the verb; a bare `cd` is
/// [`CdScan::Bare`]. cmd expands no `~` and has no `-` convention, so `-`, `~` and `~/x` are
/// ordinary names. Any other switch-shaped word (`/x`) is [`CdScan::BadOption`], as is one
/// whose quote characters cmd.exe would read differently. `words` are [`tokenize`]'s raw
/// spellings, so a quoted target keeps its inner spaces and its quotes are judged here.
#[must_use]
pub(super) fn cd_scan<'a>(words: &[&'a str]) -> CdScan<'a> {
    let mut i = usize::from(words.first().is_some_and(|w| w.eq_ignore_ascii_case("/d")));
    let Some(word) = words.get(i) else {
        return CdScan::Bare;
    };
    if word.starts_with('/') || word.contains('\'') {
        return CdScan::BadOption;
    }
    let Some(target) = strip_double_quotes(word) else {
        // An interior or unbalanced `"` is a spelling cmd reads differently.
        return CdScan::BadOption;
    };
    if target.is_empty() {
        return CdScan::BadOption;
    }
    i += 1;
    CdScan::Target(target, i)
}

/// POSIX `fnmatch` without pathname semantics, for the Windows lane with no libc: `*` (any
/// run, `/` included), `?`, bracket expressions (`[abc]`, `[!abc]`, `[^abc]`, ranges) and `\`
/// escaping. `period` implements `FNM_PERIOD`. A malformed bracket matches nothing.
#[must_use]
pub(super) fn fnmatch(pattern: &str, name: &str, period: bool) -> bool {
    let p: Vec<char> = pattern.chars().collect();
    let n: Vec<char> = name.chars().collect();
    matches_from(&p, 0, &n, 0, period)
}

/// The bracket expression at `p[i] == '['`: whether `c` is in the class and the index past
/// the closing `]`. `None` for a malformed expression (fail-closed, as the hosts do).
fn bracket_match(p: &[char], i: usize, c: char) -> Option<(bool, usize)> {
    let mut j = i + 1;
    let negated = matches!(p.get(j), Some('!' | '^'));
    if negated {
        j += 1;
    }
    let mut matched = false;
    // A `]` directly after the (optional) negation is a member, not the close.
    if p.get(j) == Some(&']') {
        matched = c == ']';
        j += 1;
    }
    loop {
        let start = *p.get(j)?;
        if start == ']' {
            return Some((matched != negated, j + 1));
        }
        // `\` escapes the next character (FNM_NOESCAPE is not set).
        let (start, next) = if start == '\\' {
            (*p.get(j + 1)?, j + 2)
        } else {
            (start, j + 1)
        };
        // A range is `x-y` with the `-` neither first nor last.
        if p.get(next) == Some(&'-') && p.get(next + 1).is_some_and(|&end| end != ']') {
            let end = p[next + 1];
            if start > end {
                return None;
            }
            if (start..=end).contains(&c) {
                matched = true;
            }
            j = next + 2;
            continue;
        }
        if start == c {
            matched = true;
        }
        j = next;
    }
}

/// One step of [`fnmatch`]: compare `p` from `pi` against `n` from `ni`.
fn matches_from(p: &[char], mut pi: usize, n: &[char], mut ni: usize, period: bool) -> bool {
    // FNM_PERIOD: a leading dot is matched only by a literal dot, never by a wildcard or class.
    if period && ni == 0 && n.first() == Some(&'.') {
        let literal_dot =
            p.get(pi) == Some(&'.') || (p.get(pi) == Some(&'\\') && p.get(pi + 1) == Some(&'.'));
        if !literal_dot {
            return false;
        }
    }
    loop {
        let Some(&c) = p.get(pi) else {
            return ni == n.len();
        };
        match c {
            '*' => {
                while p.get(pi) == Some(&'*') {
                    pi += 1;
                }
                if pi == p.len() {
                    // A trailing `*` matches any remaining run (leading-dot ruled out on entry).
                    return true;
                }
                let mut k = ni;
                loop {
                    if matches_from(p, pi, n, k, period) {
                        return true;
                    }
                    if k == n.len() {
                        return false;
                    }
                    k += 1;
                }
            }
            '?' => {
                if ni == n.len() {
                    return false;
                }
                pi += 1;
                ni += 1;
            }
            '[' => {
                if ni == n.len() {
                    return false;
                }
                let Some((matched, next)) = bracket_match(p, pi, n[ni]) else {
                    return false;
                };
                if !matched {
                    return false;
                }
                pi = next;
                ni += 1;
            }
            '\\' => {
                // A trailing backslash stands for itself, matching the host implementations.
                let (literal, step) = match p.get(pi + 1) {
                    Some(&next) => (next, 2),
                    None => ('\\', 1),
                };
                if n.get(ni) != Some(&literal) {
                    return false;
                }
                pi += step;
                ni += 1;
            }
            literal => {
                if n.get(ni) != Some(&literal) {
                    return false;
                }
                pi += 1;
                ni += 1;
            }
        }
    }
}

// The whole model is pure string/path work driven by a runtime platform value.

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

    /// Assert the segmenter's `(segment, following-connector)` pairs for a line it reads.
    fn assert_segments(command: &str, expected: &[(&str, &str)]) {
        let got = segment_command(command)
            .unwrap_or_else(|| panic!("{command:?}: expected a readable line"));
        let want: Vec<(String, String)> = expected
            .iter()
            .map(|(s, c)| ((*s).to_string(), (*c).to_string()))
            .collect();
        assert_eq!(got, want, "{command:?}");
    }

    #[test]
    fn connectors_split_like_cmd() {
        assert_segments("a & b", &[("a", "&"), ("b", "")]);
        assert_segments("a && b", &[("a", "&&"), ("b", "")]);
        assert_segments("a | b", &[("a", "|"), ("b", "")]);
        assert_segments("a || b", &[("a", "||"), ("b", "")]);
        assert_segments("echo a & grep x f", &[("echo a", "&"), ("grep x f", "")]);
        assert_segments("  a  &&  b  ", &[("a", "&&"), ("b", "")]);
        // A bare `&` at the end of a `&&`/`||` run is already consumed; a lone
        // trailing connector leaves cmd an empty command.
        assert!(segment_command("a &").is_none());
        assert!(segment_command("a &&").is_none());
        assert!(segment_command("a |").is_none());
        assert!(segment_command("a ||").is_none());
        assert!(segment_command("&& a").is_none());
        assert!(segment_command("| a").is_none());
    }

    #[test]
    fn quoting_and_unreadable_shapes() {
        // Inside a double-quoted span every connector and metacharacter is
        // literal; `""` inside the span is a literal quote.
        assert_segments("\"a & b\"", &[("\"a & b\"", "")]);
        assert_segments("echo \"x | y\"", &[("echo \"x | y\"", "")]);
        assert_segments("grep \"a\"\"&b\" f", &[("grep \"a\"\"&b\" f", "")]);
        // A redirect keeps its own `&`: the descriptor merge is part of the
        // member, not a separator.
        assert_segments("a 2>&1 b", &[("a 2>&1 b", "")]);
        assert_segments("a >&2 b", &[("a >&2 b", "")]);
        assert_segments("a >& out b", &[("a >& out b", "")]);
        // `;` is ordinary text: one member, never a connector.
        assert_segments("a;b", &[("a;b", "")]);
        assert_segments(
            "grep -n x a.txt; echo done",
            &[("grep -n x a.txt; echo done", "")],
        );
        // `^` and `(...)` are unmodellable outside quotes; inside they are not.
        assert!(segment_command("echo ^& grep x f").is_none());
        assert!(segment_command("(a) & b").is_none());
        assert_segments("echo \"a^b(c)\"", &[("echo \"a^b(c)\"", "")]);
        // Unbalanced quotes.
        assert!(segment_command("\"a & b").is_none());
    }

    /// `windows_line` removed every break this model could read before it sees the text: a
    /// plain break is respelled as `&` and an operator continuation is joined. A break
    /// reaching the segmenter is therefore a caret or a group, which it cannot read.
    #[test]
    fn a_line_break_the_shell_still_hands_over_is_refused() {
        for text in ["a\nb", "a\r\nb", "a\n\nb", "a\n", "\n& a"] {
            assert!(
                segment_command(text).is_none(),
                "a break must be refused: {text:?}"
            );
        }
    }

    #[test]
    fn unquoted_semicolon_sees_only_outside_quotes() {
        assert!(unquoted_semicolon("grep x a; b"));
        assert!(!unquoted_semicolon("grep \"a;b\" f"));
        assert!(!unquoted_semicolon("echo a\"\"b"));
        assert!(unquoted_semicolon("echo \"a;b\" & c;d"));
    }

    #[test]
    fn grep_verb_folds_case_and_the_exe_suffix() {
        let rows = [
            ("grep", Some("grep")),
            ("GREP", Some("grep")),
            ("Grep", Some("grep")),
            ("grep.exe", Some("grep")),
            ("GREP.EXE", Some("grep")),
            ("Grep.EXE", Some("grep")),
            ("Grep.Exe", Some("grep")),
            ("egrep.exe", Some("egrep")),
            ("fgrep.exe", Some("fgrep")),
            ("\"grep\"", Some("grep")),
            ("findstr", None),
            ("grep.com", None),
            ("grep.bat", None),
            (r"C:\bin\grep.exe", None),
            ("/usr/bin/grep", None),
            ("", None),
            ("\"grep", None),
        ];
        for (word, expected) in rows {
            assert_eq!(grep_verb(word), expected, "{word}");
        }
    }

    #[test]
    fn tokenize_reads_cmd_words() {
        let words = tokenize("grep \"a b\" c").expect("balanced quotes");
        let got: Vec<(&str, &str)> = words
            .iter()
            .map(|w| (w.value.as_str(), w.raw.as_str()))
            .collect();
        assert_eq!(got, [("grep", "grep"), ("a b", "\"a b\""), ("c", "c")]);

        // `""` inside a span is a literal quote; `a""b` is outside any span, so cmd delivers
        // the two letters.
        let words = tokenize("grep \"a\"\"b\" \"\"").expect("balanced quotes");
        let got: Vec<&str> = words.iter().map(|w| w.value.as_str()).collect();
        assert_eq!(got, ["grep", "a\"b", ""]);
        let words = tokenize("grep a\"\"b").expect("balanced quotes");
        assert_eq!(words[1].value, "ab");

        // `'` and `\` are ordinary, and `$` stays literal (cmd expands neither; `$` is an anchor).
        let words = tokenize("grep 'a\\b' ^$ f").expect("balanced quotes");
        let got: Vec<&str> = words.iter().map(|w| w.value.as_str()).collect();
        assert_eq!(got, ["grep", "'a\\b'", "^$", "f"]);

        // Whitespace inside quotes does not split the word.
        let words = tokenize("grep \"a|b\" f").expect("balanced quotes");
        assert_eq!(words.len(), 3);
        assert_eq!(words[1].value, "a|b");
        assert!(!words[1].redirect);

        // A redirect word is classified through the shared classifier: a descriptor merge is
        // self-contained, a `>` or `<` is not. (command, redirect word index, needs a target)
        let redirects = [
            ("grep x f 2>&1", 3, false),
            ("grep x f > out.txt", 3, true),
            ("grep x < in.txt", 2, true),
        ];
        for (command, at, needs_target) in redirects {
            let words = tokenize(command).expect("balanced quotes");
            assert!(words[at].redirect, "{command}: word {at} is a redirect");
            assert_eq!(
                words[at].needs_target, needs_target,
                "{command}: target of word {at}"
            );
        }

        assert!(tokenize("grep \"a").is_none());
    }

    /// [`unquote_word`] is handed token values as well as raw words: it must strip the
    /// quoting cmd.exe removed and nothing else (`""` inside a span is one literal quote).
    #[test]
    fn unquote_word_is_idempotent_on_token_values() {
        // (token value, the word cmd delivers)
        let rows = [
            ("a bare word", "\"a b\"", "a b"),
            ("a quoted span with a literal quote", "\"a\"\"b\"", "a\"b"),
            ("an empty span between two letters", "a\"\"b", "ab"),
            ("no quoting at all", "a b", "a b"),
            ("single quotes are ordinary characters", "'a'", "'a'"),
            ("the empty word", "", ""),
        ];
        for (name, raw, value) in rows {
            assert_eq!(unquote_word(raw), value, "{name}: {raw:?}");
        }
    }

    /// A walked entry is displayed under the operand's own spelling, its separator included.
    #[test]
    fn traversal_display_joins_with_the_windows_separator() {
        // (a root, an entry's relative suffix, the display path)
        let rows = [
            (
                "a root with no separator",
                r"C:\ws",
                r"src\main.rs",
                r"C:\ws\src\main.rs",
            ),
            (
                "a root that already ends in one",
                r"C:\ws\",
                r"src\main.rs",
                r"C:\ws\src\main.rs",
            ),
            (
                "a bare separator as the root",
                "\\",
                r"src\main.rs",
                r"\src\main.rs",
            ),
            ("a unix-shaped root", "/", "src", "/src"),
        ];
        for (name, root, rel, expected) in rows {
            assert_eq!(traversal_display(root, rel), expected, "{name}");
        }
    }

    #[test]
    fn cmd_quote_refuses_only_what_cmd_rewrites_inside_quotes() {
        assert_eq!(cmd_quote(r"C:\ws\a b.txt").unwrap(), "\"C:\\ws\\a b.txt\"");
        assert_eq!(cmd_quote("x").unwrap(), "\"x\"");
        // Metacharacters cmd stops treating as syntax inside a quoted argument (this makes an
        // install under `C:\Program Files (x86)` servable).
        for safe in ["a&b", "a|b", "a<b", "a>b", "a(b", "a;b", "a^b", "a=b"] {
            assert_eq!(cmd_quote(safe).unwrap(), format!("\"{safe}\""));
        }
        // What cmd rewrites even inside quotes.
        for bad in ["%TEMP%", "a!b", "a\"b", "a\nb", "a\rb"] {
            assert!(cmd_quote(bad).is_err(), "{bad:?} must be refused");
        }
    }

    #[test]
    fn spec_files_are_allocated_uniquely_and_written_by_path() {
        let first = spec_file_path();
        let second = spec_file_path();
        assert_ne!(first, second, "every member gets its own file");
        assert_eq!(first.extension(), Some("json".as_ref()), "{first:?}");

        // The writer owns the directory and the file: it creates the former and replaces the
        // latter, so a leftover entry cannot turn a served member into a refusal.
        let dir = tempfile::TempDir::new().expect("temp dir");
        let path = dir.path().join("nested").join("one.json");
        write_spec_file(&path, "{\"a\":1}").expect("write");
        assert_eq!(fs::read_to_string(&path).expect("read"), "{\"a\":1}");
        write_spec_file(&path, "{\"b\":2}").expect("rewrite");
        assert_eq!(fs::read_to_string(&path).expect("read"), "{\"b\":2}");

        // A directory is not writable as a file: an error the caller refuses the member on.
        assert!(write_spec_file(dir.path(), "{}").is_err());
    }

    /// Which spellings this platform reads as which: an absolute path, an operand carrying a
    /// glob outside quotes, and two spellings of one directory.
    #[test]
    fn path_and_word_spellings_are_read_as_windows_writes_them() {
        // (word, is the word an absolute path)
        let absolute = [
            (r"C:\ws", true),
            ("C:/ws", true),
            (r"\\srv\share", true),
            ("//srv/share", true),
            (r"\ws", true),
            ("/ws", true),
            ("C:ws", false),
            (r"C:", false),
            (r"sub\ws", false),
            ("ws", false),
            ("", false),
        ];
        for (word, expected) in absolute {
            assert_eq!(is_absolute_word(word), expected, "absolute? {word:?}");
        }

        // (operand, does it carry a glob the operand itself does not quote)
        let globs = [
            ("*.txt", true),
            ("a?c", true),
            ("[ab]c", true),
            ("\"*.txt\"", false),
            ("plain.txt", false),
            ("\"a\"\"*\"", false),
            ("\"a\"\"b\"*", true),
        ];
        for (operand, expected) in globs {
            assert_eq!(has_unquoted_glob(operand), expected, "glob? {operand:?}");
        }

        // (one spelling, another spelling of the same directory or not)
        let spellings = [
            (r"C:\ws", r"C:\WS\", true),
            (r"C:\ws", r"\\?\C:\ws", true),
            ("C:/ws/", r"C:\ws", true),
            (r"\\?\UNC\srv\share", r"\\SRV\Share", true),
            (r"C:\ws\a", r"C:\ws", false),
            // A drive root is not its drive-relative spelling.
            (r"C:\", "C:", false),
            (r"C:\", "C:/", true),
        ];
        for (left, right, expected) in spellings {
            assert_eq!(
                same_spelling(Path::new(left), Path::new(right)),
                expected,
                "same? {left:?} {right:?}"
            );
        }
    }

    #[test]
    fn glob_patterns_split_and_join_by_their_anchor() {
        let rows: &[(&str, &str, &[&str])] = &[
            (r"C:\ws\*.txt", r"C:\", &["ws", "*.txt"]),
            ("C:/ws/*", "C:/", &["ws", "*"]),
            (r"\\srv\share\a\*", r"\\srv\share\", &["a", "*"]),
            ("//srv/share/*", "//srv/share/", &["*"]),
            (r"\sub\*", r"\", &["sub", "*"]),
            ("/sub/*", "/", &["sub", "*"]),
            (r"sub\*.txt", "", &["sub", "*.txt"]),
            ("sub/*.txt", "", &["sub", "*.txt"]),
            ("*.txt", "", &["*.txt"]),
        ];
        for (pattern, prefix, comps) in rows {
            let got = split_components(pattern).unwrap_or_else(|| panic!("{pattern}"));
            assert_eq!(got.0, *prefix, "prefix of {pattern}");
            let got_c: Vec<&str> = got.1.iter().map(String::as_str).collect();
            assert_eq!(got_c, *comps, "components of {pattern}");
        }
        for bad in [r"C:foo\*", r"\\srv\*", r"\\srv\share", "", r"C:\", r"\\"] {
            assert!(split_components(bad).is_none(), "{bad} has no walk root");
        }

        // Separator runs collapse: a component is never empty.
        let (prefix, comps) = split_components(r"a\\b\*").expect("relative pattern");
        assert!(
            prefix.is_empty(),
            "a relative pattern keeps no prefix: {prefix}"
        );
        assert_eq!(comps, ["a", "b", "*"]);

        assert_eq!(join_display(r"C:\ws", "a.txt"), r"C:\ws\a.txt");
        assert_eq!(join_display(r"C:\", "ws"), r"C:\ws");
        assert_eq!(join_display("", "ws"), "ws");
        assert_eq!(join_display("/", "ws"), "/ws");
        // Round trip: every component joined back onto its prefix spells the operand as typed.
        for (pattern, prefix, comps) in rows {
            let mut built = (*prefix).to_string();
            for c in *comps {
                built = join_display(&built, c);
            }
            assert_eq!(
                built.replace('/', "\\"),
                pattern.replace('/', "\\"),
                "round trip of {pattern}"
            );
        }
    }

    #[test]
    fn cd_grammar_is_cmd_shaped() {
        assert_eq!(cd_scan(&[]), CdScan::Bare);
        assert_eq!(cd_scan(&["/d"]), CdScan::Bare);
        assert_eq!(cd_scan(&["sub"]), CdScan::Target("sub", 1));
        assert_eq!(cd_scan(&["/D", "sub"]), CdScan::Target("sub", 2));
        // `~`, `-` and `~/x` are ordinary names: cmd expands none of them.
        assert_eq!(cd_scan(&["~"]), CdScan::Target("~", 1));
        assert_eq!(cd_scan(&["-"]), CdScan::Target("-", 1));
        assert_eq!(cd_scan(&["~", "sub"]), CdScan::Target("~", 1));
        assert_eq!(cd_scan(&[r"~\sub"]), CdScan::Target(r"~\sub", 1));
        assert_eq!(cd_scan(&[r"C:\ws"]), CdScan::Target(r"C:\ws", 1));
        assert_eq!(cd_scan(&["\"my dir\""]), CdScan::Target("my dir", 1));
        // Switch-shaped words and quote spellings cmd reads differently.
        assert_eq!(cd_scan(&["/x"]), CdScan::BadOption);
        assert_eq!(cd_scan(&["-P"]), CdScan::Target("-P", 1));
        assert_eq!(cd_scan(&["'sub'"]), CdScan::BadOption);
        assert_eq!(cd_scan(&["\"sub"]), CdScan::BadOption);
        assert_eq!(cd_scan(&["\"\""]), CdScan::BadOption);
        assert_eq!(cd_scan(&["/d", "/d"]), CdScan::BadOption);
    }
}