use crate::error::{Error, Result};
use std::path::{Path, PathBuf};
pub const DEFAULT_BUDGET_CHARS: usize = 3000;
pub const SEPARATOR: &str = "§";
const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
const LOCK_POLL: std::time::Duration = std::time::Duration::from_millis(40);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Changed {
entry: String,
chars: usize,
budget: usize,
},
Full {
chars: usize,
budget: usize,
entries: Vec<String>,
},
NotFound(String),
Unchanged(String),
}
impl Outcome {
pub fn changed(&self) -> bool {
matches!(self, Outcome::Changed { .. })
}
pub fn describe(&self) -> String {
match self {
Outcome::Changed {
entry,
chars,
budget,
} => format!(
"memory: {} — {char_chars} chars used of {budget}",
clip(entry, 80),
char_chars = chars
),
Outcome::Full {
chars,
budget,
entries,
} => format!(
"memory is full ({chars} of {budget} chars): remove or shorten an entry first. \
Current entries:\n{}",
entries
.iter()
.enumerate()
.map(|(i, e)| format!("{}. {}", i + 1, clip(e, 120)))
.collect::<Vec<_>>()
.join("\n")
),
Outcome::NotFound(text) => format!("no memory entry matches {:?}", clip(text, 60)),
Outcome::Unchanged(entry) => {
format!("memory already says {:?}", clip(entry, 60))
}
}
}
}
fn clip(text: &str, max: usize) -> String {
let first_line = text.lines().next().unwrap_or("").trim();
let mut out: String = first_line.chars().take(max).collect();
if first_line.chars().count() > max || text.lines().count() > 1 {
out.push('…');
}
out
}
#[derive(Debug, Clone)]
pub struct Memory {
path: PathBuf,
budget_chars: usize,
}
impl Memory {
pub fn new(path: impl Into<PathBuf>, budget_chars: usize) -> Self {
Self {
path: path.into(),
budget_chars,
}
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn budget(&self) -> usize {
self.budget_chars
}
fn lock_path(&self) -> PathBuf {
let mut name = self.path.clone().into_os_string();
name.push(".lock");
PathBuf::from(name)
}
pub fn read(&self) -> Result<Vec<String>> {
match std::fs::read_to_string(&self.path) {
Ok(text) => Ok(parse(&text)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
Err(e) => Err(Error::io(&self.path, e)),
}
}
pub fn size(&self) -> Result<usize> {
Ok(render(&self.read()?).chars().count())
}
pub fn add(&self, text: &str) -> Result<Outcome> {
let entry = text.trim();
if entry.is_empty() {
return Ok(Outcome::NotFound("(empty)".into()));
}
self.mutate(|entries| {
if entries.iter().any(|e| same(e, entry)) {
return Ok(Change::Keep(Outcome::Unchanged(entry.to_string())));
}
let mut next = entries.to_vec();
next.push(entry.to_string());
Ok(Change::Write(next))
})
}
pub fn patch(&self, old: &str, new: &str) -> Result<Outcome> {
let new = new.trim();
if old.trim().is_empty() {
return Ok(Outcome::NotFound("(empty)".into()));
}
if new.is_empty() {
return self.remove(old);
}
self.mutate(|entries| {
let Some(at) = entries.iter().position(|e| e.contains(old.trim())) else {
return Ok(Change::Keep(Outcome::NotFound(old.to_string())));
};
let mut next = entries.to_vec();
next[at] = new.to_string();
Ok(Change::Write(next))
})
}
pub fn remove(&self, text: &str) -> Result<Outcome> {
let needle = text.trim().to_string();
if needle.is_empty() {
return Ok(Outcome::NotFound("(empty)".into()));
}
self.mutate(|entries| {
let Some(at) = entries.iter().position(|e| e.contains(&needle)) else {
return Ok(Change::Keep(Outcome::NotFound(needle.clone())));
};
let mut next = entries.to_vec();
next.remove(at);
Ok(Change::Write(next))
})
}
pub fn replace(&self, entries: Vec<String>) -> Result<Outcome> {
self.mutate(|_old| Ok(Change::Write(entries.clone())))
}
fn mutate(&self, decide: impl FnOnce(&[String]) -> Result<Change>) -> Result<Outcome> {
let _guard = self.lock()?;
let entries = self.read()?;
let next = match decide(&entries)? {
Change::Keep(outcome) => return Ok(outcome),
Change::Write(next) => next,
};
let text = render(&next);
let chars = text.chars().count();
if self.budget_chars > 0 && chars > self.budget_chars {
return Ok(Outcome::Full {
chars,
budget: self.budget_chars,
entries,
});
}
self.write_atomically(&text, &next)?;
Ok(Outcome::Changed {
entry: next.last().cloned().unwrap_or_default(),
chars,
budget: self.budget_chars,
})
}
fn write_atomically(&self, text: &str, entries: &[String]) -> Result<()> {
crate::atomic::write_file_atomically(&self.path, text)
.map_err(|e| Error::io(&self.path, e))?;
if entries.is_empty() {
std::fs::remove_file(&self.path).ok();
}
Ok(())
}
fn lock(&self) -> Result<LockGuard> {
let path = self.lock_path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;
}
let mut opts = std::fs::OpenOptions::new();
opts.create(true).read(true).write(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
let file = opts.open(&path).map_err(|e| Error::io(&path, e))?;
let deadline = std::time::Instant::now() + LOCK_WAIT;
loop {
match try_lock(&file) {
Ok(true) => return Ok(LockGuard { _file: file }),
Ok(false) if std::time::Instant::now() < deadline => {
std::thread::sleep(LOCK_POLL);
}
Ok(false) => {
return Err(Error::Config(format!(
"another eclipse is writing {} (waited {}s); try again",
self.path.display(),
LOCK_WAIT.as_secs()
)))
}
Err(e) => return Err(Error::io(&path, e)),
}
}
}
}
enum Change {
Keep(Outcome),
Write(Vec<String>),
}
struct LockGuard {
_file: std::fs::File,
}
#[cfg(unix)]
fn try_lock(file: &std::fs::File) -> std::io::Result<bool> {
use std::os::unix::io::AsRawFd;
let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if rc == 0 {
return Ok(true);
}
let err = std::io::Error::last_os_error();
match err.raw_os_error() {
Some(libc::EWOULDBLOCK) => Ok(false),
_ => Err(err),
}
}
#[cfg(not(unix))]
fn try_lock(_file: &std::fs::File) -> std::io::Result<bool> {
Ok(true)
}
fn same(a: &str, b: &str) -> bool {
a.trim().eq_ignore_ascii_case(b.trim())
}
pub fn parse(text: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut current: Vec<&str> = Vec::new();
for line in text.lines() {
if line.trim() == SEPARATOR || line.trim() == "§§" {
push_entry(&mut out, &mut current);
continue;
}
current.push(line);
}
push_entry(&mut out, &mut current);
out
}
fn push_entry(out: &mut Vec<String>, current: &mut Vec<&str>) {
let text = current.join("\n").trim().to_string();
current.clear();
if !text.is_empty() {
out.push(text);
}
}
pub fn render(entries: &[String]) -> String {
if entries.is_empty() {
return String::new();
}
let mut out = String::new();
for (i, entry) in entries.iter().enumerate() {
if i > 0 {
out.push_str(SEPARATOR);
out.push('\n');
}
out.push_str(entry.trim());
out.push('\n');
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn memory(dir: &Path, budget: usize) -> Memory {
Memory::new(dir.join("MEMORY.md"), budget)
}
#[test]
fn entries_round_trip_through_the_separator() {
let entries = vec![
"one line".to_string(),
"two\nlines in one entry".to_string(),
"third".to_string(),
];
let text = render(&entries);
assert_eq!(text, "one line\n§\ntwo\nlines in one entry\n§\nthird\n");
assert_eq!(parse(&text), entries);
assert_eq!(parse(""), Vec::<String>::new());
assert_eq!(parse("§\n§\n"), Vec::<String>::new());
}
#[test]
fn add_read_patch_remove_round_trip() {
let tmp = tempfile::tempdir().unwrap();
let m = memory(tmp.path(), 1000);
assert!(m.add("the fleet is two servers").unwrap().changed());
assert!(m.add("Max prefers local inference").unwrap().changed());
assert_eq!(m.read().unwrap().len(), 2);
assert_eq!(
m.add(" the fleet is two servers ").unwrap(),
Outcome::Unchanged("the fleet is two servers".into())
);
assert!(m
.patch("two servers", "the fleet is a server and two desktops")
.unwrap()
.changed());
assert_eq!(
m.read().unwrap()[0],
"the fleet is a server and two desktops"
);
assert!(m.remove("prefers local").unwrap().changed());
assert_eq!(
m.read().unwrap(),
["the fleet is a server and two desktops"]
);
assert_eq!(
m.remove("nothing like this").unwrap(),
Outcome::NotFound("nothing like this".into())
);
}
#[test]
fn the_budget_refuses_the_write_and_hands_back_what_is_there() {
let tmp = tempfile::tempdir().unwrap();
let m = memory(tmp.path(), 60);
assert!(m.add(&"a".repeat(30)).unwrap().changed());
let outcome = m.add(&"b".repeat(30)).unwrap();
match outcome {
Outcome::Full {
chars,
budget,
entries,
} => {
assert_eq!(budget, 60);
assert!(chars > 60, "{chars}");
assert_eq!(
entries.len(),
1,
"the current entries, so the next try can prune"
);
}
other => panic!("expected Full, got {other:?}"),
}
assert_eq!(m.read().unwrap().len(), 1);
assert!(m
.add(&"b".repeat(30))
.unwrap()
.describe()
.contains("memory is full"));
}
#[test]
fn a_zero_budget_means_no_ceiling() {
let tmp = tempfile::tempdir().unwrap();
let m = memory(tmp.path(), 0);
assert!(m.add(&"x".repeat(5000)).unwrap().changed());
assert_eq!(m.size().unwrap(), 5001);
}
#[test]
fn the_file_is_replaced_atomically_and_reads_as_a_whole() {
let tmp = tempfile::tempdir().unwrap();
let m = memory(tmp.path(), 1000);
m.add("first").unwrap();
let leftovers: Vec<_> = std::fs::read_dir(tmp.path())
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().to_string())
.filter(|n| n.contains("tmp"))
.collect();
assert!(leftovers.is_empty(), "{leftovers:?}");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(m.path()).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
}
#[test]
fn two_writers_in_a_row_never_lose_an_entry() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("MEMORY.md");
let a = Memory::new(&path, 10_000);
let b = Memory::new(&path, 10_000);
for i in 0..10 {
a.add(&format!("a{i}")).unwrap();
b.add(&format!("b{i}")).unwrap();
}
let entries = a.read().unwrap();
assert_eq!(entries.len(), 20, "{entries:?}");
assert!(entries.iter().any(|e| e == "a9"));
assert!(entries.iter().any(|e| e == "b9"));
}
#[test]
fn a_missing_file_is_an_empty_memory() {
let tmp = tempfile::tempdir().unwrap();
let m = memory(tmp.path(), 100);
assert_eq!(m.read().unwrap(), Vec::<String>::new());
assert_eq!(m.size().unwrap(), 0);
}
#[test]
fn removing_the_last_entry_removes_the_file() {
let tmp = tempfile::tempdir().unwrap();
let m = memory(tmp.path(), 100);
m.add("only").unwrap();
assert!(m.path().exists());
m.remove("only").unwrap();
assert!(
!m.path().exists(),
"an empty MEMORY.md is not worth keeping"
);
assert_eq!(m.read().unwrap(), Vec::<String>::new());
}
#[test]
fn a_multi_line_entry_survives_the_separator_format() {
let tmp = tempfile::tempdir().unwrap();
let m = memory(tmp.path(), 1000);
m.add("first line\nsecond line").unwrap();
m.add("another").unwrap();
assert_eq!(m.read().unwrap(), ["first line\nsecond line", "another"]);
}
}