use std::path::{Path, PathBuf};
use serde::Deserialize;
pub const FILE: &str = "memfork-autopilot.toml";
pub const DEFAULT_TIMEOUT_SECONDS: u64 = 300;
pub const MAX_TIMEOUT_SECONDS: u64 = 3600;
pub const DEFAULT_MAX_FILES: u64 = 5;
pub const MAX_CHECK_CHARS: usize = 1000;
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
struct FileShape {
enabled: Option<bool>,
follow: Follow,
fork: Fork,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
struct Follow {
git_branch: Option<bool>,
}
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
struct Fork {
before_risky: Option<bool>,
check: Option<String>,
timeout_seconds: Option<u64>,
max_files: Option<u64>,
extra_rules: Vec<String>,
ignore_rules: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
pub path: PathBuf,
pub enabled: bool,
pub follow_git: bool,
pub fork_before_risky: bool,
pub check: Option<String>,
pub timeout_seconds: u64,
pub max_files: u64,
pub extra_rules: Vec<String>,
pub ignore_rules: Vec<String>,
}
impl Config {
pub fn follows(&self) -> bool {
self.enabled && self.follow_git
}
pub fn forks(&self) -> bool {
self.enabled && self.fork_before_risky
}
pub fn timeout(&self) -> std::time::Duration {
std::time::Duration::from_secs(self.timeout_seconds.clamp(1, MAX_TIMEOUT_SECONDS))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Read {
Absent,
Broken(String),
Config(Config),
}
impl Read {
pub fn config(&self) -> Option<&Config> {
match self {
Read::Config(c) => Some(c),
_ => None,
}
}
}
pub fn read(root: &Path) -> Read {
let path = root.join(FILE);
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Read::Absent,
Err(e) => return Read::Broken(format!("{} cannot be read: {e}", path.display())),
};
match parse(&path, &text) {
Ok(config) => Read::Config(config),
Err(why) => Read::Broken(why),
}
}
fn parse(path: &Path, text: &str) -> Result<Config, String> {
let shape: FileShape = toml::from_str(text)
.map_err(|e| format!("{} is not a usable autopilot file: {e}", path.display()))?;
let check = shape
.fork
.check
.as_deref()
.map(str::trim)
.filter(|c| !c.is_empty())
.map(str::to_owned);
if check
.as_ref()
.is_some_and(|c| c.chars().count() > MAX_CHECK_CHARS)
{
return Err(format!(
"{}: the check command is over {MAX_CHECK_CHARS} characters",
path.display()
));
}
if check.as_ref().is_some_and(|c| c.contains('\n')) {
return Err(format!(
"{}: the check command must be one line",
path.display()
));
}
Ok(Config {
path: path.to_path_buf(),
enabled: shape.enabled.unwrap_or(true),
follow_git: shape.follow.git_branch.unwrap_or(true),
fork_before_risky: shape.fork.before_risky.unwrap_or(true),
check,
timeout_seconds: shape
.fork
.timeout_seconds
.unwrap_or(DEFAULT_TIMEOUT_SECONDS)
.clamp(1, MAX_TIMEOUT_SECONDS),
max_files: shape.fork.max_files.unwrap_or(DEFAULT_MAX_FILES).max(1),
extra_rules: shape.fork.extra_rules,
ignore_rules: shape.fork.ignore_rules,
})
}
pub fn template(check: Option<&str>) -> String {
let check_line = match check {
Some(command) => format!("check = {}", toml_string(command)),
None => "# check = \"cargo test\"".to_owned(),
};
format!(
"\
# MemFork autopilot for this repository, written by `memfork init --project
# --autopilot`. Delete the file, or run `memfork autopilot off`, to stop it.
# `memfork autopilot status` reports what is in force.
enabled = true
[follow]
# Memory follows the git branch: switching branches in git switches the
# memory branch of the same name, forking it from the branch you came from
# the first time; merging a branch in git merges its memory the same way.
git_branch = true
[fork]
# Memory is forked before a risky action and merged or discarded by the
# outcome. Only where a client's own hooks are installed (`memfork autopilot
# status` says which); nothing here runs without them.
before_risky = true
# The command that decides whether a risky action worked. It runs in this
# repository, and only because this file names it. Without one, a shell
# command is judged by its own outcome (a failure the client reports, the
# trailing `exit: N` line Claude Code's wrapper prints, then the exit
# status) and an edit sweep is kept as a fork for you to merge or discard.
{check_line}
# Seconds the check may take before it counts as failed.
timeout_seconds = {DEFAULT_TIMEOUT_SECONDS}
# An edit sweep touching more than this many distinct files is risky.
max_files = {DEFAULT_MAX_FILES}
# Regular expressions of this project's own, and built-in rules switched off
# by name. `memfork autopilot rules` lists the built-in ones.
extra_rules = []
ignore_rules = []
"
)
}
fn toml_string(text: &str) -> String {
toml_edit::Value::from(text).to_string()
}
pub fn set_enabled(text: &str, on: bool) -> Result<String, String> {
let mut doc: toml_edit::DocumentMut = text
.parse()
.map_err(|e| format!("the autopilot file is not valid TOML: {e}"))?;
doc["enabled"] = toml_edit::value(on);
Ok(doc.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_template_parses_to_the_defaults_and_toggles_in_place() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(FILE);
std::fs::write(&path, template(None)).unwrap();
let Read::Config(config) = read(dir.path()) else {
panic!("the template did not parse");
};
assert!(config.enabled && config.follow_git && config.fork_before_risky);
assert_eq!(config.check, None);
assert_eq!(config.timeout_seconds, DEFAULT_TIMEOUT_SECONDS);
assert_eq!(config.max_files, DEFAULT_MAX_FILES);
let text = std::fs::read_to_string(&path).unwrap();
let off = set_enabled(&text, false).unwrap();
std::fs::write(&path, &off).unwrap();
let config = read(dir.path());
assert!(!config.config().unwrap().enabled);
assert!(!config.config().unwrap().follows());
assert_eq!(
off.replace("enabled = false", "enabled = true"),
text,
"more than the switch changed"
);
let with_check = template(Some("cargo test --workspace"));
std::fs::write(&path, with_check).unwrap();
assert_eq!(
read(dir.path()).config().unwrap().check.as_deref(),
Some("cargo test --workspace")
);
}
#[test]
fn absent_means_off_and_broken_says_why() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(read(dir.path()), Read::Absent);
std::fs::write(dir.path().join(FILE), "enabled = \"yes\"\n").unwrap();
assert!(matches!(read(dir.path()), Read::Broken(_)));
std::fs::write(dir.path().join(FILE), "[fork]\ncheck = \"a\\nb\"\n").unwrap();
assert!(matches!(read(dir.path()), Read::Broken(why) if why.contains("one line")));
std::fs::write(dir.path().join(FILE), "unknown = 1\n").unwrap();
assert!(matches!(read(dir.path()), Read::Broken(_)));
}
#[test]
fn values_are_bounded() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join(FILE),
"[fork]\ntimeout_seconds = 999999\nmax_files = 0\ncheck = \" \"\n",
)
.unwrap();
let config = read(dir.path());
let config = config.config().unwrap();
assert_eq!(config.timeout_seconds, MAX_TIMEOUT_SECONDS);
assert_eq!(config.max_files, 1);
assert_eq!(config.check, None);
}
}