Skip to main content

eclipse_core/
memory.rs

1//! `MEMORY.md`: the durable facts the agent learned, and the budget that keeps them honest.
2//!
3//! The file is a flat list of entries separated by a line holding `§`:
4//!
5//! ```text
6//! the model server is on the LAN
7//! §
8//! Max prefers local inference over cloud
9//! §
10//! Max prefers local inference over cloud
11//! ```
12//!
13//! Nothing here is clever. An entry is free text, it may span lines, and a memory that needs
14//! a date carries it in the text — no timestamps are stored, because the file is also meant
15//! to be read and edited by hand.
16//!
17//! Two writers (the CLI and the dashboard) can be alive at once, so every mutation takes an
18//! advisory `flock` on `<file>.lock` and replaces the file atomically (`write` to a temp file
19//! in the same directory, then `rename`). A reader therefore never sees half a file, and a
20//! crash cannot leave one.
21
22use crate::error::{Error, Result};
23use std::path::{Path, PathBuf};
24
25/// Ceiling on the rendered file, in characters, unless the config says otherwise.
26pub const DEFAULT_BUDGET_CHARS: usize = 3000;
27/// The line that separates two entries.
28pub const SEPARATOR: &str = "§";
29/// How long a writer waits for a concurrent one before giving up.
30const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
31const LOCK_POLL: std::time::Duration = std::time::Duration::from_millis(40);
32
33/// What a mutation did, in words worth showing the person watching.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum Outcome {
36    /// The file changed: the entry, and the room left afterwards.
37    Changed {
38        entry: String,
39        chars: usize,
40        budget: usize,
41    },
42    /// The change would not fit. The current entries come back so the next attempt can prune
43    /// instead of guessing.
44    Full {
45        chars: usize,
46        budget: usize,
47        entries: Vec<String>,
48    },
49    /// Nothing matched, so nothing changed.
50    NotFound(String),
51    /// Nothing to do: the text is already there.
52    Unchanged(String),
53}
54
55impl Outcome {
56    pub fn changed(&self) -> bool {
57        matches!(self, Outcome::Changed { .. })
58    }
59
60    /// One line for the CLI and for the model.
61    pub fn describe(&self) -> String {
62        match self {
63            Outcome::Changed {
64                entry,
65                chars,
66                budget,
67            } => format!(
68                "memory: {} — {char_chars} chars used of {budget}",
69                clip(entry, 80),
70                char_chars = chars
71            ),
72            Outcome::Full {
73                chars,
74                budget,
75                entries,
76            } => format!(
77                "memory is full ({chars} of {budget} chars): remove or shorten an entry first. \
78                 Current entries:\n{}",
79                entries
80                    .iter()
81                    .enumerate()
82                    .map(|(i, e)| format!("{}. {}", i + 1, clip(e, 120)))
83                    .collect::<Vec<_>>()
84                    .join("\n")
85            ),
86            Outcome::NotFound(text) => format!("no memory entry matches {:?}", clip(text, 60)),
87            Outcome::Unchanged(entry) => {
88                format!("memory already says {:?}", clip(entry, 60))
89            }
90        }
91    }
92}
93
94fn clip(text: &str, max: usize) -> String {
95    let first_line = text.lines().next().unwrap_or("").trim();
96    let mut out: String = first_line.chars().take(max).collect();
97    if first_line.chars().count() > max || text.lines().count() > 1 {
98        out.push('…');
99    }
100    out
101}
102
103/// One profile's memory file.
104#[derive(Debug, Clone)]
105pub struct Memory {
106    path: PathBuf,
107    budget_chars: usize,
108}
109
110impl Memory {
111    pub fn new(path: impl Into<PathBuf>, budget_chars: usize) -> Self {
112        Self {
113            path: path.into(),
114            budget_chars,
115        }
116    }
117
118    pub fn path(&self) -> &Path {
119        &self.path
120    }
121
122    pub fn budget(&self) -> usize {
123        self.budget_chars
124    }
125
126    fn lock_path(&self) -> PathBuf {
127        let mut name = self.path.clone().into_os_string();
128        name.push(".lock");
129        PathBuf::from(name)
130    }
131
132    /// The entries, in file order. A missing file is an empty memory, not an error.
133    pub fn read(&self) -> Result<Vec<String>> {
134        match std::fs::read_to_string(&self.path) {
135            Ok(text) => Ok(parse(&text)),
136            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
137            Err(e) => Err(Error::io(&self.path, e)),
138        }
139    }
140
141    /// Characters the rendered file occupies — what the budget actually measures.
142    pub fn size(&self) -> Result<usize> {
143        Ok(render(&self.read()?).chars().count())
144    }
145
146    /// Append an entry, refusing past the budget.
147    pub fn add(&self, text: &str) -> Result<Outcome> {
148        let entry = text.trim();
149        if entry.is_empty() {
150            return Ok(Outcome::NotFound("(empty)".into()));
151        }
152        self.mutate(|entries| {
153            if entries.iter().any(|e| same(e, entry)) {
154                return Ok(Change::Keep(Outcome::Unchanged(entry.to_string())));
155            }
156            let mut next = entries.to_vec();
157            next.push(entry.to_string());
158            Ok(Change::Write(next))
159        })
160    }
161
162    /// Rewrite the first entry that contains `old`, keeping everything else.
163    pub fn patch(&self, old: &str, new: &str) -> Result<Outcome> {
164        let new = new.trim();
165        if old.trim().is_empty() {
166            return Ok(Outcome::NotFound("(empty)".into()));
167        }
168        if new.is_empty() {
169            return self.remove(old);
170        }
171        self.mutate(|entries| {
172            let Some(at) = entries.iter().position(|e| e.contains(old.trim())) else {
173                return Ok(Change::Keep(Outcome::NotFound(old.to_string())));
174            };
175            let mut next = entries.to_vec();
176            next[at] = new.to_string();
177            Ok(Change::Write(next))
178        })
179    }
180
181    /// Drop the first entry that contains `text`.
182    pub fn remove(&self, text: &str) -> Result<Outcome> {
183        let needle = text.trim().to_string();
184        if needle.is_empty() {
185            return Ok(Outcome::NotFound("(empty)".into()));
186        }
187        self.mutate(|entries| {
188            let Some(at) = entries.iter().position(|e| e.contains(&needle)) else {
189                return Ok(Change::Keep(Outcome::NotFound(needle.clone())));
190            };
191            let mut next = entries.to_vec();
192            next.remove(at);
193            Ok(Change::Write(next))
194        })
195    }
196
197    /// Put the entries back as they were — for `eclipse memory prune`, which decides what to
198    /// drop itself.
199    pub fn replace(&self, entries: Vec<String>) -> Result<Outcome> {
200        self.mutate(|_old| Ok(Change::Write(entries.clone())))
201    }
202
203    /// The one path every mutation goes through: lock, read, decide, check the budget, write
204    /// atomically, unlock.
205    fn mutate(&self, decide: impl FnOnce(&[String]) -> Result<Change>) -> Result<Outcome> {
206        let _guard = self.lock()?;
207        let entries = self.read()?;
208        let next = match decide(&entries)? {
209            Change::Keep(outcome) => return Ok(outcome),
210            Change::Write(next) => next,
211        };
212        let text = render(&next);
213        let chars = text.chars().count();
214        if self.budget_chars > 0 && chars > self.budget_chars {
215            return Ok(Outcome::Full {
216                chars,
217                budget: self.budget_chars,
218                entries,
219            });
220        }
221        self.write_atomically(&text, &next)?;
222        Ok(Outcome::Changed {
223            entry: next.last().cloned().unwrap_or_default(),
224            chars,
225            budget: self.budget_chars,
226        })
227    }
228
229    fn write_atomically(&self, text: &str, entries: &[String]) -> Result<()> {
230        crate::atomic::write_file_atomically(&self.path, text)
231            .map_err(|e| Error::io(&self.path, e))?;
232        // A memory tool that wrote nothing would look like a bug in the transcript.
233        if entries.is_empty() {
234            std::fs::remove_file(&self.path).ok();
235        }
236        Ok(())
237    }
238
239    fn lock(&self) -> Result<LockGuard> {
240        let path = self.lock_path();
241        if let Some(parent) = path.parent() {
242            std::fs::create_dir_all(parent).map_err(|e| Error::io(parent, e))?;
243        }
244        let mut opts = std::fs::OpenOptions::new();
245        opts.create(true).read(true).write(true);
246        #[cfg(unix)]
247        {
248            use std::os::unix::fs::OpenOptionsExt;
249            opts.mode(0o600);
250        }
251        let file = opts.open(&path).map_err(|e| Error::io(&path, e))?;
252        let deadline = std::time::Instant::now() + LOCK_WAIT;
253        loop {
254            match try_lock(&file) {
255                Ok(true) => return Ok(LockGuard { _file: file }),
256                Ok(false) if std::time::Instant::now() < deadline => {
257                    std::thread::sleep(LOCK_POLL);
258                }
259                Ok(false) => {
260                    return Err(Error::Config(format!(
261                        "another eclipse is writing {} (waited {}s); try again",
262                        self.path.display(),
263                        LOCK_WAIT.as_secs()
264                    )))
265                }
266                Err(e) => return Err(Error::io(&path, e)),
267            }
268        }
269    }
270}
271
272enum Change {
273    /// Nothing to write, and what to say about it.
274    Keep(Outcome),
275    Write(Vec<String>),
276}
277
278struct LockGuard {
279    _file: std::fs::File,
280}
281
282#[cfg(unix)]
283fn try_lock(file: &std::fs::File) -> std::io::Result<bool> {
284    use std::os::unix::io::AsRawFd;
285    // SAFETY: `file` owns a valid descriptor for the duration of the call.
286    let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
287    if rc == 0 {
288        return Ok(true);
289    }
290    let err = std::io::Error::last_os_error();
291    match err.raw_os_error() {
292        Some(libc::EWOULDBLOCK) => Ok(false),
293        _ => Err(err),
294    }
295}
296
297#[cfg(not(unix))]
298fn try_lock(_file: &std::fs::File) -> std::io::Result<bool> {
299    // No portable advisory lock without another dependency; the atomic rename is what keeps
300    // the file whole here (documented in the limits).
301    Ok(true)
302}
303
304fn same(a: &str, b: &str) -> bool {
305    a.trim().eq_ignore_ascii_case(b.trim())
306}
307
308/// Entries out of the file text: a line holding `§` separates them, blank lines around it and
309/// at the ends are dropped, and anything else (including blank lines inside an entry) is kept.
310pub fn parse(text: &str) -> Vec<String> {
311    let mut out: Vec<String> = Vec::new();
312    let mut current: Vec<&str> = Vec::new();
313    for line in text.lines() {
314        if line.trim() == SEPARATOR || line.trim() == "§§" {
315            push_entry(&mut out, &mut current);
316            continue;
317        }
318        current.push(line);
319    }
320    push_entry(&mut out, &mut current);
321    out
322}
323
324fn push_entry(out: &mut Vec<String>, current: &mut Vec<&str>) {
325    let text = current.join("\n").trim().to_string();
326    current.clear();
327    if !text.is_empty() {
328        out.push(text);
329    }
330}
331
332/// Entries back into the file text, ending with a newline so appends stay one-per-block.
333pub fn render(entries: &[String]) -> String {
334    if entries.is_empty() {
335        return String::new();
336    }
337    let mut out = String::new();
338    for (i, entry) in entries.iter().enumerate() {
339        if i > 0 {
340            out.push_str(SEPARATOR);
341            out.push('\n');
342        }
343        out.push_str(entry.trim());
344        out.push('\n');
345    }
346    out
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352
353    fn memory(dir: &Path, budget: usize) -> Memory {
354        Memory::new(dir.join("MEMORY.md"), budget)
355    }
356
357    #[test]
358    fn entries_round_trip_through_the_separator() {
359        let entries = vec![
360            "one line".to_string(),
361            "two\nlines in one entry".to_string(),
362            "third".to_string(),
363        ];
364        let text = render(&entries);
365        assert_eq!(text, "one line\n§\ntwo\nlines in one entry\n§\nthird\n");
366        assert_eq!(parse(&text), entries);
367        assert_eq!(parse(""), Vec::<String>::new());
368        assert_eq!(parse("§\n§\n"), Vec::<String>::new());
369    }
370
371    #[test]
372    fn add_read_patch_remove_round_trip() {
373        let tmp = tempfile::tempdir().unwrap();
374        let m = memory(tmp.path(), 1000);
375        assert!(m.add("the fleet is two servers").unwrap().changed());
376        assert!(m.add("Max prefers local inference").unwrap().changed());
377        assert_eq!(m.read().unwrap().len(), 2);
378
379        // Adding the same thing twice is not a change.
380        assert_eq!(
381            m.add("  the fleet is two servers ").unwrap(),
382            Outcome::Unchanged("the fleet is two servers".into())
383        );
384
385        assert!(m
386            .patch("two servers", "the fleet is a server and two desktops")
387            .unwrap()
388            .changed());
389        assert_eq!(
390            m.read().unwrap()[0],
391            "the fleet is a server and two desktops"
392        );
393
394        assert!(m.remove("prefers local").unwrap().changed());
395        assert_eq!(
396            m.read().unwrap(),
397            ["the fleet is a server and two desktops"]
398        );
399
400        assert_eq!(
401            m.remove("nothing like this").unwrap(),
402            Outcome::NotFound("nothing like this".into())
403        );
404    }
405
406    #[test]
407    fn the_budget_refuses_the_write_and_hands_back_what_is_there() {
408        let tmp = tempfile::tempdir().unwrap();
409        let m = memory(tmp.path(), 60);
410        assert!(m.add(&"a".repeat(30)).unwrap().changed());
411        let outcome = m.add(&"b".repeat(30)).unwrap();
412        match outcome {
413            Outcome::Full {
414                chars,
415                budget,
416                entries,
417            } => {
418                assert_eq!(budget, 60);
419                assert!(chars > 60, "{chars}");
420                assert_eq!(
421                    entries.len(),
422                    1,
423                    "the current entries, so the next try can prune"
424                );
425            }
426            other => panic!("expected Full, got {other:?}"),
427        }
428        // Nothing was written.
429        assert_eq!(m.read().unwrap().len(), 1);
430        // ...and the refusal says how to fix it.
431        assert!(m
432            .add(&"b".repeat(30))
433            .unwrap()
434            .describe()
435            .contains("memory is full"));
436    }
437
438    #[test]
439    fn a_zero_budget_means_no_ceiling() {
440        let tmp = tempfile::tempdir().unwrap();
441        let m = memory(tmp.path(), 0);
442        assert!(m.add(&"x".repeat(5000)).unwrap().changed());
443        assert_eq!(m.size().unwrap(), 5001);
444    }
445
446    #[test]
447    fn the_file_is_replaced_atomically_and_reads_as_a_whole() {
448        let tmp = tempfile::tempdir().unwrap();
449        let m = memory(tmp.path(), 1000);
450        m.add("first").unwrap();
451        // No temp files are left behind.
452        let leftovers: Vec<_> = std::fs::read_dir(tmp.path())
453            .unwrap()
454            .filter_map(|e| e.ok())
455            .map(|e| e.file_name().to_string_lossy().to_string())
456            .filter(|n| n.contains("tmp"))
457            .collect();
458        assert!(leftovers.is_empty(), "{leftovers:?}");
459        #[cfg(unix)]
460        {
461            use std::os::unix::fs::PermissionsExt;
462            let mode = std::fs::metadata(m.path()).unwrap().permissions().mode() & 0o777;
463            assert_eq!(mode, 0o600);
464        }
465    }
466
467    #[test]
468    fn two_writers_in_a_row_never_lose_an_entry() {
469        let tmp = tempfile::tempdir().unwrap();
470        let path = tmp.path().join("MEMORY.md");
471        let a = Memory::new(&path, 10_000);
472        let b = Memory::new(&path, 10_000);
473        for i in 0..10 {
474            a.add(&format!("a{i}")).unwrap();
475            b.add(&format!("b{i}")).unwrap();
476        }
477        let entries = a.read().unwrap();
478        assert_eq!(entries.len(), 20, "{entries:?}");
479        assert!(entries.iter().any(|e| e == "a9"));
480        assert!(entries.iter().any(|e| e == "b9"));
481    }
482
483    #[test]
484    fn a_missing_file_is_an_empty_memory() {
485        let tmp = tempfile::tempdir().unwrap();
486        let m = memory(tmp.path(), 100);
487        assert_eq!(m.read().unwrap(), Vec::<String>::new());
488        assert_eq!(m.size().unwrap(), 0);
489    }
490
491    #[test]
492    fn removing_the_last_entry_removes_the_file() {
493        let tmp = tempfile::tempdir().unwrap();
494        let m = memory(tmp.path(), 100);
495        m.add("only").unwrap();
496        assert!(m.path().exists());
497        m.remove("only").unwrap();
498        assert!(
499            !m.path().exists(),
500            "an empty MEMORY.md is not worth keeping"
501        );
502        assert_eq!(m.read().unwrap(), Vec::<String>::new());
503    }
504
505    #[test]
506    fn a_multi_line_entry_survives_the_separator_format() {
507        let tmp = tempfile::tempdir().unwrap();
508        let m = memory(tmp.path(), 1000);
509        m.add("first line\nsecond line").unwrap();
510        m.add("another").unwrap();
511        assert_eq!(m.read().unwrap(), ["first line\nsecond line", "another"]);
512    }
513}