croft-software 0.2.132

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
//! User-defined problem matchers (#252): regexes that turn command output
//! into PROBLEMS entries, extending the built-in table in
//! `build_matchers.rs` to tools it does not know, plus VS Code
//! `problemMatcher` mapping for tasks.json tasks and background/watch
//! matchers (`begins`/`ends` patterns) that repopulate PROBLEMS on every
//! recompile cycle of a long-running watcher without waiting for the
//! process to exit.
//!
//! Three sources feed one internal representation ([`CompiledMatcher`]):
//! - `matchers.json` next to `triggers.json` (`~/.config/croft/`, plus a
//!   workspace `.croft/matchers.json`) — croft-native schema with NAMED
//!   capture groups: `(?P<file>…)`, `(?P<line>…)`, `(?P<col>…)`,
//!   `(?P<severity>…)`, `(?P<message>…)`, `(?P<code>…)`.
//! - tasks.json `problemMatcher` — VS Code's schema: `$well-known` names
//!   map onto the built-in table; inline pattern objects (numeric group
//!   indices) translate into the same representation.
//! - the well-known table itself (`$tsc`, `$tsc-watch`, `$rustc`,
//!   `$eslint-stylish`, `$gcc`).
//!
//! Batch scanning happens at the `FinishedCommand` boundary like the
//! built-ins. Watch matchers run on the live stream: the trigger engine's
//! per-line scanner (`triggers::TriggerScanner`) already completes
//! escape-stripped primary-screen lines, so [`WatchEngine`] consumes those
//! lines rather than adding a second byte scanner — `begins` opens a
//! collection window, `ends` publishes the window's diagnostics as the
//! pane's new batch (replacing the previous one, so fixed errors clear).
//!
//! A matcher whose regex fails to compile is dropped with a warning
//! surfaced once at load; the stream path only ever sees compiled regexes.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use regex::Regex;

use crate::build_matchers::BuildDiag;
use crate::lsp::manager::DiagnosticSeverity;

/// Hard cap on a watch window's collected lines: a watcher that never
/// prints its `ends` pattern must not grow memory without bound, and no
/// real compile cycle's diagnostics need more.
pub const WATCH_WINDOW_CAP: usize = 5000;

/// Where a diagnostic field comes from in a pattern's captures.
#[derive(Clone, Debug, PartialEq, Eq)]
enum GroupRef {
    /// A named group (matchers.json style); absent groups resolve to None.
    Name(&'static str),
    /// A numeric group index (VS Code pattern style); 0 = whole match.
    Index(usize),
    /// The field is not captured by this pattern.
    None,
}

impl GroupRef {
    fn get<'t>(&self, caps: &regex::Captures<'t>) -> Option<&'t str> {
        match self {
            GroupRef::Name(n) => caps.name(n).map(|m| m.as_str()),
            GroupRef::Index(i) => caps.get(*i).map(|m| m.as_str()),
            GroupRef::None => None,
        }
    }
}

/// One compiled line pattern of a matcher's (possibly multi-line) sequence.
#[derive(Clone, Debug)]
struct CompiledPattern {
    regex: Regex,
    file: GroupRef,
    line: GroupRef,
    col: GroupRef,
    severity: GroupRef,
    message: GroupRef,
    code: GroupRef,
    /// VS Code `"loop": true` on the LAST pattern: it re-applies to each
    /// following line, emitting one diagnostic per match (eslint-style
    /// indented rows under a file header).
    loops: bool,
}

/// Watch-task window delimiters (VS Code `background.beginsPattern` /
/// `endsPattern`).
#[derive(Clone, Debug)]
pub struct Background {
    begins: Regex,
    ends: Regex,
    /// VS Code `activeOnStart`: the task starts already inside its first
    /// window, which may then close on `ends` with no `begins` ever seen
    /// (#1541). Only a task-assigned matcher opens a window this way.
    active_on_start: bool,
}

/// One matcher, from any source, compiled and ready to scan.
#[derive(Clone, Debug)]
pub struct CompiledMatcher {
    pub name: String,
    /// Empty ⇒ delegate batch scanning to the built-in table
    /// (`build_matchers::scan`), optionally narrowed by `builtin_filter`.
    patterns: Vec<CompiledPattern>,
    /// For well-known `$names`: keep only built-in diags with this source
    /// tag (`$gcc` ⇒ "build"), so the task reports what VS Code would.
    builtin_filter: Option<&'static str>,
    /// Extra severity words beyond error/warning/info ("E" ⇒ error, …).
    severity_map: BTreeMap<String, DiagnosticSeverity>,
    /// Glob over the finished command line (batch scans only): the matcher
    /// fires only for commands it claims. No glob ⇒ every command.
    applies_to: Option<String>,
    pub background: Option<Background>,
    /// The rest of a tasks.json matcher list (`["$tsc", "$eslint-stylish"]`):
    /// batch scans run each and concatenate, as VS Code does (#1240).
    also: Vec<CompiledMatcher>,
}

/// Severity words every matcher understands; `severity_map` extends them.
fn severity_word(word: &str, map: &BTreeMap<String, DiagnosticSeverity>) -> DiagnosticSeverity {
    if let Some(s) = map.get(word).or_else(|| map.get(&word.to_lowercase())) {
        return *s;
    }
    match word.to_lowercase().as_str() {
        "error" | "fatal error" | "fatal" | "err" | "e" => DiagnosticSeverity::Error,
        "warning" | "warn" | "w" => DiagnosticSeverity::Warning,
        "hint" => DiagnosticSeverity::Hint,
        _ => DiagnosticSeverity::Information,
    }
}

fn parse_severity_name(s: &str) -> Option<DiagnosticSeverity> {
    match s.to_lowercase().as_str() {
        "error" => Some(DiagnosticSeverity::Error),
        "warning" => Some(DiagnosticSeverity::Warning),
        "info" | "information" => Some(DiagnosticSeverity::Information),
        "hint" => Some(DiagnosticSeverity::Hint),
        _ => None,
    }
}

/// Minimal glob: `*` matches any run (including empty), `?` one char,
/// everything else literal. Matched against the trimmed command line.
fn glob_match(pattern: &str, text: &str) -> bool {
    fn inner(p: &[char], t: &[char]) -> bool {
        match p.first() {
            None => t.is_empty(),
            Some('*') => (0..=t.len()).any(|i| inner(&p[1..], &t[i..])),
            Some('?') => !t.is_empty() && inner(&p[1..], &t[1..]),
            Some(c) => t.first() == Some(c) && inner(&p[1..], &t[1..]),
        }
    }
    let p: Vec<char> = pattern.chars().collect();
    let t: Vec<char> = text.trim().chars().collect();
    inner(&p, &t)
}

/// 1-based tool coordinate → the 0-based one PROBLEMS uses.
fn zero(n: Option<&str>) -> u32 {
    n.and_then(|s| s.parse::<u32>().ok())
        .unwrap_or(1)
        .saturating_sub(1)
}

impl CompiledMatcher {
    /// Whether this matcher claims `command` (batch scans; watch windows
    /// are gated by `begins` instead).
    pub fn applies_to_command(&self, command: &str) -> bool {
        self.applies_to
            .as_deref()
            .is_none_or(|g| glob_match(g, command))
    }

    /// Scan a whole output block (a finished command, or a watch window).
    pub fn scan_batch(&self, output: &str) -> Vec<BuildDiag> {
        let mut out = self.scan_batch_own(output);
        for m in &self.also {
            out.extend(m.scan_batch(output));
        }
        out
    }

    /// [`Self::scan_batch`] for this matcher alone, without the rest of its
    /// list.
    fn scan_batch_own(&self, output: &str) -> Vec<BuildDiag> {
        if self.patterns.is_empty() {
            let mut diags = crate::build_matchers::scan(output);
            if let Some(tag) = self.builtin_filter {
                diags.retain(|d| d.source == tag);
            }
            return diags;
        }
        let lines: Vec<&str> = output.lines().collect();
        let mut out = Vec::new();
        let mut i = 0;
        while i < lines.len() {
            match self.try_sequence_at(&lines, i, &mut out) {
                Some(consumed) => i += consumed.max(1),
                None => i += 1,
            }
        }
        out
    }

    /// Try the full pattern sequence anchored at `lines[start]`. On success
    /// pushes the diagnostics and returns how many lines were consumed.
    fn try_sequence_at(
        &self,
        lines: &[&str],
        start: usize,
        out: &mut Vec<BuildDiag>,
    ) -> Option<usize> {
        // Fields accumulate across the sequence (file from the header line,
        // line/col/message from later ones), VS Code's multi-line model.
        #[derive(Default, Clone)]
        struct Acc {
            file: Option<String>,
            line: Option<String>,
            col: Option<String>,
            severity: Option<String>,
            message: Option<String>,
            code: Option<String>,
        }
        fn absorb(acc: &mut Acc, p: &CompiledPattern, caps: &regex::Captures) {
            let take = |g: &GroupRef| g.get(caps).map(str::to_string);
            if let Some(v) = take(&p.file) {
                acc.file = Some(v);
            }
            if let Some(v) = take(&p.line) {
                acc.line = Some(v);
            }
            if let Some(v) = take(&p.col) {
                acc.col = Some(v);
            }
            if let Some(v) = take(&p.severity) {
                acc.severity = Some(v);
            }
            if let Some(v) = take(&p.message) {
                acc.message = Some(v);
            }
            if let Some(v) = take(&p.code) {
                acc.code = Some(v);
            }
        }
        let emit = |acc: &Acc, fallback_line: &str, out: &mut Vec<BuildDiag>| -> bool {
            let Some(file) = acc.file.clone() else {
                return false;
            };
            let severity = acc
                .severity
                .as_deref()
                .map(|w| severity_word(w, &self.severity_map))
                .unwrap_or(DiagnosticSeverity::Error);
            let mut message = acc
                .message
                .clone()
                .unwrap_or_else(|| fallback_line.trim().to_string());
            if let Some(code) = &acc.code {
                message = format!("{code}: {message}");
            }
            out.push(BuildDiag {
                file,
                line: zero(acc.line.as_deref()),
                col: zero(acc.col.as_deref()),
                severity,
                message,
                source: self.name.clone(),
                needs_file: false,
            });
            true
        };

        let mut acc = Acc::default();
        let mut idx = start;
        for (pi, p) in self.patterns.iter().enumerate() {
            let last = pi == self.patterns.len() - 1;
            if last && p.loops && self.patterns.len() > 1 {
                // The looping tail: one diagnostic per consecutive match.
                let mut any = false;
                while idx < lines.len()
                    && let Some(caps) = p.regex.captures(lines[idx])
                {
                    let mut row = acc.clone();
                    absorb(&mut row, p, &caps);
                    any |= emit(&row, lines[idx], out);
                    idx += 1;
                }
                if !any {
                    return None;
                }
                return Some(idx - start);
            }
            let caps = p.regex.captures(lines.get(idx)?)?;
            absorb(&mut acc, p, &caps);
            idx += 1;
        }
        if emit(&acc, lines[idx - 1], out) {
            Some(idx - start)
        } else {
            None
        }
    }
}

/// Every loaded matcher plus the load warnings to surface once.
#[derive(Clone, Debug, Default)]
pub struct MatcherSet {
    pub matchers: Vec<Arc<CompiledMatcher>>,
    pub warnings: Vec<String>,
}

/// The background-capable subset, shared with every pane's reader thread
/// (swapped whole on reload, like `TriggerSet`).
#[derive(Clone, Debug, Default)]
pub struct WatchSet {
    pub matchers: Vec<Arc<CompiledMatcher>>,
}

pub fn matchers_path() -> PathBuf {
    crate::paths::config_dir().join("matchers.json")
}

pub fn workspace_matchers_path(root: &Path) -> PathBuf {
    root.join(".croft").join("matchers.json")
}

/// The starter file written on first "Open Problem Matchers (JSON)".
pub const TEMPLATE: &str = r##"// croft problem matchers: regexes that turn command output into PROBLEMS
// entries, extending the built-in set (rustc, tsc, gcc, python, eslint).
// Each entry:
//   "name"      tag shown in the PROBLEMS panel
//   "pattern"   regex with NAMED groups: (?P<file>…) (?P<line>…) (?P<col>…)
//               (?P<severity>…) (?P<message>…) (?P<code>…)  — file is
//               required, the rest optional
//   "patterns"  instead of "pattern": an array matched against consecutive
//               lines (file header line, then rows); add "loop": true on
//               the last one to emit a diagnostic per repeated row
//   "applies_to"   command-line glob, e.g. "mylint*" — only matching
//                  commands are scanned (omit to scan every command)
//   "severity_map" extra severity words: { "E": "error", "W": "warning" }
//   "background"   watch tasks: { "begins": "…", "ends": "…" } — output
//                  between the two is collected and (re)published to
//                  PROBLEMS on every cycle, replacing the previous batch
//   "enabled": false keeps an entry without running it
[
  // {
  //   "name": "mylint",
  //   "pattern": "^(?P<file>\\S+):(?P<line>\\d+):(?P<col>\\d+) (?P<severity>\\w+) (?P<message>.+)$",
  //   "applies_to": "mylint*"
  // }
]
"##;

/// One raw matchers.json row before compilation.
#[derive(serde::Deserialize)]
struct MatcherRow {
    name: String,
    #[serde(default)]
    pattern: Option<String>,
    #[serde(default)]
    patterns: Option<Vec<serde_json::Value>>,
    #[serde(default)]
    severity_map: BTreeMap<String, String>,
    #[serde(default)]
    applies_to: Option<String>,
    #[serde(default)]
    background: Option<BackgroundRow>,
    #[serde(default = "enabled_default")]
    enabled: bool,
}

#[derive(serde::Deserialize)]
struct BackgroundRow {
    begins: String,
    ends: String,
}

fn enabled_default() -> bool {
    true
}

/// Compile a matchers.json regex whose named groups name the fields.
fn compile_named_pattern(src: &str, loops: bool) -> Result<CompiledPattern, String> {
    let regex = Regex::new(src).map_err(|e| format!("bad regex `{src}`: {e}"))?;
    let has = |n: &str| regex.capture_names().flatten().any(|g| g == n);
    let named = |n: &'static str| {
        if has(n) {
            GroupRef::Name(n)
        } else {
            GroupRef::None
        }
    };
    Ok(CompiledPattern {
        file: named("file"),
        line: named("line"),
        col: named("col"),
        severity: named("severity"),
        message: named("message"),
        code: named("code"),
        loops,
        regex,
    })
}

impl MatcherSet {
    /// Load and merge the user and workspace matcher files. Missing files
    /// contribute nothing; a bad row drops with a warning, never blocks
    /// startup. Workspace matchers are regexes applied to output — they
    /// never execute anything — so repo-provided ones are safe to honour.
    pub fn load(user: &Path, workspace: Option<&Path>) -> Self {
        let mut set = Self::default();
        for path in std::iter::once(user).chain(workspace) {
            let Ok(json) = std::fs::read_to_string(path) else {
                continue;
            };
            set.extend_from_json(&json, &path.display().to_string());
        }
        set
    }

    /// Test seam: one in-memory document, no filesystem.
    #[cfg(test)]
    pub fn from_json(json: &str) -> Self {
        let mut set = Self::default();
        set.extend_from_json(json, "matchers.json");
        set
    }

    fn extend_from_json(&mut self, json: &str, origin: &str) {
        let stripped = crate::jsonc::strip_jsonc(json);
        let rows: Vec<serde_json::Value> = match serde_json::from_str(&stripped) {
            Ok(rows) => rows,
            Err(e) => {
                self.warnings
                    .push(format!("{origin}: not a JSON array: {e}"));
                return;
            }
        };
        for row in rows {
            let row: MatcherRow = match serde_json::from_value(row) {
                Ok(r) => r,
                Err(e) => {
                    self.warnings
                        .push(format!("{origin}: skipped an entry: {e}"));
                    continue;
                }
            };
            if !row.enabled {
                continue;
            }
            match compile_row(row) {
                Ok(m) => self.matchers.push(Arc::new(m)),
                Err(e) => self.warnings.push(format!("{origin}: {e}")),
            }
        }
    }

    /// The background-capable subset for the pane reader threads.
    pub fn watch_set(&self) -> WatchSet {
        WatchSet {
            matchers: self
                .matchers
                .iter()
                .filter(|m| m.background.is_some())
                .cloned()
                .collect(),
        }
    }

    /// Batch-scan a finished command's output: user matchers that claim the
    /// command first, then the built-in table, dropping built-in rows that
    /// duplicate a custom row's location (a custom matcher for a gcc-shaped
    /// format must not double-report).
    pub fn scan_batch(&self, output: &str, command: &str) -> Vec<BuildDiag> {
        let mut out = Vec::new();
        for m in &self.matchers {
            if m.patterns.is_empty() || !m.applies_to_command(command) {
                continue;
            }
            out.extend(m.scan_batch(output));
        }
        let custom: std::collections::BTreeSet<(String, u32, u32)> = out
            .iter()
            .map(|d| (d.file.clone(), d.line, d.col))
            .collect();
        out.extend(
            crate::build_matchers::scan(output)
                .into_iter()
                .filter(|d| !custom.contains(&(d.file.clone(), d.line, d.col))),
        );
        out
    }
}

fn compile_row(row: MatcherRow) -> Result<CompiledMatcher, String> {
    let name = row.name;
    let mut patterns = Vec::new();
    if let Some(p) = &row.pattern {
        patterns.push(compile_named_pattern(p, false).map_err(|e| format!("{name}: {e}"))?);
    } else if let Some(seq) = &row.patterns {
        let n = seq.len();
        for (i, v) in seq.iter().enumerate() {
            let (src, loops) = match v {
                serde_json::Value::String(s) => (s.as_str(), false),
                serde_json::Value::Object(o) => (
                    o.get("regex")
                        .and_then(|r| r.as_str())
                        .ok_or_else(|| format!("{name}: patterns[{i}] has no \"regex\""))?,
                    o.get("loop").and_then(|l| l.as_bool()).unwrap_or(false),
                ),
                _ => return Err(format!("{name}: patterns[{i}] must be a string or object")),
            };
            if loops && i + 1 != n {
                return Err(format!("{name}: only the last pattern may set \"loop\""));
            }
            patterns.push(compile_named_pattern(src, loops).map_err(|e| format!("{name}: {e}"))?);
        }
    }
    let background = row
        .background
        .map(|b| -> Result<Background, String> {
            Ok(Background {
                begins: Regex::new(&b.begins)
                    .map_err(|e| format!("{name}: bad begins regex: {e}"))?,
                ends: Regex::new(&b.ends).map_err(|e| format!("{name}: bad ends regex: {e}"))?,
                active_on_start: false,
            })
        })
        .transpose()?;
    if patterns.is_empty() && background.is_none() {
        return Err(format!(
            "{name}: needs a \"pattern\", \"patterns\" or \"background\""
        ));
    }
    let severity_map = row
        .severity_map
        .into_iter()
        .filter_map(|(k, v)| parse_severity_name(&v).map(|s| (k, s)))
        .collect();
    Ok(CompiledMatcher {
        name,
        patterns,
        builtin_filter: None,
        severity_map,
        applies_to: row.applies_to,
        background,
        also: Vec::new(),
    })
}

/// The VS Code well-known matcher names croft maps onto its built-in
/// table. `$tsc-watch` additionally carries tsc's watch-cycle delimiters.
pub fn well_known(name: &str) -> Option<CompiledMatcher> {
    let (tag, filter): (&str, &'static str) = match name {
        "$tsc" => ("tsc", "tsc"),
        "$rustc" => ("rustc", "rustc"),
        "$eslint-stylish" => ("eslint", "eslint"),
        "$gcc" => ("gcc", "build"),
        "$go" => ("go", "go"),
        "$eslint-compact" => ("eslint-compact", "eslint-compact"),
        "$msCompile" => ("msCompile", "msCompile"),
        "$tsc-watch" => {
            return Some(CompiledMatcher {
                name: String::from("tsc-watch"),
                patterns: Vec::new(),
                builtin_filter: Some("tsc"),
                severity_map: BTreeMap::new(),
                applies_to: None,
                background: Some(Background {
                    begins: Regex::new(
                        r"Starting compilation in watch mode|File change detected\. Starting incremental compilation",
                    )
                    .unwrap(),
                    ends: Regex::new(r"Watching for file changes\.").unwrap(),
                    active_on_start: false,
                }),
                also: Vec::new(),
            });
        }
        _ => return None,
    };
    Some(CompiledMatcher {
        name: tag.to_string(),
        patterns: Vec::new(),
        builtin_filter: Some(filter),
        severity_map: BTreeMap::new(),
        applies_to: None,
        background: None,
        also: Vec::new(),
    })
}

/// Translate a tasks.json `problemMatcher` value (string, object, or
/// array — every usable entry runs) into a matcher. `None` means "no
/// usable matcher": unknown `$names` and untranslatable shapes degrade to
/// the built-in first-match-wins scan rather than erroring.
pub fn from_tasks_json(value: &serde_json::Value) -> Option<CompiledMatcher> {
    match value {
        serde_json::Value::String(s) => {
            let known = well_known(s);
            // Said, not dropped: the task otherwise runs with the generic
            // table and nothing tells the user their matcher was ignored.
            if known.is_none() {
                crate::output::push(
                    "Matchers",
                    crate::output::OutputLevel::Warn,
                    &format!(
                        "tasks.json: problemMatcher \"{s}\" is not one croft knows; the built-in matchers run instead"
                    ),
                );
            }
            known
        }
        serde_json::Value::Array(items) => {
            let mut all: Vec<CompiledMatcher> = items.iter().filter_map(from_tasks_json).collect();
            // A background entry anywhere makes it a watch task (VS Code), and
            // the pane's watch engine reads the head's `background`.
            let head = all.iter().position(|m| m.background.is_some()).unwrap_or(0);
            if all.is_empty() {
                return None;
            }
            let mut head = all.remove(head);
            head.also.extend(all);
            Some(head)
        }
        serde_json::Value::Object(o) => from_vscode_object(o),
        _ => None,
    }
}

/// An inline VS Code problemMatcher object: `pattern` uses NUMERIC group
/// indices (`"file": 1`), `background.beginsPattern`/`endsPattern` gate
/// watch mode. `base` (`"$tsc"`-style) supplies what the object omits.
fn from_vscode_object(o: &serde_json::Map<String, serde_json::Value>) -> Option<CompiledMatcher> {
    let base = o.get("base").and_then(|b| b.as_str()).and_then(well_known);
    let idx = |v: Option<&serde_json::Value>, default: usize| -> GroupRef {
        match v.and_then(|v| v.as_u64()) {
            Some(i) => GroupRef::Index(i as usize),
            None if default != usize::MAX => GroupRef::Index(default),
            None => GroupRef::None,
        }
    };
    let compile_one = |p: &serde_json::Map<String, serde_json::Value>| -> Option<CompiledPattern> {
        let src = p.get("regexp")?.as_str()?;
        Some(CompiledPattern {
            regex: Regex::new(src).ok()?,
            file: idx(p.get("file"), 1),
            line: idx(p.get("line"), 2),
            col: idx(p.get("column"), 3),
            severity: idx(p.get("severity"), usize::MAX),
            message: idx(p.get("message"), usize::MAX),
            code: idx(p.get("code"), usize::MAX),
            loops: p.get("loop").and_then(|l| l.as_bool()).unwrap_or(false),
        })
    };
    let patterns: Vec<CompiledPattern> = match o.get("pattern") {
        Some(serde_json::Value::Object(p)) => compile_one(p).into_iter().collect(),
        Some(serde_json::Value::Array(seq)) => {
            let compiled: Vec<_> = seq
                .iter()
                .filter_map(|v| v.as_object())
                .filter_map(compile_one)
                .collect();
            // A partially-compiled sequence would mis-consume lines.
            if compiled.len() != seq.len() {
                return base;
            }
            compiled
        }
        Some(serde_json::Value::String(s)) => return well_known(s).or(base),
        _ => Vec::new(),
    };
    let pattern_str = |v: Option<&serde_json::Value>| -> Option<Regex> {
        let v = v?;
        let src = v.as_str().or_else(|| v.get("regexp")?.as_str())?;
        Regex::new(src).ok()
    };
    let background = o.get("background").and_then(|b| {
        Some(Background {
            begins: pattern_str(b.get("beginsPattern"))?,
            ends: pattern_str(b.get("endsPattern"))?,
            active_on_start: b
                .get("activeOnStart")
                .and_then(serde_json::Value::as_bool)
                .unwrap_or(false),
        })
    });
    if patterns.is_empty() && background.is_none() {
        return base;
    }
    let owner = o
        .get("owner")
        .and_then(|s| s.as_str())
        .unwrap_or("task")
        .to_string();
    let base = base.unwrap_or(CompiledMatcher {
        name: owner.clone(),
        patterns: Vec::new(),
        builtin_filter: None,
        severity_map: BTreeMap::new(),
        applies_to: None,
        background: None,
        also: Vec::new(),
    });
    Some(CompiledMatcher {
        name: if o.contains_key("owner") {
            owner
        } else {
            base.name
        },
        patterns: if patterns.is_empty() {
            base.patterns
        } else {
            patterns
        },
        builtin_filter: base.builtin_filter,
        severity_map: base.severity_map,
        applies_to: None,
        background: background.or(base.background),
        also: Vec::new(),
    })
}

/// Per-pane streaming state machine for watch matchers. Fed the completed
/// escape-stripped primary-screen lines the trigger scanner already
/// produces; returns a published batch when a window closes.
#[derive(Default)]
pub struct WatchEngine {
    active: Option<(Arc<CompiledMatcher>, Vec<String>)>,
    /// A task matcher was just assigned and its command's output has not
    /// started yet (#1541); see [`Self::assign`].
    start: Option<TaskStart>,
}

/// How long a newly assigned task matcher waits for the shell's OSC 133
/// marks before it takes the pane's lines as they come. A pane whose shell
/// has no integration never sends one; one that has sends its prompt mark
/// well inside this.
pub const TASK_START_GRACE: std::time::Duration = std::time::Duration::from_secs(2);

/// The window between a task matcher's assignment and its command's first
/// output. The task is typed into a shell, so what the pane prints first is
/// the shell's echo of the command line (the tty's, and again the line
/// editor's once the prompt is up), not the task's output; a command line
/// that names the matcher's `begins` or `ends` text would open or close a
/// window on that echo and publish a cycle that never ran.
struct TaskStart {
    /// When the assignment was seen, for [`TASK_START_GRACE`].
    since: std::time::Instant,
    /// Lines seen since, replayed if no mark comes within the grace.
    held: Vec<String>,
    /// A mark arrived, so the shell has integration and the command's own
    /// `133;C` is coming: no grace, wait for it.
    marked: bool,
    /// The grace ran out with no mark: lines are fed as they come, but a
    /// late `133;C` still restarts the engine at the real output.
    live: bool,
}

impl WatchEngine {
    /// Feed one completed line. `pane_matcher` (the task's own matcher, if
    /// any) outranks the global set when both could open a window.
    pub fn feed(
        &mut self,
        line: &str,
        set: &WatchSet,
        pane_matcher: Option<&Arc<CompiledMatcher>>,
    ) -> Option<Vec<BuildDiag>> {
        if let Some(start) = &mut self.start
            && !start.live
        {
            if start.held.len() < WATCH_WINDOW_CAP {
                start.held.push(line.to_string());
            }
            return None;
        }
        if let Some((matcher, window)) = &mut self.active {
            let bg = matcher
                .background
                .as_ref()
                .expect("active window implies background");
            if bg.ends.is_match(line) {
                let output = window.join("\n");
                let diags = matcher.scan_batch(&output);
                self.active = None;
                return Some(diags);
            }
            if window.len() < WATCH_WINDOW_CAP {
                window.push(line.to_string());
            }
            // A new begins inside the window restarts the cycle (a watcher
            // interrupted mid-compile starts over; stale lines must not
            // leak into the fresh window).
            if bg.begins.is_match(line) {
                window.clear();
            }
            return None;
        }
        // An explicit task matcher is EXCLUSIVE for its pane (VS Code's
        // model, same rule as the FinishedCommand scan): global watch
        // matchers never open windows on task-owned output, or an
        // unrelated global `begins` could claim the cycle and its publish
        // would suppress the task matcher's own results.
        let global = if pane_matcher.is_some() {
            &[][..]
        } else {
            &set.matchers[..]
        };
        for m in pane_matcher.into_iter().chain(global) {
            if let Some(bg) = &m.background
                && bg.begins.is_match(line)
            {
                self.active = Some((m.clone(), Vec::new()));
                return None;
            }
        }
        None
    }

    /// Drop any half-open watch window. Called when matcher ownership
    /// changes under the engine (config reload, task (re)assignment) so
    /// the next `ends` can't scan stale lines with the old matcher.
    pub fn reset(&mut self) {
        self.active = None;
    }

    /// A new task matcher took over the pane at `now`: drop any half-open
    /// window, as [`Self::reset`] does, and hold the pane's lines until the
    /// task's command starts (#1541): the shell's `133;C` mark
    /// ([`Self::mark`]), or [`TASK_START_GRACE`] with no mark at all
    /// ([`Self::expire`]). The first window then opens at once when the
    /// matcher is `activeOnStart`, since its task may print only `ends` for
    /// its initial build. Clearing the matcher (`None`) feeds lines at once.
    pub fn assign(&mut self, pane_matcher: Option<&Arc<CompiledMatcher>>, now: std::time::Instant) {
        self.active = None;
        self.start = pane_matcher.map(|_| TaskStart {
            since: now,
            held: Vec::new(),
            marked: false,
            live: false,
        });
    }

    /// An OSC 133 mark, in stream order with the lines fed around it. A
    /// prompt mark means the lines held so far came before the prompt that
    /// reads the task's command; `133;C` (`command_start`) means its output
    /// starts here, so the engine starts fresh on it.
    pub fn mark(&mut self, command_start: bool, pane_matcher: Option<&Arc<CompiledMatcher>>) {
        let Some(start) = &mut self.start else {
            return;
        };
        if command_start {
            self.start = None;
            self.open_first_window(pane_matcher);
            return;
        }
        // A late prompt after the grace ran out: the shell has integration
        // after all, so what it printed so far was not the task's output.
        if start.live {
            self.active = None;
        }
        start.held.clear();
        start.marked = true;
        start.live = false;
    }

    /// When the reader must call [`Self::expire`] if no output comes first:
    /// the end of the grace, while it is still running.
    pub fn deadline(&self) -> Option<std::time::Instant> {
        self.start
            .as_ref()
            .filter(|s| !s.marked && !s.live)
            .map(|s| s.since + TASK_START_GRACE)
    }

    /// The grace ran out at `now` with no mark: the pane's shell has no
    /// integration, so the held lines are taken as the task's output after
    /// all and fed through. Returns the batches they publish.
    pub fn expire(
        &mut self,
        now: std::time::Instant,
        set: &WatchSet,
        pane_matcher: Option<&Arc<CompiledMatcher>>,
    ) -> Vec<Vec<BuildDiag>> {
        if self.deadline().is_none_or(|d| now < d) {
            return Vec::new();
        }
        let Some(start) = &mut self.start else {
            return Vec::new();
        };
        start.live = true;
        let held = std::mem::take(&mut start.held);
        self.open_first_window(pane_matcher);
        held.iter()
            .filter_map(|line| self.feed(line, set, pane_matcher))
            .collect()
    }

    /// The task's output starts: an `activeOnStart` matcher is inside its
    /// first window already.
    fn open_first_window(&mut self, pane_matcher: Option<&Arc<CompiledMatcher>>) {
        self.active = pane_matcher
            .filter(|m| m.background.as_ref().is_some_and(|b| b.active_on_start))
            .map(|m| (m.clone(), Vec::new()));
    }
}

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

    #[test]
    fn a_single_line_named_group_matcher_extracts_the_fields() {
        let set = MatcherSet::from_json(
            r##"[
  { "name": "mylint",
    "pattern": "^(?P<file>\\S+):(?P<line>\\d+):(?P<col>\\d+) (?P<severity>\\w+) (?P<message>.+)$",
    "severity_map": { "E": "error", "W": "warning" },
    "applies_to": "mylint*" }
]"##,
        );
        assert!(set.warnings.is_empty(), "{:?}", set.warnings);
        let out = set.scan_batch(
            "src/a.py:12:5 E undefined name 'x'\nok line\n",
            "mylint src/",
        );
        assert_eq!(out.len(), 1, "{out:?}");
        assert_eq!(out[0].file, "src/a.py");
        assert_eq!((out[0].line, out[0].col), (11, 4), "0-based conversion");
        assert_eq!(out[0].severity, DiagnosticSeverity::Error);
        assert_eq!(out[0].message, "undefined name 'x'");
        assert_eq!(out[0].source, "mylint");
        // The applies_to glob gates the matcher off other commands.
        assert!(
            set.scan_batch("src/a.py:12:5 E undefined name 'x'\n", "cargo build")
                .is_empty()
        );
    }

    #[test]
    fn a_multi_line_matcher_with_a_looping_tail_handles_header_plus_rows() {
        let set = MatcherSet::from_json(
            r##"[
  { "name": "homelint",
    "patterns": [
      "^== (?P<file>\\S+) ==$",
      { "regex": "^\\s+(?P<line>\\d+):(?P<col>\\d+)\\s+(?P<severity>\\w+)\\s+(?P<message>.+)$", "loop": true }
    ] }
]"##,
        );
        assert!(set.warnings.is_empty(), "{:?}", set.warnings);
        let out = set.scan_batch(
            "== src/main.c ==\n  3:1  warning  short name\n  9:2  error  bad cast\nnoise\n== src/util.c ==\n  1:1  error  oops\n",
            "homelint",
        );
        assert_eq!(out.len(), 3, "{out:?}");
        assert_eq!(out[0].file, "src/main.c");
        assert_eq!(out[0].severity, DiagnosticSeverity::Warning);
        assert_eq!(out[1].message, "bad cast");
        assert_eq!(out[2].file, "src/util.c");
        assert_eq!((out[2].line, out[2].col), (0, 0));
    }

    #[test]
    fn bad_rows_warn_once_and_never_reach_the_matcher_list() {
        let set = MatcherSet::from_json(
            r##"[
  { "name": "broken", "pattern": "((unclosed" },
  { "name": "empty" },
  { "name": "off", "pattern": "(?P<file>.+)", "enabled": false },
  { "name": "good", "pattern": "^(?P<file>\\S+): (?P<message>.+)$" }
]"##,
        );
        assert_eq!(set.matchers.len(), 1, "{:?}", set.warnings);
        assert_eq!(set.matchers[0].name, "good");
        assert_eq!(set.warnings.len(), 2, "{:?}", set.warnings);
        assert!(set.warnings[0].contains("broken"), "{:?}", set.warnings);
        let garbage = MatcherSet::from_json("not json");
        assert!(garbage.matchers.is_empty());
        assert_eq!(garbage.warnings.len(), 1);
    }

    #[test]
    fn custom_diags_suppress_duplicate_builtin_rows_but_builtins_still_run() {
        // A custom matcher over a gcc-shaped line: the built-in GENERIC
        // matcher would report the same location; only the custom row
        // survives, while an untouched rustc block still comes through.
        let set = MatcherSet::from_json(
            r##"[ { "name": "cc", "pattern": "^(?P<file>\\S+):(?P<line>\\d+):(?P<col>\\d+): (?P<severity>\\w+): (?P<message>.+)$" } ]"##,
        );
        let out = set.scan_batch(
            "main.c:7:3: error: expected ';'\nerror[E0308]: mismatched types\n  --> src/lib.rs:2:1\n",
            "make",
        );
        assert_eq!(out.len(), 2, "{out:?}");
        assert_eq!(out[0].source, "cc");
        assert_eq!(out[1].source, "rustc");
    }

    #[test]
    fn well_known_names_map_onto_the_builtin_table_with_a_source_filter() {
        let gcc = well_known("$gcc").unwrap();
        let out = gcc
            .scan_batch("main.c:7:3: error: expected ';'\nsrc/app.ts(4,10): error TS2322: nope\n");
        assert_eq!(
            out.len(),
            1,
            "$gcc must only report gcc-shaped rows: {out:?}"
        );
        assert_eq!(out[0].file, "main.c");
        assert!(well_known("$tsc-watch").unwrap().background.is_some());
        assert!(well_known("$made-up-name").is_none());
    }

    /// #1594: VS Code's `$go`, `$eslint-compact` and `$msCompile` are known,
    /// each reporting its own tool's rows only, and `$gcc` does not pick up
    /// mypy's column-less row.
    #[test]
    fn go_eslint_compact_and_ms_compile_are_well_known() {
        let mixed = "./main.go:4:6: declared and not used: unused\n\
                     web/a.js: line 2, col 1, Warning - Missing semicolon. (semi)\n\
                     Program.cs(3,1): error CS0103: The name 'x' does not exist\n\
                     main.c:7:3: error: expected ';'\n\
                     app.py:2: error: Incompatible types in assignment\n";
        for (name, file) in [
            ("$gcc", "main.c"),
            ("$go", "./main.go"),
            ("$eslint-compact", "web/a.js"),
            ("$msCompile", "Program.cs"),
        ] {
            let out = well_known(name).unwrap().scan_batch(mixed);
            assert_eq!(out.len(), 1, "{name}: {out:?}");
            assert_eq!(out[0].file, file, "{name}");
        }
    }

    /// #1594: a matcher name croft does not know is said in OUTPUT ·
    /// Matchers instead of being dropped without a word.
    #[test]
    fn an_unknown_task_matcher_name_is_reported() {
        assert!(from_tasks_json(&serde_json::json!("$nosuch-1594")).is_none());
        let lines = crate::output::snapshot("Matchers").unwrap_or_default();
        assert!(
            lines.iter().any(|l| l.text.contains("\"$nosuch-1594\"")),
            "{lines:?}"
        );
    }

    /// gcc diagnostics, then eslint's default "stylish" report (#1240).
    const GCC_THEN_ESLINT: &str = "bad.c:2:11: error: initialization of 'int' from 'char *'\nbad.c:3:10: error: 'y' undeclared\n\nweb/app.js\n  1:5  error  a is assigned a value but never used  no-unused-vars\n  2:5  error  b is assigned a value but never used  no-unused-vars\n\n\u{2716} 2 problems (2 errors, 0 warnings)\n";

    /// Every matcher in a tasks.json list runs, in either order, as in VS
    /// Code: a compile-and-lint task reports both tools' errors.
    #[test]
    fn a_problem_matcher_list_runs_every_matcher() {
        for list in [
            serde_json::json!(["$gcc", "$eslint-stylish"]),
            serde_json::json!(["$eslint-stylish", "$gcc"]),
        ] {
            let m = from_tasks_json(&list).unwrap();
            let out = m.scan_batch(GCC_THEN_ESLINT);
            let files: Vec<&str> = out.iter().map(|d| d.file.as_str()).collect();
            assert_eq!(
                files.iter().filter(|f| **f == "bad.c").count(),
                2,
                "{list}: {out:?}"
            );
            assert_eq!(
                files.iter().filter(|f| **f == "web/app.js").count(),
                2,
                "{list}: {out:?}"
            );
        }
    }

    /// A background matcher anywhere in the list makes the task a watch
    /// task, as in VS Code.
    #[test]
    fn a_background_matcher_anywhere_in_a_list_makes_a_watch_task() {
        let m = from_tasks_json(&serde_json::json!(["$gcc", "$tsc-watch"])).unwrap();
        assert!(m.background.is_some());
    }

    /// Entries that don't translate are skipped, and a single usable one is
    /// exactly that matcher: no other tool's rows leak in.
    #[test]
    fn a_list_with_one_usable_matcher_reports_only_its_rows() {
        let m = from_tasks_json(&serde_json::json!(["$nope", "$gcc"])).unwrap();
        let out = m.scan_batch(GCC_THEN_ESLINT);
        assert_eq!(out.len(), 2, "{out:?}");
        assert!(out.iter().all(|d| d.file == "bad.c"));
        assert!(from_tasks_json(&serde_json::json!(["$nope", "$also-nope"])).is_none());
    }

    #[test]
    fn tasks_json_problem_matcher_values_translate() {
        // A $name string.
        let v: serde_json::Value = serde_json::json!("$gcc");
        assert_eq!(from_tasks_json(&v).unwrap().name, "gcc");
        // Unknown $name degrades to None (built-in scan takes over).
        assert!(from_tasks_json(&serde_json::json!("$whatever")).is_none());
        // An inline VS Code pattern object with numeric indices.
        let v = serde_json::json!({
            "owner": "mytool",
            "pattern": {
                "regexp": "^(.+?)\\|(\\d+)\\|(\\d+)\\|(error|warning)\\|(.+)$",
                "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5
            }
        });
        let m = from_tasks_json(&v).unwrap();
        let out = m.scan_batch("src/x.zig|4|2|warning|unused variable\n");
        assert_eq!(out.len(), 1, "{out:?}");
        assert_eq!(out[0].file, "src/x.zig");
        assert_eq!(out[0].severity, DiagnosticSeverity::Warning);
        assert_eq!(out[0].source, "mytool");
        // An array picks the first usable entry.
        let v = serde_json::json!(["$nope", "$rustc"]);
        assert_eq!(from_tasks_json(&v).unwrap().name, "rustc");
        // background with string patterns (VS Code allows both shapes).
        let v = serde_json::json!({
            "base": "$tsc",
            "background": { "beginsPattern": "Compiling…", "endsPattern": "Done\\." }
        });
        let m = from_tasks_json(&v).unwrap();
        assert!(m.background.is_some());
        assert_eq!(m.builtin_filter, Some("tsc"));
    }

    #[test]
    fn the_watch_engine_collects_between_begins_and_ends_and_republishes() {
        let matcher = Arc::new(well_known("$tsc-watch").unwrap());
        let set = WatchSet::default();
        let mut engine = WatchEngine::default();
        let feed = |e: &mut WatchEngine, line: &str| e.feed(line, &set, Some(&matcher));
        assert!(feed(&mut engine, "stray line").is_none());
        assert!(feed(&mut engine, "Starting compilation in watch mode...").is_none());
        assert!(feed(&mut engine, "src/app.ts(4,10): error TS2322: bad type.").is_none());
        let batch = feed(&mut engine, "Found 1 error. Watching for file changes.").unwrap();
        assert_eq!(batch.len(), 1, "{batch:?}");
        assert_eq!(batch[0].file, "src/app.ts");
        // Next cycle: clean compile publishes an EMPTY batch, which is what
        // clears the fixed errors from PROBLEMS.
        assert!(
            feed(
                &mut engine,
                "File change detected. Starting incremental compilation..."
            )
            .is_none()
        );
        let batch = feed(&mut engine, "Found 0 errors. Watching for file changes.").unwrap();
        assert!(batch.is_empty(), "{batch:?}");
    }

    #[test]
    fn a_begins_inside_an_open_window_restarts_the_cycle() {
        let set = MatcherSet::from_json(
            r##"[ { "name": "watchy",
                   "pattern": "^(?P<file>\\S+): (?P<message>.+)$",
                   "background": { "begins": "^BUILD START$", "ends": "^BUILD END$" } } ]"##,
        );
        let watch = set.watch_set();
        assert_eq!(watch.matchers.len(), 1);
        let mut engine = WatchEngine::default();
        assert!(engine.feed("BUILD START", &watch, None).is_none());
        assert!(engine.feed("stale.c: old error", &watch, None).is_none());
        assert!(engine.feed("BUILD START", &watch, None).is_none());
        assert!(engine.feed("fresh.c: new error", &watch, None).is_none());
        let batch = engine.feed("BUILD END", &watch, None).unwrap();
        assert_eq!(
            batch.len(),
            1,
            "the restarted window dropped stale lines: {batch:?}"
        );
        assert_eq!(batch[0].file, "fresh.c");
    }

    /// A task matcher in the shape of the #1541 tests: `t`'s errors,
    /// between `BUILD START` and `BUILD END`.
    fn start_end_task(active_on_start: bool) -> Arc<CompiledMatcher> {
        let json = serde_json::json!({
            "owner": "t",
            "pattern": { "regexp": "^(\\S+):(\\d+):(\\d+): (.+)$", "message": 4 },
            "background": {
                "activeOnStart": active_on_start,
                "beginsPattern": "^BUILD START$",
                "endsPattern": "^BUILD END$"
            }
        });
        Arc::new(from_tasks_json(&json).unwrap())
    }

    /// #1541: an `activeOnStart` task matcher opens its first window when
    /// its command starts, so an initial build that prints only `ends`
    /// still publishes; later cycles wait for `begins` again. Without the
    /// flag the same lines publish nothing.
    #[test]
    fn an_active_on_start_matcher_publishes_a_first_cycle_with_no_begins() {
        let watch = WatchSet::default();
        let task = start_end_task(true);
        let mut engine = WatchEngine::default();
        engine.assign(Some(&task), std::time::Instant::now());
        engine.mark(true, Some(&task));
        assert!(engine.feed("a.c:1:2: boom", &watch, Some(&task)).is_none());
        let batch = engine.feed("BUILD END", &watch, Some(&task)).unwrap();
        assert_eq!(batch.len(), 1, "{batch:?}");
        assert_eq!(batch[0].file, "a.c");
        // The next cycle is an ordinary one: no begins, no window.
        assert!(engine.feed("b.c:1:2: boom", &watch, Some(&task)).is_none());
        assert!(engine.feed("BUILD END", &watch, Some(&task)).is_none());

        let lazy = start_end_task(false);
        let mut engine = WatchEngine::default();
        engine.assign(Some(&lazy), std::time::Instant::now());
        engine.mark(true, Some(&lazy));
        assert!(engine.feed("a.c:1:2: boom", &watch, Some(&lazy)).is_none());
        assert!(engine.feed("BUILD END", &watch, Some(&lazy)).is_none());
    }

    /// #1541: the shell echoes the task's command line before running it,
    /// once from the tty and again from its line editor once the prompt is
    /// up. A command line naming `begins` and `ends` published an empty
    /// cycle from those echoes, which launched past a build with errors.
    /// Lines before the command's `133;C` mark are not its output.
    #[test]
    fn a_task_matcher_ignores_the_echo_of_its_command_line() {
        let watch = WatchSet::default();
        let echo = "sh -c 'echo BUILD START; echo a.c:1:2: boom; echo BUILD END'";
        for active in [false, true] {
            let task = start_end_task(active);
            let mut engine = WatchEngine::default();
            engine.assign(Some(&task), std::time::Instant::now());
            // The tty's echo, typed before the shell's first prompt.
            assert!(engine.feed("BUILD START", &watch, Some(&task)).is_none());
            assert!(engine.feed("BUILD END", &watch, Some(&task)).is_none());
            engine.mark(false, Some(&task));
            // The line editor's, after the prompt.
            assert!(engine.feed(echo, &watch, Some(&task)).is_none());
            assert!(engine.feed("BUILD END", &watch, Some(&task)).is_none());
            assert_eq!(engine.deadline(), None, "a marked shell waits for 133;C");
            engine.mark(true, Some(&task));
            for line in ["BUILD START", "a.c:1:2: boom"] {
                assert!(engine.feed(line, &watch, Some(&task)).is_none());
            }
            let batch = engine.feed("BUILD END", &watch, Some(&task)).unwrap();
            assert_eq!(batch.len(), 1, "active={active}: {batch:?}");
        }
    }

    /// #1541: a shell with no integration sends no marks, so after the
    /// grace the held lines are the task's output after all, and a first
    /// cycle among them publishes; a late `133;C` still starts afresh.
    #[test]
    fn a_task_matcher_with_no_marks_feeds_its_lines_after_the_grace() {
        let watch = WatchSet::default();
        let task = start_end_task(true);
        let t0 = std::time::Instant::now();
        let mut engine = WatchEngine::default();
        engine.assign(Some(&task), t0);
        assert!(engine.feed("a.c:1:2: boom", &watch, Some(&task)).is_none());
        assert!(engine.feed("BUILD END", &watch, Some(&task)).is_none());
        assert_eq!(engine.deadline(), Some(t0 + TASK_START_GRACE));
        assert!(
            engine.expire(t0, &watch, Some(&task)).is_empty(),
            "too soon"
        );
        let batches = engine.expire(t0 + TASK_START_GRACE, &watch, Some(&task));
        assert_eq!(batches.len(), 1, "{batches:?}");
        assert_eq!(batches[0].len(), 1, "{batches:?}");
        assert_eq!(engine.deadline(), None);
        // Live now: the next cycle publishes as it ends.
        assert!(engine.feed("BUILD START", &watch, Some(&task)).is_none());
        assert!(engine.feed("BUILD END", &watch, Some(&task)).is_some());
        // A slow shell's late command mark restarts at its real output.
        assert!(engine.feed("BUILD START", &watch, Some(&task)).is_none());
        engine.mark(true, Some(&task));
        assert!(engine.feed("b.c:1:2: boom", &watch, Some(&task)).is_none());
        let batch = engine.feed("BUILD END", &watch, Some(&task)).unwrap();
        assert_eq!(batch[0].file, "b.c", "{batch:?}");
    }

    #[test]
    fn a_pane_matcher_excludes_global_watch_matchers_and_reset_drops_the_window() {
        let set = MatcherSet::from_json(
            r##"[ { "name": "globby",
                   "pattern": "^(?P<file>\\S+): (?P<message>.+)$",
                   "background": { "begins": "^GLOBAL START$", "ends": "^GLOBAL END$" } } ]"##,
        );
        let watch = set.watch_set();
        let task = Arc::new(well_known("$tsc-watch").unwrap());
        // Task-owned pane: a global begins must NOT open a window — the
        // task matcher is exclusive, and a global publish would suppress
        // the task's own FinishedCommand scan via the skip-once flag.
        let mut engine = WatchEngine::default();
        assert!(engine.feed("GLOBAL START", &watch, Some(&task)).is_none());
        assert!(
            engine.feed("stale.c: err", &watch, Some(&task)).is_none()
                && engine.feed("GLOBAL END", &watch, Some(&task)).is_none(),
            "no window ever opened on the task pane"
        );
        // Without a pane matcher the same lines publish normally.
        let mut free = WatchEngine::default();
        assert!(free.feed("GLOBAL START", &watch, None).is_none());
        assert!(free.feed("a.c: boom", &watch, None).is_none());
        assert_eq!(free.feed("GLOBAL END", &watch, None).unwrap().len(), 1);
        // reset() mid-window: the interrupted cycle never publishes.
        let mut resettable = WatchEngine::default();
        assert!(resettable.feed("GLOBAL START", &watch, None).is_none());
        assert!(resettable.feed("a.c: boom", &watch, None).is_none());
        resettable.reset();
        assert!(
            resettable.feed("GLOBAL END", &watch, None).is_none(),
            "the dropped window's ends must not scan stale lines"
        );
    }

    #[test]
    fn glob_matching_covers_star_and_question_mark() {
        assert!(glob_match("mylint*", "mylint src/"));
        assert!(glob_match("*test*", "cargo test --all"));
        assert!(glob_match("l?nt", "lint"));
        assert!(!glob_match("mylint*", "cargo build"));
        assert!(glob_match("*", "anything at all"));
    }
}