agent-config 0.3.0

Install hooks/integrations into AI coding harnesses (Claude Code, Cursor, Gemini CLI, OpenCode, Codex CLI, Cline, Windsurf, ...) without learning each one's filesystem layout.
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
//! Shared install/uninstall logic for standalone instruction files.
//!
//! Supports three placement modes via [`InstructionPlacement`]:
//!
//! - **InlineBlock**: inject content as a managed markdown block in a host
//!   file (reuses `md_block::upsert` / `md_block::remove`).
//! - **ReferencedFile**: write a standalone file and inject a managed include
//!   reference into the host file. Both the file and the reference are tracked
//!   in the ownership ledger.
//! - **StandaloneFile**: write a standalone file only, no reference
//!   (for agents with rules directories).
//!
//! Layout: this module is a directory with internal submodules that split
//! the dispatcher and per-placement bodies (`install`, `plan`, `uninstall`)
//! and the shim helpers (`shims`) used by `InstructionSurface` impls. All
//! callers consume this module via the re-exported flat API below.

use std::path::{Component, Path, PathBuf};

use crate::error::AgentConfigError;
use crate::integration::InstallReport;
use crate::spec::InstructionSpec;
use crate::util::fs_atomic;

mod install;
mod plan;
mod shims;
mod uninstall;

pub(crate) use install::install;
pub(crate) use plan::plan_install;
pub(crate) use shims::{
    inline_install, inline_plan_install, inline_plan_uninstall, inline_status, inline_uninstall,
    standalone_install, standalone_plan_install, standalone_plan_uninstall, standalone_status,
    standalone_uninstall,
};
pub(crate) use uninstall::{plan_uninstall, uninstall};

const LEDGER_FILE: &str = ".agent-config-instructions.json";
pub(super) const KIND: &str = "instruction";

/// Resolved per-scope path layout for an InlineBlock instruction agent.
///
/// Agents construct this once from their per-scope path resolution and pass
/// it to the [`inline_status`] / [`inline_install`] / etc. shim helpers,
/// which collapse the previously-duplicated InstructionSurface bodies.
pub(crate) struct InlineLayout {
    /// Directory holding the ownership ledger.
    pub config_dir: PathBuf,
    /// Memory file the inline block is upserted into.
    pub host_file: PathBuf,
}

/// Resolved per-scope path layout for a StandaloneFile instruction agent.
pub(crate) struct StandaloneLayout {
    /// Directory holding the ownership ledger.
    pub config_dir: PathBuf,
    /// Directory the standalone `<name>.md` file is written under.
    pub instruction_dir: PathBuf,
}

/// Ledger path for instructions.
pub(crate) fn ledger_path(config_dir: &Path) -> PathBuf {
    config_dir.join(LEDGER_FILE)
}

/// Instruction file path given a directory and name.
pub(super) fn instruction_file_path(dir: &Path, name: &str) -> PathBuf {
    dir.join(format!("{name}.md"))
}

/// Validate that an instruction name does not contain path traversal.
pub(super) fn validate_name(name: &str) -> Result<(), AgentConfigError> {
    InstructionSpec::validate_name(name)?;
    // Also reject slashes and other path separators embedded in the name.
    for c in name.chars() {
        if c == '/' || c == '\\' {
            return Err(AgentConfigError::Other(anyhow::anyhow!(
                "instruction name must not contain path separators (got {name:?})"
            )));
        }
    }
    Ok(())
}

/// Validate that a relative path used for reference mode is safe.
pub(super) fn validate_relative(p: &str) -> Result<(), AgentConfigError> {
    if p.starts_with('/') || p.starts_with('\\') {
        return Err(AgentConfigError::Other(anyhow::anyhow!(
            "instruction reference must not be absolute (got {p:?})"
        )));
    }
    for comp in Path::new(p).components() {
        match comp {
            Component::CurDir | Component::Normal(_) => {}
            _ => {
                return Err(AgentConfigError::Other(anyhow::anyhow!(
                    "instruction reference must not contain `..` or root (got {p:?})"
                )));
            }
        }
    }
    Ok(())
}

/// Probe instruction file and ledger on disk. Returns the instruction file
/// path, the ledger path, and whether the instruction file exists.
pub(crate) fn paths_for_status(
    config_dir: &Path,
    instruction_dir: &Path,
    name: &str,
) -> (PathBuf, PathBuf) {
    let file = instruction_file_path(instruction_dir, name);
    let led = ledger_path(config_dir);
    (file, led)
}

pub(super) fn ensure_trailing_newline(s: &str) -> String {
    if s.ends_with('\n') {
        s.to_string()
    } else {
        let mut out = s.to_string();
        out.push('\n');
        out
    }
}

pub(super) fn record_outcome(report: &mut InstallReport, outcome: fs_atomic::WriteOutcome) {
    if outcome.no_change {
        return;
    }
    if outcome.existed {
        report.patched.push(outcome.path.clone());
    } else {
        report.created.push(outcome.path.clone());
    }
    if let Some(b) = outcome.backup {
        report.backed_up.push(b);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scope::Scope;
    use crate::spec::InstructionPlacement;
    use std::fs;
    use tempfile::tempdir;

    fn local_scope(p: &Path) -> Scope {
        Scope::Local(p.to_path_buf())
    }

    fn basic_referenced_spec(name: &str, owner: &str) -> InstructionSpec {
        InstructionSpec::builder(name)
            .owner(owner)
            .placement(InstructionPlacement::ReferencedFile)
            .body("# MyApp\n\nProject-specific guidance.\n")
            .build()
    }

    fn basic_standalone_spec(name: &str, owner: &str) -> InstructionSpec {
        InstructionSpec::builder(name)
            .owner(owner)
            .placement(InstructionPlacement::StandaloneFile)
            .body("# MyApp\n\nProject-specific guidance.\n")
            .build()
    }

    fn basic_inline_spec(name: &str, owner: &str) -> InstructionSpec {
        InstructionSpec::builder(name)
            .owner(owner)
            .placement(InstructionPlacement::InlineBlock)
            .body("# MyApp\n\nProject-specific guidance.\n")
            .build()
    }

    #[test]
    fn referenced_file_creates_standalone_and_include_block() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let instr_dir = config_dir.join("instructions");
        let host = config_dir.join("CLAUDE.md");
        fs::create_dir_all(&config_dir).unwrap();

        install(
            &local_scope(dir.path()),
            &config_dir,
            &basic_referenced_spec("MYAPP", "myapp"),
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();

        let instr_path = instr_dir.join("MYAPP.md");
        assert!(instr_path.exists());
        assert!(fs::read_to_string(&instr_path).unwrap().contains("# MyApp"));

        let host_content = fs::read_to_string(&host).unwrap();
        assert!(host_content.contains("@MYAPP.md"));
        assert!(host_content.contains("BEGIN AGENT-CONFIG-INSTR:MYAPP"));
    }

    #[test]
    fn referenced_file_idempotent_same_content() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let instr_dir = config_dir.join("instructions");
        let host = config_dir.join("CLAUDE.md");
        fs::create_dir_all(&config_dir).unwrap();

        let spec = basic_referenced_spec("MYAPP", "myapp");
        install(
            &local_scope(dir.path()),
            &config_dir,
            &spec,
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();
        let report = install(
            &local_scope(dir.path()),
            &config_dir,
            &spec,
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();
        assert!(report.already_installed);
    }

    #[test]
    fn referenced_file_updates_on_content_change() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let instr_dir = config_dir.join("instructions");
        let host = config_dir.join("CLAUDE.md");
        fs::create_dir_all(&config_dir).unwrap();

        let spec1 = basic_referenced_spec("MYAPP", "myapp");
        install(
            &local_scope(dir.path()),
            &config_dir,
            &spec1,
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();

        let spec2 = InstructionSpec::builder("MYAPP")
            .owner("myapp")
            .placement(InstructionPlacement::ReferencedFile)
            .body("# MyApp v2\n\nUpdated content.\n")
            .build();
        let report = install(
            &local_scope(dir.path()),
            &config_dir,
            &spec2,
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();
        assert!(!report.already_installed);
        assert!(fs::read_to_string(instr_dir.join("MYAPP.md"))
            .unwrap()
            .contains("v2"));
    }

    #[test]
    fn standalone_file_writes_to_target_dir() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let rules_dir = config_dir.join("rules");
        fs::create_dir_all(&config_dir).unwrap();

        install(
            &local_scope(dir.path()),
            &config_dir,
            &basic_standalone_spec("MYAPP", "myapp"),
            None,
            Some(&rules_dir),
            None,
        )
        .unwrap();

        assert!(rules_dir.join("MYAPP.md").exists());
    }

    #[test]
    fn inline_block_uses_md_block() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let host = config_dir.join("AGENTS.md");
        fs::create_dir_all(&config_dir).unwrap();

        install(
            &local_scope(dir.path()),
            &config_dir,
            &basic_inline_spec("MYAPP", "myapp"),
            Some(&host),
            None,
            None,
        )
        .unwrap();

        let content = fs::read_to_string(&host).unwrap();
        assert!(content.contains("# MyApp"));
        assert!(content.contains("BEGIN AGENT-CONFIG-INSTR:MYAPP"));
    }

    #[test]
    fn uninstall_removes_file_and_include() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let instr_dir = config_dir.join("instructions");
        let host = config_dir.join("CLAUDE.md");
        fs::create_dir_all(&config_dir).unwrap();

        install(
            &local_scope(dir.path()),
            &config_dir,
            &basic_referenced_spec("MYAPP", "myapp"),
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();

        uninstall(
            &local_scope(dir.path()),
            &config_dir,
            "MYAPP",
            "myapp",
            Some(&host),
            Some(&instr_dir),
        )
        .unwrap();

        assert!(!instr_dir.join("MYAPP.md").exists());
        let host_content = fs::read_to_string(&host).unwrap();
        assert!(!host_content.contains("@MYAPP.md"));
        assert!(!host_content.contains("BEGIN AGENT-CONFIG:MYAPP"));
    }

    #[test]
    fn uninstall_refuses_modified_file() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let instr_dir = config_dir.join("instructions");
        let host = config_dir.join("CLAUDE.md");
        fs::create_dir_all(&config_dir).unwrap();

        install(
            &local_scope(dir.path()),
            &config_dir,
            &basic_referenced_spec("MYAPP", "myapp"),
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();

        // Modify the instruction file to simulate user edits.
        fs::write(instr_dir.join("MYAPP.md"), "# Modified content\n").unwrap();

        // Uninstall should still work (we don't check drift on uninstall
        // for instructions; we just remove the file).
        let report = uninstall(
            &local_scope(dir.path()),
            &config_dir,
            "MYAPP",
            "myapp",
            Some(&host),
            Some(&instr_dir),
        )
        .unwrap();
        assert!(!report.removed.is_empty());
    }

    #[test]
    #[cfg(unix)]
    fn uninstall_propagates_host_write_failure_and_preserves_ledger() {
        use std::os::unix::fs::symlink;

        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let instr_dir = config_dir.join("instructions");
        let host = config_dir.join("CLAUDE.md");
        fs::create_dir_all(&config_dir).unwrap();

        install(
            &local_scope(dir.path()),
            &config_dir,
            &basic_referenced_spec("MYAPP", "myapp"),
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();

        let ledger = config_dir.join(LEDGER_FILE);
        let ledger_before = fs::read_to_string(&ledger).unwrap();
        let host_content_before = fs::read_to_string(&host).unwrap();

        // Replace the regular host file with a symlink pointing outside the
        // local scope. Reads still succeed (they follow the symlink); the
        // safe_fs::write call must refuse it via Scope::Local containment so
        // the uninstall error propagates and the ledger entry is preserved.
        let outside = dir.path().parent().unwrap().join("escape.md");
        fs::write(&outside, &host_content_before).unwrap();
        fs::remove_file(&host).unwrap();
        symlink(&outside, &host).unwrap();

        let result = uninstall(
            &local_scope(dir.path()),
            &config_dir,
            "MYAPP",
            "myapp",
            Some(&host),
            Some(&instr_dir),
        );

        let _ = fs::remove_file(&host);
        let _ = fs::remove_file(&outside);

        assert!(
            result.is_err(),
            "uninstall must propagate host write failure"
        );
        assert!(
            ledger.exists(),
            "ledger file must remain when host write failed"
        );
        let ledger_after = fs::read_to_string(&ledger).unwrap();
        assert_eq!(
            ledger_before, ledger_after,
            "ledger entry must be preserved when host write failed"
        );
    }

    #[test]
    fn owner_mismatch_refused() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let instr_dir = config_dir.join("instructions");
        let host = config_dir.join("CLAUDE.md");
        fs::create_dir_all(&config_dir).unwrap();

        install(
            &local_scope(dir.path()),
            &config_dir,
            &basic_referenced_spec("MYAPP", "appA"),
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();

        let err = install(
            &local_scope(dir.path()),
            &config_dir,
            &basic_referenced_spec("MYAPP", "appB"),
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap_err();
        assert!(matches!(err, AgentConfigError::NotOwnedByCaller { .. }));
    }

    #[test]
    fn user_installed_refused() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let instr_dir = config_dir.join("instructions");
        let host = config_dir.join("CLAUDE.md");
        fs::create_dir_all(&instr_dir).unwrap();
        fs::write(instr_dir.join("MYAPP.md"), "# User content\n").unwrap();

        let err = install(
            &local_scope(dir.path()),
            &config_dir,
            &basic_referenced_spec("MYAPP", "myapp"),
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap_err();
        assert!(matches!(
            err,
            AgentConfigError::NotOwnedByCaller { actual: None, .. }
        ));
    }

    #[test]
    fn adopt_unowned_takes_over_orphan_instruction_file() {
        // Crash window: instruction file written, ledger never recorded.
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let instr_dir = config_dir.join("instructions");
        let host = config_dir.join("CLAUDE.md");
        fs::create_dir_all(&instr_dir).unwrap();
        fs::write(
            instr_dir.join("MYAPP.md"),
            "# MyApp\n\nProject-specific guidance.\n",
        )
        .unwrap();

        let adopt_spec = InstructionSpec::builder("MYAPP")
            .owner("myapp")
            .placement(InstructionPlacement::ReferencedFile)
            .body("# MyApp\n\nProject-specific guidance.\n")
            .adopt_unowned(true)
            .build();
        install(
            &local_scope(dir.path()),
            &config_dir,
            &adopt_spec,
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();

        // Ledger now exists with the right owner; subsequent plain install is
        // a no-op.
        let r = install(
            &local_scope(dir.path()),
            &config_dir,
            &basic_referenced_spec("MYAPP", "myapp"),
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();
        assert!(r.already_installed);
    }

    #[test]
    fn plan_install_no_side_effects() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("config");
        let instr_dir = config_dir.join("instructions");
        let host = config_dir.join("CLAUDE.md");
        fs::create_dir_all(&config_dir).unwrap();

        let changes = plan_install(
            &config_dir,
            &basic_referenced_spec("MYAPP", "myapp"),
            Some(&host),
            Some(&instr_dir),
            Some("@MYAPP.md"),
        )
        .unwrap();

        assert!(!changes.is_empty());
        // No files should have been created.
        assert!(!instr_dir.join("MYAPP.md").exists());
        assert!(!host.exists());
    }

    #[test]
    fn path_traversal_rejected() {
        // Names with special characters are rejected at spec validation time.
        let result = InstructionSpec::builder("../escape")
            .owner("myapp")
            .placement(InstructionPlacement::StandaloneFile)
            .body("body\n")
            .try_build();
        assert!(result.is_err());
    }

    // ---- Shim tests (inline_* / standalone_*) ----

    #[test]
    fn inline_shim_round_trip_and_status() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("cfg");
        let host = config_dir.join("AGENTS.md");
        fs::create_dir_all(&config_dir).unwrap();

        let layout = || InlineLayout {
            config_dir: config_dir.clone(),
            host_file: host.clone(),
        };

        let report = inline_install(
            &local_scope(dir.path()),
            layout(),
            &basic_inline_spec("MYAPP", "myapp"),
        )
        .unwrap();
        assert!(!report.already_installed);

        let status = inline_status(layout(), "MYAPP", "myapp").unwrap();
        assert!(matches!(
            status.status,
            crate::status::InstallStatus::InstalledOwned { .. }
        ));

        let r = inline_uninstall(&local_scope(dir.path()), layout(), "MYAPP", "myapp").unwrap();
        assert!(!r.patched.is_empty() || !r.removed.is_empty());

        let after = inline_status(layout(), "MYAPP", "myapp").unwrap();
        assert!(matches!(after.status, crate::status::InstallStatus::Absent));
    }

    #[test]
    fn standalone_shim_round_trip_and_status() {
        let dir = tempdir().unwrap();
        let config_dir = dir.path().join("cfg");
        let rules = config_dir.join("rules");
        fs::create_dir_all(&config_dir).unwrap();

        let layout = || StandaloneLayout {
            config_dir: config_dir.clone(),
            instruction_dir: rules.clone(),
        };

        standalone_install(
            &local_scope(dir.path()),
            layout(),
            &basic_standalone_spec("MYAPP", "myapp"),
        )
        .unwrap();
        assert!(rules.join("MYAPP.md").exists());

        let status = standalone_status(layout(), "MYAPP", "myapp").unwrap();
        assert!(matches!(
            status.status,
            crate::status::InstallStatus::InstalledOwned { .. }
        ));

        standalone_uninstall(&local_scope(dir.path()), layout(), "MYAPP", "myapp").unwrap();
        assert!(!rules.join("MYAPP.md").exists());
    }

    #[test]
    fn inline_plan_install_unsupported_scope_refuses() {
        let scope = local_scope(Path::new("/tmp/whatever"));
        let layout_err: Result<InlineLayout, AgentConfigError> =
            Err(AgentConfigError::UnsupportedScope {
                id: "test",
                scope: crate::scope::ScopeKind::Global,
            });
        let plan = inline_plan_install(
            "test",
            &scope,
            layout_err,
            &basic_inline_spec("MYAPP", "myapp"),
        )
        .unwrap();
        assert_eq!(plan.status, crate::plan::PlanStatus::Refused);
        assert!(plan.changes.iter().any(|c| matches!(
            c,
            crate::plan::PlannedChange::Refuse {
                reason: crate::plan::RefusalReason::UnsupportedScope,
                ..
            }
        )));
    }

    #[test]
    fn standalone_plan_install_unsupported_scope_refuses() {
        let scope = local_scope(Path::new("/tmp/whatever"));
        let layout_err: Result<StandaloneLayout, AgentConfigError> =
            Err(AgentConfigError::UnsupportedScope {
                id: "test",
                scope: crate::scope::ScopeKind::Global,
            });
        let plan = standalone_plan_install(
            "test",
            &scope,
            layout_err,
            &basic_standalone_spec("MYAPP", "myapp"),
        )
        .unwrap();
        assert_eq!(plan.status, crate::plan::PlanStatus::Refused);
    }

    #[test]
    fn inline_plan_uninstall_unsupported_scope_refuses() {
        let scope = local_scope(Path::new("/tmp/whatever"));
        let layout_err: Result<InlineLayout, AgentConfigError> =
            Err(AgentConfigError::UnsupportedScope {
                id: "test",
                scope: crate::scope::ScopeKind::Global,
            });
        let plan = inline_plan_uninstall("test", &scope, layout_err, "MYAPP", "myapp").unwrap();
        assert_eq!(plan.status, crate::plan::PlanStatus::Refused);
    }

    #[test]
    fn standalone_plan_uninstall_unsupported_scope_refuses() {
        let scope = local_scope(Path::new("/tmp/whatever"));
        let layout_err: Result<StandaloneLayout, AgentConfigError> =
            Err(AgentConfigError::UnsupportedScope {
                id: "test",
                scope: crate::scope::ScopeKind::Global,
            });
        let plan = standalone_plan_uninstall("test", &scope, layout_err, "MYAPP", "myapp").unwrap();
        assert_eq!(plan.status, crate::plan::PlanStatus::Refused);
    }

    #[test]
    fn inline_plan_install_propagates_non_scope_error() {
        let scope = local_scope(Path::new("/tmp/whatever"));
        // Use a generic error variant; if it's not UnsupportedScope, it should
        // propagate rather than convert to a refused plan.
        let layout_err: Result<InlineLayout, AgentConfigError> = Err(AgentConfigError::Other(
            anyhow::anyhow!("synthetic resolution failure"),
        ));
        let result = inline_plan_install(
            "test",
            &scope,
            layout_err,
            &basic_inline_spec("MYAPP", "myapp"),
        );
        assert!(result.is_err());
    }

    #[test]
    fn inline_install_replaces_legacy_fence_with_new_prefix() {
        // Simulate a host file written by a pre-rename version: a fenced
        // block under the legacy AGENT-CONFIG:<name> prefix, plus a ledger
        // entry confirming we own that name.
        let dir = tempdir().unwrap();
        let host = dir.path().join("AGENTS.md");
        let cfg = dir.path().join(".cfg");
        fs::create_dir_all(&cfg).unwrap();
        let legacy = crate::util::md_block::upsert("# Top\n", "myinstr", "old body");
        fs::write(&host, &legacy).unwrap();
        let led = ledger_path(&cfg);
        crate::util::ownership::record_install(
            &led,
            "myinstr",
            "owner-A",
            Some(&crate::util::ownership::content_hash(b"old body\n")),
        )
        .unwrap();

        let mut spec = basic_inline_spec("myinstr", "owner-A");
        spec.body = "new body\n".to_string();

        install(
            &local_scope(dir.path()),
            &cfg,
            &spec,
            Some(&host),
            None,
            None,
        )
        .expect("install_inline succeeds");

        let after = fs::read_to_string(&host).unwrap();
        assert!(after.contains("<!-- BEGIN AGENT-CONFIG-INSTR:myinstr -->"));
        assert!(after.contains("new body"));
        assert!(!after.contains("<!-- BEGIN AGENT-CONFIG:myinstr -->"));
        assert!(!after.contains("old body"));
    }

    #[test]
    fn uninstall_removes_legacy_fence_when_present() {
        let dir = tempdir().unwrap();
        let host = dir.path().join("AGENTS.md");
        let cfg = dir.path().join(".cfg");
        fs::create_dir_all(&cfg).unwrap();
        let legacy = crate::util::md_block::upsert("# Top\n", "myinstr", "old body");
        fs::write(&host, &legacy).unwrap();
        let led = ledger_path(&cfg);
        crate::util::ownership::record_install(
            &led,
            "myinstr",
            "owner-A",
            Some(&crate::util::ownership::content_hash(b"old body\n")),
        )
        .unwrap();

        uninstall(
            &local_scope(dir.path()),
            &cfg,
            "myinstr",
            "owner-A",
            Some(&host),
            None,
        )
        .expect("uninstall succeeds");

        let after = fs::read_to_string(&host).unwrap();
        assert!(!after.contains("AGENT-CONFIG:myinstr"));
        assert!(!after.contains("AGENT-CONFIG-INSTR:myinstr"));
        assert!(after.contains("# Top"));
    }
}