patchloom 0.31.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
use super::execute::TxState;
use super::output::{TxSearchMatch, TxSearchResult};
use crate::plan::Operation;

use std::path::{Path, PathBuf};

/// Execute a search operation within a transaction.
///
/// If `path` is a directory, walks it in parallel (respecting `.gitignore`)
/// and searches each non-binary file, mirroring the standalone `search`
/// command. Scanned files are not inserted into pending unless a prior write
/// already staged them.
pub(crate) fn execute_search_op(op: &Operation, tx: &mut TxState<'_>) -> anyhow::Result<()> {
    crate::verbose!(
        "search_op: path={}, pattern_len={}, regex={}, case_insensitive={}",
        if let Operation::Search { path, .. } = op {
            path.as_str()
        } else {
            "<unknown>"
        },
        if let Operation::Search { pattern, .. } = op {
            pattern.len()
        } else {
            0
        },
        matches!(op, Operation::Search { regex: true, .. }),
        matches!(
            op,
            Operation::Search {
                case_insensitive: true,
                ..
            }
        ),
    );
    let Operation::Search {
        path,
        pattern,
        regex,
        case_insensitive,
        multiline,
        invert_match,
        context,
        before_context,
        after_context,
        assert_count,
        literal,
        globs,
        max_results,
        exclude_patterns,
        custom_ignore_filenames,
    } = op
    else {
        anyhow::bail!("execute_search_op called with non-Search operation")
    };

    if *invert_match && *multiline {
        return Err(crate::exit::InvalidInputError {
            msg: "invert_match and multiline cannot be combined".into(),
        }
        .into());
    }
    if *literal && *regex {
        return Err(crate::exit::InvalidInputError {
            msg: "search: literal and regex cannot be combined".into(),
        }
        .into());
    }

    // Treat pattern as literal text only when explicitly requested.
    // Default (both literal=false, regex=false) is regex to match CLI
    // and MCP behavior.
    let pat = if *literal {
        regex::escape(pattern)
    } else {
        pattern.clone()
    };
    let re = {
        let mut builder = crate::bounded_regex_builder(&pat);
        builder.case_insensitive(*case_insensitive);
        builder.multi_line(true);
        builder.dot_matches_new_line(*multiline);
        crate::bounded_regex_build(&mut builder)?
    };

    let ctx_before = before_context.or(*context).unwrap_or(0);
    let ctx_after = after_context.or(*context).unwrap_or(0);

    let resolved = tx.cwd.join(path);
    let is_dir = resolved.is_dir();
    // Parallel collect (same WalkBuilder::build_parallel engine as CLI) when
    // the files/cli walker is available. Search is read-only: do not insert
    // scanned files into pending unless a prior write already staged them.
    #[cfg(any(feature = "cli", feature = "files"))]
    let candidate_paths: Vec<PathBuf> = if is_dir {
        crate::files::collect_file_paths_with_ignores(
            &resolved,
            custom_ignore_filenames,
            exclude_patterns,
            false,
        )?
    } else {
        vec![resolved.clone()]
    };
    #[cfg(not(any(feature = "cli", feature = "files")))]
    let candidate_paths: Vec<PathBuf> = if is_dir {
        let mut paths = Vec::new();
        for entry in WalkBuilder::new(&resolved).build() {
            let entry = entry?;
            if entry.file_type().is_some_and(|ft| ft.is_file()) {
                paths.push(entry.into_path());
            }
        }
        paths.sort();
        paths
    } else {
        vec![resolved.clone()]
    };

    let glob_matcher = crate::files::build_glob_matcher(globs)?;
    // glob_roots used for relative glob matching; use the search root (dir or parent of file)
    let glob_root = if is_dir {
        resolved.clone()
    } else {
        resolved.parent().unwrap_or(&resolved).to_path_buf()
    };
    let glob_roots = vec![glob_root];

    let file_paths: Vec<PathBuf> = if let Some(m) = &glob_matcher {
        candidate_paths
            .into_iter()
            .filter(|p| crate::files::matches_glob_with_roots(p, Some(m), &glob_roots))
            .collect()
    } else {
        candidate_paths
    };

    let is_multi_file = file_paths.len() > 1;
    let scan = TxSearchScan {
        cwd: tx.cwd,
        is_multi_file,
        re: &re,
        invert_match: *invert_match,
        multiline: *multiline,
        ctx_before,
        ctx_after,
    };
    let mut all_matches = Vec::new();

    let mut pending_paths = Vec::new();
    let mut disk_paths = Vec::new();
    for file_path in &file_paths {
        if tx.pending.contains_key(file_path) {
            pending_paths.push(file_path);
        } else {
            disk_paths.push(file_path.clone());
        }
    }

    // Already-staged writes: search the in-tx buffer, leave pending as-is.
    for file_path in pending_paths {
        let content = &tx.pending[file_path].1;
        all_matches.extend(collect_tx_search_matches(content, file_path, &scan));
    }

    if is_dir {
        #[cfg(any(feature = "cli", feature = "files"))]
        {
            let disk_results: Vec<anyhow::Result<Vec<TxSearchMatch>>> =
                crate::files::par_process_files(&disk_paths, None, &[], |file_path| {
                    match search_disk_file(file_path, true, &scan) {
                        Ok(ms) if ms.is_empty() => None,
                        other => Some(other),
                    }
                });
            for result in disk_results {
                all_matches.extend(result?);
            }
        }
        #[cfg(not(any(feature = "cli", feature = "files")))]
        {
            for file_path in &disk_paths {
                all_matches.extend(search_disk_file(file_path, true, &scan)?);
            }
        }
    } else {
        for file_path in &disk_paths {
            all_matches.extend(search_disk_file(file_path, false, &scan)?);
        }
    }

    // Validate assert_count against the true total before truncation.
    let total_match_count = all_matches.len();

    if let Some(expected) = assert_count
        && total_match_count != *expected
    {
        // CLI search --assert-count mismatch is CHANGES_DETECTED (2), not a
        // hard operation_failed. Keep the same exit for plan/tx.
        return Err(crate::exit::ChangesDetectedError {
            msg: format!(
                "search assert_count: expected {expected} matches for '{pattern}' in {path}, found {total_match_count}"
            ),
        }
        .into());
    }

    // Cap after assertion check. match_count is the true total (honesty).
    let truncated = *max_results > 0 && all_matches.len() > *max_results;
    if *max_results > 0 {
        all_matches.truncate(*max_results);
    }

    tx.tx_searches.push(TxSearchResult {
        path: path.clone(),
        pattern: pattern.clone(),
        match_count: total_match_count,
        matches: all_matches,
        truncated,
    });
    Ok(())
}

/// Shared match options for one search op (avoids 9-arg helpers).
struct TxSearchScan<'a> {
    cwd: &'a Path,
    is_multi_file: bool,
    re: &'a regex::Regex,
    invert_match: bool,
    multiline: bool,
    ctx_before: usize,
    ctx_after: usize,
}

/// Search `content` without touching tx pending.
fn collect_tx_search_matches(
    content: &str,
    file_path: &Path,
    scan: &TxSearchScan<'_>,
) -> Vec<TxSearchMatch> {
    let lines: Vec<&str> = content.lines().collect();
    let mut matches = Vec::new();
    if scan.multiline {
        for m in scan.re.find_iter(content) {
            let line_idx = content[..m.start()].matches('\n').count();
            let match_end_line = line_idx + m.as_str().matches('\n').count();
            let start = line_idx.saturating_sub(scan.ctx_before);
            let end = (match_end_line + 1 + scan.ctx_after).min(lines.len());
            let matched_text = m.as_str().to_string();
            let text = if scan.is_multi_file {
                let display_path = file_path
                    .strip_prefix(scan.cwd)
                    .unwrap_or(file_path)
                    .to_string_lossy();
                format!("{display_path}:{matched_text}")
            } else {
                matched_text
            };
            let col = m.start() - content[..m.start()].rfind('\n').map_or(0, |p| p + 1);
            matches.push(TxSearchMatch {
                line: line_idx + 1,
                column: col + 1,
                text,
                context_before: lines[start..line_idx.min(lines.len())]
                    .iter()
                    .map(|s| s.to_string())
                    .collect(),
                context_after: if match_end_line + 1 < lines.len() {
                    lines[match_end_line + 1..end]
                        .iter()
                        .map(|s| s.to_string())
                        .collect()
                } else {
                    vec![]
                },
            });
        }
    } else {
        for (i, line) in lines.iter().enumerate() {
            let found = scan.re.find(line);
            let is_match = if scan.invert_match {
                found.is_none()
            } else {
                found.is_some()
            };
            if is_match {
                let start = i.saturating_sub(scan.ctx_before);
                let end = (i + 1 + scan.ctx_after).min(lines.len());
                let text = if scan.is_multi_file {
                    let display_path = file_path
                        .strip_prefix(scan.cwd)
                        .unwrap_or(file_path)
                        .to_string_lossy();
                    format!("{display_path}:{line}")
                } else {
                    line.to_string()
                };
                let column = found.map_or(1, |m| m.start() + 1);
                matches.push(TxSearchMatch {
                    line: i + 1,
                    column,
                    text,
                    context_before: lines[start..i].iter().map(|s| s.to_string()).collect(),
                    context_after: lines[i + 1..end].iter().map(|s| s.to_string()).collect(),
                });
            }
        }
    }
    matches
}

/// Load from disk into a stack buffer. Directory walks soft-skip non-text;
/// sole-path search stays strict.
fn search_disk_file(
    file_path: &Path,
    is_dir_walk: bool,
    scan: &TxSearchScan<'_>,
) -> anyhow::Result<Vec<TxSearchMatch>> {
    let content = if is_dir_walk {
        match crate::files::try_read_text_file(file_path) {
            Ok(s) => s,
            Err(
                crate::files::SoftTextSkip::Binary
                | crate::files::SoftTextSkip::InvalidUtf8
                | crate::files::SoftTextSkip::NotRegularFile,
            ) => return Ok(Vec::new()),
            Err(crate::files::SoftTextSkip::Unreadable) => {
                return match std::fs::read(file_path) {
                    Ok(_) => Err(anyhow::anyhow!("failed to read {}", file_path.display())),
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                        Err(anyhow::Error::new(e)
                            .context(format!("failed to read {}", file_path.display())))
                    }
                    Err(e) => Err(crate::exit::InvalidInputError {
                        msg: format!("failed to read {}: {e}", file_path.display()),
                    }
                    .into()),
                };
            }
        }
    } else {
        let display = file_path.display().to_string();
        crate::files::load_text_strict(file_path, &display)?
    };
    Ok(collect_tx_search_matches(&content, file_path, scan))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tx::TxStateFixture;
    use tempfile::TempDir;

    fn search_op(path: &str, pattern: &str) -> Operation {
        Operation::Search {
            path: path.into(),
            pattern: pattern.into(),
            regex: false,
            case_insensitive: false,
            multiline: false,
            invert_match: false,
            context: None,
            before_context: None,
            after_context: None,
            assert_count: None,
            literal: false,
            globs: Vec::new(),
            max_results: 0,
            exclude_patterns: Vec::new(),
            custom_ignore_filenames: Vec::new(),
        }
    }

    #[test]
    fn search_literal_match() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "line one\nline two\nline three\n").unwrap();

        let op = search_op("test.txt", "two");

        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        assert_eq!(f.searches.len(), 1);
        assert_eq!(f.searches[0].match_count, 1);
        assert_eq!(f.searches[0].matches[0].line, 2);
    }

    #[test]
    fn search_no_match() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "hello world\n").unwrap();

        let op = search_op("test.txt", "nonexistent");

        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        assert_eq!(f.searches[0].match_count, 0);
    }

    #[test]
    fn search_regex_mode() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "foo123\nbar456\n").unwrap();

        let op = Operation::Search {
            path: "test.txt".into(),
            pattern: r"\d+".into(),
            regex: true,
            case_insensitive: false,
            multiline: false,
            invert_match: false,
            context: None,
            before_context: None,
            after_context: None,
            assert_count: None,
            literal: false,
            globs: Vec::new(),
            max_results: 0,
            exclude_patterns: Vec::new(),
            custom_ignore_filenames: Vec::new(),
        };

        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        assert_eq!(f.searches[0].match_count, 2);
    }

    #[test]
    fn search_case_insensitive() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "Hello World\n").unwrap();

        let op = Operation::Search {
            path: "test.txt".into(),
            pattern: "hello".into(),
            regex: false,
            case_insensitive: true,
            multiline: false,
            invert_match: false,
            context: None,
            before_context: None,
            after_context: None,
            assert_count: None,
            literal: false,
            globs: Vec::new(),
            max_results: 0,
            exclude_patterns: Vec::new(),
            custom_ignore_filenames: Vec::new(),
        };

        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        assert_eq!(f.searches[0].match_count, 1);
    }

    #[test]
    fn search_invert_match() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "keep\nskip this\nkeep too\n").unwrap();

        let op = Operation::Search {
            path: "test.txt".into(),
            pattern: "skip".into(),
            regex: false,
            case_insensitive: false,
            multiline: false,
            invert_match: true,
            context: None,
            before_context: None,
            after_context: None,
            assert_count: None,
            literal: false,
            globs: Vec::new(),
            max_results: 0,
            exclude_patterns: Vec::new(),
            custom_ignore_filenames: Vec::new(),
        };

        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        assert_eq!(f.searches[0].match_count, 2); // "keep" and "keep too"
    }

    #[test]
    fn search_assert_count_mismatch_errors() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "one match\n").unwrap();

        let op = Operation::Search {
            path: "test.txt".into(),
            pattern: "match".into(),
            regex: false,
            case_insensitive: false,
            multiline: false,
            invert_match: false,
            context: None,
            before_context: None,
            after_context: None,
            assert_count: Some(5), // expect 5 but only 1 exists
            literal: false,
            globs: Vec::new(),
            max_results: 0,
            exclude_patterns: Vec::new(),
            custom_ignore_filenames: Vec::new(),
        };

        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        let result = execute_search_op(&op, &mut tx);
        assert!(result.is_err(), "expected error, got Ok: {result:?}");
        assert!(result.unwrap_err().to_string().contains("assert_count"));
    }

    #[test]
    fn search_literal_and_regex_combined_errors() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("test.txt"), "content").unwrap();

        let op = Operation::Search {
            path: "test.txt".into(),
            pattern: "x".into(),
            regex: true,
            case_insensitive: false,
            multiline: false,
            invert_match: false,
            context: None,
            before_context: None,
            after_context: None,
            assert_count: None,
            literal: true,
            globs: Vec::new(),
            max_results: 0,
            exclude_patterns: Vec::new(),
            custom_ignore_filenames: Vec::new(),
        };

        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        let result = execute_search_op(&op, &mut tx);
        result.expect_err("expected error");
    }

    #[test]
    fn search_with_context() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "aaa\nbbb\nccc\nddd\neee\n").unwrap();

        let op = Operation::Search {
            path: "test.txt".into(),
            pattern: "ccc".into(),
            regex: false,
            case_insensitive: false,
            multiline: false,
            invert_match: false,
            context: None,
            before_context: Some(1),
            after_context: Some(1),
            assert_count: None,
            literal: false,
            globs: Vec::new(),
            max_results: 0,
            exclude_patterns: Vec::new(),
            custom_ignore_filenames: Vec::new(),
        };

        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        let m = &f.searches[0].matches[0];
        assert_eq!(m.line, 3);
        assert_eq!(m.context_before, vec!["bbb"]);
        assert_eq!(m.context_after, vec!["ddd"]);
    }

    #[test]
    fn search_max_results_cap() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "aaa\naaa\naaa\naaa\naaa\n").unwrap();

        let op = Operation::Search {
            path: "test.txt".into(),
            pattern: "aaa".into(),
            regex: false,
            case_insensitive: false,
            multiline: false,
            invert_match: false,
            context: None,
            before_context: None,
            after_context: None,
            assert_count: None,
            literal: false,
            globs: Vec::new(),
            max_results: 2,
            exclude_patterns: Vec::new(),
            custom_ignore_filenames: Vec::new(),
        };

        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        // match_count reports the true total (5 matches), not the truncated count
        assert_eq!(f.searches[0].match_count, 5);
        // matches vec is truncated to max_results
        assert_eq!(f.searches[0].matches.len(), 2);
        assert!(
            f.searches[0].truncated,
            "agents must see truncated when matches are capped"
        );
    }

    #[test]
    fn search_assert_count_checks_before_max_results_truncation() {
        // File has 3 matches. assert_count=3 should pass even with max_results=1.
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "foo\nfoo\nfoo\n").unwrap();

        let op = Operation::Search {
            path: "test.txt".into(),
            pattern: "foo".into(),
            regex: false,
            case_insensitive: false,
            multiline: false,
            invert_match: false,
            context: None,
            before_context: None,
            after_context: None,
            assert_count: Some(3),
            literal: false,
            globs: Vec::new(),
            max_results: 1,
            exclude_patterns: Vec::new(),
            custom_ignore_filenames: Vec::new(),
        };

        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        // match_count reports the true total, not the truncated count
        assert_eq!(f.searches[0].match_count, 3);
        // matches is truncated to max_results
        assert_eq!(f.searches[0].matches.len(), 1);
    }

    #[test]
    fn search_multiline_context_at_eof_no_panic() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        // File ending with newline; regex matching at end-of-string
        std::fs::write(&file, "hello\nworld\n").unwrap();

        let op = Operation::Search {
            path: "test.txt".into(),
            pattern: "world".into(),
            regex: true,
            context: Some(2),
            before_context: None,
            after_context: None,
            max_results: 0,
            case_insensitive: false,
            invert_match: false,
            multiline: true,
            assert_count: None,
            literal: false,
            globs: vec![],
            exclude_patterns: vec![],
            custom_ignore_filenames: vec![],
        };

        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        // Should not panic even when match is near end of file
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        assert_eq!(f.searches[0].match_count, 1);
    }

    #[test]
    fn search_default_mode_is_regex_not_literal() {
        // Regression: when both literal=false and regex=false (defaults),
        // the pattern should be treated as regex, matching CLI/MCP behavior.
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "fooXbar\nfoo.bar\n").unwrap();

        // Pattern "foo.bar" should match both lines (dot is regex wildcard)
        let op = search_op("test.txt", "foo.bar");
        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        assert_eq!(
            f.searches[0].match_count, 2,
            "regex dot should match any char, yielding 2 matches"
        );
    }

    #[test]
    fn search_multiline_context_after_excludes_match_lines() {
        // Regression: context_after should start after the last line of
        // a multiline match, not after the first line.
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        std::fs::write(&file, "aaa\nbbb\nccc\nddd\neee\nfff\n").unwrap();

        let op = Operation::Search {
            path: "test.txt".into(),
            pattern: "bbb\nccc\nddd".into(),
            regex: true,
            case_insensitive: false,
            multiline: true,
            invert_match: false,
            context: None,
            before_context: None,
            after_context: Some(1),
            assert_count: None,
            literal: false,
            globs: Vec::new(),
            max_results: 0,
            exclude_patterns: Vec::new(),
            custom_ignore_filenames: Vec::new(),
        };
        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        assert_eq!(f.searches[0].match_count, 1);
        let ctx_after = &f.searches[0].matches[0].context_after;
        assert_eq!(
            ctx_after,
            &["eee"],
            "context_after should be the line after the match, not a match line"
        );
    }

    #[test]
    fn search_only_does_not_insert_into_pending() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("a.txt"), "alpha\n").unwrap();
        std::fs::write(dir.path().join("b.txt"), "beta\n").unwrap();

        let op = search_op(".", "alpha");
        let mut f = TxStateFixture::new();
        let mut tx = f.state(dir.path());
        execute_search_op(&op, &mut tx).unwrap();
        drop(tx);
        assert_eq!(f.searches[0].match_count, 1);
        assert!(
            f.pending.is_empty(),
            "search-only files must not stay in pending: {:?}",
            f.pending.keys().collect::<Vec<_>>()
        );
        assert!(
            f.existed_before.is_empty() && f.write_targets.is_empty(),
            "search-only must not mark write/existed_before"
        );
    }

    #[test]
    fn search_uses_already_pending_content() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("staged.txt");
        std::fs::write(&file, "disk only\n").unwrap();

        let op = search_op("staged.txt", "pending");
        let mut f = TxStateFixture::new();
        f.pending
            .insert(file.clone(), ("disk only\n".into(), "pending hit\n".into()));
        f.existed_before.insert(file.clone());
        f.write_targets.insert(file.clone());
        {
            let mut tx = f.state(dir.path());
            execute_search_op(&op, &mut tx).unwrap();
        }
        assert_eq!(
            f.searches[0].match_count, 1,
            "search must see in-tx pending content, not disk"
        );
        assert_eq!(f.pending.len(), 1, "must not add extra pending entries");
        assert_eq!(f.pending[&file].1, "pending hit\n");
    }
}