patchloom 0.11.0

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

#[derive(Debug, Args)]
#[command(after_help = "\
EXAMPLES:
  patchloom search 'TODO' src/
  patchloom search 'fn main' src/ --count
  patchloom search 'error|warn' --regex src/ -C 2
  patchloom search 'password' . --glob '*.yaml'
  patchloom search 'TODO' . --ignore-file .blineignore --exclude 'target/**' --max-results 50")]
pub struct SearchArgs {
    /// Pattern to search for.
    pub pattern: String,
    /// Paths to search in.
    pub paths: Vec<String>,
    /// Treat pattern as a literal string.
    #[arg(long, short = 'F', conflicts_with = "regex")]
    pub literal: bool,
    /// Treat pattern as a regex (default).
    #[arg(long, conflicts_with = "literal")]
    pub regex: bool,
    /// Lines of context around matches (shorthand for -B N -A N).
    #[arg(long, short = 'C')]
    pub context: Option<usize>,
    /// Lines of context before each match.
    #[arg(long, short = 'B')]
    pub before_context: Option<usize>,
    /// Lines of context after each match.
    #[arg(long, short = 'A')]
    pub after_context: Option<usize>,
    // ref:search-mode:files-with-matches
    /// Only print file paths with matches.
    #[arg(long, short = 'l', conflicts_with = "count")]
    pub files_with_matches: bool,
    // ref:search-mode:count
    /// Only print match counts per file.
    #[arg(long, short = 'c', conflicts_with = "files_with_matches")]
    pub count: bool,
    // ref:search-mode:invert-match
    /// Show lines that do NOT match the pattern.
    #[arg(long, short = 'v')]
    pub invert_match: bool,
    // ref:search-mode:multiline
    /// Enable multiline matching (dot matches newlines).
    #[arg(long, short = 'U')]
    pub multiline: bool,
    // ref:search-mode:case-insensitive
    /// Case-insensitive matching.
    #[arg(long, short = 'i')]
    pub case_insensitive: bool,
    // ref:search-mode:assert-count
    /// Assert that the total match count equals N. Exits 0 if exact, 2 otherwise.
    #[arg(long)]
    pub assert_count: Option<usize>,

    /// Maximum number of detailed match results to return (0 = unlimited).
    /// Primarily affects non-count output modes. Matches library SearchOptions.max_results behavior.
    #[arg(long, default_value_t = 0)]
    pub max_results: usize,
}

#[derive(Debug, Serialize)]
struct SearchOutput {
    ok: bool,
    matches: Vec<SearchMatch>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    files: Vec<SearchFileEntry>,
    match_count: usize,
    file_count: usize,
}

#[derive(Debug, Serialize)]
struct SearchFileEntry {
    path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    count: Option<usize>,
}

#[derive(Debug, Serialize)]
struct SearchAssertCount {
    expected: usize,
    actual: usize,
    matched: bool,
}

#[derive(Debug, Serialize)]
struct SearchAssertCountOutput {
    ok: bool,
    status: &'static str,
    assert_count: SearchAssertCount,
}

pub(crate) fn collect_matches(
    args: &SearchArgs,
    global: &GlobalFlags,
) -> anyhow::Result<SearchResults> {
    crate::verbose!(
        "search: pattern={:?} literal={} paths={:?}",
        args.pattern,
        args.literal,
        args.paths
    );
    let cwd = global.resolve_cwd()?;
    // --contain applies to search paths (agent sandbox must not read secrets
    // outside the workspace; MPI cycle 18).
    global.check_paths_contained(&cwd, &args.paths)?;
    let glob_matcher = crate::build_glob_matcher_from_global(global)?;
    let matcher = ops_search::build_matcher(
        &args.pattern,
        args.literal,
        args.case_insensitive,
        args.multiline,
    )?;
    let file_paths = crate::collect_file_paths_opts(&args.paths, global, false, Some(&cwd))?;
    let glob_roots = crate::collect_glob_roots_from_global(&args.paths, global, Some(&cwd))?;
    let count_only = args.count || args.files_with_matches;

    // Process files in parallel (#167).
    let cwd_ref = &cwd;
    let search_params = ops_search::SearchFileParams {
        multiline: args.multiline,
        invert_match: args.invert_match,
        count_only,
        files_with_matches: args.files_with_matches,
        assert_count: args.assert_count,
        before_context: args.before_context,
        after_context: args.after_context,
        context: args.context,
        quiet: global.quiet,
    };
    let file_results =
        crate::par_process_files(&file_paths, glob_matcher.as_ref(), &glob_roots, |path| {
            ops_search::search_one_file(path, &matcher, &search_params, cwd_ref)
        });

    Ok(ops_search::merge_file_results(
        file_results,
        count_only,
        args.max_results,
    ))
}

pub(crate) fn format_results(
    results: SearchResults,
    args: &SearchArgs,
    global: &GlobalFlags,
) -> anyhow::Result<String> {
    use std::fmt::Write;
    let mut out = String::new();

    if global.json {
        let files: Vec<SearchFileEntry> = if args.files_with_matches {
            results
                .file_match_counts
                .keys()
                .map(|p| SearchFileEntry {
                    path: p.to_string(),
                    count: None,
                })
                .collect()
        } else if args.count {
            results
                .file_match_counts
                .iter()
                .map(|(p, c)| SearchFileEntry {
                    path: p.to_string(),
                    count: Some(*c),
                })
                .collect()
        } else {
            Vec::new()
        };
        let payload = SearchOutput {
            ok: true,
            match_count: results.file_match_counts.values().sum(),
            file_count: results.file_match_counts.len(),
            matches: results.matches,
            files,
        };
        out = serde_json::to_string_pretty(&payload)?;
        out.push('\n');
    } else if global.jsonl {
        if args.files_with_matches {
            // count_only mode: matches is empty, emit one line per file.
            for path in results.file_match_counts.keys() {
                out.push_str(&serde_json::to_string(
                    &serde_json::json!({"path": &**path}),
                )?);
                out.push('\n');
            }
        } else if args.count {
            for (path, count) in &results.file_match_counts {
                out.push_str(&serde_json::to_string(
                    &serde_json::json!({"path": &**path, "count": count}),
                )?);
                out.push('\n');
            }
        } else {
            for m in &results.matches {
                out.push_str(&serde_json::to_string(m)?);
                out.push('\n');
            }
        }
    } else if args.files_with_matches {
        let color = global.should_color();
        for path in results.file_match_counts.keys() {
            if color {
                let _ = writeln!(out, "\x1b[35m{path}\x1b[0m");
            } else {
                out.push_str(path);
                out.push('\n');
            }
        }
    } else if args.count {
        let color = global.should_color();
        for (path, count) in &results.file_match_counts {
            if color {
                let _ = writeln!(out, "\x1b[35m{path}\x1b[0m:{count}");
            } else {
                let _ = writeln!(out, "{path}:{count}");
            }
        }
    } else {
        let color = global.should_color();
        let (path_c, sep_c, ln_c, reset) = if color {
            ("\x1b[35m", "\x1b[36m", "\x1b[32m", "\x1b[0m")
        } else {
            ("", "", "", "")
        };
        let has_ctx =
            args.context.is_some() || args.before_context.is_some() || args.after_context.is_some();
        let mut prev_end: Option<(usize, usize)> = None; // (match index, last line covered)
        let mut emitted_up_to: usize = 0; // last 1-based line printed for current file
        for (mi, m) in results.matches.iter().enumerate() {
            if has_ctx {
                // Only print separator between non-contiguous groups,
                // matching standard grep/ripgrep behavior (#1111).
                let cur_start = m
                    .line
                    .saturating_sub(m.context_before.as_ref().map_or(0, |b| b.len()));
                if let Some((prev_idx, prev_last_line)) = prev_end {
                    let prev_path = &results.matches[prev_idx].path;
                    if **prev_path != *m.path {
                        emitted_up_to = 0;
                        out.push_str("--\n");
                    } else if cur_start > prev_last_line + 1 {
                        out.push_str("--\n");
                    }
                }
                let after_ctx_len = m.context_after.as_ref().map_or(0, |a| a.len());
                prev_end = Some((mi, m.line + after_ctx_len));
            }
            if let Some(ref before) = m.context_before {
                for (j, ctx) in before.iter().enumerate() {
                    let ln = m.line - before.len() + j;
                    // Skip lines already emitted by the previous match's
                    // context-after window to avoid duplicates (#1160).
                    if has_ctx && ln <= emitted_up_to {
                        continue;
                    }
                    let _ = writeln!(
                        out,
                        "{path_c}{}{reset}{sep_c}-{reset}{ln_c}{ln}{reset}{sep_c}-{reset}{ctx}",
                        m.path
                    );
                }
            }
            let _ = writeln!(
                out,
                "{path_c}{}{reset}{sep_c}:{reset}{ln_c}{}{reset}{sep_c}:{reset}{}{sep_c}:{reset}{}",
                m.path, m.line, m.column, m.text
            );
            if has_ctx {
                emitted_up_to = m.line;
            }
            if let Some(ref after) = m.context_after {
                for (j, ctx) in after.iter().enumerate() {
                    let ln = m.line + 1 + j;
                    // Skip context-after lines that will be printed as a
                    // subsequent match line to avoid duplicates (#1182).
                    let is_future_match = results.matches[mi + 1..]
                        .iter()
                        .take_while(|next| *next.path == *m.path)
                        .any(|next| next.line == ln);
                    if is_future_match {
                        continue;
                    }
                    let _ = writeln!(
                        out,
                        "{path_c}{}{reset}{sep_c}-{reset}{ln_c}{ln}{reset}{sep_c}-{reset}{ctx}",
                        m.path
                    );
                }
                if has_ctx {
                    let last_after_ln = m.line + after.len();
                    if last_after_ln > emitted_up_to {
                        emitted_up_to = last_after_ln;
                    }
                }
            }
        }
    }

    Ok(out)
}

pub fn run(args: SearchArgs, global: &GlobalFlags) -> anyhow::Result<u8> {
    if args.pattern.is_empty() {
        bail!("search pattern must not be empty");
    }
    if args.invert_match && args.multiline {
        bail!("--invert-match and --multiline cannot be combined");
    }

    let results = collect_matches(&args, global)?;

    // --assert-count mode: succeed only if total count equals N.
    if let Some(expected) = args.assert_count {
        let actual: usize = results.file_match_counts.values().sum();
        let matches = actual == expected;
        let status = if matches {
            "success"
        } else {
            "changes_detected"
        };
        let code = if matches {
            exit::SUCCESS
        } else {
            exit::CHANGES_DETECTED
        };
        if global.emit_json(&SearchAssertCountOutput {
            ok: true,
            status,
            assert_count: SearchAssertCount {
                expected,
                actual,
                matched: matches,
            },
        })? {
            return Ok(code);
        }
        if !global.quiet {
            if matches {
                eprintln!("assert-count: {actual} matches (expected {expected})");
            } else {
                eprintln!("assert-count: expected {expected} matches, found {actual}");
            }
        }
        return Ok(code);
    }

    let has_matches = if args.count || args.files_with_matches {
        !results.file_match_counts.is_empty()
    } else {
        !results.matches.is_empty()
    };
    if !has_matches {
        let payload = SearchOutput {
            ok: false,
            match_count: 0,
            file_count: 0,
            matches: vec![],
            files: vec![],
        };
        global.emit_json(&payload)?;
        if !global.quiet && !global.json && !global.jsonl {
            let path_desc = global.path_scope_description(&args.paths);
            eprintln!("no matches for '{}' in {path_desc}", args.pattern);
            if args.literal && crate::files::has_regex_metacharacters(&args.pattern) {
                eprintln!(
                    "hint: --literal is set but the pattern looks like a regex, try removing --literal"
                );
            }
            if !args.case_insensitive {
                eprintln!("hint: try -i for case-insensitive matching");
            }
        }
        return Ok(exit::NO_MATCHES);
    }

    if global.json || global.jsonl || !global.quiet {
        let output = format_results(results, &args, global)?;
        print!("{output}");
    }

    Ok(exit::SUCCESS)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn make_test_dir() -> TempDir {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("hello.txt"),
            "Hello, world!\nThis is a test file.\nHello again!\n",
        )
        .unwrap();
        fs::write(
            dir.path().join("code.rs"),
            "fn main() {\n    println!(\"hello\");\n}\n",
        )
        .unwrap();
        dir
    }

    fn make_args(pattern: &str, paths: Vec<String>) -> SearchArgs {
        SearchArgs {
            pattern: pattern.to_string(),
            paths,
            literal: false,
            regex: false,
            context: None,
            before_context: None,
            after_context: None,
            files_with_matches: false,
            count: false,
            invert_match: false,
            multiline: false,
            case_insensitive: false,
            assert_count: None,
            max_results: 0,
        }
    }

    #[test]
    fn empty_pattern_rejected() {
        let dir = make_test_dir();
        let args = make_args("", vec![dir.path().to_string_lossy().into_owned()]);
        let result = run(args, &GlobalFlags::test_default());
        let msg = result
            .expect_err("empty pattern should be rejected")
            .to_string();
        assert!(
            msg.contains("must not be empty"),
            "error should mention empty pattern: {msg}"
        );
    }

    #[test]
    fn max_results_limits_detailed_matches_but_not_counts() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.max_results = 1;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        // detailed matches capped
        assert_eq!(results.matches.len(), 1);
        // file_match_counts reflect the pre-limit collection (fixture has 2 "Hello" matches total)
        let total: usize = results.file_match_counts.values().sum();
        assert_eq!(
            total, 2,
            "counts should be full (2), not capped by max_results"
        );
    }

    #[test]
    fn max_results_with_context() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.context = Some(1);
        args.max_results = 1;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(results.matches.len(), 1);
        // context fields may be present depending on impl
    }

    #[test]
    fn max_results_does_not_affect_assert_count() {
        // Per design: assert_count uses full file_match_counts even when max_results caps detailed matches.
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.max_results = 1;
        args.assert_count = Some(2); // fixture has 2 "Hello" matches
        let code = run(args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(
            code,
            exit::SUCCESS,
            "assert should pass on full count despite max=1"
        );
    }

    #[test]
    fn literal_match_finds_expected() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.literal = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(results.matches.len(), 2);
        assert!(results.matches.iter().all(|m| m.text.contains("Hello")));
    }

    #[test]
    fn regex_match_works() {
        let dir = make_test_dir();
        let args = make_args(r"Hello.*!", vec![dir.path().to_string_lossy().into_owned()]);
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(results.matches.len(), 2);
        for m in &results.matches {
            assert!(m.text.contains("Hello"));
            assert!(m.text.ends_with('!'), "regex match should end with '!'");
        }
    }

    #[test]
    fn no_matches_returns_exit_code_3() {
        let dir = make_test_dir();
        let args = make_args(
            "zzz_no_match_zzz",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        let code = run(args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(code, exit::NO_MATCHES);
    }

    #[test]
    fn files_with_matches_output() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.files_with_matches = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        let output = format_results(results, &args, &GlobalFlags::test_default()).unwrap();
        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines.len(), 1);
        assert!(lines[0].ends_with("hello.txt"));
        // Pure paths – no colon-separated match fields after the filename
        assert!(
            lines[0].ends_with("hello.txt"),
            "expected bare path, got: {}",
            lines[0]
        );
    }

    #[test]
    fn count_output() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.count = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        let output = format_results(results, &args, &GlobalFlags::test_default()).unwrap();
        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines.len(), 1);
        assert!(lines[0].ends_with(":2"));
        assert!(lines[0].contains("hello.txt:"));
    }

    #[test]
    fn line_and_column_for_offset_maps_multiline_positions() {
        let newline_offsets = vec![2, 5];
        assert_eq!(
            ops_search::line_and_column_for_offset(&newline_offsets, 0),
            (1, 1)
        );
        assert_eq!(
            ops_search::line_and_column_for_offset(&newline_offsets, 2),
            (1, 3)
        );
        assert_eq!(
            ops_search::line_and_column_for_offset(&newline_offsets, 3),
            (2, 1)
        );
        assert_eq!(
            ops_search::line_and_column_for_offset(&newline_offsets, 6),
            (3, 1)
        );
    }

    #[test]
    fn count_only_skips_match_construction() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.count = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        // count_only optimization: matches vec should be empty
        assert!(
            results.matches.is_empty(),
            "count mode should not build SearchMatch objects"
        );
        assert_eq!(results.file_match_counts.values().sum::<usize>(), 2);
    }

    #[test]
    fn files_with_matches_skips_match_construction() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.files_with_matches = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        assert!(
            results.matches.is_empty(),
            "files_with_matches should not build SearchMatch objects"
        );
        assert_eq!(results.file_match_counts.len(), 1);
    }

    #[test]
    fn multiline_count_skips_match_construction() {
        let dir = make_test_dir();
        let mut args = make_args(
            r"fn main\(\).*\}",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        args.multiline = true;
        args.count = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        assert!(
            results.matches.is_empty(),
            "multiline count should not build SearchMatch objects"
        );
        assert_eq!(results.file_match_counts.values().sum::<usize>(), 1);
    }

    #[test]
    fn multiline_files_with_matches_stops_after_first_match() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("multi.txt"), "foo\nbar\nfoo\n").unwrap();

        let mut args = make_args("foo", vec![dir.path().to_string_lossy().into_owned()]);
        args.multiline = true;
        args.files_with_matches = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        assert!(
            results.matches.is_empty(),
            "multiline files-with-matches should not build SearchMatch objects"
        );
        assert_eq!(results.file_match_counts.values().sum::<usize>(), 1);
    }

    #[test]
    fn multiline_files_with_matches_with_assert_count_counts_all_matches() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("multi.txt"), "foo\nbar\nfoo\n").unwrap();

        let mut args = make_args("foo", vec![dir.path().to_string_lossy().into_owned()]);
        args.multiline = true;
        args.files_with_matches = true;
        args.assert_count = Some(2);
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        assert!(
            results.matches.is_empty(),
            "multiline files-with-matches assert-count should not build SearchMatch objects"
        );
        assert_eq!(results.file_match_counts.values().sum::<usize>(), 2);
    }

    #[test]
    fn invert_match_excludes_matching_lines() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.invert_match = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        // hello.txt has 3 lines, 2 match "Hello", so 1 non-matching line.
        // code.rs has 3 lines, 0 match "Hello" (case-sensitive), so 3 non-matching.
        // Total: 4 non-matching lines.
        assert_eq!(results.matches.len(), 4);
        for m in &results.matches {
            assert!(
                !m.text.contains("Hello"),
                "inverted match should not contain 'Hello': {}",
                m.text
            );
        }
    }

    #[test]
    fn multiline_match_spans_lines() {
        let dir = make_test_dir();
        let mut args = make_args(
            r"fn main\(\).*\}",
            vec![dir.path().to_string_lossy().into_owned()],
        );
        args.multiline = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(results.matches.len(), 1);
        let m = &results.matches[0];
        assert!(
            m.path.ends_with("code.rs"),
            "should match code.rs: {}",
            m.path
        );
        assert!(m.text.contains("fn main()"), "text: {}", m.text);
        assert!(
            m.text.contains('}'),
            "text should span to closing brace: {}",
            m.text
        );
        assert_eq!(m.line, 1, "match starts on line 1");
        assert_eq!(m.column, 1, "match starts at column 1");
    }

    #[test]
    fn invert_match_multiline_is_rejected() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.invert_match = true;
        args.multiline = true;
        let err = run(args, &GlobalFlags::test_default()).unwrap_err();
        assert!(
            err.to_string().contains("--invert-match and --multiline"),
            "should reject incompatible flags: {}",
            err
        );
    }

    #[test]
    fn context_lines_included_in_output() {
        let dir = make_test_dir();
        let mut args = make_args("test file", vec![dir.path().to_string_lossy().into_owned()]);
        args.context = Some(1);
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(results.matches.len(), 1);
        let m = &results.matches[0];
        let before = m
            .context_before
            .as_ref()
            .expect("should have context_before");
        assert_eq!(before.len(), 1);
        assert!(
            before[0].contains("Hello, world!"),
            "context before: {:?}",
            before
        );
        let after = m.context_after.as_ref().expect("should have context_after");
        assert_eq!(after.len(), 1);
        assert!(
            after[0].contains("Hello again!"),
            "context after: {:?}",
            after
        );
    }

    #[test]
    fn json_output_values() {
        let dir = make_test_dir();
        let args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        let mut global = GlobalFlags::test_default();
        global.json = true;
        let results = collect_matches(&args, &global).unwrap();
        let output = format_results(results, &args, &global).unwrap();
        let v: serde_json::Value = serde_json::from_str(&output).expect("valid JSON");
        assert_eq!(v["ok"], serde_json::json!(true));
        // "Hello" appears in two lines of hello.txt, one file.
        assert_eq!(v["match_count"], serde_json::json!(2));
        assert_eq!(v["file_count"], serde_json::json!(1));
        let matches = v["matches"].as_array().expect("matches is array");
        assert_eq!(matches.len(), 2);
        // Matches are ordered by line within the file.
        for m in matches {
            let path = m["path"].as_str().unwrap();
            assert!(path.ends_with("hello.txt"), "unexpected path: {path}");
            let text = m["text"].as_str().unwrap();
            assert!(text.contains("Hello"), "match text missing 'Hello': {text}");
        }
        // "Hello" appears at column 1 on lines 1 ("Hello, world!") and 3 ("Hello again!").
        assert_eq!(matches[0]["line"].as_u64().unwrap(), 1, "first match line");
        assert_eq!(
            matches[0]["column"].as_u64().unwrap(),
            1,
            "first match column"
        );
        assert_eq!(matches[1]["line"].as_u64().unwrap(), 3, "second match line");
        assert_eq!(
            matches[1]["column"].as_u64().unwrap(),
            1,
            "second match column"
        );
    }

    #[test]
    fn json_files_with_matches_lists_file_paths() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.files_with_matches = true;
        let mut global = GlobalFlags::test_default();
        global.json = true;
        let results = collect_matches(&args, &global).unwrap();
        let output = format_results(results, &args, &global).unwrap();
        let v: serde_json::Value = serde_json::from_str(&output).expect("valid JSON");
        assert_eq!(v["ok"], serde_json::json!(true));
        assert_eq!(v["file_count"], serde_json::json!(1));
        // matches is empty in files-with-matches mode (by design).
        assert_eq!(v["matches"].as_array().unwrap().len(), 0);
        // files array must contain the matching file paths.
        let files = v["files"].as_array().expect("files array must be present");
        assert_eq!(files.len(), 1);
        assert!(files[0]["path"].as_str().unwrap().ends_with("hello.txt"));
    }

    #[test]
    fn json_count_lists_file_counts() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.count = true;
        let mut global = GlobalFlags::test_default();
        global.json = true;
        let results = collect_matches(&args, &global).unwrap();
        let output = format_results(results, &args, &global).unwrap();
        let v: serde_json::Value = serde_json::from_str(&output).expect("valid JSON");
        assert_eq!(v["ok"], serde_json::json!(true));
        // files array must contain the per-file counts.
        let files = v["files"].as_array().expect("files array must be present");
        assert_eq!(files.len(), 1);
        assert!(files[0]["path"].as_str().unwrap().ends_with("hello.txt"));
        assert_eq!(files[0]["count"], serde_json::json!(2));
    }

    #[test]
    fn case_insensitive_finds_all_cases() {
        let dir = make_test_dir();
        // hello.txt has "Hello" (uppercase H); code.rs has "hello" (lowercase).
        let mut args = make_args("hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.case_insensitive = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        // hello.txt: 2 lines with "Hello", code.rs: 1 line with "hello" => 3
        assert_eq!(results.matches.len(), 3);
    }

    #[test]
    fn case_insensitive_literal_escapes_regex_chars() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("special.txt"), "foo(BAR)\nbaz\n").unwrap();

        let mut args = make_args("foo(bar)", vec![dir.path().to_string_lossy().into_owned()]);
        args.literal = true;
        args.case_insensitive = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(results.matches.len(), 1);
        assert!(results.matches[0].text.contains("foo(BAR)"));
    }

    #[test]
    fn invert_match_count_counts_non_matching_lines() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.invert_match = true;
        args.count = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        // count mode should not build SearchMatch objects
        assert!(results.matches.is_empty());
        // hello.txt: 3 lines, 2 match "Hello", so 1 non-matching.
        // code.rs: 3 lines, 0 match, so 3 non-matching.
        assert_eq!(results.file_match_counts.values().sum::<usize>(), 4);
    }

    #[test]
    fn invert_match_files_with_matches_lists_files_with_non_matching_lines() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.invert_match = true;
        args.files_with_matches = true;
        let results = collect_matches(&args, &GlobalFlags::test_default()).unwrap();
        assert!(results.matches.is_empty());
        // Both files have non-matching lines.
        assert_eq!(results.file_match_counts.len(), 2);
    }

    #[test]
    fn invert_match_assert_count_exact() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.invert_match = true;
        args.assert_count = Some(4); // 1 from hello.txt + 3 from code.rs
        let code = run(args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(code, exit::SUCCESS);
    }

    #[test]
    fn invert_match_assert_count_mismatch() {
        let dir = make_test_dir();
        let mut args = make_args("Hello", vec![dir.path().to_string_lossy().into_owned()]);
        args.invert_match = true;
        args.assert_count = Some(99);
        let code = run(args, &GlobalFlags::test_default()).unwrap();
        assert_eq!(code, exit::CHANGES_DETECTED);
    }

    /// Overlapping context windows must not produce duplicate lines (#1160).
    #[test]
    fn context_no_duplicate_lines() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("close.txt"),
            "line1\nmatch_a\nline3\nmatch_b\nline5\n",
        )
        .unwrap();
        let mut args = make_args("match", vec![dir.path().to_string_lossy().into_owned()]);
        args.context = Some(1);
        let global = GlobalFlags::test_default();
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);
    }

    /// Verify plain-text context output does not repeat lines between
    /// close matches (regression for #1160).
    #[test]
    fn context_plain_text_no_repeated_lines() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("close.txt");
        fs::write(&file, "line1\nmatch_a\nline3\nmatch_b\nline5\n").unwrap();
        let mut args = make_args("match", vec![file.to_string_lossy().into_owned()]);
        args.context = Some(1);
        let global = GlobalFlags::test_default();
        let output =
            format_results(collect_matches(&args, &global).unwrap(), &args, &global).unwrap();
        // "line3" should appear exactly once, not twice.
        let count = output.matches("line3").count();
        assert_eq!(count, 1, "line3 should appear once, got: {output}");
    }

    #[test]
    fn context_after_not_duplicated_for_adjacent_matches() {
        // #1182: When two matches are on adjacent lines, the context-after
        // of match A includes match B's line. That line must NOT appear
        // twice (once as context, once as match).
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("adj.txt");
        fs::write(&file, "line1\nmatch_a\nmatch_b\nline4\n").unwrap();
        let mut args = make_args("match", vec![file.to_string_lossy().into_owned()]);
        args.context = Some(1);
        let global = GlobalFlags::test_default();
        let output =
            format_results(collect_matches(&args, &global).unwrap(), &args, &global).unwrap();
        // "match_b" should appear exactly once (as a match line).
        let count = output.matches("match_b").count();
        assert_eq!(
            count, 1,
            "match_b should appear once, got {count}: {output}"
        );
    }
}