use std::path::{Path, PathBuf};
use crate::cli::harness::{
AttachEntry, HarnessFormat, HarnessId, HarnessRegistry, HarnessState, apply_attach_entry,
};
use crate::cli::init::read_config_text;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlannedAction {
Add,
Refresh,
Skip(String),
Error(String),
}
#[derive(Debug, Clone)]
pub struct PlannedChange {
pub id: HarnessId,
pub config_path: PathBuf,
pub format: HarnessFormat,
pub action: PlannedAction,
}
impl PlannedChange {
pub fn writes(&self) -> bool {
matches!(self.action, PlannedAction::Add | PlannedAction::Refresh)
}
}
#[derive(Debug, Clone)]
pub struct ApplyPlan {
pub entry: AttachEntry,
pub changes: Vec<PlannedChange>,
}
#[derive(Debug, Clone)]
pub struct BackupRecord {
pub source: PathBuf,
pub backup: PathBuf,
}
#[derive(Debug, Clone)]
pub enum ApplyOutcome {
Wrote {
id: HarnessId,
config_path: PathBuf,
backup: Option<BackupRecord>,
},
Skipped { id: HarnessId, reason: String },
Failed { id: HarnessId, reason: String },
}
pub fn plan(registry: &HarnessRegistry, entry: &AttachEntry) -> ApplyPlan {
let statuses = registry.scan(entry);
let changes = statuses
.into_iter()
.map(|status| {
let action = match status.state {
HarnessState::NotInstalled => {
PlannedAction::Skip("client not installed".to_string())
}
HarnessState::PresentCurrent => PlannedAction::Skip("already current".to_string()),
HarnessState::Absent => PlannedAction::Add,
HarnessState::PresentStale(_) => PlannedAction::Refresh,
HarnessState::Malformed(why) => {
PlannedAction::Error(format!("config does not parse: {why}"))
}
};
PlannedChange {
id: status.id,
config_path: status.config_path,
format: status.format,
action,
}
})
.collect();
ApplyPlan {
entry: entry.clone(),
changes,
}
}
pub fn apply(plan: &ApplyPlan) -> Vec<ApplyOutcome> {
plan.changes
.iter()
.map(|change| match &change.action {
PlannedAction::Skip(reason) => ApplyOutcome::Skipped {
id: change.id,
reason: reason.clone(),
},
PlannedAction::Error(reason) => ApplyOutcome::Failed {
id: change.id,
reason: reason.clone(),
},
PlannedAction::Add | PlannedAction::Refresh => apply_one(change, &plan.entry),
})
.collect()
}
fn apply_one(change: &PlannedChange, entry: &AttachEntry) -> ApplyOutcome {
let path = &change.config_path;
let existing_text = if path.exists() {
match read_config_text(path) {
Ok(text) => Some(text),
Err(e) => {
return ApplyOutcome::Failed {
id: change.id,
reason: format!("cannot read {}: {e}", path.display()),
};
}
}
} else {
None
};
let new_content = match apply_attach_entry(change.format, existing_text.as_deref(), entry) {
Ok(content) => content,
Err(e) => {
return ApplyOutcome::Failed {
id: change.id,
reason: format!("building entry for {}: {e}", path.display()),
};
}
};
let backup = if path.exists() {
match write_backup(path) {
Ok(record) => Some(record),
Err(e) => {
return ApplyOutcome::Failed {
id: change.id,
reason: format!("backing up {}: {e}", path.display()),
};
}
}
} else {
if let Some(parent) = path.parent()
&& let Err(e) = std::fs::create_dir_all(parent)
{
return ApplyOutcome::Failed {
id: change.id,
reason: format!("creating {}: {e}", parent.display()),
};
}
None
};
if let Err(e) = atomic_write(path, new_content.as_bytes()) {
return ApplyOutcome::Failed {
id: change.id,
reason: format!("writing {}: {e}", path.display()),
};
}
ApplyOutcome::Wrote {
id: change.id,
config_path: path.clone(),
backup,
}
}
pub fn write_backup(path: &Path) -> std::io::Result<BackupRecord> {
let prior = std::fs::read(path)?;
let backup = backup_path(path);
std::fs::write(&backup, &prior)?;
Ok(BackupRecord {
source: path.to_path_buf(),
backup,
})
}
fn backup_path(path: &Path) -> PathBuf {
let ts = chrono::Utc::now().format("%Y%m%dT%H%M%S%3fZ").to_string();
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "config".to_string());
let backup_name = format!("{name}.{ts}.bak");
match path.parent() {
Some(parent) => parent.join(backup_name),
None => PathBuf::from(backup_name),
}
}
pub fn restore(record: &BackupRecord) -> std::io::Result<()> {
let bytes = std::fs::read(&record.backup)?;
atomic_write(&record.source, &bytes)
}
pub(crate) fn atomic_write(path: &Path, content: &[u8]) -> std::io::Result<()> {
use std::io::Write;
let real = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
if std::fs::read(&real).is_ok_and(|existing| existing == content) {
return Ok(());
}
let path = real.as_path();
let parent = path.parent().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"config path has no parent directory",
)
})?;
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
tmp.write_all(content)?;
tmp.flush()?;
tmp.as_file().sync_all()?;
let tmp = tmp.into_temp_path();
std::fs::rename(&tmp, path)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::harness::{HarnessTarget, SYMFORGE_SERVER_NAME};
#[test]
fn atomic_write_keeps_a_symlinked_config_linked() {
let tmp = tempfile::tempdir().unwrap();
let dotfiles = tmp.path().join("dotfiles");
std::fs::create_dir_all(&dotfiles).unwrap();
let real = dotfiles.join("config.toml");
std::fs::write(&real, "old").unwrap();
let link = tmp.path().join("config.toml");
#[cfg(unix)]
std::os::unix::fs::symlink(&real, &link).unwrap();
#[cfg(windows)]
if let Err(error) = std::os::windows::fs::symlink_file(&real, &link) {
eprintln!("skipped: this host cannot create a file symlink: {error}");
return;
}
atomic_write(&link, b"new").unwrap();
assert!(
std::fs::symlink_metadata(&link)
.unwrap()
.file_type()
.is_symlink(),
"the config must stay a link into the dotfiles repo"
);
assert_eq!(std::fs::read(&real).unwrap(), b"new");
}
fn entry() -> AttachEntry {
AttachEntry::new("http://127.0.0.1:8787/mcp", Some("sf_key".to_string()))
}
fn json_target(id: HarnessId, path: PathBuf) -> HarnessTarget {
HarnessTarget {
id,
config_path: path,
format: HarnessFormat::Json,
}
}
#[test]
fn plan_classifies_absent_as_add() {
let dir = tempfile::tempdir().unwrap();
let cfg = dir.path().join(".claude.json");
std::fs::write(&cfg, "{}").unwrap();
let reg = HarnessRegistry::from_targets(vec![json_target(HarnessId::ClaudeCode, cfg)]);
let p = plan(®, &entry());
assert_eq!(p.changes[0].action, PlannedAction::Add);
}
#[test]
fn apply_creates_backup_and_restores_byte_exact() {
let dir = tempfile::tempdir().unwrap();
let cfg = dir.path().join("config.json");
let original = "{\n \"mcpServers\": {}\n}\n";
std::fs::write(&cfg, original).unwrap();
let reg =
HarnessRegistry::from_targets(vec![json_target(HarnessId::ClaudeCode, cfg.clone())]);
let p = plan(®, &entry());
let outcomes = apply(&p);
let backup = match &outcomes[0] {
ApplyOutcome::Wrote { backup, .. } => backup.clone().expect("backup recorded"),
other => panic!("expected Wrote, got {other:?}"),
};
let after = std::fs::read_to_string(&cfg).unwrap();
assert!(after.contains(SYMFORGE_SERVER_NAME));
restore(&backup).unwrap();
let restored = std::fs::read(&cfg).unwrap();
assert_eq!(restored, original.as_bytes());
}
#[test]
fn second_apply_is_noop() {
let dir = tempfile::tempdir().unwrap();
let cfg = dir.path().join("config.json");
std::fs::write(&cfg, "{}").unwrap();
let reg =
HarnessRegistry::from_targets(vec![json_target(HarnessId::ClaudeCode, cfg.clone())]);
apply(&plan(®, &entry()));
let after_first = std::fs::read(&cfg).unwrap();
let p2 = plan(®, &entry());
assert!(matches!(p2.changes[0].action, PlannedAction::Skip(_)));
let outcomes2 = apply(&p2);
assert!(matches!(outcomes2[0], ApplyOutcome::Skipped { .. }));
let after_second = std::fs::read(&cfg).unwrap();
assert_eq!(
after_first, after_second,
"second apply must not change bytes"
);
}
#[test]
fn malformed_is_reported_not_written() {
let dir = tempfile::tempdir().unwrap();
let cfg = dir.path().join("config.json");
let bad = "{ not valid json";
std::fs::write(&cfg, bad).unwrap();
let reg =
HarnessRegistry::from_targets(vec![json_target(HarnessId::ClaudeCode, cfg.clone())]);
let p = plan(®, &entry());
assert!(matches!(p.changes[0].action, PlannedAction::Error(_)));
let outcomes = apply(&p);
assert!(matches!(outcomes[0], ApplyOutcome::Failed { .. }));
assert_eq!(std::fs::read_to_string(&cfg).unwrap(), bad);
}
}