Skip to main content

microclaw_engine/tools/
file_state.rs

1//! Stale-read guard shared by `read_file`, `edit_file` and `write_file`.
2//!
3//! The tools of one registry share a [`FileStateTable`] that remembers a
4//! content fingerprint for every file the agent read or wrote. Before
5//! overwriting a file it has seen, a tool compares the current on-disk content
6//! with that fingerprint; a mismatch means someone else (the user's editor, a
7//! formatter, another process) changed the file after the agent looked at it,
8//! and the write is refused so those changes are not silently clobbered.
9//! Files the agent never read are not tracked and are unaffected.
10//!
11//! The table belongs to a `ToolRegistry` rather than the process, so separate
12//! runtimes (and tests) never observe each other's reads.
13
14use std::collections::HashMap;
15use std::path::{Path, PathBuf};
16use std::sync::Mutex;
17
18use sha2::{Digest, Sha256};
19
20/// Bound on tracked files; the table is cleared when it grows past this.
21const MAX_TRACKED_FILES: usize = 4096;
22
23type Fingerprint = [u8; 32];
24
25/// Content fingerprints of files read or written through one tool registry.
26#[derive(Debug, Default)]
27pub struct FileStateTable {
28    entries: Mutex<HashMap<PathBuf, Fingerprint>>,
29}
30
31fn key(path: &Path) -> PathBuf {
32    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
33}
34
35fn fingerprint(content: &[u8]) -> Fingerprint {
36    Sha256::digest(content).into()
37}
38
39impl FileStateTable {
40    /// Remember the content the agent has just read or written.
41    pub fn record(&self, path: &Path, content: &[u8]) {
42        let key = key(path);
43        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
44        if entries.len() >= MAX_TRACKED_FILES && !entries.contains_key(&key) {
45            entries.clear();
46        }
47        entries.insert(key, fingerprint(content));
48    }
49
50    /// Return an error message when `current` differs from the content the
51    /// agent last read or wrote at `path`.
52    pub fn check_fresh(&self, path: &Path, current: &[u8]) -> Result<(), String> {
53        let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
54        match entries.get(&key(path)) {
55            Some(known) if *known != fingerprint(current) => Err(format!(
56                "{} was modified on disk after you last read it (by the user, an editor, or another process). Read the file again before editing so those changes are not overwritten.",
57                path.display()
58            )),
59            _ => Ok(()),
60        }
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn untracked_files_are_always_fresh() {
70        let table = FileStateTable::default();
71        let dir = tempfile::tempdir().unwrap();
72        let file = dir.path().join("a.txt");
73        std::fs::write(&file, "one").unwrap();
74        assert!(table.check_fresh(&file, b"anything").is_ok());
75    }
76
77    #[test]
78    fn external_change_after_read_is_detected() {
79        let table = FileStateTable::default();
80        let dir = tempfile::tempdir().unwrap();
81        let file = dir.path().join("a.txt");
82        std::fs::write(&file, "one").unwrap();
83        table.record(&file, b"one");
84        assert!(table.check_fresh(&file, b"one").is_ok());
85        let err = table.check_fresh(&file, b"two").unwrap_err();
86        assert!(err.contains("modified on disk"));
87    }
88
89    #[test]
90    fn tables_are_independent() {
91        let a = FileStateTable::default();
92        let b = FileStateTable::default();
93        let dir = tempfile::tempdir().unwrap();
94        let file = dir.path().join("a.txt");
95        a.record(&file, b"one");
96        assert!(b.check_fresh(&file, b"two").is_ok());
97    }
98}