use std::fs;
pub fn restore_prompt_if_needed() -> anyhow::Result<bool> {
let prompt_path = Path::new("PROMPT.md");
if is_prompt_present(prompt_path) {
return Ok(true);
}
if try_restore_backups(prompt_path) {
return Ok(false);
}
anyhow::bail!(
"PROMPT.md is missing/empty and no valid backup available (tried .agent/PROMPT.md.backup, .agent/PROMPT.md.backup.1, .agent/PROMPT.md.backup.2)"
);
}
fn is_prompt_present(prompt_path: &Path) -> bool {
prompt_path
.exists()
.then(|| fs::read_to_string(prompt_path).ok())
.flatten()
.is_some_and(|s| !s.trim().is_empty())
}
fn try_restore_backups(prompt_path: &Path) -> bool {
let backup_paths = [
Path::new(".agent/PROMPT.md.backup"),
Path::new(".agent/PROMPT.md.backup.1"),
Path::new(".agent/PROMPT.md.backup.2"),
];
backup_paths
.iter()
.filter(|backup_path| backup_path.exists())
.find_map(|backup_path| {
let backup_content = fs::read_to_string(backup_path).ok()?;
if backup_content.trim().is_empty() {
return None;
}
fs::write(prompt_path, backup_content).ok()?;
set_prompt_readonly_permissions(prompt_path);
Some(())
})
.is_some()
}
fn set_prompt_readonly_permissions(prompt_path: &Path) {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(prompt_path, fs::Permissions::from_mode(0o444));
}
#[cfg(windows)]
{
use std::os::windows::fs::{PermissionsExt, FILE_ATTRIBUTE_READONLY};
let _ = fs::set_permissions(
prompt_path,
fs::Permissions::from_attributes(FILE_ATTRIBUTE_READONLY),
);
}
}
#[must_use]
pub fn validate_prompt_md(strict: bool, interactive: bool) -> PromptValidationResult {
let root = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
let workspace = WorkspaceFs::new(root);
validate_prompt_md_with_workspace(&workspace, strict, interactive)
}