use std::collections::HashMap;
use std::path::Path;
use crate::agents::builder::{AgentBuildError, compose_agent, source_chain};
use crate::agents::frontmatter::validate_frontmatter;
use crate::agents::manifest::{
AgentManifest, MANIFEST_FILE, ManifestEntry, ManifestError, ManifestLoad, Origin, atomic_write,
checksum, manifest_lock_path, with_agent_manifest_lock,
};
use crate::agents::metadata::agent_metadata_from_str;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DeployResult {
pub deployed: Vec<String>,
pub skipped: Vec<String>,
pub unchanged: Vec<String>,
pub adopted: Vec<String>,
pub untracked_modified: Vec<String>,
pub declared_skills: HashMap<String, Vec<String>>,
pub failed: Vec<String>,
pub repaired: Vec<String>,
}
pub fn is_agent_file(name: &str) -> bool {
name.ends_with(".md")
}
pub fn deploy_agents(
source_dir: &Path,
target_dir: &Path,
) -> Result<DeployResult, AgentBuildError> {
deploy_agents_filtered(source_dir, target_dir, |_name| true)
}
pub fn deploy_agents_filtered(
source_dir: &Path,
target_dir: &Path,
select: impl Fn(&str) -> bool,
) -> Result<DeployResult, AgentBuildError> {
if !source_dir.is_dir() {
return Ok(DeployResult::default());
}
with_agent_manifest_lock(target_dir, || {
deploy_agents_locked(source_dir, target_dir, select)
})
}
fn deploy_agents_locked(
source_dir: &Path,
target_dir: &Path,
select: impl Fn(&str) -> bool,
) -> Result<DeployResult, AgentBuildError> {
let mut result = DeployResult::default();
let mut manifest = match AgentManifest::load_checked(target_dir) {
ManifestLoad::Ok(m) => m,
ManifestLoad::Corrupt(detail) => {
return Err(AgentBuildError::FrontmatterParse(format!(
"agent manifest is corrupt and cannot be safely loaded; \
run `tm repair deploy` to recover. Detail: {detail}"
)));
}
};
let now = chrono::Utc::now().to_rfc3339();
let mut names: Vec<String> = Vec::new();
for entry in std::fs::read_dir(source_dir)? {
let entry = entry?;
let file_name = entry.file_name();
let Some(name) = file_name.to_str() else {
continue;
};
if entry.file_type()?.is_file() && is_agent_file(name) {
let stem = name.trim_end_matches(".md").to_string();
if select(&stem) {
names.push(stem);
}
}
}
names.sort_unstable();
for name in names {
let filename = format!("{name}.md");
let composed = match compose_agent(&name, source_dir) {
Ok(c) => c,
Err(err) => {
tracing::error!(
agent = %name,
"agent compose FAILED — skipping this agent, roster deploy \
continues for the rest of the roster: {err}"
);
result.failed.push(format!("{name}: {err}"));
continue;
}
};
if let Err(detail) = validate_frontmatter(&composed) {
tracing::error!(
agent = %name,
file = %filename,
"composed agent frontmatter FAILED strict YAML validation — \
skipping this agent, roster deploy continues for the rest of \
the roster: {detail}"
);
result
.failed
.push(format!("{name}: invalid frontmatter YAML: {detail}"));
continue;
}
let target_path = target_dir.join(&filename);
result
.declared_skills
.insert(name.clone(), agent_metadata_from_str(&composed).skills);
if target_path.exists() {
if !manifest.is_managed(&filename) {
let current = std::fs::read_to_string(&target_path)?;
if checksum(¤t) == checksum(&composed) {
manifest.managed.insert(
filename.clone(),
ManifestEntry {
source_chain: source_chain(&name, source_dir)?,
checksum: checksum(&composed),
deployed_at: now.clone(),
origin: Origin::Bundled,
},
);
result.adopted.push(filename);
} else {
result.skipped.push(filename.clone());
result.untracked_modified.push(filename);
}
continue;
}
let current = std::fs::read_to_string(&target_path)?;
let recorded_owner = manifest
.managed
.get(&filename)
.map(|e| (e.checksum.clone(), e.origin.is_framework_owned()));
if manifest.checksum_matches(&filename, ¤t) {
if checksum(&composed) == checksum(¤t) {
result.unchanged.push(filename);
continue;
}
} else if let Some((expected, true)) = recorded_owner {
tracing::warn!(
file = %filename,
expected_checksum = %expected,
found_checksum = %checksum(¤t),
found_bytes = current.len(),
"bundled agent file drifted from its manifest checksum — \
re-deploying the bundled composition over it (framework-owned \
files are refreshed, not preserved; issue #4408)"
);
result.repaired.push(filename.clone());
} else {
result.skipped.push(filename);
continue;
}
}
std::fs::create_dir_all(target_dir)?;
atomic_write(&target_path, &composed).map_err(|e| match e {
ManifestError::Io(io) => AgentBuildError::Io(io),
other => AgentBuildError::FrontmatterParse(other.to_string()),
})?;
manifest.managed.insert(
filename.clone(),
ManifestEntry {
source_chain: source_chain(&name, source_dir)?,
checksum: checksum(&composed),
deployed_at: now.clone(),
origin: Origin::Bundled,
},
);
result.deployed.push(filename);
}
if !result.untracked_modified.is_empty() {
let count = result.untracked_modified.len();
let preview = result
.untracked_modified
.iter()
.take(5)
.cloned()
.collect::<Vec<_>>()
.join(", ");
let ellipsis = if count > 5 { ", …" } else { "" };
tracing::warn!(
count,
"{count} agent file(s) untracked by the deploy manifest differ from the \
bundled composition and were skipped: {preview}{ellipsis}. Run \
`tm install --reset-agents` to review and reconcile them."
);
}
manifest.save(target_dir).map_err(|e| match e {
ManifestError::Io(io) => AgentBuildError::Io(io),
other => AgentBuildError::FrontmatterParse(other.to_string()),
})?;
Ok(result)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RetractResult {
pub removed: Vec<String>,
pub preserved: Vec<String>,
}
pub fn retract_framework_agents(target_dir: &Path) -> Result<RetractResult, AgentBuildError> {
retract_framework_agents_filtered(target_dir, |_name| true)
}
pub fn retract_framework_agents_filtered(
target_dir: &Path,
select: impl Fn(&str) -> bool,
) -> Result<RetractResult, AgentBuildError> {
if !target_dir.is_dir() {
return Ok(RetractResult::default());
}
with_agent_manifest_lock(target_dir, || retract_locked(target_dir, select))
}
fn retract_locked(
target_dir: &Path,
select: impl Fn(&str) -> bool,
) -> Result<RetractResult, AgentBuildError> {
let mut result = RetractResult::default();
let mut manifest = match AgentManifest::load_checked(target_dir) {
ManifestLoad::Ok(m) => m,
ManifestLoad::Corrupt(detail) => {
return Err(AgentBuildError::FrontmatterParse(format!(
"agent manifest is corrupt; refusing to retract any file on the strength \
of an unreadable ownership ledger. `tm repair deploy` cannot fix this — \
it only repairs the user-tier deploy, not this workspace's ledger. \
Delete `.claude/agents/.trusty-mpm-manifest.json` in this workspace by \
hand (and any stale framework-owned agent files alongside it) to clear \
it; the next session launch will not redeploy here since bundled agents \
now come from the user tier. Detail: {detail}"
)));
}
};
let mut tracked: Vec<String> = manifest.managed.keys().cloned().collect();
tracked.sort_unstable();
for filename in tracked {
let framework_owned = manifest
.managed
.get(&filename)
.is_some_and(|entry| entry.origin.is_framework_owned());
if !framework_owned {
result.preserved.push(filename);
continue;
}
if !select(filename.trim_end_matches(".md")) {
continue;
}
match std::fs::remove_file(target_dir.join(&filename)) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => {
save_pruned(&manifest, target_dir, &result);
return Err(AgentBuildError::Io(e));
}
}
manifest.managed.remove(&filename);
result.removed.push(filename);
}
if result.removed.is_empty() {
return Ok(result);
}
tracing::info!(
removed = result.removed.len(),
preserved = result.preserved.len(),
dir = %target_dir.display(),
"retracted per-workspace bundled agents — the canonical tier is now the \
tm-managed CLAUDE_CONFIG_DIR (issue #4409)"
);
if manifest.managed.is_empty() {
match std::fs::remove_file(target_dir.join(MANIFEST_FILE)) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(AgentBuildError::Io(e)),
}
if only_the_lock_sidecar_remains(target_dir)? {
let _ = std::fs::remove_file(manifest_lock_path(target_dir));
}
if std::fs::read_dir(target_dir)?.next().is_none() {
let _ = std::fs::remove_dir(target_dir);
}
return Ok(result);
}
manifest.save(target_dir).map_err(|e| match e {
ManifestError::Io(io) => AgentBuildError::Io(io),
other => AgentBuildError::FrontmatterParse(other.to_string()),
})?;
Ok(result)
}
fn only_the_lock_sidecar_remains(target_dir: &Path) -> Result<bool, AgentBuildError> {
let sidecar = manifest_lock_path(target_dir);
let sidecar_name = sidecar.file_name();
for entry in std::fs::read_dir(target_dir)? {
if Some(entry?.file_name().as_os_str()) != sidecar_name {
return Ok(false);
}
}
Ok(true)
}
fn save_pruned(manifest: &AgentManifest, target_dir: &Path, result: &RetractResult) {
if result.removed.is_empty() {
return;
}
if let Err(e) = manifest.save(target_dir) {
tracing::warn!(
dir = %target_dir.display(),
"could not persist the partially-pruned agent manifest after a retraction \
failure; the next run self-heals: {e}"
);
}
}
#[cfg(test)]
#[path = "deployer_tests.rs"]
mod tests;