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
use super::*;

#[test]
fn test_init_creates_agents_md_in_empty_dir() {
    let dir = TempDir::new().unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["init", "--yes", "--cwd"])
        .arg(dir.path())
        .output()
        .unwrap();
    assert!(output.status.success());
    let agents = dir.path().join("AGENTS.md");
    assert!(agents.exists(), "AGENTS.md should be created");
    let content = fs::read_to_string(&agents).unwrap();
    assert!(content.contains("patchloom"));
    assert!(content.contains("# Patchloom"));
}

#[test]
fn test_init_appends_to_existing_agents_md() {
    let dir = TempDir::new().unwrap();
    fs::write(dir.path().join("AGENTS.md"), "# My Rules\n").unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["init", "--yes", "--cwd"])
        .arg(dir.path())
        .output()
        .unwrap();
    assert!(output.status.success());
    let content = fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
    assert!(
        content.starts_with("# My Rules\n"),
        "original content should be preserved"
    );
    assert!(
        content.contains("# Patchloom"),
        "patchloom rules should be appended"
    );
}

#[test]
fn test_init_appends_when_existing_agents_mentions_patchloom_without_generated_header() {
    let dir = TempDir::new().unwrap();
    fs::write(
        dir.path().join("AGENTS.md"),
        "# Rules\nUse patchloom for edits.\n",
    )
    .unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["init", "--yes", "--cwd"])
        .arg(dir.path())
        .env("SHELL", "unknown")
        .output()
        .unwrap();
    assert!(output.status.success());
    let content = fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
    assert!(content.starts_with("# Rules\nUse patchloom for edits.\n"));
    assert!(content.contains("# Patchloom"));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("appended patchloom rules"));
}

#[test]
fn test_init_skips_if_patchloom_already_present() {
    let dir = TempDir::new().unwrap();
    fs::write(
        dir.path().join("AGENTS.md"),
        "# Rules\n<!-- Generated by patchloom v0.1.0 -->\n",
    )
    .unwrap();
    let before = fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["init", "--yes", "--cwd"])
        .arg(dir.path())
        .output()
        .unwrap();
    assert!(output.status.success());
    let after = fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
    assert_eq!(before, after, "file should not be modified");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("already contains patchloom rules"));
}

#[test]
fn test_init_errors_on_non_utf8_existing_agents_md() {
    let dir = TempDir::new().unwrap();
    let agents = dir.path().join("AGENTS.md");
    fs::write(&agents, [0xff, 0xfe, 0x00]).unwrap();
    let before = fs::read(&agents).unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["init", "--yes", "--cwd"])
        .arg(dir.path())
        .env("SHELL", "unknown")
        .output()
        .unwrap();
    assert!(!output.status.success());
    assert_eq!(
        fs::read(&agents).unwrap(),
        before,
        "file should not be modified"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("could not read")
            && (stderr.contains("binary") || stderr.contains("UTF-8")),
        "human init must name the read failure: {stderr}"
    );
}

#[test]
fn test_init_appends_to_existing_claude_md() {
    let dir = TempDir::new().unwrap();
    let claude = dir.path().join("Claude.md");
    fs::write(&claude, "# Claude Rules\n").unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["init", "--yes", "--cwd"])
        .arg(dir.path())
        .env("SHELL", "unknown")
        .output()
        .unwrap();
    assert!(output.status.success());
    assert!(!dir.path().join("AGENTS.md").exists());
    let content = fs::read_to_string(&claude).unwrap();
    assert!(content.starts_with("# Claude Rules\n"));
    assert!(content.contains("# Patchloom"));
}

#[test]
fn test_init_quiet_suppresses_output() {
    let dir = TempDir::new().unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["init", "--yes", "--quiet", "--cwd"])
        .arg(dir.path())
        .output()
        .unwrap();
    assert!(output.status.success());
    // File should still be created
    assert!(dir.path().join("AGENTS.md").exists());
    // But stderr should be empty
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.is_empty(), "stderr should be empty with --quiet");
}

/// Global --json must not leave agents with human text on stdout.
#[test]
fn test_init_json_emits_structured_report() {
    let dir = TempDir::new().unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["--json", "init", "--yes", "--cwd"])
        .arg(dir.path())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "init --json must be JSON ({e}): {}",
            String::from_utf8_lossy(&output.stdout)
        )
    });
    assert_eq!(json["ok"], true, "{json}");
    assert_eq!(json["agent_rules"], "created", "{json}");
    assert_eq!(json["agent_rules_path"], "AGENTS.md", "{json}");
    assert!(
        json["gitignore"].as_str().is_some_and(|s| !s.is_empty()),
        "gitignore field required: {json}"
    );
    assert!(dir.path().join("AGENTS.md").exists());
    assert!(
        json.get("error_kind").is_none() || json["error_kind"].is_null(),
        "success report must not set error_kind: {json}"
    );
}

/// Hard-fail init --json must set error_kind so agents can branch.
#[test]
fn test_init_json_hard_fail_sets_error_kind() {
    let dir = TempDir::new().unwrap();
    fs::write(dir.path().join("AGENTS.md"), b"hello \xff world").unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["--json", "init", "--yes", "--cwd"])
        .arg(dir.path())
        .env("SHELL", "unknown")
        .output()
        .unwrap();
    assert_eq!(
        output.status.code(),
        Some(1),
        "stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "init --json must be JSON ({e}): {}",
            String::from_utf8_lossy(&output.stdout)
        )
    });
    assert_eq!(json["ok"], false, "{json}");
    assert_eq!(json["error_kind"], "invalid_encoding", "{json}");
    assert!(
        json["error"]
            .as_str()
            .is_some_and(|s| s.contains("UTF-8") || s.contains("encoding")),
        "error must name encoding: {json}"
    );
    assert!(
        json["agent_rules"]
            .as_str()
            .is_some_and(|s| s.starts_with("error:")),
        "agent_rules still reports error: {json}"
    );
}

#[test]
fn test_init_json_agents_md_directory_sets_error_kind() {
    let dir = TempDir::new().unwrap();
    fs::create_dir(dir.path().join("AGENTS.md")).unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["--json", "init", "--yes", "--cwd"])
        .arg(dir.path())
        .env("SHELL", "unknown")
        .output()
        .unwrap();
    assert_eq!(
        output.status.code(),
        Some(1),
        "stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["ok"], false, "{json}");
    assert_eq!(json["error_kind"], "invalid_input", "{json}");
    assert!(
        json["error"]
            .as_str()
            .is_some_and(|s| s.contains("not a file")),
        "error must name dest kind: {json}"
    );
}

/// #1833: `init --json` without `--yes` must still create AGENTS.md (agent bootstrap).
#[test]
fn test_init_json_without_yes_creates_agents_md() {
    let dir = TempDir::new().unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["--json", "init", "--cwd"])
        .arg(dir.path())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "init --json must be JSON ({e}): {}",
            String::from_utf8_lossy(&output.stdout)
        )
    });
    assert_eq!(json["ok"], true, "{json}");
    assert_eq!(
        json["agent_rules"], "created",
        "structured init must not skip AGENTS.md without --yes (#1833): {json}"
    );
    assert!(
        dir.path().join("AGENTS.md").exists(),
        "AGENTS.md must exist after init --json without --yes"
    );
    assert!(
        dir.path().join(".gitignore").exists(),
        "structured init must still write .gitignore (auto-accept)"
    );
    let content = fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
    assert!(
        content.contains("patchloom") || content.len() > 100,
        "AGENTS.md should contain generated rules"
    );
}

#[test]
fn test_init_falls_back_to_completion_command_when_completion_dir_creation_fails() {
    let dir = TempDir::new().unwrap();
    let fake_home = dir.path().join("fake-home");
    let blocking_file = fake_home.join(".config");
    fs::create_dir_all(&fake_home).unwrap();
    fs::write(&blocking_file, "not a directory\n").unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["init", "--yes", "--cwd"])
        .arg(dir.path())
        .env("HOME", &fake_home)
        .env("SHELL", "fish")
        .output()
        .unwrap();
    assert!(output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("failed to prepare completion directory:"));
    assert!(
        stderr.contains("patchloom completions fish > ~/.config/fish/completions/patchloom.fish")
    );
}

#[cfg(unix)]
#[test]
fn test_init_confirm_eof_skips_agents_creation() {
    let dir = TempDir::new().unwrap();
    // Two prompts now: AGENTS.md and .gitignore. EOF on each declines both.
    let output = run_patchloom_confirm_in_pty_with_env(
        &["init", "--cwd", dir.path().to_str().unwrap()],
        "\u{4}\u{4}",
        &[("SHELL", "unknown")],
    );

    assert!(output.status.success());
    assert!(!dir.path().join("AGENTS.md").exists());
    assert!(
        !dir.path().join(".gitignore").exists(),
        "declined gitignore must not create .gitignore"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("Create AGENTS.md? [Y/n]"));
    assert!(
        stdout.contains("skipped AGENTS.md")
            && stdout.contains("--yes")
            && stdout.contains("--json"),
        "decline must name remediation flags: {stdout}"
    );
}

/// Non-TTY plain `init` (no --yes) declines confirm and must not look like a silent no-op (#1922 / fixrealloop).
#[test]
fn test_init_noninteractive_without_yes_hints_use_yes() {
    let dir = TempDir::new().unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["init", "--cwd"])
        .arg(dir.path())
        .env("SHELL", "unknown")
        .output()
        .unwrap();
    assert!(output.status.success());
    assert!(
        !dir.path().join("AGENTS.md").exists(),
        "non-interactive init without --yes must not create AGENTS.md"
    );
    assert!(
        !dir.path().join(".gitignore").exists(),
        "non-interactive init without --yes must not silently create .gitignore"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("skipped AGENTS.md")
            && stderr.contains("--yes")
            && stderr.contains("--json"),
        "stderr must explain how to create rules: {stderr}"
    );
    assert!(
        stderr.contains("skipped .gitignore") || stderr.contains(".gitignore"),
        "stderr must mention gitignore skip: {stderr}"
    );
}

#[cfg(feature = "mcp")]
#[test]
fn test_init_shows_vscode_mcp_json_hint() {
    if !has_mcp_support() {
        return;
    }

    let dir = TempDir::new().unwrap();
    fs::create_dir(dir.path().join(".vscode")).unwrap();
    let home = TempDir::new().unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["init", "--yes", "--cwd"])
        .arg(dir.path())
        .env("HOME", home.path())
        .env("SHELL", "unknown")
        .output()
        .unwrap();

    assert!(output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("VS Code: create .vscode/mcp.json:"));
    assert!(stderr.contains(
        "\"servers\": { \"patchloom\": { \"command\": \"patchloom\", \"args\": [\"mcp-server\"] } }"
    ));
    assert!(!stderr.contains(".vscode/settings.json"));
}

#[cfg(feature = "mcp")]
#[test]
fn test_init_shows_cursor_mcp_json_hint() {
    if !has_mcp_support() {
        return;
    }

    let dir = TempDir::new().unwrap();
    fs::create_dir(dir.path().join(".cursor")).unwrap();
    let home = TempDir::new().unwrap();
    let output = Command::cargo_bin("patchloom")
        .unwrap()
        .args(["init", "--yes", "--cwd"])
        .arg(dir.path())
        .env("HOME", home.path())
        .env("SHELL", "unknown")
        .output()
        .unwrap();

    assert!(output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("Cursor: create .cursor/mcp.json:"));
    assert!(stderr.contains(
        "\"servers\": { \"patchloom\": { \"command\": \"patchloom\", \"args\": [\"mcp-server\"] } }"
    ));
}

// ---------------------------------------------------------------------------
// --glob flag
// ---------------------------------------------------------------------------