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,
};
#[derive(Debug, Clone, Copy, Default)]
pub struct CopilotAgent {
_private: (),
}
impl CopilotAgent {
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"),
})
}
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);
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());
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 {
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 { .. }));
}
}