patchloom 0.1.3

A Rust CLI for agent-grade repo operations
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
pub mod batch;
pub mod create;
pub mod delete;
pub mod doc;
pub mod explain;
pub mod init;
#[cfg(feature = "mcp")]
pub mod mcp;
pub mod md;
pub mod patch;
pub mod read;
pub mod rename;
pub mod replace;
pub mod search;
pub mod status;
pub mod tidy;
pub mod tx;
pub mod undo;

use crate::cli::Cli;
use clap::{Args, Subcommand, ValueEnum};

#[derive(Debug, Subcommand)]
pub enum Command {
    /// Create a new file with specified content.
    Create(create::CreateArgs),
    /// Delete a file.
    Delete(delete::DeleteArgs),
    /// Fast literal or regex search across text files.
    Search(search::SearchArgs),
    /// Mechanical string replacement across text files with diff preview.
    Replace(replace::ReplaceArgs),
    /// Show which files have uncommitted changes.
    Status(status::StatusArgs),
    /// Preview or apply unified diffs safely.
    Patch(patch::PatchArgs),
    /// Read file contents with optional line range.
    Read(read::ReadArgs),
    /// Rename (move) a file.
    Rename(rename::RenameArgs),
    /// Markdown section-aware operations.
    Md(md::MdArgs),
    /// Parser-backed JSON, YAML, and TOML operations.
    Doc(doc::DocArgs),
    /// Text-file newline, line ending, and whitespace normalization.
    Tidy(tidy::TidyArgs),
    /// Execute a multi-operation plan atomically.
    Tx(tx::TxArgs),
    /// Execute multiple operations from a simple line-oriented format.
    Batch(batch::BatchArgs),
    /// Explain a tx plan in plain English.
    Explain(explain::ExplainArgs),
    /// Restore files from a backup created by --apply.
    Undo(undo::UndoArgs),
    /// Print agent rules for using patchloom (AGENTS.md content for end users).
    AgentRules(AgentRulesArgs),
    /// Set up patchloom in the current project.
    Init(init::InitArgs),
    /// Start an MCP (Model Context Protocol) server on stdio.
    #[cfg(feature = "mcp")]
    McpServer {
        /// Allow tx plans to run shell commands via format/validate lifecycle
        /// steps. Without this flag, plans containing shell commands are
        /// rejected. Enable only when the MCP client is trusted.
        #[arg(long)]
        allow_shell: bool,
        /// Log every tool call to a JSONL file (tool name, duration, status).
        /// Also settable via PATCHLOOM_MCP_LOG env var; the flag takes precedence.
        #[arg(long)]
        log: Option<String>,
    },
    /// Generate shell completions for bash, zsh, fish, or elvish.
    Completions {
        /// Shell to generate completions for.
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum AgentMode {
    /// Include both CLI and MCP instructions (default).
    All,
    /// CLI-only: omit MCP section.
    Cli,
    /// MCP-only: omit CLI shell examples, lead with MCP tools.
    Mcp,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum AgentPlatform {
    /// Include both Linux and Windows examples where they differ (default).
    All,
    /// Linux/macOS only: heredocs, single-quote shell syntax.
    Linux,
    /// Windows only: file arguments, double-quote escaping.
    Windows,
}

#[derive(Debug, Args)]
#[command(after_help = "\
EXAMPLES:
  patchloom agent-rules >> AGENTS.md
  patchloom agent-rules --mode mcp
  patchloom agent-rules --platform linux")]
pub struct AgentRulesArgs {
    /// Which integration mode to generate instructions for.
    #[arg(long, value_enum, default_value = "all")]
    pub mode: AgentMode,
    /// Which platform to generate shell examples for.
    #[arg(long, value_enum, default_value = "all")]
    pub platform: AgentPlatform,
}

pub(crate) const AGENT_RULES_GENERATED_MARKER: &str = "<!-- Generated by patchloom v";

fn generate_agent_rules(args: &AgentRulesArgs) -> String {
    let version = env!("CARGO_PKG_VERSION");
    let show_cli = matches!(args.mode, AgentMode::All | AgentMode::Cli);
    let show_mcp = matches!(args.mode, AgentMode::All | AgentMode::Mcp);
    let show_linux = matches!(args.platform, AgentPlatform::All | AgentPlatform::Linux);
    let show_windows = matches!(args.platform, AgentPlatform::All | AgentPlatform::Windows);

    let mut out = String::new();

    // Header
    out.push_str(&format!(
        "{AGENT_RULES_GENERATED_MARKER}{version} — https://github.com/patchloom/patchloom -->\n\
         # Patchloom\n\n"
    ));

    if show_mcp && !show_cli {
        out.push_str(
            "You have MCP tools for file reads, edits, and searches. \
             Use them for ALL file operations.\n\n",
        );
    }
    if show_mcp && show_cli {
        out.push_str(
            "**Decision rule: always use patchloom MCP tools instead of your native agent \
             tools for file edits.** Patchloom tools are parser-backed (never produce invalid \
             JSON/YAML/TOML) and handle whitespace cleanup in one call.\n\n",
        );
    }
    if show_cli {
        out.push_str(
            "**Decision rule: if you are about to make 3+ tool calls for file edits, use \
             `patchloom batch` instead.** One call replaces N round-trips.\n\n",
        );
    }

    // When to use
    if show_mcp {
        out.push_str(
            "## Tool selection guide\n\n\
             | Task pattern | Tool to use |\n\
             |---|---|\n\
             | Set/get a key in JSON, YAML, or TOML | `doc_set`, `doc_get`, `doc_query` |\n\
             | Edit markdown section, bullet, or table | `md_replace_section`, `md_upsert_bullet`, `md_table_append` |\n\
             | Insert text after/before a heading | `md_insert_after_heading`, `md_insert_before_heading` |\n\
             | Fix trailing whitespace or missing newlines | `fix_whitespace` (one file) or `batch_tidy` (multiple files) |\n\
             | Create, rename, or delete a file | `create_file`, `move_file`, `delete_file` |\n\
             | Find/replace text in a file | `replace_text` (one file) or `batch_replace` (same replacement across multiple files) |\n\
             | Search across files | `search_files` |\n\n",
        );
    }
    if show_cli && !show_mcp {
        out.push_str(
            "Use patchloom when:\n\
             - Editing JSON, YAML, or TOML (parser-backed, preserves comments, output is always valid)\n\
             - Editing markdown sections, bullets, or tables by heading\n\
             - Batching edits across multiple files in one call\n\
             - You need atomic rollback if any edit fails\n\n\
             For single-file read, search, create, delete, or rename, your native agent tools are faster.\n\n",
        );
    }
    if show_cli && show_mcp {
        out.push_str(
            "Use patchloom when:\n\
             - Editing JSON, YAML, or TOML (parser-backed, preserves comments, output is always valid)\n\
             - Editing markdown sections, bullets, or tables by heading\n\
             - Batching edits across multiple files in one call\n\
             - You need atomic rollback if any edit fails\n\n",
        );
    }

    // MCP section
    if show_mcp {
        out.push_str(
            "## MCP mode\n\n\
             **ALWAYS use MCP tools for ALL file edits.** Use `batch_replace` or `batch_tidy` \
             when applying the same operation to multiple files; use individual tools otherwise.\n\n",
        );
    }

    // Batching section
    if show_cli {
        out.push_str("## Batching (the main speed win)\n\n\
             Six file edits via native tools = six round-trips. One `batch` call = one round-trip:\n\n");

        if show_linux {
            out.push_str(
                "```bash\n\
                 patchloom batch --apply <<'EOF'\n\
                 doc.set config.json version \"2.0.0\"\n\
                 doc.set config.yaml app.version \"2.0.0\"\n\
                 replace README.md \"1.0.0\" \"2.0.0\"\n\
                 file.create hello.txt \"Hello, World!\"\n\
                 file.rename old.txt new.txt\n\
                 md.upsert_bullet CHANGELOG.md \"## Changes\" \"- Bumped to 2.0.0\"\n\
                 EOF\n\
                 ```\n\n\
                 One line per operation. Double-quote values with spaces.\n\n\
                 **Note:** Values are parsed as JSON. A quoted `\"1.0\"` produces the JSON number `1.0`, not the string `\"1.0\"`. To set a string that looks numeric, omit the outer quotes: `doc.set config.json version 1.0`.\n\n",
            );
        }

        if show_windows {
            if show_linux {
                out.push_str(
                    "On Windows (where heredocs are not available), write operations to a file and pass it:\n\n",
                );
            }
            out.push_str(
                "```bash\n\
                 patchloom batch ops.txt --apply\n\
                 ```\n\n",
            );
            if !show_linux {
                out.push_str(
                    "One line per operation in the file. Double-quote values with spaces.\n\n\
                     **Note:** Values are parsed as JSON. A quoted `\"1.0\"` produces the JSON number `1.0`, not the string `\"1.0\"`. To set a string that looks numeric, omit the outer quotes: `doc.set config.json version 1.0`.\n\n",
                );
            }
        }

        out.push_str(
            "For complex plans needing format/validate lifecycle, regex replace, or `--nth`, use `tx` with JSON:\n\n\
             ```bash\n\
             patchloom tx plan.json --apply\n\
             ```\n\n",
        );

        // Structured edits section
        out.push_str("## Structured edits\n\n");

        if show_linux {
            out.push_str(
                "```bash\n\
                 # Edit a value in JSON/YAML/TOML by selector (parser-backed, preserves comments)\n\
                 patchloom doc set config.json version '\"2.0.0\"' --apply\n\
                 patchloom doc merge config.yaml --value '{\"db\":{\"pool\":10}}' --apply\n\
                 \n\
                 # Append a row to a markdown table\n\
                 patchloom md table-append README.md --heading \"## API\" --row \"| new | row |\" --apply\n\
                 ```\n\n",
            );
        }

        if show_windows {
            if show_linux {
                out.push_str("On Windows, use double-quote escaping:\n\n");
            }
            out.push_str(
                "```bash\n\
                 patchloom doc set config.json version \"\\\"2.0.0\\\"\" --apply\n\
                 patchloom doc merge config.yaml --value \"{\\\"db\\\":{\\\"pool\\\":10}}\" --apply\n\
                 patchloom md table-append README.md --heading \"## API\" --row \"| new | row |\" --apply\n\
                 ```\n\n",
            );
        }

        out.push_str(
            "Add `--apply` to all write commands. Without it, patchloom previews changes without writing.\n\n",
        );
    }

    // Workflow examples (CLI only)
    if show_cli {
        out.push_str("## Workflow examples\n\n");

        out.push_str(
            "### Rename a function across a codebase\n\n\
             ```bash\n\
             # Find all occurrences first\n\
             patchloom search --count \"old_function_name\" src/\n\n\
             # Replace in all matching files\n\
             patchloom replace \"old_function_name\" --to \"new_function_name\" src/ --apply\n\
             ```\n\n",
        );

        out.push_str(
            "### Edit a CI workflow\n\n\
             ```bash\n\
             # Set a value in a YAML workflow by selector (preserves comments and formatting)\n\
             patchloom doc set .github/workflows/ci.yml jobs.test.timeout-minutes 30 --apply\n\
             ```\n\n",
        );

        if show_linux {
            out.push_str(
                "### Bump a version across config files\n\n\
                 ```bash\n\
                 patchloom batch --apply <<'EOF'\n\
                 doc.set package.json version \"2.0.0\"\n\
                 doc.set Cargo.toml package.version \"2.0.0\"\n\
                 replace README.md \"1.0.0\" \"2.0.0\"\n\
                 md.upsert_bullet CHANGELOG.md \"## [2.0.0]\" \"- Initial 2.0 release\"\n\
                 EOF\n\
                 ```\n\n",
            );

            out.push_str("### Multi-file refactoring with a transaction\n\n\
                 ```bash\n\
                 patchloom tx - --apply <<'EOF'\n\
                 {\"version\": \"1\", \"operations\": [\n\
                   {\"op\": \"replace\", \"path\": \"src/config.rs\", \"from\": \"old_default\", \"to\": \"new_default\"},\n\
                   {\"op\": \"doc.set\", \"path\": \"config.toml\", \"selector\": \"default_value\", \"value\": \"new_default\"},\n\
                   {\"op\": \"md.replace_section\", \"path\": \"docs/config.md\", \"heading\": \"## Defaults\",\n\
                    \"content\": \"The default value is now `new_default`.\\n\"}\n\
                 ]}\n\
                 EOF\n\
                 ```\n\n\
                 All operations succeed atomically or roll back together.\n\n");
        }
    }

    // Selector syntax (always shown — used by all doc.* operations)
    out.push_str(
        "## Selector syntax\n\n\
         All `doc` operations use selectors to address values inside JSON, YAML, and TOML files.\n\n\
         | Syntax | Meaning | Example |\n\
         |--------|---------|---------|\n\
         | `key` | Object key | `database.host` |\n\
         | `[N]` | Array index (zero-based) | `servers[0].port` |\n\
         | `[*]` | Wildcard (all array elements) | `jobs[*].timeout` |\n\
         | `[key=val]` | Predicate (filter by field value) | `deps[name=express].version` |\n\n\
         Segments are separated by `.` or adjacent brackets. Examples:\n\n\
         ```text\n\
         scripts.test                    # simple key path\n\
         jobs[0].steps[*].name           # index + wildcard\n\
         dependencies[name=react].version # predicate filter\n\
         ```\n\n",
    );

    // Exit codes (CLI only — MCP tools return results as JSON, not exit codes)
    if show_cli {
        out.push_str(
            "## Exit codes\n\n\
             | Code | Meaning |\n\
             |------|---------|\n\
             | 0 | Success (operation completed, or no changes needed) |\n\
             | 1 | Failure (error during execution) |\n\
             | 2 | Changes detected (`--check` mode found pending changes) |\n\
             | 3 | No matches (search/replace found nothing matching the pattern) |\n\
             | 4 | Parse error (malformed input file or plan) |\n\
             | 5 | Ambiguous (replacement matched multiple locations without `--nth`, or stale/missing patch context) |\n\
             | 6 | Validation failed (tx plan validation step returned non-zero) |\n\
             | 7 | Rollback (tx apply failed partway; changes were rolled back) |\n",
        );
    }

    out
}

/// Load and apply project config from `.patchloom.toml`.
fn load_project_config(global: &mut crate::cli::global::GlobalFlags) {
    let cwd = global.resolve_cwd().unwrap_or_default();
    if let Some((config, _)) = crate::config::find_and_load(&cwd) {
        crate::config::apply_config(global, &config);
    }
}

pub fn dispatch(cli: Cli) -> anyhow::Result<u8> {
    let mut global = cli.global;

    // Load config early for read-only commands (no merge_write).
    // Write commands call load_project_config after merge_write.
    match cli.command {
        #[cfg(feature = "mcp")]
        Command::McpServer { allow_shell, log } => {
            load_project_config(&mut global);
            mcp::run_mcp_server(&global, allow_shell, log)
        }
        Command::AgentRules(args) => {
            let output = generate_agent_rules(&args);
            print!("{output}");
            Ok(crate::exit::SUCCESS)
        }
        Command::Init(args) => init::run(args, &global),
        Command::Completions { shell } => {
            let mut cmd = <Cli as clap::CommandFactory>::command();
            clap_complete::generate(shell, &mut cmd, "patchloom", &mut std::io::stdout());
            Ok(crate::exit::SUCCESS)
        }
        Command::Read(args) => {
            load_project_config(&mut global);
            read::run(args, &global)
        }
        Command::Explain(args) => {
            load_project_config(&mut global);
            explain::run(args, &global)
        }
        Command::Undo(args) => {
            load_project_config(&mut global);
            undo::run(args, &global)
        }
        Command::Search(args) => {
            load_project_config(&mut global);
            search::run(args, &global)
        }
        Command::Status(args) => {
            load_project_config(&mut global);
            status::run(args, &global)
        }
        Command::Create(args) => {
            global.merge_write(&args.write);
            load_project_config(&mut global);
            create::run(args, &global)
        }
        Command::Delete(args) => {
            global.merge_write(&args.write);
            load_project_config(&mut global);
            delete::run(args, &global)
        }
        Command::Rename(args) => {
            global.merge_write(&args.write);
            load_project_config(&mut global);
            rename::run(args, &global)
        }
        Command::Replace(args) => {
            global.merge_write(&args.write);
            load_project_config(&mut global);
            replace::run(args, &global)
        }
        Command::Patch(args) => {
            global.merge_write(&args.write);
            load_project_config(&mut global);
            patch::run(args, &global)
        }
        Command::Md(args) => {
            global.merge_write(&args.write);
            load_project_config(&mut global);
            md::run(args, &global)
        }
        Command::Doc(args) => {
            global.merge_write(&args.write);
            load_project_config(&mut global);
            doc::run(args, &global)
        }
        Command::Tidy(args) => {
            global.merge_write(&args.write);
            load_project_config(&mut global);
            tidy::run(args, &global)
        }
        Command::Tx(args) => {
            global.merge_write(&args.write);
            load_project_config(&mut global);
            tx::run(args, &global)
        }
        Command::Batch(args) => {
            global.merge_write(&args.write);
            load_project_config(&mut global);
            batch::run(args, &global)
        }
    }
}

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

    fn args(mode: AgentMode, platform: AgentPlatform) -> AgentRulesArgs {
        AgentRulesArgs { mode, platform }
    }

    #[test]
    fn default_includes_all_sections() {
        let out = generate_agent_rules(&args(AgentMode::All, AgentPlatform::All));
        assert!(out.contains("# Patchloom"));
        assert!(out.contains("## MCP mode"));
        assert!(out.contains("## Tool selection guide"));
        assert!(out.contains("## Batching"));
        assert!(out.contains("## Structured edits"));
        assert!(out.contains("## Exit codes"));
        assert!(out.contains("<<'EOF'"));
        assert!(out.contains("batch ops.txt"));
    }

    #[test]
    fn mode_cli_omits_mcp_keeps_cli() {
        let out = generate_agent_rules(&args(AgentMode::Cli, AgentPlatform::All));
        assert!(!out.contains("## MCP mode"));
        assert!(!out.contains("## Tool selection guide"));
        assert!(out.contains("## Batching"));
        assert!(out.contains("## Structured edits"));
        // CLI-only mode keeps the "native tools are faster" note
        assert!(out.contains("native agent tools are faster"));
    }

    #[test]
    fn mode_mcp_omits_cli_keeps_mcp() {
        let out = generate_agent_rules(&args(AgentMode::Mcp, AgentPlatform::All));
        assert!(out.contains("## MCP mode"));
        assert!(out.contains("## Tool selection guide"));
        // MCP-only mode must not mention batch/transaction tools or CLI
        assert!(!out.contains("batch({\"operations\":"));
        assert!(!out.contains("transaction({\"operations\":"));
        assert!(!out.contains("search_replace"));
        assert!(!out.contains("run_terminal_command"));
        assert!(!out.contains("command line"));
        assert!(out.contains("Use them for ALL file operations"));
        // CLI-only sections must be absent (check for h2 headings, not h3)
        assert!(!out.contains("\n## Batching"));
        assert!(!out.contains("\n## Structured edits"));
        // Must not tell agent to prefer native tools
        assert!(!out.contains("native agent tools are faster"));
    }

    #[test]
    fn platform_linux_omits_windows() {
        let out = generate_agent_rules(&args(AgentMode::All, AgentPlatform::Linux));
        assert!(out.contains("<<'EOF'"));
        assert!(!out.contains("batch ops.txt"));
        // Single-quote syntax present in CLI section
        assert!(out.contains("'\"2.0.0\"'"));
        // Windows-only double-quote escaping in CLI section absent
        // (MCP section has its own escaped quotes but that's platform-independent)
        assert!(!out.contains("patchloom doc set config.json version \"\\\"2.0.0\\\"\""));
    }

    #[test]
    fn platform_windows_omits_heredoc() {
        let out = generate_agent_rules(&args(AgentMode::All, AgentPlatform::Windows));
        assert!(!out.contains("<<'EOF'"));
        assert!(out.contains("batch ops.txt"));
        // Windows escaping present in CLI section
        assert!(out.contains("patchloom doc set config.json version \"\\\"2.0.0\\\"\""));
        // Linux single-quote syntax absent
        assert!(!out.contains("'\"2.0.0\"'"));
    }

    #[test]
    fn exit_codes_present_for_cli_modes() {
        // Exit codes are CLI-only (MCP returns JSON results, not exit codes)
        for mode in [AgentMode::All, AgentMode::Cli] {
            for platform in [
                AgentPlatform::All,
                AgentPlatform::Linux,
                AgentPlatform::Windows,
            ] {
                let out = generate_agent_rules(&args(mode, platform));
                assert!(
                    out.contains("## Exit codes"),
                    "exit codes missing for mode={mode:?} platform={platform:?}"
                );
            }
        }
        // MCP-only mode must NOT have exit codes
        let out = generate_agent_rules(&args(AgentMode::Mcp, AgentPlatform::All));
        assert!(!out.contains("## Exit codes"));
    }

    #[test]
    fn version_is_embedded() {
        let out = generate_agent_rules(&args(AgentMode::All, AgentPlatform::All));
        let version = env!("CARGO_PKG_VERSION");
        assert!(out.contains(&format!("patchloom v{version}")));
    }

    #[test]
    fn mcp_and_windows_compose_to_minimal() {
        let out = generate_agent_rules(&args(AgentMode::Mcp, AgentPlatform::Windows));
        assert!(out.contains("## MCP mode"));
        // MCP mode must not contain batch/transaction or CLI content
        assert!(!out.contains("batch({\"operations\":"));
        assert!(!out.contains("transaction({\"operations\":"));
        assert!(!out.contains("\n## Batching"));
        assert!(!out.contains("batch ops.txt"));
        assert!(!out.contains("<<'EOF'"));
    }
}