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
//! Text replacement operations for the public library API.
//!
//! Delegates to the tx engine via `execute_as_edit_result`.

use std::path::Path;

use crate::containment::PathGuard;
use crate::plan::Operation;

use super::{ApplyMode, ContentEditResult, EditResult, ReplaceOptions};

/// Replace text in a file using literal or regex matching.
///
/// When `opts.insert_before` or `opts.insert_after` is set, the matched text
/// is preserved and the insertion is added adjacent to it.
pub fn replace_text(
    path: &Path,
    from: &str,
    to: &str,
    opts: &ReplaceOptions,
    mode: ApplyMode,
    guard: Option<&PathGuard>,
) -> anyhow::Result<EditResult> {
    // Pre-validate before building the Operation.
    if from.is_empty() && !opts.regex {
        anyhow::bail!("empty search pattern");
    }
    if opts.range.is_some() && !opts.whole_line {
        anyhow::bail!("range requires whole_line to be true");
    }
    if opts.whole_line && opts.multiline {
        anyhow::bail!("whole_line and multiline cannot be combined");
    }

    let range_str = opts.range.map(|(start, end)| {
        if let Some(e) = end {
            format!("{start}:{e}")
        } else {
            format!("{start}:")
        }
    });
    let op = Operation::Replace {
        glob: None,
        path: Some(path.to_string_lossy().into()),
        regex: opts.regex,
        old: from.into(),
        new_text: Some(to.into()),
        nth: opts.nth,
        insert_before: opts.insert_before.clone(),
        insert_after: opts.insert_after.clone(),
        case_insensitive: opts.case_insensitive,
        multiline: opts.multiline,
        if_exists: opts.if_exists,
        whole_line: opts.whole_line,
        range: range_str,
        word_boundary: opts.word_boundary,
        before_context: opts.before_context.clone(),
        after_context: opts.after_context.clone(),
        unique: opts.unique,
    };
    replace_write(op, path, mode, guard, opts.fuzzy)
}

/// Unified write path for replace operations.
#[cfg(any(feature = "cli", feature = "files"))]
fn replace_write(
    op: Operation,
    path: &Path,
    mode: ApplyMode,
    guard: Option<&PathGuard>,
    _fuzzy: bool,
) -> anyhow::Result<EditResult> {
    let cwd = path.parent().unwrap_or_else(|| Path::new("."));
    super::execute_as_edit_result(op, mode, cwd, guard, "replace", None)
}

#[cfg(not(any(feature = "cli", feature = "files")))]
fn replace_write(
    op: Operation,
    path: &Path,
    mode: ApplyMode,
    guard: Option<&PathGuard>,
    fuzzy: bool,
) -> anyhow::Result<EditResult> {
    use crate::ops;
    use anyhow::{Context, bail};

    // Fallback for no-cli/files builds: delegate to ops layer directly.
    if let Operation::Replace {
        old,
        new_text,
        regex: regex_mode,
        insert_before,
        insert_after,
        case_insensitive,
        multiline,
        if_exists,
        whole_line,
        range,
        word_boundary,
        nth,
        unique,
        before_context,
        after_context,
        ..
    } = op
    {
        let path_str = path.to_string_lossy();
        let original = std::fs::read_to_string(path)
            .with_context(|| format!("failed to read {}", path.display()))?;

        let is_regex = regex_mode;
        if old.is_empty() && !is_regex {
            bail!("empty search pattern");
        }

        let compiled_re = ops::replace::compile_replace_regex(
            &old,
            is_regex,
            case_insensitive,
            multiline,
            word_boundary,
        )?;

        let direct_to = if insert_before.is_none() && insert_after.is_none() {
            new_text.clone()
        } else {
            None
        };
        let replacement = ops::replace::replacement_text(
            &old,
            &direct_to,
            &insert_before,
            &insert_after,
            compiled_re.is_some(),
            is_regex,
        );

        let parsed_range = range.as_deref().map(|r| {
            let parts: Vec<&str> = r.splitn(2, ':').collect();
            let start: usize = parts[0].parse().unwrap_or(1);
            let end: Option<usize> = parts
                .get(1)
                .and_then(|s| if s.is_empty() { None } else { s.parse().ok() });
            (start, end)
        });

        let (new_content, count) = if whole_line {
            ops::replace::replace_whole_lines(
                &original,
                &old,
                &replacement,
                compiled_re.as_ref(),
                nth,
                parsed_range,
            )
        } else {
            ops::replace::replace_content(&original, &old, &replacement, compiled_re.as_ref(), nth)
        };

        // Context disambiguation: when multiple exact matches and context is
        // provided, select the match nearest to the context instead of
        // replacing all (mirrors tx engine logic in replace_op.rs).
        if count > 1
            && nth.is_none()
            && !whole_line
            && !is_regex
            && (before_context.is_some() || after_context.is_some())
        {
            if let Some(target_offset) = ops::replace::context_filtered_offset(
                &original,
                &old,
                before_context.as_deref(),
                after_context.as_deref(),
            ) {
                let ctx_content = format!(
                    "{}{}{}",
                    &original[..target_offset],
                    &replacement,
                    &original[target_offset + old.len()..],
                );
                let policy = crate::write::WritePolicy::default();
                let applied = super::write_if_apply(path, &ctx_content, mode, &policy, guard)?;
                let mut result = super::build_edit_result(
                    &path_str,
                    original,
                    ctx_content,
                    applied,
                    "replace",
                    None,
                );
                result.match_count = 1;
                return Ok(result);
            }
        }

        let new_content = new_content.into_owned();

        // Note: context disambiguation runs BEFORE unique, so context can
        // resolve ambiguity even with unique=true. This diverges from the tx
        // engine (which bails on unique before context), but is intentional:
        // context-resolved results are unambiguous by definition.
        if unique && count > 1 {
            bail!(
                "ambiguous match: pattern {:?} matches {} times; provide more context to disambiguate",
                old,
                count
            );
        }

        // Fuzzy/context fallback: when exact match fails and fuzzy or context
        // is enabled, try resolve_with_fallback for anchor/similarity matching
        // (mirrors tx engine fallback in replace_op.rs).
        if count == 0 && !is_regex && (fuzzy || before_context.is_some() || after_context.is_some())
        {
            use crate::fallback;
            match fallback::resolve_with_fallback(
                &original,
                &old,
                before_context.as_deref(),
                after_context.as_deref(),
            ) {
                Ok(anchor) => {
                    let to_text = if let Some(ib) = &insert_before {
                        format!("{}{}", ib, anchor.matched_text)
                    } else if let Some(ia) = &insert_after {
                        format!("{}{}", anchor.matched_text, ia)
                    } else {
                        new_text.as_deref().unwrap_or("").to_string()
                    };
                    let fb_content = format!(
                        "{}{}{}",
                        &original[..anchor.start_offset],
                        to_text,
                        &original[anchor.start_offset + anchor.matched_text.len()..],
                    );
                    let policy = crate::write::WritePolicy::default();
                    let applied = super::write_if_apply(path, &fb_content, mode, &policy, guard)?;
                    let mut result = super::build_edit_result(
                        &path_str, original, fb_content, applied, "replace", None,
                    );
                    result.match_count = 1;
                    return Ok(result);
                }
                Err(edit_error) => {
                    if if_exists {
                        return Ok(super::build_edit_result(
                            &path_str,
                            original.clone(),
                            original,
                            false,
                            "replace",
                            None,
                        ));
                    }
                    let similar = fallback::find_similar_targets(&original, &old, 3);
                    let mut msg = format!("no matches for {:?}", old);
                    if let Some(suggestion) = &edit_error.suggestion {
                        msg.push_str(&format!(" (suggestion: {})", suggestion));
                    }
                    if !similar.is_empty() {
                        msg.push_str(&format!(" (did you mean: {}?)", similar.join(", ")));
                    }
                    bail!("{msg}");
                }
            }
        }

        if count == 0 && if_exists {
            return Ok(super::build_edit_result(
                &path_str,
                original.clone(),
                original,
                false,
                "replace",
                None,
            ));
        }

        let policy = crate::write::WritePolicy::default();
        let applied = super::write_if_apply(path, &new_content, mode, &policy, guard)?;
        let mut result =
            super::build_edit_result(&path_str, original, new_content, applied, "replace", None);
        result.match_count = count;
        Ok(result)
    } else {
        bail!("expected Replace operation")
    }
}

/// Replace text in a content string (no disk I/O).
///
/// Applies the same replacement logic as [`replace_text`] but operates on an
/// in-memory string instead of a file path. Supports all [`ReplaceOptions`]
/// features: regex, word boundary, nth, case insensitive, multiline,
/// insert_before/after, whole_line, range, if_exists, unique, fuzzy,
/// before_context, and after_context.
pub fn replace_in_content(
    content: &str,
    from: &str,
    to: &str,
    opts: &ReplaceOptions,
) -> anyhow::Result<ContentEditResult> {
    use crate::ops;
    use anyhow::bail;

    let is_regex = opts.regex;
    if from.is_empty() && !is_regex {
        bail!("empty search pattern");
    }
    if opts.range.is_some() && !opts.whole_line {
        bail!("range requires whole_line to be true");
    }
    if opts.whole_line && opts.multiline {
        bail!("whole_line and multiline cannot be combined");
    }

    let compiled_re = ops::replace::compile_replace_regex(
        from,
        is_regex,
        opts.case_insensitive,
        opts.multiline,
        opts.word_boundary,
    )?;

    let direct_to = if opts.insert_before.is_none() && opts.insert_after.is_none() {
        Some(to.to_string())
    } else {
        None
    };
    let replacement = ops::replace::replacement_text(
        from,
        &direct_to,
        &opts.insert_before,
        &opts.insert_after,
        compiled_re.is_some(),
        is_regex,
    );

    let parsed_range = opts.range;

    let (new_content, count) = if opts.whole_line {
        ops::replace::replace_whole_lines(
            content,
            from,
            &replacement,
            compiled_re.as_ref(),
            opts.nth,
            parsed_range,
        )
    } else {
        ops::replace::replace_content(content, from, &replacement, compiled_re.as_ref(), opts.nth)
    };

    // Context disambiguation (#1315): when multiple exact matches and context
    // is provided, select the match nearest to the context instead of
    // replacing all (mirrors replace_write and tx engine logic).
    if count > 1
        && opts.nth.is_none()
        && !opts.whole_line
        && !is_regex
        && (opts.before_context.is_some() || opts.after_context.is_some())
        && let Some(target_offset) = ops::replace::context_filtered_offset(
            content,
            from,
            opts.before_context.as_deref(),
            opts.after_context.as_deref(),
        )
    {
        let ctx_content = format!(
            "{}{}{}",
            &content[..target_offset],
            replacement,
            &content[target_offset + from.len()..],
        );
        let diff = super::make_diff("<content>", content, &ctx_content);
        return Ok(ContentEditResult {
            original: content.to_string(),
            new_content: ctx_content,
            diff,
            changed: true,
            match_count: 1,
        });
    }

    let new_content = new_content.into_owned();

    if opts.unique && count > 1 {
        anyhow::bail!(
            "ambiguous match: pattern {:?} matches {} times; provide more context to disambiguate",
            from,
            count
        );
    }

    // Fuzzy/context fallback (#1286, #1315): when exact match fails and fuzzy
    // or context is enabled, try resolve_with_fallback for anchor/similarity
    // matching (matches replace_write and tx engine behavior).
    if count == 0
        && !is_regex
        && (opts.fuzzy || opts.before_context.is_some() || opts.after_context.is_some())
    {
        use crate::fallback;
        match fallback::resolve_with_fallback(
            content,
            from,
            opts.before_context.as_deref(),
            opts.after_context.as_deref(),
        ) {
            Ok(anchor) => {
                let to_text = if let Some(ib) = &opts.insert_before {
                    format!("{}{}", ib, anchor.matched_text)
                } else if let Some(ia) = &opts.insert_after {
                    format!("{}{}", anchor.matched_text, ia)
                } else {
                    to.to_string()
                };
                let fuzzy_content = format!(
                    "{}{}{}",
                    &content[..anchor.start_offset],
                    to_text,
                    &content[anchor.start_offset + anchor.matched_text.len()..]
                );
                let diff = super::make_diff("<content>", content, &fuzzy_content);
                return Ok(ContentEditResult {
                    original: content.to_string(),
                    new_content: fuzzy_content,
                    diff,
                    changed: true,
                    match_count: 1,
                });
            }
            Err(edit_error) => {
                if opts.if_exists {
                    return Ok(ContentEditResult {
                        original: content.to_string(),
                        new_content: content.to_string(),
                        diff: String::new(),
                        changed: false,
                        match_count: 0,
                    });
                }
                let similar = fallback::find_similar_targets(content, from, 3);
                let mut msg = format!("no matches for {:?}", from);
                if let Some(suggestion) = &edit_error.suggestion {
                    msg.push_str(&format!(" (suggestion: {})", suggestion));
                }
                if !similar.is_empty() {
                    msg.push_str(&format!(" (did you mean: {}?)", similar.join(", ")));
                }
                bail!("{msg}");
            }
        }
    }

    if count == 0 && opts.if_exists {
        return Ok(ContentEditResult {
            original: content.to_string(),
            new_content: content.to_string(),
            diff: String::new(),
            changed: false,
            match_count: 0,
        });
    }

    let changed = content != new_content;
    let diff = if changed {
        super::make_diff("<content>", content, &new_content)
    } else {
        String::new()
    };

    Ok(ContentEditResult {
        original: content.to_string(),
        new_content,
        diff,
        changed,
        match_count: count,
    })
}