agent-config 0.1.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
//! GitHub Copilot integration (CLI + cloud agent + VS Code agent).
//!
//! Copilot loads hook configs from any `.json` file under
//! `<project>/.github/hooks/`. We write one file per consumer
//! (`<tag>-rewrite.json`) so multiple CLIs coexist cleanly without sharing a
//! single mutable JSON document.
//!
//! Copilot uses lowerCamelCase events (`preToolUse`) and a flat entry shape
//! with `bash` (or `powershell`) as the command field, not `command`:
//!
//! ```json
//! {
//!   "version": 1,
//!   "hooks": {
//!     "preToolUse": [
//!       { "type": "command", "bash": "...", "comment": "..." }
//!     ]
//!   }
//! }
//! ```
//!
//! Optional prompt surface: `<project>/.github/copilot-instructions.md` with
//! a tagged HTML-comment fence.

use std::path::PathBuf;

use serde_json::json;

use crate::agents::planning as agent_planning;
use crate::error::AgentConfigError;
use crate::integration::{
    InstallReport, InstructionSurface, Integration, McpSurface, SkillSurface, UninstallReport,
};
use crate::paths;
use crate::plan::{has_refusal, InstallPlan, PlanTarget, RefusalReason, UninstallPlan};
use crate::scope::{Scope, ScopeKind};
use crate::spec::{Event, HookSpec, InstructionSpec, Matcher, McpSpec, SkillSpec};
use crate::status::StatusReport;
use crate::util::{
    file_lock, fs_atomic, instructions_dir, mcp_json_map, md_block, ownership, planning, safe_fs,
    skills_dir,
};

/// GitHub Copilot.
#[derive(Debug, Clone, Copy, Default)]
pub struct CopilotAgent {
    _private: (),
}

impl CopilotAgent {
    /// Construct an instance. Stateless.
    pub const fn new() -> Self {
        Self { _private: () }
    }

    fn hooks_file(scope: &Scope, tag: &str) -> Result<PathBuf, AgentConfigError> {
        let root = match scope {
            Scope::Local(p) => p,
            Scope::Global => {
                return Err(AgentConfigError::UnsupportedScope {
                    id: "copilot",
                    scope: ScopeKind::Global,
                });
            }
        };
        Ok(root
            .join(".github")
            .join("hooks")
            .join(format!("{tag}-rewrite.json")))
    }

    fn instructions_path(scope: &Scope) -> Result<PathBuf, AgentConfigError> {
        let Scope::Local(root) = scope else {
            return Err(AgentConfigError::UnsupportedScope {
                id: "copilot",
                scope: ScopeKind::Global,
            });
        };
        Ok(root.join(".github").join("copilot-instructions.md"))
    }

    fn mcp_path(scope: &Scope) -> Result<PathBuf, AgentConfigError> {
        Ok(match scope {
            Scope::Global => paths::home_dir()?.join(".copilot").join("mcp-config.json"),
            Scope::Local(root) => root.join(".mcp.json"),
        })
    }

    fn skills_root(scope: &Scope) -> Result<PathBuf, AgentConfigError> {
        Ok(match scope {
            Scope::Global => paths::home_dir()?.join(".copilot").join("skills"),
            Scope::Local(root) => root.join(".github").join("skills"),
        })
    }

    /// Directory holding the instruction ownership ledger. Local-only;
    /// lives next to the host file under `<root>/.github/`.
    fn instruction_config_dir(scope: &Scope) -> Result<PathBuf, AgentConfigError> {
        let Scope::Local(root) = scope else {
            return Err(AgentConfigError::UnsupportedScope {
                id: "copilot",
                scope: ScopeKind::Global,
            });
        };
        Ok(root.join(".github"))
    }
}

impl Integration for CopilotAgent {
    fn id(&self) -> &'static str {
        "copilot"
    }

    fn display_name(&self) -> &'static str {
        "GitHub Copilot"
    }

    fn supported_scopes(&self) -> &'static [ScopeKind] {
        &[ScopeKind::Local]
    }

    fn status(&self, scope: &Scope, tag: &str) -> Result<StatusReport, AgentConfigError> {
        HookSpec::validate_tag(tag)?;
        let p = Self::hooks_file(scope, tag)?;
        Ok(StatusReport::for_file_hook(tag, p))
    }

    fn plan_install(
        &self,
        scope: &Scope,
        spec: &HookSpec,
    ) -> Result<InstallPlan, AgentConfigError> {
        HookSpec::validate_tag(&spec.tag)?;
        let target = PlanTarget::Hook {
            integration_id: Integration::id(self),
            scope: scope.clone(),
            tag: spec.tag.clone(),
        };
        let p = match Self::hooks_file(scope, &spec.tag) {
            Ok(p) => p,
            Err(AgentConfigError::UnsupportedScope { .. }) => {
                return Ok(InstallPlan::refused(
                    target,
                    None,
                    RefusalReason::UnsupportedScope,
                ));
            }
            Err(e) => return Err(e),
        };

        let event_key = event_to_string(&spec.event);
        let matcher_str = matcher_to_copilot(&spec.matcher);
        let entry = json!({
            "type": "command",
            "bash": spec.command.render_shell(),
            "matcher": matcher_str,
        });
        let doc = json!({
            "version": 1,
            "hooks": { event_key: [entry] },
        });
        let mut bytes = serde_json::to_vec_pretty(&doc).expect("serialize");
        bytes.push(b'\n');

        let mut changes = Vec::new();
        planning::plan_write_file(&mut changes, &p, &bytes, true)?;
        if has_refusal(&changes) {
            return Ok(InstallPlan::from_changes(target, changes));
        }

        if let Some(rules) = &spec.rules {
            let instr = Self::instructions_path(scope)?;
            planning::plan_markdown_upsert(&mut changes, &instr, &spec.tag, &rules.content)?;
        }

        Ok(InstallPlan::from_changes(target, changes))
    }

    fn plan_uninstall(&self, scope: &Scope, tag: &str) -> Result<UninstallPlan, AgentConfigError> {
        HookSpec::validate_tag(tag)?;
        let target = PlanTarget::Hook {
            integration_id: Integration::id(self),
            scope: scope.clone(),
            tag: tag.to_string(),
        };
        let p = match Self::hooks_file(scope, tag) {
            Ok(p) => p,
            Err(AgentConfigError::UnsupportedScope { .. }) => {
                return Ok(UninstallPlan::refused(
                    target,
                    None,
                    RefusalReason::UnsupportedScope,
                ));
            }
            Err(e) => return Err(e),
        };
        let mut changes = Vec::new();
        planning::plan_remove_file(&mut changes, &p);
        let instr = Self::instructions_path(scope)?;
        planning::plan_markdown_remove(&mut changes, &instr, tag)?;
        Ok(UninstallPlan::from_changes(target, changes))
    }

    fn install(&self, scope: &Scope, spec: &HookSpec) -> Result<InstallReport, AgentConfigError> {
        HookSpec::validate_tag(&spec.tag)?;
        let mut report = InstallReport::default();

        let p = Self::hooks_file(scope, &spec.tag)?;
        scope.ensure_contained(&p)?;
        let event_key = event_to_string(&spec.event);
        let matcher_str = matcher_to_copilot(&spec.matcher);

        // Each per-consumer file owns its whole contents. No tag dedupe inside
        // the file because the filename itself carries the tag.
        let entry = json!({
            "type": "command",
            "bash": spec.command.render_shell(),
            "matcher": matcher_str,
        });
        let doc = json!({
            "version": 1,
            "hooks": { event_key: [entry] },
        });
        let bytes = {
            let mut b = serde_json::to_vec_pretty(&doc).expect("serialize");
            b.push(b'\n');
            b
        };
        let outcome = safe_fs::write(scope, &p, &bytes, true)?;
        if outcome.no_change {
            report.already_installed = true;
        } else 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);
        }

        if let Some(rules) = &spec.rules {
            let instr = Self::instructions_path(scope)?;
            scope.ensure_contained(&instr)?;
            file_lock::with_lock(&instr, || {
                let host = fs_atomic::read_to_string_or_empty(&instr)?;
                let new_host = md_block::upsert(&host, &spec.tag, &rules.content);
                let outcome = safe_fs::write(scope, &instr, new_host.as_bytes(), true)?;
                if outcome.existed && !outcome.no_change {
                    report.patched.push(outcome.path.clone());
                    report.already_installed = false;
                } else if !outcome.existed {
                    report.created.push(outcome.path.clone());
                    report.already_installed = false;
                }
                if let Some(b) = outcome.backup {
                    report.backed_up.push(b);
                }
                Ok::<(), AgentConfigError>(())
            })?;
        }

        Ok(report)
    }

    fn uninstall(&self, scope: &Scope, tag: &str) -> Result<UninstallReport, AgentConfigError> {
        HookSpec::validate_tag(tag)?;
        let mut report = UninstallReport::default();

        let p = Self::hooks_file(scope, tag)?;
        scope.ensure_contained(&p)?;
        if p.exists() {
            safe_fs::remove_file(scope, &p)?;
            report.removed.push(p.clone());

            // Tidy: remove .github/hooks/ if empty.
            if let Some(parent) = p.parent() {
                if std::fs::read_dir(parent)
                    .map(|mut it| it.next().is_none())
                    .unwrap_or(false)
                {
                    let _ = safe_fs::remove_empty_dir(scope, parent);
                }
            }
        }

        let instr = Self::instructions_path(scope)?;
        scope.ensure_contained(&instr)?;
        file_lock::with_lock(&instr, || {
            let host = fs_atomic::read_to_string_or_empty(&instr)?;
            let (stripped, removed) = md_block::remove(&host, tag);
            if removed {
                if stripped.trim().is_empty() {
                    if safe_fs::restore_backup_if_matches(scope, &instr, stripped.as_bytes())? {
                        report.restored.push(instr.clone());
                    } else {
                        safe_fs::remove_file(scope, &instr)?;
                        report.removed.push(instr.clone());
                    }
                } else {
                    safe_fs::write(scope, &instr, stripped.as_bytes(), false)?;
                    report.patched.push(instr.clone());
                }
            }
            Ok::<(), AgentConfigError>(())
        })?;

        if report.removed.is_empty() && report.patched.is_empty() && report.restored.is_empty() {
            report.not_installed = true;
        }
        Ok(report)
    }
}

impl McpSurface for CopilotAgent {
    fn id(&self) -> &'static str {
        "copilot"
    }

    fn supported_mcp_scopes(&self) -> &'static [ScopeKind] {
        &[ScopeKind::Global, ScopeKind::Local]
    }

    fn mcp_status(
        &self,
        scope: &Scope,
        name: &str,
        expected_owner: &str,
    ) -> Result<StatusReport, AgentConfigError> {
        McpSpec::validate_name(name)?;
        let cfg = Self::mcp_path(scope)?;
        let ledger = ownership::mcp_ledger_for(&cfg);
        let presence = mcp_json_map::config_presence(
            &cfg,
            &["mcpServers"],
            name,
            mcp_json_map::ConfigFormat::Json,
        )?;
        let recorded = ownership::owner_of(&ledger, name)?;
        Ok(StatusReport::for_mcp(
            name,
            cfg,
            ledger,
            presence,
            expected_owner,
            recorded,
        ))
    }

    fn plan_install_mcp(
        &self,
        scope: &Scope,
        spec: &McpSpec,
    ) -> Result<InstallPlan, AgentConfigError> {
        agent_planning::mcp_json_map_install(
            McpSurface::id(self),
            scope,
            spec,
            Self::mcp_path(scope),
            &["mcpServers"],
            mcp_json_map::mcp_servers_value,
            mcp_json_map::ConfigFormat::Json,
        )
    }

    fn plan_uninstall_mcp(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallPlan, AgentConfigError> {
        agent_planning::mcp_json_map_uninstall(
            McpSurface::id(self),
            scope,
            name,
            owner_tag,
            Self::mcp_path(scope),
            &["mcpServers"],
            mcp_json_map::ConfigFormat::Json,
        )
    }

    fn install_mcp(
        &self,
        scope: &Scope,
        spec: &McpSpec,
    ) -> Result<InstallReport, AgentConfigError> {
        spec.validate()?;
        let cfg = Self::mcp_path(scope)?;
        spec.validate_local_secret_policy(scope)?;
        scope.ensure_contained(&cfg)?;
        let ledger = ownership::mcp_ledger_for(&cfg);
        mcp_json_map::install(
            &cfg,
            &ledger,
            spec,
            &["mcpServers"],
            mcp_json_map::mcp_servers_value,
            mcp_json_map::ConfigFormat::Json,
        )
    }

    fn uninstall_mcp(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallReport, AgentConfigError> {
        McpSpec::validate_name(name)?;
        HookSpec::validate_tag(owner_tag)?;
        let cfg = Self::mcp_path(scope)?;
        scope.ensure_contained(&cfg)?;
        let ledger = ownership::mcp_ledger_for(&cfg);
        mcp_json_map::uninstall(
            &cfg,
            &ledger,
            name,
            owner_tag,
            "mcp server",
            &["mcpServers"],
            mcp_json_map::ConfigFormat::Json,
        )
    }
}

impl SkillSurface for CopilotAgent {
    fn id(&self) -> &'static str {
        "copilot"
    }

    fn supported_skill_scopes(&self) -> &'static [ScopeKind] {
        &[ScopeKind::Global, ScopeKind::Local]
    }

    fn skill_status(
        &self,
        scope: &Scope,
        name: &str,
        expected_owner: &str,
    ) -> Result<StatusReport, AgentConfigError> {
        SkillSpec::validate_name(name)?;
        let root = Self::skills_root(scope)?;
        let (dir, manifest, ledger) = skills_dir::paths_for_status(&root, name);
        let recorded = ownership::owner_of(&ledger, name)?;
        Ok(StatusReport::for_skill(
            name,
            dir,
            manifest,
            ledger,
            expected_owner,
            recorded,
        ))
    }

    fn plan_install_skill(
        &self,
        scope: &Scope,
        spec: &SkillSpec,
    ) -> Result<InstallPlan, AgentConfigError> {
        agent_planning::skill_install(
            SkillSurface::id(self),
            scope,
            spec,
            Self::skills_root(scope),
        )
    }

    fn plan_uninstall_skill(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallPlan, AgentConfigError> {
        agent_planning::skill_uninstall(
            SkillSurface::id(self),
            scope,
            name,
            owner_tag,
            Self::skills_root(scope),
        )
    }

    fn install_skill(
        &self,
        scope: &Scope,
        spec: &SkillSpec,
    ) -> Result<InstallReport, AgentConfigError> {
        let root = Self::skills_root(scope)?;
        scope.ensure_contained(&root)?;
        skills_dir::install(&root, spec)
    }

    fn uninstall_skill(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallReport, AgentConfigError> {
        let root = Self::skills_root(scope)?;
        scope.ensure_contained(&root)?;
        skills_dir::uninstall(&root, name, owner_tag)
    }
}

impl CopilotAgent {
    fn inline_layout(
        &self,
        scope: &Scope,
    ) -> Result<instructions_dir::InlineLayout, AgentConfigError> {
        Ok(instructions_dir::InlineLayout {
            config_dir: Self::instruction_config_dir(scope)?,
            host_file: Self::instructions_path(scope)?,
        })
    }
}

impl InstructionSurface for CopilotAgent {
    fn id(&self) -> &'static str {
        "copilot"
    }

    fn supported_instruction_scopes(&self) -> &'static [ScopeKind] {
        &[ScopeKind::Local]
    }

    fn instruction_status(
        &self,
        scope: &Scope,
        name: &str,
        expected_owner: &str,
    ) -> Result<StatusReport, AgentConfigError> {
        instructions_dir::inline_status(self.inline_layout(scope)?, name, expected_owner)
    }

    fn plan_install_instruction(
        &self,
        scope: &Scope,
        spec: &InstructionSpec,
    ) -> Result<InstallPlan, AgentConfigError> {
        instructions_dir::inline_plan_install(
            InstructionSurface::id(self),
            scope,
            self.inline_layout(scope),
            spec,
        )
    }

    fn plan_uninstall_instruction(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallPlan, AgentConfigError> {
        instructions_dir::inline_plan_uninstall(
            InstructionSurface::id(self),
            scope,
            self.inline_layout(scope),
            name,
            owner_tag,
        )
    }

    fn install_instruction(
        &self,
        scope: &Scope,
        spec: &InstructionSpec,
    ) -> Result<InstallReport, AgentConfigError> {
        instructions_dir::inline_install(scope, self.inline_layout(scope)?, spec)
    }

    fn uninstall_instruction(
        &self,
        scope: &Scope,
        name: &str,
        owner_tag: &str,
    ) -> Result<UninstallReport, AgentConfigError> {
        instructions_dir::inline_uninstall(scope, self.inline_layout(scope)?, name, owner_tag)
    }
}

fn matcher_to_copilot(m: &Matcher) -> String {
    // Same family as Cursor: lowerCamelCase events, PascalCase tool names.
    match m {
        Matcher::All => "*".to_string(),
        Matcher::Bash => "Shell".to_string(),
        Matcher::Exact(s) => s.clone(),
        Matcher::AnyOf(names) => names.join("|"),
        Matcher::Regex(s) => s.clone(),
    }
}

fn event_to_string(e: &Event) -> String {
    match e {
        Event::PreToolUse => "preToolUse".into(),
        Event::PostToolUse => "postToolUse".into(),
        Event::Custom(s) => s.clone(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{json, Value};
    use tempfile::tempdir;

    fn local_spec(tag: &str) -> HookSpec {
        HookSpec::builder(tag)
            .command_program("myapp", ["hook"])
            .matcher(Matcher::Bash)
            .event(Event::PreToolUse)
            .build()
    }

    fn mcp_spec(name: &str, owner: &str) -> McpSpec {
        McpSpec::builder(name)
            .owner(owner)
            .stdio("npx", ["-y", "@example/server"])
            .build()
    }

    fn read_json(p: &std::path::Path) -> Value {
        serde_json::from_slice(&std::fs::read(p).unwrap()).unwrap()
    }

    #[test]
    fn install_writes_per_tag_file_with_bash_field() {
        let dir = tempdir().unwrap();
        let agent = CopilotAgent::new();
        let scope = Scope::Local(dir.path().to_path_buf());
        agent.install(&scope, &local_spec("alpha")).unwrap();

        let p = dir.path().join(".github/hooks/alpha-rewrite.json");
        let v = read_json(&p);
        assert_eq!(v["version"], json!(1));
        assert_eq!(v["hooks"]["preToolUse"][0]["bash"], json!("myapp hook"));
        assert_eq!(v["hooks"]["preToolUse"][0]["matcher"], json!("Shell"));
    }

    #[test]
    fn distinct_tags_get_distinct_files() {
        let dir = tempdir().unwrap();
        let agent = CopilotAgent::new();
        let scope = Scope::Local(dir.path().to_path_buf());
        agent.install(&scope, &local_spec("alpha")).unwrap();
        agent.install(&scope, &local_spec("beta")).unwrap();
        assert!(dir.path().join(".github/hooks/alpha-rewrite.json").exists());
        assert!(dir.path().join(".github/hooks/beta-rewrite.json").exists());
    }

    #[test]
    fn uninstall_removes_only_our_file() {
        let dir = tempdir().unwrap();
        let agent = CopilotAgent::new();
        let scope = Scope::Local(dir.path().to_path_buf());
        agent.install(&scope, &local_spec("alpha")).unwrap();
        agent.install(&scope, &local_spec("beta")).unwrap();
        agent.uninstall(&scope, "alpha").unwrap();

        assert!(!dir.path().join(".github/hooks/alpha-rewrite.json").exists());
        assert!(dir.path().join(".github/hooks/beta-rewrite.json").exists());
    }

    #[test]
    fn rejects_global_scope() {
        let agent = CopilotAgent::new();
        let err = agent.is_installed(&Scope::Global, "alpha").unwrap_err();
        assert!(matches!(err, AgentConfigError::UnsupportedScope { .. }));
    }

    #[test]
    fn install_mcp_writes_cli_workspace_file() {
        let dir = tempdir().unwrap();
        let agent = CopilotAgent::new();
        let scope = Scope::Local(dir.path().to_path_buf());
        agent
            .install_mcp(&scope, &mcp_spec("memory", "myapp"))
            .unwrap();

        let p = dir.path().join(".mcp.json");
        let v = read_json(&p);
        assert_eq!(v["mcpServers"]["memory"]["command"], json!("npx"));
    }

    #[test]
    fn install_mcp_idempotent() {
        let dir = tempdir().unwrap();
        let agent = CopilotAgent::new();
        let scope = Scope::Local(dir.path().to_path_buf());
        let s = mcp_spec("memory", "myapp");
        agent.install_mcp(&scope, &s).unwrap();
        let r = agent.install_mcp(&scope, &s).unwrap();
        assert!(r.already_installed);
    }

    #[test]
    fn uninstall_mcp_owner_mismatch_refused() {
        let dir = tempdir().unwrap();
        let agent = CopilotAgent::new();
        let scope = Scope::Local(dir.path().to_path_buf());
        agent
            .install_mcp(&scope, &mcp_spec("memory", "appA"))
            .unwrap();
        let err = agent.uninstall_mcp(&scope, "memory", "appB").unwrap_err();
        assert!(matches!(err, AgentConfigError::NotOwnedByCaller { .. }));
    }
}