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
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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
use super::*;
use crate::ops::md::{find_section, has_dangerous_git_add_dot, strip_inline_code};
use std::fs;
use tempfile::TempDir;

mod basic {
    use super::*;

    // -- backup ------------------------------------------------------------

    #[test]
    fn replace_section_apply_creates_backup_session() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Title\nold content\n# Other\nkept\n").unwrap();

        let args = MdArgs {
            action: MdAction::ReplaceSection {
                file: file.to_str().unwrap().to_string(),
                heading: "Title".into(),
                stdin: false,
                content: Some("new content".into()),
            },
            write: Default::default(),
        };
        let mut global = GlobalFlags::test_with_cwd(dir.path());
        global.apply = true;

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let backup_dir = dir.path().join(".patchloom/backups");
        assert!(
            backup_dir.exists(),
            "backup directory should exist after md replace-section --apply"
        );
        let sessions: Vec<_> = fs::read_dir(&backup_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().is_dir())
            .collect();
        assert!(
            !sessions.is_empty(),
            "at least one backup session should be created"
        );
    }

    // -- replace-section ----------------------------------------------------

    #[test]
    fn replace_section_replaces_correct_content() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Title\nold content\n# Other\nkept\n").unwrap();

        let args = MdArgs {
            action: MdAction::ReplaceSection {
                file: file.to_str().unwrap().to_string(),
                heading: "Title".into(),
                stdin: false,
                content: Some("new content".into()),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let result = fs::read_to_string(&file).unwrap();
        assert!(result.contains("new content"), "missing new content");
        assert!(!result.contains("old content"), "old content still present");
        assert!(
            result.contains("# Other\nkept\n"),
            "adjacent section damaged"
        );
    }

    // -- insert-after-heading -----------------------------------------------

    #[test]
    fn insert_after_heading_inserts_at_correct_position() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Title\nexisting\n").unwrap();

        let args = MdArgs {
            action: MdAction::InsertAfterHeading {
                file: file.to_str().unwrap().to_string(),
                heading: "Title".into(),
                stdin: false,
                content: Some("inserted".into()),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let result = fs::read_to_string(&file).unwrap();
        assert!(
            result.starts_with("# Title\ninserted\n"),
            "insertion not at correct position: {result}"
        );
        assert!(result.contains("existing"), "existing content lost");
    }

    // -- upsert-bullet ------------------------------------------------------

    #[test]
    fn upsert_bullet_adds_new_bullet() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# List\n- item1\n").unwrap();

        let args = MdArgs {
            action: MdAction::UpsertBullet {
                file: file.to_str().unwrap().to_string(),
                heading: "List".into(),
                bullet: "item2".into(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let result = fs::read_to_string(&file).unwrap();
        assert!(result.contains("- item2"), "new bullet missing");
        assert!(result.contains("- item1"), "existing bullet lost");
    }

    // -- dedupe-headings ----------------------------------------------------

    #[test]
    fn dedupe_headings_removes_duplicate_headings() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(
            &file,
            "# Section\nfirst\n# Section\nsecond\n# Other\nkept\n",
        )
        .unwrap();

        let args = MdArgs {
            action: MdAction::DedupeHeadings {
                file: file.to_str().unwrap().to_string(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(
            result.matches("# Section").count(),
            1,
            "duplicate not removed: {result}"
        );
        assert!(result.contains("first"), "first occurrence body lost");
        assert!(!result.contains("second"), "duplicate body remains");
        assert!(
            result.contains("# Other\nkept\n"),
            "unrelated section damaged"
        );
    }

    #[test]
    fn lint_agents_finds_missing_final_newline() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("AGENTS.md");
        fs::write(&file, "# Rules\nNo trailing newline").unwrap();

        let args = MdArgs {
            action: MdAction::LintAgents {
                file: file.to_str().unwrap().to_string(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::CHANGES_DETECTED);
    }

    #[test]
    fn strip_inline_code_removes_backtick_spans() {
        assert_eq!(
            strip_inline_code("use `git add .` carefully"),
            "use  carefully"
        );
        assert_eq!(strip_inline_code("no backticks here"), "no backticks here");
        assert_eq!(strip_inline_code("`all code`"), "");
        assert_eq!(strip_inline_code("a `b` c `d` e"), "a  c  e");
    }

    // -- parser unit tests --------------------------------------------------

    #[test]
    fn parse_headings_basic() {
        let content = "# A\ntext\n## B\nmore\n# C\n";
        let h = crate::ops::md::parse_headings(content);
        assert_eq!(h.len(), 3);
        assert_eq!(h[0].level, 1);
        assert_eq!(h[0].text, "A");
        assert_eq!(h[1].level, 2);
        assert_eq!(h[1].text, "B");
        assert_eq!(h[2].level, 1);
        assert_eq!(h[2].text, "C");
        // A ends at C (level 1 <= 1).
        assert_eq!(h[0].line_end, 4);
        // B ends at C (level 1 <= 2).
        assert_eq!(h[1].line_end, 4);
        // C ends at EOF.
        assert_eq!(h[2].line_end, 5);
    }

    #[test]
    fn find_section_returns_correct_body() {
        let content = "# A\nbody a\n# B\nbody b\n";
        let (start, end) = find_section(content, "A").unwrap();
        assert_eq!(&content[start..end], "body a\n");

        let (start, end) = find_section(content, "B").unwrap();
        assert_eq!(&content[start..end], "body b\n");
    }

    // -- table-append -------------------------------------------------------

    #[test]
    fn table_append_adds_row() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Table\n| H1 | H2 |\n|---|---|\n| A | B |\n").unwrap();

        let args = MdArgs {
            action: MdAction::TableAppend {
                file: file.to_str().unwrap().to_string(),
                heading: "Table".into(),
                row: "| C | D |".into(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let result = fs::read_to_string(&file).unwrap();
        assert!(result.contains("| C | D |"), "new row missing");
        let a_pos = result.find("| A | B |").unwrap();
        let c_pos = result.find("| C | D |").unwrap();
        assert!(c_pos > a_pos, "new row not after existing data row");
    }

    // -- move-section -------------------------------------------------------

    #[test]
    fn move_section_same_file_reorder_before() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# A\na-content\n# B\nb-content\n# C\nc-content\n").unwrap();

        let args = MdArgs {
            action: MdAction::MoveSection {
                file: file.to_str().unwrap().to_string(),
                heading: "C".into(),
                to: None,
                before: Some("B".into()),
                after: None,
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let result = fs::read_to_string(&file).unwrap();
        let a_pos = result.find("# A").unwrap();
        let c_pos = result.find("# C").unwrap();
        let b_pos = result.find("# B").unwrap();
        assert!(a_pos < c_pos, "A should come before C");
        assert!(c_pos < b_pos, "C should come before B after move");
        assert!(result.contains("a-content"), "A content lost");
        assert!(result.contains("b-content"), "B content lost");
        assert!(result.contains("c-content"), "C content lost");
    }

    #[test]
    fn move_section_same_file_reorder_after() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# A\na-content\n# B\nb-content\n# C\nc-content\n").unwrap();

        let args = MdArgs {
            action: MdAction::MoveSection {
                file: file.to_str().unwrap().to_string(),
                heading: "A".into(),
                to: None,
                before: None,
                after: Some("B".into()),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let result = fs::read_to_string(&file).unwrap();
        let b_pos = result.find("# B").unwrap();
        let a_pos = result.find("# A").unwrap();
        let c_pos = result.find("# C").unwrap();
        assert!(b_pos < a_pos, "B should come before A after move");
        assert!(a_pos < c_pos, "A should come before C");
    }

    #[test]
    fn move_section_cross_file() {
        let dir = TempDir::new().unwrap();
        let src = dir.path().join("source.md");
        let dst = dir.path().join("dest.md");
        fs::write(
            &src,
            "# Keep\nkept\n# Move Me\nmoved content\n# Also Keep\nalso\n",
        )
        .unwrap();
        fs::write(&dst, "# Intro\nintro text\n# End\nend text\n").unwrap();

        let args = MdArgs {
            action: MdAction::MoveSection {
                file: src.to_str().unwrap().to_string(),
                heading: "Move Me".into(),
                to: Some(dst.to_str().unwrap().to_string()),
                before: Some("End".into()),
                after: None,
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let src_result = fs::read_to_string(&src).unwrap();
        assert!(
            !src_result.contains("# Move Me"),
            "section not removed from source"
        );
        assert!(
            !src_result.contains("moved content"),
            "section body not removed from source"
        );
        assert!(src_result.contains("# Keep"), "kept section lost");
        assert!(src_result.contains("# Also Keep"), "other section lost");

        let dst_result = fs::read_to_string(&dst).unwrap();
        assert!(
            dst_result.contains("# Move Me"),
            "section not added to dest"
        );
        assert!(
            dst_result.contains("moved content"),
            "section body not in dest"
        );
        let move_pos = dst_result.find("# Move Me").unwrap();
        let end_pos = dst_result.find("# End").unwrap();
        assert!(move_pos < end_pos, "section not inserted before End");
    }
}

mod edge_cases {
    use super::*;

    #[test]
    fn upsert_bullet_is_idempotent_when_bullet_exists() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# List\n- item1\n").unwrap();

        let args = MdArgs {
            action: MdAction::UpsertBullet {
                file: file.to_str().unwrap().to_string(),
                heading: "List".into(),
                bullet: "- item1".into(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let result = fs::read_to_string(&file).unwrap();
        assert_eq!(
            result.matches("- item1").count(),
            1,
            "bullet duplicated: {result}"
        );
    }

    #[test]
    fn find_section_accepts_hash_prefixed_query() {
        let content = "## Sub\ndata\n";
        let (start, end) = find_section(content, "## Sub").unwrap();
        assert_eq!(&content[start..end], "data\n");
    }

    #[test]
    fn move_section_explicit_to_same_file_reorders_not_duplicates() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# A\na-content\n# B\nb-content\n# C\nc-content\n").unwrap();

        let path_str = file.to_str().unwrap().to_string();
        let args = MdArgs {
            action: MdAction::MoveSection {
                file: path_str.clone(),
                heading: "C".into(),
                to: Some(path_str),
                before: Some("B".into()),
                after: None,
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let result = fs::read_to_string(&file).unwrap();
        let a_pos = result.find("# A").unwrap();
        let c_pos = result.find("# C").unwrap();
        let b_pos = result.find("# B").unwrap();
        assert!(a_pos < c_pos, "A should come before C");
        assert!(c_pos < b_pos, "C should come before B after move");
        assert_eq!(
            result.matches("# C").count(),
            1,
            "section C must appear exactly once (not duplicated)"
        );
        assert_eq!(
            result.matches("c-content").count(),
            1,
            "content must not be duplicated"
        );
    }
}

mod error_handling {
    use super::*;

    #[test]
    fn replace_section_missing_heading_returns_exit_3() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Title\ncontent\n").unwrap();

        let args = MdArgs {
            action: MdAction::ReplaceSection {
                file: file.to_str().unwrap().to_string(),
                heading: "Missing".into(),
                stdin: false,
                content: Some("new".into()),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::NO_MATCHES);
    }

    #[test]
    fn insert_after_heading_missing_returns_exit_3() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Title\ncontent\n").unwrap();

        let args = MdArgs {
            action: MdAction::InsertAfterHeading {
                file: file.to_str().unwrap().to_string(),
                heading: "Missing".into(),
                stdin: false,
                content: Some("inserted".into()),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::NO_MATCHES);
    }

    #[test]
    fn upsert_bullet_missing_heading_returns_exit_3() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Title\ncontent\n").unwrap();

        let args = MdArgs {
            action: MdAction::UpsertBullet {
                file: file.to_str().unwrap().to_string(),
                heading: "Missing".into(),
                bullet: "new item".into(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::NO_MATCHES);
    }

    #[test]
    fn table_append_heading_not_found_returns_exit_3() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Title\n| H1 |\n|---|\n| A |\n").unwrap();

        let args = MdArgs {
            action: MdAction::TableAppend {
                file: file.to_str().unwrap().to_string(),
                heading: "Missing".into(),
                row: "| X |".into(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::NO_MATCHES);
    }

    #[test]
    fn replace_section_missing_heading_json_emits_error() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Title\ncontent\n").unwrap();

        let args = MdArgs {
            action: MdAction::ReplaceSection {
                file: file.to_str().unwrap().to_string(),
                heading: "Missing".into(),
                stdin: false,
                content: Some("new".into()),
            },
            write: Default::default(),
        };
        let mut global = GlobalFlags::test_apply();
        global.json = true;
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::NO_MATCHES);
        // The JSON error is emitted via global.emit_json which writes to
        // stdout. We verify the exit code; the unit tests in output.rs
        // verify that emit_json produces valid JSON.
    }

    #[test]
    fn table_append_missing_heading_json_emits_error() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Title\n| H1 |\n|---|\n| A |\n").unwrap();

        let args = MdArgs {
            action: MdAction::TableAppend {
                file: file.to_str().unwrap().to_string(),
                heading: "Missing".into(),
                row: "| X |".into(),
            },
            write: Default::default(),
        };
        let mut global = GlobalFlags::test_apply();
        global.json = true;
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::NO_MATCHES);
    }

    #[test]
    fn table_append_no_table_returns_error() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Title\nsome text but no table\n").unwrap();

        let args = MdArgs {
            action: MdAction::TableAppend {
                file: file.to_str().unwrap().to_string(),
                heading: "Title".into(),
                row: "| X |".into(),
            },
            write: Default::default(),
        };
        let result = run(args, &GlobalFlags::test_apply());
        assert!(result.is_err(), "expected error when no table is present");
    }

    #[test]
    fn file_not_found_propagates_as_error_not_no_matches() {
        // R3 fix: only "heading ... not found" maps to NO_MATCHES.
        // A missing file ("not found" in the I/O error) must propagate
        // as an error, not be silently treated as NO_MATCHES.
        let dir = TempDir::new().unwrap();
        let missing = dir.path().join("does_not_exist.md");

        let args = MdArgs {
            action: MdAction::ReplaceSection {
                file: missing.to_str().unwrap().to_string(),
                heading: "Title".into(),
                stdin: false,
                content: Some("new".into()),
            },
            write: Default::default(),
        };
        let result = run(args, &GlobalFlags::test_apply());
        // Must be an error (file not found), not Ok(exit::NO_MATCHES).
        assert!(
            result.is_err(),
            "missing file should propagate as error, not NO_MATCHES"
        );
    }

    #[test]
    fn find_section_none_for_missing() {
        assert!(find_section("# X\n", "Y").is_none());
    }

    #[test]
    fn move_section_missing_heading_returns_exit_3() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# A\ncontent\n").unwrap();

        let args = MdArgs {
            action: MdAction::MoveSection {
                file: file.to_str().unwrap().to_string(),
                heading: "Missing".into(),
                to: None,
                before: Some("A".into()),
                after: None,
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::NO_MATCHES);
    }

    #[test]
    fn move_section_no_before_or_after_returns_error() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# A\ncontent\n").unwrap();

        let args = MdArgs {
            action: MdAction::MoveSection {
                file: file.to_str().unwrap().to_string(),
                heading: "A".into(),
                to: None,
                before: None,
                after: None,
            },
            write: Default::default(),
        };
        let result = run(args, &GlobalFlags::test_apply());
        assert!(
            result.is_err(),
            "expected error when neither --before nor --after is provided"
        );
    }
}

mod security {
    use super::*;

    // -- lint-agents --------------------------------------------------------

    #[test]
    fn lint_agents_finds_duplicate_headings() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("AGENTS.md");
        fs::write(&file, "# Rules\nfoo\n# Rules\nbar\n").unwrap();

        let args = MdArgs {
            action: MdAction::LintAgents {
                file: file.to_str().unwrap().to_string(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::CHANGES_DETECTED);
    }

    #[test]
    fn lint_agents_finds_dangerous_git_add_dot() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("AGENTS.md");
        fs::write(&file, "# Rules\nRun git add . to stage\n").unwrap();

        let args = MdArgs {
            action: MdAction::LintAgents {
                file: file.to_str().unwrap().to_string(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::CHANGES_DETECTED);
    }

    #[test]
    fn lint_agents_finds_dangerous_git_add_all_long_form() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("AGENTS.md");
        fs::write(&file, "# Rules\nRun git add --all to stage\n").unwrap();

        let args = MdArgs {
            action: MdAction::LintAgents {
                file: file.to_str().unwrap().to_string(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::CHANGES_DETECTED);
    }

    #[test]
    fn lint_agents_skips_dangerous_cmd_in_code_fence() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("AGENTS.md");
        fs::write(
            &file,
            "# Rules\n\n```bash\n# BAD example\ngit add .\n```\n\nStage explicitly.\n",
        )
        .unwrap();

        let args = MdArgs {
            action: MdAction::LintAgents {
                file: file.to_str().unwrap().to_string(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);
    }

    #[test]
    fn lint_agents_skips_dangerous_cmd_in_tilde_fence() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("AGENTS.md");
        fs::write(
            &file,
            "# Rules\n\n~~~bash\n# BAD example\ngit add .\n~~~\n\nStage explicitly.\n",
        )
        .unwrap();

        let args = MdArgs {
            action: MdAction::LintAgents {
                file: file.to_str().unwrap().to_string(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);
    }

    #[test]
    fn lint_agents_skips_dangerous_cmd_in_inline_code() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("AGENTS.md");
        fs::write(&file, "# Rules\nNever use `git add .` or `git add -A`.\n").unwrap();

        let args = MdArgs {
            action: MdAction::LintAgents {
                file: file.to_str().unwrap().to_string(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);
    }

    #[test]
    fn has_dangerous_git_add_dot_true_cases() {
        assert!(has_dangerous_git_add_dot("git add ."));
        assert!(has_dangerous_git_add_dot("run git add . first"));
        assert!(has_dangerous_git_add_dot("git add . && git commit"));
    }

    #[test]
    fn has_dangerous_git_add_dot_false_for_dotfiles() {
        assert!(!has_dangerous_git_add_dot("git add .gitignore"));
        assert!(!has_dangerous_git_add_dot("git add .editorconfig"));
        assert!(!has_dangerous_git_add_dot(
            "git add .github/workflows/ci.yml"
        ));
    }

    #[test]
    fn has_dangerous_git_add_dot_slash() {
        // "git add ./" is equivalent to "git add ." and should be caught.
        assert!(has_dangerous_git_add_dot("git add ./"));
        assert!(has_dangerous_git_add_dot("git add ./ && git commit"));
        // But "git add ./foo" is explicit file staging and is safe.
        assert!(!has_dangerous_git_add_dot("git add ./foo"));
        assert!(!has_dangerous_git_add_dot("git add ./src/main.rs"));
    }

    #[test]
    fn lint_agents_allows_git_add_dotfile() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("AGENTS.md");
        fs::write(&file, "# Rules\nRun git add .gitignore to stage\n").unwrap();

        let args = MdArgs {
            action: MdAction::LintAgents {
                file: file.to_str().unwrap().to_string(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);
    }
}

mod format_preservation {
    use super::*;

    // -- final newline ------------------------------------------------------

    #[test]
    fn final_newline_is_preserved_on_write() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(&file, "# Title\ncontent\n").unwrap();

        let mut global = GlobalFlags::test_apply();
        global.ensure_final_newline = true;

        let args = MdArgs {
            action: MdAction::ReplaceSection {
                file: file.to_str().unwrap().to_string(),
                heading: "Title".into(),
                stdin: false,
                content: Some("replaced".into()),
            },
            write: Default::default(),
        };
        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let result = fs::read_to_string(&file).unwrap();
        assert!(result.ends_with('\n'), "final newline missing: {result:?}");
    }

    #[test]
    fn table_append_preserves_surrounding_content() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.md");
        fs::write(
            &file,
            "# Before\npre-content\n# Table\n| H1 |\n|---|\n| A |\n\nAfter table text.\n# After\npost-content\n",
        )
        .unwrap();

        let args = MdArgs {
            action: MdAction::TableAppend {
                file: file.to_str().unwrap().to_string(),
                heading: "Table".into(),
                row: "| B |".into(),
            },
            write: Default::default(),
        };
        let code = run(args, &GlobalFlags::test_apply()).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let result = fs::read_to_string(&file).unwrap();
        assert!(
            result.contains("# Before\npre-content\n"),
            "content before heading damaged"
        );
        assert!(
            result.contains("After table text.\n"),
            "content after table damaged"
        );
        assert!(
            result.contains("# After\npost-content\n"),
            "next section damaged"
        );
        assert!(result.contains("| B |"), "new row missing");
    }
}