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
//! Patchloom: agent-grade repo operations as a Rust library.
//!
//! This crate provides both a CLI binary and a library API for structured
//! file editing operations. The [`api`] module is the main entry point for
//! library consumers.
//!
//! # Feature flags
//!
//! | Feature | Default | Description |
//! |---------|---------|-------------|
//! | `cli` | **yes** | CLI parser (clap) and all subcommand implementations. Disable for pure library use. |
//! | `mcp` | **yes** | MCP server support (adds `tokio`, `rmcp`, `schemars`) |
//! | `ast` | **yes** | AST-aware operations using tree-sitter (20 language grammars) |
//! | `files` | no | File scanning helpers + library plan execution + search_directory + append etc. for pure-library use (no CLI/clap). |
//! | `full` | no | Everything: `cli` + `mcp` + `ast` |
//!
//! ## Embedding as a library
//!
//! To use patchloom as a library (no CLI, no MCP):
//!
//! ```toml
//! [dependencies]
//! patchloom = { version = "0.22", default-features = false }
//! ```
//!
//! Or with AST support:
//!
//! ```toml
//! patchloom = { version = "0.22", default-features = false, features = ["ast"] }
//! ```
//!
//! (Keep the version in sync with Cargo.toml / release-please. See the release checklist.)
//!
//! This gives you the [`api`] module (primary editing interface), [`ops`],
//! and utility modules:
//!
//! - [`containment`] -- workspace path guard (flexible `AbsolutePathPolicy` via builder for temp dirs/extra roots in library use; strict `Reject` for MCP)
//! - [`exec`] -- shell command execution with process-tree management
//! - [`fallback`] -- multi-strategy edit recovery (exact, anchor, similarity)
//! - [`files`] -- text I/O honesty (#1894): `classify_text_bytes`, `load_text_strict` (sole path),
//! `try_read_text_file` / `SoftTextSkip` / `read_text_file` (walk soft skip), `is_binary` /
//! `is_binary_file` (#1884), and (with "files") scan helpers
//! - [`write`] -- atomic file writes with write-policy transformations
//!
//! With "files" feature you also get `api::search_directory`, `api::execute_plan`,
//! `api::file_append`/`file_prepend`, and full plan execution for library use.
//! For advanced search ignore (e.g. `.agentignore` on top of `.gitignore`) + custom walkers:
//! Use `SearchOptions::exclude_patterns` and `custom_ignore_filenames` with `search_directory`/`search_file`,
//! or collect paths with `files::collect_file_paths_with_ignores` (or your own `WalkBuilder`) then
//! pair with the low-level `api::search_one_file` inside `par_process_files` + `format_search_results` / `build_context_lines`.
//! See `api::search_one_file` (and its docs for custom `WalkBuilder` use), `api::SearchOptions`, and `files` module.
//!
//! Example (pure library with plans):
//! ```rust,ignore
//! use patchloom::api::{execute_plan, parse_plan, ApplyMode, file_append};
//! use patchloom::containment::PathGuard;
//! use std::path::Path;
//!
//! let guard = PathGuard::builder(std::env::current_dir().unwrap())
//! .allow_temp_directory()
//! .build()?;
//!
//! // Simple append via api
//! let _ = file_append(Path::new("log.txt"), "entry\n", ApplyMode::Apply, Some(&guard))?;
//!
//! // Or via plan for atomic multi-op
//! let plan_json = r#"{"version":1,"ops":[{"op":"file.append","path":"log.txt","content":"more\n"}]}"#;
//! let plan = parse_plan(plan_json)?;
//! let report = execute_plan(plan, Path::new("."), Some(&guard))?;
//! assert!(report.ok);
//! # Ok::<(), anyhow::Error>(())
//! ```
//!
//! For AST signature edits (library embedder surface, #1459 / #821 / #1493):
//!
//! - In-memory: `api::ast_rewrite_signature_in_content` or
//! `ast::rewrite::rewrite_function_signature` with `FunctionSigEdit`
//! - Parse Rust fragments: `FunctionSigEdit::parse_rust("pub fn f(x: i32) -> T")`
//! - Full-string rewrites accept a logical signature without trailing space;
//! high-level helpers preserve the body gap before `{` (`splice_function_signature`, #1503)
//! - On disk: `api::ast_rewrite_signature`, `api::ast_rename`, `api::ast_replace_in_symbol`
//! - Multi-file rename: `api::ast_rename_batch` (same-file serialization, per-file results; #1495)
//! - Plans / MCP: op `ast.rewrite_signature` / tool `ast_rewrite_signature`
//!
//! CLI `ast rewrite-signature` is still optional; library + plan + MCP cover embedders.
//!
//! Fail-closed text edits for agent hosts (#1492 / #1965 / #2005): use
//! [`ReplaceOptions::for_agent`] so primary and fallback replace paths share one
//! policy (`unique`, `require_change`, fuzzy with floor, `allow_absent_old: false`,
//! `refuse_suspicious_fuzzy: true` for over-wide fuzzy auto-refuse).
//! Zero matches become `EditErrorKind::NoMatch` (not `Ok(changed=false)`). Match
//! kinds via `api::edit_error_kind(&err)` without scraping English. That helper
//! also peels CLI/tx typed errors (`InvalidInputError` for empty patterns / bad
//! regex, `NoMatchError`, `TypeErrorError` → `EditErrorKind::TypeError` for
//! multi-doc bare keys (#1883), …) so hosts need not know which construction path
//! produced the failure. Example:
//!
//! ```rust,no_run
//! use patchloom::api::{self, ReplaceOptions, edit_error_kind, EditErrorKind};
//! let opts = ReplaceOptions::for_agent();
//! match api::replace_in_content("a b", "missing", "x", &opts) {
//! Ok(r) => assert!(r.changed),
//! Err(e) => assert_eq!(edit_error_kind(&e), Some(EditErrorKind::NoMatch)),
//! }
//! match api::replace_in_content("a b", "", "x", &ReplaceOptions::default()) {
//! Err(e) => assert_eq!(edit_error_kind(&e), Some(EditErrorKind::InvalidInput)),
//! Ok(_) => panic!("empty pattern must error"),
//! }
//! ```
//!
//! Shell command-position matching (#1494 / #1666): opt-in
//! `ReplaceOptions.command_position` rewrites invocable tokens
//! (`pip install`, `sudo -E pip`, `timeout 30 pip`, `nice -n 10 pip`, `setsid pip`,
//! `busybox wget`, `flock /tmp/l pip`, `runuser -u app pip`, `chpst -u app pip`,
//! `with-contenv pip`, `envdir /env pip`) without touching arguments (`uv pip`) or
//! longer words (`pipenv`). Not the same as `word_boundary`. Incompatible with
//! `regex`, `whole_line`, `multiline`, `nth`, insert before/after, fuzzy, and
//! context anchors (typed `InvalidInput`). Works on `replace_text`,
//! `replace_in_content`, `ContentEdit::Replace`, plan/MCP `command_position`, and
//! CLI `--command-position`. Post-Apply validate/revert: use
//! `api::run_post_write_validation` (#1663) or
//! `backup::restore_path_from_session` / `restore_path_from_latest_backup` (#1660).
//! After Apply, `EditResult.backup_session` names the session created for that
//! write so hosts can call `restore_path_from_session` without re-listing
//! backups (#1686). Nested monorepos: `backup::list_sessions_under` walks
//! descendant `.patchloom/backups` roots (#1688). Ancestor discovery:
//! `backup::find_backup_roots(path)` walks parents for roots that contain
//! `.patchloom/backups` (#1934). File create/delete/rename/append and
//! `ast_rewrite_signature` peel via `edit_error_kind` (`AlreadyExists` for
//! dest-exists without force, `NotFound` for missing path I/O, `Binary` /
//! `InvalidEncoding` for content SoftSkip, `InvalidInput` for dir/empty path,
//! `NoMatch` for missing AST symbols, `GuardRejected`
//! for PathGuard; #1935 / #1936 / #1947). Fuzzy policy:
//! `ReplaceOptions.min_fuzzy_score` rejects weak similarity matches (#1687).
//! Project-wide rename: `api::ast_rename_project` (#1689). Post-Apply hooks:
//! `ReplaceOptions.post_write` / `WritePolicyOptions.post_write` / batch
//! `AstRenameBatchOptions.post_write` (#1690).
//!
//! Match honesty for agents (#1662 / #1669 / #1674): `EditResult` /
//! `ContentEditResult` / `ContentEditsResult` expose `match_mode`
//! (`Exact` / `Fuzzy` / `Anchored`) and optional `match_score` so hosts can warn on
//! low-confidence fuzzy sites without re-running the matcher. Plan/tx JSON
//! (`PlanReport` / `TxOutput`) and MCP `batch_replace` / `execute_plan` include
//! the same fields on each replace-backed change plus a worst-case aggregate.
//!
//! Non-anyhow hosts (#1659): branch with `api::classify_error(&*err as &dyn Error)`
//! or `classify_error_ref` for `similar_targets`; `edit_error_kind` remains for
//! `anyhow::Error` chains.
//!
//! For several ordered text edits on **one buffer** then a single write (agent intent engines):
//! use `api::apply_content_edits` / `apply_content_edits_with_label` /
//! `api::apply_content_edits_to_file` with
//! `ContentEdit::{Replace, InsertBefore, InsertAfter, Append, Prepend}` (all-or-nothing).
//! Results expose rolled-up `match_count` across replace ops. Multi-file multi-op remains
//! `execute_plan`.
//!
//! **Note on results**: Single-file ops return `EditResult` (with `action`, `dest_path`,
//! `match_count` for replace, and `removed` for `doc.delete` / `doc.delete_where`).
//! `execute_plan` (library) returns `PlanReport` (typed TxOutput) with `ok`, `changes`
//! (optional per-change `match_mode` / `match_score` / `match_count` for replace), `searches`, `reads`,
//! `error`, plus `mutations` / aggregate `changed` / `removed` for deletes
//! (including idempotent `removed: 0` no-ops) (#811, #1439, #1459, #1674).
//! See `api::PlanReport`, `api::execute_plan`, and embedding docs. CLI/MCP retain (code, json) for compatibility.
//!
//! For library users needing relaxed containment (e.g. LLM agents using temp files or host experiment mode):
//! ```rust,no_run
//! use patchloom::containment::PathGuard;
//! let guard = PathGuard::builder(std::env::current_dir().unwrap())
//! .allow_temp_directory() // includes /tmp and handles macOS /tmp -> /private/tmp
//! .build()
//! .expect("guard");
//! // pass to high-level api functions, e.g.
//! let _ = patchloom::api::replace_text(
//! std::path::Path::new("foo.txt"),
//! "old",
//! "new",
//! &patchloom::api::ReplaceOptions::default(),
//! patchloom::api::ApplyMode::Preview,
//! Some(&guard),
//! );
//! ```
//!
//! The `files` module (pure helpers like `is_binary`, `is_binary_file` path preflight,
//! `load_text_strict`, `read_text_file`, and scanning tools when "files" feature enabled)
//! is always available. The `cli` and `cmd` modules require the `cli` feature.
//!
//! ## Embedder cookbook: text load, binary preflight, multi-doc (#1910 / #1909)
//!
//! | Need | Use |
//! |------|-----|
//! | Sole path as editable text (binary / bad UTF-8 → typed error) | [`api::load_text`] or [`files::load_text_strict`] |
//! | Cheap binary path check before open (open fail → `false`) | [`api::is_binary_file`] / [`files::is_binary_file`] |
//! | Map multi-doc bare key / wrong-root merge to tool `invalid_args` | [`EditErrorKind::TypeError`] / [`api::is_type_error`] |
//! | Multi-doc YAML merge into document 0 | [`api::doc_merge`](..., `Some("0")`) |
//! | Map empty pattern / directory target to `invalid_args` | [`EditErrorKind::InvalidInput`] / [`api::is_invalid_input`] |
//! | Map sole binary / NUL content | [`EditErrorKind::Binary`] / [`api::is_binary`] (`binary`) |
//! | Map invalid UTF-8 content | [`EditErrorKind::InvalidEncoding`] / [`api::is_invalid_encoding`] |
//! | Force create over binary/unreadable prior | [`api::file_create`](..., `force: true`) (#1962) |
//! | Path-only rename/delete non-text (byte backup, no OS dual-path) | [`api::file_rename`] / [`api::file_delete`] (#2031) |
//! | Delete FIFO/socket/device/symlink under PathGuard | [`api::file_delete`] (dirs still refused; #2087) |
//! | Rename symlink/FIFO/dangling (path-only; never rewrites link target) | [`api::file_rename`] (#2091) |
//! | YAML presentation drift on library writes | [`EditResult::style_changed`] / [`api::is_style_changed`] (#2088) |
//! | Morph-class freeform on disk | [`api::apply_fragment_to_file`] + [`FragmentPlacement`] (#2032) |
//! | Host unit-test honesty rows (`#[non_exhaustive]`) | [`ContentEditHonesty::exact`] / [`ContentEditHonesty::fuzzy`] (#2033) |
//! | Map create/rename dest-exists to force/overwrite recovery | [`EditErrorKind::AlreadyExists`] / [`api::is_already_exists`] |
//! | CLI-stable kind string for host JSON envelopes | [`api::error_kind_str`] / [`api::peel_error`] |
//! | Map missing path I/O to not-found (not generic op fail) | [`EditErrorKind::NotFound`] / [`api::is_not_found`] |
//! | Map patch merge conflict markers | [`EditErrorKind::Conflicts`] / [`api::is_conflicts`] (distinct from batch [`EditErrorKind::ConflictingEdit`]) |
//! | Map check/assert-count exit-2 soft failures | [`EditErrorKind::ChangesDetected`] / [`api::is_changes_detected`] |
//! | PathGuard / `--contain` rejection | [`EditErrorKind::GuardRejected`] / [`api::is_guard_rejected`] |
//! | Soft zero matches | [`EditErrorKind::NoMatch`] / [`api::is_no_match`] (JSON kind `no_matches`) |
//! | Unique multi-match ambiguity | [`EditErrorKind::AmbiguousTarget`] / [`api::is_ambiguous`] (JSON `ambiguous`) |
//! | Post-write format/lint failure | [`EditErrorKind::FormatFailed`] / [`api::is_format_failed`] |
//! | Shared agent replace policy (primary + fallback) | [`ReplaceOptions::for_agent`] / [`AGENT_MIN_FUZZY_SCORE`] (#1965 / #2005) |
//! | Over-wide fuzzy auto-refuse on `for_agent` | [`ReplaceOptions::refuse_suspicious_fuzzy`] / [`EditErrorKind::FuzzySpanSuspicious`] / [`api::is_fuzzy_span_suspicious`] (#2005) |
//! | Custom over-wide fuzzy refuse | [`api::fuzzy_span_suspicious`] / [`FuzzySpanPolicy`] (#1981) |
//! | Multi-op per-replace honesty | [`ContentEditsResult::op_honesty`] / [`ContentEditHonesty`] (#2006) |
//! | Buffer multi-op over-wide fuzzy refuse | [`api::refuse_batch_if_suspicious_fuzzy`] (#2064) |
//! | Plan/tx multi-path worst-case span | [`prefer_widest_matched_text`] / top-level `matched_text` (#2007) |
//! | File multi-op pre-write span refuse | [`apply_content_edits_to_file_with_span_policy`] + [`FuzzySpanPolicy`] (#2008) |
//! | Sole-path load failed as binary/encoding/invalid_input | [`api::is_load_text_strict_fail`] (#1963) |
//! | Ordered host onboarding (primary + fallback + peels + multi-op) | [Embedder host checklist](docs/getting-started/embedder-host.md) (#2009) |
//!
//! `EditErrorKind` is `#[non_exhaustive]`: always include a wildcard arm when matching.
//!
//! ```rust,no_run
//! use patchloom::api::{self, edit_error_kind, EditErrorKind, ApplyMode};
//! use std::path::Path;
//!
//! let path = Path::new("stream.yaml");
//! if api::is_binary_file(path) {
//! // host: refuse tool call as invalid_args
//! }
//! let _text = api::load_text(path)?; // Binary / InvalidEncoding if non-text
//! match api::doc_merge(path, serde_json::json!({"c": 3}), ApplyMode::Apply, None, Some("0")) {
//! Ok(r) => assert!(r.changed),
//! Err(e) if edit_error_kind(&e) == Some(EditErrorKind::TypeError) => {
//! // multi-doc bare root / wrong type
//! }
//! Err(e) => return Err(e),
//! }
//! # Ok::<(), anyhow::Error>(())
//! ```
//!
//! For pure library use with plans and execution (post #792), prefer
//! `features = ["ast", "files"]` (or "files"). `execute_plan` is available
//! under `any(feature = "cli", "files")` and delegates to the `tx` module.
//!
//! ## Migration for high-level api::* signature changes (PathGuard, #758)
//!
//! The addition of the trailing `guard: Option<&PathGuard>` parameter to all mutating
//! functions (replace_text, doc_*, md_*, file_*, tidy, apply_patch, etc.) and to
//! `execute_plan` is a source-breaking change from pre-#749 usage.
//!
//! ```rust,ignore
//! // Before
//! patchloom::api::doc_set(&p, "k", v, ApplyMode::Apply)?;
//!
//! // After (pass None to keep previous strict-root behavior, or a guard for relaxed)
//! patchloom::api::doc_set(&p, "k", v, ApplyMode::Apply, None)?;
//! ```
//!
//! See the "Using with PathGuard" section in the `api` module docs, the builder
//! for relaxed policies, and AGENTS.md "High-level library API signature changes"
//! for the full checklist (doctests, greps, examples, tests). `execute_plan` now
//! also accepts the guard (threaded into tx; #755).
//!
//! With `features = ["ast"]`, the [`ast`] module provides tree-sitter parsing,
//! symbol extraction, structural search, rename, and more for 20 languages.
//!
//! No `clap`, `tokio` or other heavy dependencies are pulled in when `cli` and `mcp` are disabled.
//!
//! ## Thread safety
//!
//! All public API types ([`api::EditResult`], [`api::ApplyMode`], etc.) are
//! `Send + Sync`. Library functions are safe to call concurrently from
//! multiple threads with one constraint:
//!
//! - **Different files**: fully safe. Multiple threads can edit different files
//! simultaneously with no coordination.
//! - **Same file**: the caller must serialize access. Concurrent writes to the
//! same file are inherently racy (last writer wins). Use a mutex or other
//! synchronization if you need to coordinate edits to a single file.
//!
//! Backup sessions use unique directory names (nanosecond timestamp +
//! monotonic counter) so concurrent backup creation never collides.
//!
//! Configuration can be loaded once with [`config::CachedConfig`] and reused
//! across threads, avoiding repeated disk reads.
pub
pub
// Fail-closed structured stdout helper (CLI + library agent hosts). Not CLI-only:
// used by `GlobalFlags`, `cmd/doc`, and `api::format_search_results` (#1651 class).
pub
// Re-exports for library ergonomics (no need to dig into api/plan when using ["ast","files"]).
pub use search_one_file;
pub use ;
pub use ;
pub use Plan;
pub
pub use *;
// ---------------------------------------------------------------------------
// Verbose logging
// ---------------------------------------------------------------------------
/// Global flag set once at startup; checked by the `verbose!` macro.
static VERBOSE: AtomicBool = new;
/// Returns `true` if verbose mode is enabled.
/// Enable verbose mode globally. Called once at startup.
/// Print a verbose diagnostic message to stderr.
///
/// Usage: `verbose!("processing {} files", count);`
// ---------------------------------------------------------------------------
// Bounded regex compilation
// ---------------------------------------------------------------------------
/// Create a [`regex::RegexBuilder`] with bounded compilation limits.
///
/// All user-supplied regex patterns must go through this function so that
/// pathological patterns cannot exhaust memory (important when patchloom
/// runs as an MCP server handling untrusted input).
/// Finish a [`bounded_regex_builder`] with typed [`exit::InvalidInputError`].
///
/// Use this instead of `.build()?` so CLI JSON and library `edit_error_kind`
/// peel `invalid_input` for bad patterns without scraping the regex crate.
/// Run the patchloom CLI. Returns the exit code as a u8.
///
/// Requires the `cli` feature (enabled by default).
///
/// CLI usage errors (unknown flags, invalid enum values, missing required
/// args, unrecognized subcommands) map to [`exit::FAILURE`] (1). Clap's
/// default exit 2 collides with [`exit::CHANGES_DETECTED`] (preview/`--check`
/// pending changes), so agents and scripts must not treat clap's default as
/// "changes detected."
/// Compact clap usage text for JSON envelopes: drop the `error: ` prefix and
/// trailing Usage / help footer so agents get a single actionable sentence.
/// Build the JSON error envelope and exit code for a dispatch `Err` under
/// `--json` / `--jsonl`. Typed exit kinds (`NoMatchError`, `AmbiguousError`,
/// `InvalidInputError`, `ParseErrorError`, …) get `error_kind` and exit codes.
/// Post-write format failures also expose `backup_session` when known.