agent-config 0.4.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
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
//! The contract every AI-harness integration implements.
//!
//! There are several distinct **surfaces** an integration may expose:
//!
//! - [`Integration`]: the hooks surface.
//! - [`McpSurface`]: MCP server registration.
//! - [`SkillSurface`]: skill installation.
//! - [`InstructionSurface`]: standalone instruction files.
//!
//! Each surface is its own trait so callers cannot accidentally call
//! `install_mcp` on a harness that does not support MCP, the type system
//! forbids it. Use [`crate::registry::mcp_capable`] to enumerate the agents
//! that implement `McpSurface`.

use std::path::PathBuf;

use crate::error::AgentConfigError;
use crate::plan::{InstallPlan, PlanTarget, UninstallPlan};
use crate::scope::{Scope, ScopeKind};
use crate::spec::{HookSpec, InstructionSpec, McpSpec, SkillSpec};
use crate::status::{InstallStatus, StatusReport};
use crate::validation::ValidationReport;

/// One AI harness's hook installer.
///
/// The trait is intentionally narrow so adding a new harness is a small,
/// mechanical exercise: implement `Integration`, then register it in
/// [`crate::registry::all`].
///
/// All operations must be idempotent: calling `install` twice with the same
/// spec, or `uninstall` twice with the same tag, must produce the same end
/// state as calling once.
pub trait Integration: Send + Sync {
    /// Stable, kebab-case identifier (e.g., `"claude"`, `"cursor"`).
    fn id(&self) -> &'static str;

    /// Human-readable name (e.g., `"Claude Code"`).
    fn display_name(&self) -> &'static str;

    /// Which scopes this integration accepts.
    fn supported_scopes(&self) -> &'static [ScopeKind];

    /// Returns true if a hook with this `tag` is currently installed in this
    /// scope. Used by CLI consumers to render install/uninstall state.
    ///
    /// Default impl matches on the richer [`status`](Integration::status)
    /// result and treats [`InstallStatus::InstalledOwned`] and
    /// [`InstallStatus::InstalledOtherOwner`] as installed; agents that have
    /// already implemented `status` get this for free.
    ///
    /// # Errors
    ///
    /// Propagates whatever [`status`](Integration::status) returns: typically
    /// [`AgentConfigError::PathResolution`], [`AgentConfigError::Io`],
    /// [`AgentConfigError::JsonInvalid`], or
    /// [`AgentConfigError::ConfigTooLarge`].
    fn is_installed(&self, scope: &Scope, tag: &str) -> Result<bool, AgentConfigError> {
        Ok(matches!(
            self.status(scope, tag)?.status,
            InstallStatus::InstalledOwned { .. } | InstallStatus::InstalledOtherOwner { .. }
        ))
    }

    /// Detailed installation state for the hook identified by `tag`.
    ///
    /// Distinguishes installed-by-us from installed-by-someone-else, surfaces
    /// drift (parse failures, duplicate entries), and reports any pending
    /// `.bak` files. See [`StatusReport`] for the full shape.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::PathResolution`] when the harness config path
    ///   cannot be resolved (e.g. `$HOME` missing).
    /// - [`AgentConfigError::Io`] for unreadable files other than the
    ///   "missing" case (which becomes [`InstallStatus::Absent`]).
    /// - [`AgentConfigError::ConfigTooLarge`] when the config file exceeds
    ///   the 8 MiB read cap.
    ///
    /// Parse failures are intentionally folded into a [`StatusReport`] with
    /// [`crate::status::DriftIssue::InvalidConfig`] rather than surfaced as
    /// errors.
    fn status(&self, scope: &Scope, tag: &str) -> Result<StatusReport, AgentConfigError>;

    /// Validate hook state without mutating user files.
    ///
    /// Unlike [`status`](Integration::status), this reports whether the
    /// discovered state is internally consistent and safe to repair.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::InvalidTag`] when `tag` is not a legal hook tag.
    /// - Any error from [`status`](Integration::status) other than
    ///   [`AgentConfigError::JsonInvalid`], which is folded into the
    ///   returned [`ValidationReport`] as malformed-ledger output.
    fn validate(&self, scope: &Scope, tag: &str) -> Result<ValidationReport, AgentConfigError> {
        HookSpec::validate_tag(tag)?;
        let target = PlanTarget::Hook {
            integration_id: self.id(),
            scope: scope.clone(),
            tag: tag.to_string(),
        };
        let status = match self.status(scope, tag) {
            Ok(status) => status,
            Err(AgentConfigError::JsonInvalid { path, source }) => {
                return Ok(crate::validation::malformed_ledger_report(
                    target,
                    path,
                    source.to_string(),
                ));
            }
            Err(e) => return Err(e),
        };
        Ok(crate::validation::hook_report_from_status(target, status))
    }

    /// Plan a hook install without mutating user files.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::PathResolution`] when the target config path
    ///   cannot be resolved or escapes the scope root.
    /// - [`AgentConfigError::UnsupportedScope`] is encoded as
    ///   [`crate::plan::PlanStatus::Refused`] rather than returned.
    /// - [`AgentConfigError::Io`] / [`AgentConfigError::ConfigTooLarge`]
    ///   when the existing config cannot be read.
    /// - [`AgentConfigError::InvalidTag`] from spec re-validation.
    fn plan_install(&self, scope: &Scope, spec: &HookSpec)
        -> Result<InstallPlan, AgentConfigError>;

    /// Plan a hook uninstall without mutating user files.
    ///
    /// # Errors
    ///
    /// Same envelope as [`plan_install`](Integration::plan_install).
    /// Predictable refusals (unsupported scope, owner mismatch) are encoded
    /// as [`crate::plan::PlanStatus::Refused`].
    fn plan_uninstall(&self, scope: &Scope, tag: &str) -> Result<UninstallPlan, AgentConfigError>;

    /// Install the hook. Repeated calls with the same `spec.tag` are a no-op
    /// after the first (the on-disk state is reached, then preserved).
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::PathResolution`] when the target path escapes
    ///   the scope root or contains a symlink component.
    /// - [`AgentConfigError::UnsupportedScope`] when the scope is not in
    ///   [`supported_scopes`](Integration::supported_scopes).
    /// - [`AgentConfigError::Io`] for filesystem failures, including
    ///   permission denials and atomic-rename collisions.
    /// - [`AgentConfigError::JsonInvalid`] / [`AgentConfigError::TomlInvalid`]
    ///   when the existing config is unparseable and cannot be merged.
    /// - [`AgentConfigError::ConfigTooLarge`] when the existing config
    ///   exceeds the 8 MiB read cap.
    /// - [`AgentConfigError::BackupExists`] when a sibling `.bak` already
    ///   exists for a file we would otherwise back up.
    /// - [`AgentConfigError::MissingSpecField`] /
    ///   [`AgentConfigError::InvalidTag`] from spec re-validation.
    fn install(&self, scope: &Scope, spec: &HookSpec) -> Result<InstallReport, AgentConfigError>;

    /// Uninstall the hook identified by `tag`. Restores `.bak` files when
    /// removing our content leaves the target file empty or pristine.
    ///
    /// # Errors
    ///
    /// Same envelope as [`install`](Integration::install). Hooks have no
    /// separate ownership ledger (the tag is the owner), so there is no
    /// [`AgentConfigError::NotOwnedByCaller`] arm here.
    fn uninstall(&self, scope: &Scope, tag: &str) -> Result<UninstallReport, AgentConfigError>;

    /// Migrate any prior layout produced by an earlier version of the consumer
    /// (e.g., remove a legacy shell-script wrapper that has since been
    /// superseded by a native binary). Default impl is a no-op.
    ///
    /// # Errors
    ///
    /// Implementation-defined; the default returns [`MigrationReport::NoOp`]
    /// unconditionally. Concrete impls typically return
    /// [`AgentConfigError::Io`] or [`AgentConfigError::PathResolution`].
    fn migrate(&self, _scope: &Scope, _tag: &str) -> Result<MigrationReport, AgentConfigError> {
        Ok(MigrationReport::NoOp)
    }
}

/// One AI harness's MCP-server installer.
///
/// Implemented by harnesses that load MCP server configs from a known file.
/// Harnesses without a confirmed file-backed MCP contract do not implement
/// this trait, so callers discover that at compile time or through
/// [`crate::registry::mcp_capable`].
///
/// All operations must be idempotent: installing the same [`McpSpec`] twice
/// reaches and preserves a single on-disk state. Uninstalls refuse to remove
/// entries owned by another consumer (recorded in a sidecar ledger).
pub trait McpSurface: Send + Sync {
    /// Stable, kebab-case identifier matching [`Integration::id`] for the same
    /// agent (e.g., `"claude"`).
    fn id(&self) -> &'static str;

    /// Which scopes this MCP installer accepts.
    fn supported_mcp_scopes(&self) -> &'static [ScopeKind];

    /// Returns true if a server with `name` is currently recorded under any
    /// owner in this scope's ownership ledger.
    ///
    /// Default impl folds the richer
    /// [`mcp_status`](McpSurface::mcp_status) into the historical boolean
    /// ("under any owner"); concretely, both
    /// [`InstallStatus::InstalledOwned`] and
    /// [`InstallStatus::InstalledOtherOwner`] count as installed.
    ///
    /// # Errors
    ///
    /// Propagates whatever [`mcp_status`](McpSurface::mcp_status) returns.
    fn is_mcp_installed(&self, scope: &Scope, name: &str) -> Result<bool, AgentConfigError> {
        // Pass the agent's id as the expected owner so any real consumer
        // owner (e.g. "myapp") routes through `InstalledOtherOwner`. The
        // boolean fold collapses both arms anyway.
        Ok(matches!(
            self.mcp_status(scope, name, self.id())?.status,
            InstallStatus::InstalledOwned { .. } | InstallStatus::InstalledOtherOwner { .. }
        ))
    }

    /// Detailed installation state for the MCP server identified by `name`,
    /// scored against `expected_owner`.
    ///
    /// `expected_owner` is the consumer tag the caller wants to compare
    /// against — when the ledger records this owner, the report returns
    /// [`InstallStatus::InstalledOwned`]; anything else recorded becomes
    /// [`InstallStatus::InstalledOtherOwner`].
    ///
    /// # Errors
    ///
    /// Same envelope as [`Integration::status`]:
    /// [`AgentConfigError::PathResolution`], [`AgentConfigError::Io`], and
    /// [`AgentConfigError::ConfigTooLarge`]. Parse failures fold into
    /// [`crate::status::DriftIssue::InvalidConfig`] inside the report.
    fn mcp_status(
        &self,
        scope: &Scope,
        name: &str,
        expected_owner: &str,
    ) -> Result<StatusReport, AgentConfigError>;

    /// Validate MCP state without mutating user files.
    ///
    /// # Errors
    ///
    /// Equivalent to
    /// [`validate_mcp_for_owner`](McpSurface::validate_mcp_for_owner) with
    /// `expected_owner = None`.
    fn validate_mcp(
        &self,
        scope: &Scope,
        name: &str,
    ) -> Result<ValidationReport, AgentConfigError> {
        self.validate_mcp_for_owner(scope, name, None)
    }

    /// Validate MCP state against a caller-supplied expected owner.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::InvalidTag`] when `name` or `expected_owner`
    ///   fails identifier validation.
    /// - Any error from [`mcp_status`](McpSurface::mcp_status) other than
    ///   [`AgentConfigError::JsonInvalid`], which is folded into the
    ///   returned [`ValidationReport`] as malformed-ledger output.
    fn validate_mcp_for_owner(
        &self,
        scope: &Scope,
        name: &str,
        expected_owner: Option<&str>,
    ) -> Result<ValidationReport, AgentConfigError> {
        McpSpec::validate_name(name)?;
        if let Some(owner) = expected_owner {
            HookSpec::validate_tag(owner)?;
        }
        let status = match self.mcp_status(scope, name, expected_owner.unwrap_or("")) {
            Ok(status) => status,
            Err(AgentConfigError::JsonInvalid { path, source }) => {
                let target = PlanTarget::Mcp {
                    integration_id: self.id(),
                    scope: scope.clone(),
                    name: name.to_string(),
                    owner: expected_owner.unwrap_or_default().to_string(),
                };
                return Ok(crate::validation::malformed_ledger_report(
                    target,
                    path,
                    source.to_string(),
                ));
            }
            Err(e) => return Err(e),
        };
        let target = PlanTarget::Mcp {
            integration_id: self.id(),
            scope: scope.clone(),
            name: name.to_string(),
            owner: expected_owner
                .map(str::to_owned)
                .or_else(|| owner_from_status(&status))
                .unwrap_or_default(),
        };
        crate::validation::ledger_backed_report_from_status(target, name, expected_owner, status)
    }

    /// Plan an MCP server install without mutating user files.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::PathResolution`] when the MCP config path
    ///   cannot be resolved.
    /// - [`AgentConfigError::Io`] / [`AgentConfigError::ConfigTooLarge`]
    ///   when the existing config or ledger cannot be read.
    /// - [`AgentConfigError::MissingSpecField`] /
    ///   [`AgentConfigError::InvalidTag`] from [`McpSpec`] re-validation.
    /// - [`AgentConfigError::InlineSecretInLocalScope`] when `spec` carries an
    ///   inline secret (`SecretPolicy::Inline`) under `Scope::Local`.
    ///
    /// Predictable refusals (unsupported scope, unsupported transport, owner
    /// mismatch, parse failure) are encoded as
    /// [`crate::plan::PlanStatus::Refused`].
    fn plan_install_mcp(
        &self,
        scope: &Scope,
        spec: &McpSpec,
    ) -> Result<InstallPlan, AgentConfigError>;

    /// Plan an MCP server uninstall without mutating user files.
    ///
    /// # Errors
    ///
    /// Same envelope as [`plan_install_mcp`](McpSurface::plan_install_mcp).
    fn plan_uninstall_mcp(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallPlan, AgentConfigError>;

    /// Install (or update) the MCP server. Repeated calls with the same
    /// `spec.name` and same content are a no-op after the first.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::PathResolution`] when the target path escapes
    ///   the scope root or contains a symlink component.
    /// - [`AgentConfigError::UnsupportedScope`] when the scope is not in
    ///   [`supported_mcp_scopes`](McpSurface::supported_mcp_scopes).
    /// - [`AgentConfigError::Io`] for filesystem failures.
    /// - [`AgentConfigError::JsonInvalid`] / [`AgentConfigError::TomlInvalid`]
    ///   when the existing config is unparseable and cannot be merged.
    /// - [`AgentConfigError::ConfigTooLarge`] when an input exceeds 8 MiB.
    /// - [`AgentConfigError::BackupExists`] when a sibling `.bak` already
    ///   exists for a file that would otherwise be backed up.
    /// - [`AgentConfigError::NotOwnedByCaller`] when an existing server entry
    ///   belongs to a different consumer (or is unowned and `adopt_unowned`
    ///   is false).
    /// - [`AgentConfigError::InlineSecretInLocalScope`] under `Scope::Local`
    ///   when the spec carries an inline secret.
    /// - [`AgentConfigError::UnsupportedTransport`] when the integration does
    ///   not support the requested MCP transport.
    /// - [`AgentConfigError::MissingSpecField`] /
    ///   [`AgentConfigError::InvalidTag`] from spec re-validation.
    fn install_mcp(&self, scope: &Scope, spec: &McpSpec)
        -> Result<InstallReport, AgentConfigError>;

    /// Uninstall the MCP server identified by `name`, owned by `owner_tag`.
    ///
    /// Returns [`AgentConfigError::NotOwnedByCaller`] if the entry is recorded
    /// under a different owner, or if it exists in the harness config but is
    /// missing from the ledger (i.e., user-installed by hand).
    ///
    /// # Errors
    ///
    /// Same envelope as [`install_mcp`](McpSurface::install_mcp). The
    /// owner-mismatch case is the typical one.
    fn uninstall_mcp(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallReport, AgentConfigError>;
}

/// One AI harness's skill installer.
///
/// Skills are directory-scoped: each one is a folder under the harness's
/// `skills/` root containing a `SKILL.md` plus optional `scripts/`,
/// `references/`, and `assets/` subdirectories. Implemented by harnesses with
/// upstream Agent Skills support.
///
/// Like [`McpSurface`], ownership is tracked via a sidecar ledger so multiple
/// consumers can coexist and uninstall is refused on owner mismatch.
pub trait SkillSurface: Send + Sync {
    /// Stable, kebab-case identifier matching [`Integration::id`] for the
    /// same agent.
    fn id(&self) -> &'static str;

    /// Which scopes this skill installer accepts.
    fn supported_skill_scopes(&self) -> &'static [ScopeKind];

    /// Returns true if a skill named `name` is currently recorded in the
    /// ownership ledger for this scope.
    ///
    /// Default impl mirrors [`McpSurface::is_mcp_installed`]: both
    /// [`InstallStatus::InstalledOwned`] and
    /// [`InstallStatus::InstalledOtherOwner`] count as installed.
    ///
    /// # Errors
    ///
    /// Propagates whatever [`skill_status`](SkillSurface::skill_status) returns.
    fn is_skill_installed(&self, scope: &Scope, name: &str) -> Result<bool, AgentConfigError> {
        Ok(matches!(
            self.skill_status(scope, name, self.id())?.status,
            InstallStatus::InstalledOwned { .. } | InstallStatus::InstalledOtherOwner { .. }
        ))
    }

    /// Detailed installation state for the skill identified by `name`,
    /// scored against `expected_owner`. See [`McpSurface::mcp_status`] for
    /// the owner-comparison semantics.
    ///
    /// # Errors
    ///
    /// Same envelope as [`McpSurface::mcp_status`].
    fn skill_status(
        &self,
        scope: &Scope,
        name: &str,
        expected_owner: &str,
    ) -> Result<StatusReport, AgentConfigError>;

    /// Validate skill state without mutating user files.
    ///
    /// # Errors
    ///
    /// Equivalent to
    /// [`validate_skill_for_owner`](SkillSurface::validate_skill_for_owner)
    /// with `expected_owner = None`.
    fn validate_skill(
        &self,
        scope: &Scope,
        name: &str,
    ) -> Result<ValidationReport, AgentConfigError> {
        self.validate_skill_for_owner(scope, name, None)
    }

    /// Validate skill state against a caller-supplied expected owner.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::InvalidTag`] when `name` violates the kebab-case
    ///   skill-name contract or `expected_owner` is malformed.
    /// - Any error from [`skill_status`](SkillSurface::skill_status) other
    ///   than [`AgentConfigError::JsonInvalid`], which is folded into the
    ///   returned [`ValidationReport`] as malformed-ledger output.
    fn validate_skill_for_owner(
        &self,
        scope: &Scope,
        name: &str,
        expected_owner: Option<&str>,
    ) -> Result<ValidationReport, AgentConfigError> {
        SkillSpec::validate_name(name)?;
        if let Some(owner) = expected_owner {
            HookSpec::validate_tag(owner)?;
        }
        let status = match self.skill_status(scope, name, expected_owner.unwrap_or("")) {
            Ok(status) => status,
            Err(AgentConfigError::JsonInvalid { path, source }) => {
                let target = PlanTarget::Skill {
                    integration_id: self.id(),
                    scope: scope.clone(),
                    name: name.to_string(),
                    owner: expected_owner.unwrap_or_default().to_string(),
                };
                return Ok(crate::validation::malformed_ledger_report(
                    target,
                    path,
                    source.to_string(),
                ));
            }
            Err(e) => return Err(e),
        };
        let target = PlanTarget::Skill {
            integration_id: self.id(),
            scope: scope.clone(),
            name: name.to_string(),
            owner: expected_owner
                .map(str::to_owned)
                .or_else(|| owner_from_status(&status))
                .unwrap_or_default(),
        };
        crate::validation::skill_report_from_status(target, name, expected_owner, status)
    }

    /// Plan a skill install without mutating user files.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::PathResolution`] when the skill directory cannot
    ///   be resolved.
    /// - [`AgentConfigError::Io`] / [`AgentConfigError::ConfigTooLarge`]
    ///   when reading existing skill assets or the ledger fails.
    /// - [`AgentConfigError::MissingSpecField`] /
    ///   [`AgentConfigError::InvalidTag`] from [`SkillSpec`] re-validation.
    ///
    /// Predictable refusals (unsupported scope, owner mismatch) are encoded
    /// as [`crate::plan::PlanStatus::Refused`].
    fn plan_install_skill(
        &self,
        scope: &Scope,
        spec: &SkillSpec,
    ) -> Result<InstallPlan, AgentConfigError>;

    /// Plan a skill uninstall without mutating user files.
    ///
    /// # Errors
    ///
    /// Same envelope as
    /// [`plan_install_skill`](SkillSurface::plan_install_skill).
    fn plan_uninstall_skill(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallPlan, AgentConfigError>;

    /// Install (or update) the skill directory and record ownership.
    /// Repeated calls with byte-identical contents are a no-op after the
    /// first.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::PathResolution`] when a target path escapes the
    ///   scope root or contains a symlink component.
    /// - [`AgentConfigError::UnsupportedScope`] when the scope is not in
    ///   [`supported_skill_scopes`](SkillSurface::supported_skill_scopes).
    /// - [`AgentConfigError::Io`] for filesystem failures.
    /// - [`AgentConfigError::JsonInvalid`] when the ownership ledger is
    ///   malformed.
    /// - [`AgentConfigError::ConfigTooLarge`] when an input exceeds 8 MiB.
    /// - [`AgentConfigError::BackupExists`] when a sibling `.bak` already
    ///   exists for a file we would back up.
    /// - [`AgentConfigError::NotOwnedByCaller`] when the skill exists on
    ///   disk under another owner (or unowned and `adopt_unowned` is false).
    /// - [`AgentConfigError::MissingSpecField`] /
    ///   [`AgentConfigError::InvalidTag`] from spec re-validation.
    fn install_skill(
        &self,
        scope: &Scope,
        spec: &SkillSpec,
    ) -> Result<InstallReport, AgentConfigError>;

    /// Uninstall the skill identified by `name`, owned by `owner_tag`.
    /// Returns [`AgentConfigError::NotOwnedByCaller`] on owner mismatch or when
    /// the skill exists on disk but is missing from the ledger.
    ///
    /// # Errors
    ///
    /// Same envelope as [`install_skill`](SkillSurface::install_skill). The
    /// owner-mismatch case is the typical one.
    fn uninstall_skill(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallReport, AgentConfigError>;
}

/// One AI harness's standalone-instruction installer.
///
/// Instructions are named markdown files that provide persistent context to
/// the agent. Unlike hook rules (which are tied to a single hook spec),
/// instructions are independent documents that are loaded by the agent on
/// every session start.
///
/// Implemented by harnesses that support standalone instruction files or
/// managed include references in their memory/rules files. Use
/// [`crate::registry::instruction_capable`] to enumerate agents that
/// implement this trait.
///
/// All operations must be idempotent: installing the same [`InstructionSpec`]
/// twice reaches and preserves a single on-disk state. Uninstalls refuse to
/// remove entries owned by another consumer (recorded in a sidecar ledger).
pub trait InstructionSurface: Send + Sync {
    /// Stable, kebab-case identifier matching [`Integration::id`] for the
    /// same agent.
    fn id(&self) -> &'static str;

    /// Which scopes this instruction installer accepts.
    fn supported_instruction_scopes(&self) -> &'static [ScopeKind];

    /// Returns true if an instruction named `name` is currently recorded
    /// under any owner in this scope's ownership ledger.
    ///
    /// # Errors
    ///
    /// Propagates whatever
    /// [`instruction_status`](InstructionSurface::instruction_status) returns.
    fn is_instruction_installed(
        &self,
        scope: &Scope,
        name: &str,
    ) -> Result<bool, AgentConfigError> {
        Ok(matches!(
            self.instruction_status(scope, name, self.id())?.status,
            InstallStatus::InstalledOwned { .. } | InstallStatus::InstalledOtherOwner { .. }
        ))
    }

    /// Detailed installation state for the instruction identified by `name`,
    /// scored against `expected_owner`.
    ///
    /// # Errors
    ///
    /// Same envelope as [`McpSurface::mcp_status`].
    fn instruction_status(
        &self,
        scope: &Scope,
        name: &str,
        expected_owner: &str,
    ) -> Result<StatusReport, AgentConfigError>;

    /// Validate instruction state without mutating user files.
    ///
    /// # Errors
    ///
    /// Equivalent to
    /// [`validate_instruction_for_owner`](InstructionSurface::validate_instruction_for_owner)
    /// with `expected_owner = None`.
    fn validate_instruction(
        &self,
        scope: &Scope,
        name: &str,
    ) -> Result<ValidationReport, AgentConfigError> {
        self.validate_instruction_for_owner(scope, name, None)
    }

    /// Validate instruction state against a caller-supplied expected owner.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::InvalidTag`] when `name` or `expected_owner`
    ///   fails identifier validation.
    /// - Any error from
    ///   [`instruction_status`](InstructionSurface::instruction_status)
    ///   other than [`AgentConfigError::JsonInvalid`], which is folded into
    ///   the returned [`ValidationReport`] as malformed-ledger output.
    fn validate_instruction_for_owner(
        &self,
        scope: &Scope,
        name: &str,
        expected_owner: Option<&str>,
    ) -> Result<ValidationReport, AgentConfigError> {
        InstructionSpec::validate_name(name)?;
        if let Some(owner) = expected_owner {
            HookSpec::validate_tag(owner)?;
        }
        let status = match self.instruction_status(scope, name, expected_owner.unwrap_or("")) {
            Ok(status) => status,
            Err(AgentConfigError::JsonInvalid { path, source }) => {
                let target = PlanTarget::Instruction {
                    integration_id: self.id(),
                    scope: scope.clone(),
                    name: name.to_string(),
                    owner: expected_owner.unwrap_or_default().to_string(),
                };
                return Ok(crate::validation::malformed_ledger_report(
                    target,
                    path,
                    source.to_string(),
                ));
            }
            Err(e) => return Err(e),
        };
        let target = PlanTarget::Instruction {
            integration_id: self.id(),
            scope: scope.clone(),
            name: name.to_string(),
            owner: expected_owner
                .map(str::to_owned)
                .or_else(|| owner_from_status(&status))
                .unwrap_or_default(),
        };
        crate::validation::ledger_backed_report_from_status(target, name, expected_owner, status)
    }

    /// Plan an instruction install without mutating user files.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::PathResolution`] when the instruction or host
    ///   memory file cannot be resolved.
    /// - [`AgentConfigError::Io`] / [`AgentConfigError::ConfigTooLarge`]
    ///   when reading the existing instruction, host file, or ledger fails.
    /// - [`AgentConfigError::MissingSpecField`] /
    ///   [`AgentConfigError::InvalidTag`] from [`InstructionSpec`]
    ///   re-validation.
    ///
    /// Predictable refusals (unsupported scope, owner mismatch) are encoded
    /// as [`crate::plan::PlanStatus::Refused`].
    fn plan_install_instruction(
        &self,
        scope: &Scope,
        spec: &InstructionSpec,
    ) -> Result<InstallPlan, AgentConfigError>;

    /// Plan an instruction uninstall without mutating user files.
    ///
    /// # Errors
    ///
    /// Same envelope as
    /// [`plan_install_instruction`](InstructionSurface::plan_install_instruction).
    fn plan_uninstall_instruction(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallPlan, AgentConfigError>;

    /// Install (or update) the instruction. Repeated calls with the same
    /// name and identical content are a no-op after the first.
    ///
    /// # Errors
    ///
    /// - [`AgentConfigError::PathResolution`] when the instruction or host
    ///   path escapes the scope root or contains a symlink component.
    /// - [`AgentConfigError::UnsupportedScope`] when the scope is not in
    ///   [`supported_instruction_scopes`](InstructionSurface::supported_instruction_scopes).
    /// - [`AgentConfigError::Io`] for filesystem failures.
    /// - [`AgentConfigError::JsonInvalid`] when the ownership ledger is
    ///   malformed.
    /// - [`AgentConfigError::ConfigTooLarge`] when an input exceeds 8 MiB.
    /// - [`AgentConfigError::BackupExists`] when a sibling `.bak` already
    ///   exists for a file we would back up.
    /// - [`AgentConfigError::NotOwnedByCaller`] when the instruction or
    ///   include block exists under another owner (or unowned and
    ///   `adopt_unowned` is false).
    /// - [`AgentConfigError::MissingSpecField`] /
    ///   [`AgentConfigError::InvalidTag`] from spec re-validation.
    fn install_instruction(
        &self,
        scope: &Scope,
        spec: &InstructionSpec,
    ) -> Result<InstallReport, AgentConfigError>;

    /// Uninstall the instruction identified by `name`, owned by `owner_tag`.
    /// Returns [`AgentConfigError::NotOwnedByCaller`] on owner mismatch.
    ///
    /// # Errors
    ///
    /// Same envelope as
    /// [`install_instruction`](InstructionSurface::install_instruction).
    fn uninstall_instruction(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallReport, AgentConfigError>;
}

/// Outcome of a successful [`Integration::install`].
#[must_use]
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct InstallReport {
    /// Files this call created (did not previously exist).
    pub created: Vec<PathBuf>,
    /// Existing files this call modified.
    pub patched: Vec<PathBuf>,
    /// Sibling `.bak` files written. Each entry is the backup path; the
    /// original lives at the same path without `.bak`.
    pub backed_up: Vec<PathBuf>,
    /// True if every target was already in the desired state; nothing changed.
    pub already_installed: bool,
}

impl InstallReport {
    /// Fold another report's contents into this one.
    ///
    /// `already_installed` stays true only if both reports were already
    /// installed *and* this report has not produced any created/patched
    /// entries from earlier merges.
    pub(crate) fn merge(&mut self, from: InstallReport) {
        if !from.already_installed {
            self.already_installed = false;
        } else if self.created.is_empty() && self.patched.is_empty() {
            self.already_installed = true;
        }
        self.created.extend(from.created);
        self.patched.extend(from.patched);
        self.backed_up.extend(from.backed_up);
    }
}

/// Outcome of a successful [`Integration::uninstall`].
#[must_use]
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct UninstallReport {
    /// Files removed entirely.
    pub removed: Vec<PathBuf>,
    /// Files modified (tagged content stripped, file kept).
    pub patched: Vec<PathBuf>,
    /// Backups restored to their original location.
    pub restored: Vec<PathBuf>,
    /// True if the integration was not installed; nothing changed.
    pub not_installed: bool,
}

impl UninstallReport {
    /// Fold another report's contents into this one. `not_installed` survives
    /// only when neither report removed/patched/restored anything.
    pub(crate) fn merge(&mut self, from: UninstallReport) {
        self.not_installed = from.not_installed
            && self.removed.is_empty()
            && self.patched.is_empty()
            && self.restored.is_empty();
        self.removed.extend(from.removed);
        self.patched.extend(from.patched);
        self.restored.extend(from.restored);
    }
}

/// Outcome of a successful [`Integration::migrate`].
#[must_use]
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum MigrationReport {
    /// Nothing to migrate.
    NoOp,
    /// Migrated files. Includes paths removed and paths rewritten.
    Migrated {
        /// Paths removed during migration (e.g., legacy shell scripts).
        removed: Vec<PathBuf>,
        /// Paths rewritten in place.
        rewritten: Vec<PathBuf>,
    },
}

fn owner_from_status(status: &StatusReport) -> Option<String> {
    match &status.status {
        InstallStatus::InstalledOwned { owner }
        | InstallStatus::InstalledOtherOwner { owner }
        | InstallStatus::LedgerOnly { owner } => Some(owner.clone()),
        _ => None,
    }
}

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

    #[test]
    fn install_report_default() {
        let r = InstallReport::default();
        assert!(r.created.is_empty());
        assert!(r.patched.is_empty());
        assert!(r.backed_up.is_empty());
        assert!(!r.already_installed);
    }

    #[test]
    fn uninstall_report_default() {
        let r = UninstallReport::default();
        assert!(r.removed.is_empty());
        assert!(r.patched.is_empty());
        assert!(r.restored.is_empty());
        assert!(!r.not_installed);
    }

    #[test]
    fn migration_report_debug_clone() {
        let noop = MigrationReport::NoOp;
        let _ = format!("{noop:?}");

        let migrated = MigrationReport::Migrated {
            removed: vec![PathBuf::from("/a")],
            rewritten: vec![],
        };
        let cloned = migrated.clone();
        let _ = format!("{cloned:?}");
    }
}