Skip to main content

lean_ctx/core/agents/
diary.rs

1use lean_ctx_time::UtcDateTime;
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4
5const MAX_DIARY_ENTRIES: usize = 100;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct AgentDiary {
9    pub agent_id: String,
10    pub agent_type: String,
11    pub project_root: String,
12    pub entries: Vec<DiaryEntry>,
13    pub created_at: UtcDateTime,
14    pub updated_at: UtcDateTime,
15}
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct DiaryEntry {
19    pub entry_type: DiaryEntryType,
20    pub content: String,
21    pub context: Option<String>,
22    pub timestamp: UtcDateTime,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
26pub enum DiaryEntryType {
27    Discovery,
28    Decision,
29    Blocker,
30    Progress,
31    Insight,
32}
33
34impl AgentDiary {
35    pub(crate) fn new(agent_id: &str, agent_type: &str, project_root: &str) -> Self {
36        let now = UtcDateTime::now();
37        Self {
38            agent_id: agent_id.to_string(),
39            agent_type: agent_type.to_string(),
40            project_root: project_root.to_string(),
41            entries: Vec::new(),
42            created_at: now,
43            updated_at: now,
44        }
45    }
46
47    pub fn add_entry(&mut self, entry_type: DiaryEntryType, content: &str, context: Option<&str>) {
48        self.entries.push(DiaryEntry {
49            entry_type,
50            content: content.to_string(),
51            context: context.map(std::string::ToString::to_string),
52            timestamp: UtcDateTime::now(),
53        });
54        if self.entries.len() > MAX_DIARY_ENTRIES {
55            self.entries
56                .drain(0..self.entries.len() - MAX_DIARY_ENTRIES);
57        }
58        self.updated_at = UtcDateTime::now();
59    }
60
61    pub fn format_summary(&self) -> String {
62        if self.entries.is_empty() {
63            return format!("Diary [{}]: empty", self.agent_id);
64        }
65        let mut out = format!(
66            "Diary [{}] ({} entries):\n",
67            self.agent_id,
68            self.entries.len()
69        );
70        let now = UtcDateTime::now();
71        for e in self.entries.iter().rev().take(10) {
72            let age = (now - e.timestamp).num_minutes();
73            let prefix = match e.entry_type {
74                DiaryEntryType::Discovery => "FOUND",
75                DiaryEntryType::Decision => "DECIDED",
76                DiaryEntryType::Blocker => "BLOCKED",
77                DiaryEntryType::Progress => "DONE",
78                DiaryEntryType::Insight => "INSIGHT",
79            };
80            let ctx = e
81                .context
82                .as_deref()
83                .map(|c| format!(" [{c}]"))
84                .unwrap_or_default();
85            out.push_str(&format!("  [{prefix}] {}{ctx} ({age}m ago)\n", e.content));
86        }
87        out
88    }
89
90    /// Persist into this diary's project partition. An agent id used in two
91    /// projects keeps one diary per project.
92    pub fn save(&self) -> Result<(), String> {
93        let dir = partition_dir(&self.project_root)?;
94        // Same reasoning as #1619: name the path and the operation, or a
95        // sandbox denial reads as an unattributable "Operation not permitted".
96        std::fs::create_dir_all(&dir)
97            .map_err(|error| format!("create agent diary directory {}: {error}", dir.display()))?;
98        let path = dir.join(format!("{}.json", sanitize_filename(&self.agent_id)));
99        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
100        crate::config_io::write_atomic(&path, &json)
101            .map_err(|error| format!("write agent diary {}: {error}", path.display()))
102    }
103
104    /// The diary `agent_id` keeps in `project_root`. The stored root, not
105    /// the directory, decides: a diary of releases before 3.11.5 (shared
106    /// directory) or one left in an older partition after the project's
107    /// identity (remote, package name) changed is served to the project it
108    /// records, and the next save moves it into the current partition.
109    pub fn load_for_project(agent_id: &str, project_root: &str) -> Option<Self> {
110        let file = format!("{}.json", sanitize_filename(agent_id));
111        search_dirs(project_root)
112            .iter()
113            .filter_map(|dir| read_diary(&dir.join(&file)))
114            .find(|diary| {
115                diary.agent_id == agent_id && same_root(&diary.project_root, project_root)
116            })
117    }
118
119    pub fn load_or_create(agent_id: &str, agent_type: &str, project_root: &str) -> Self {
120        Self::load_for_project(agent_id, project_root)
121            .unwrap_or_else(|| Self::new(agent_id, agent_type, project_root))
122    }
123
124    /// `(agent_id, entries, updated_at)` of every diary kept in `project_root`.
125    pub fn list_for_project(project_root: &str) -> Vec<(String, usize, UtcDateTime)> {
126        Self::load_all_for_project(project_root)
127            .into_iter()
128            .map(|diary| (diary.agent_id, diary.entries.len(), diary.updated_at))
129            .collect()
130    }
131
132    /// Load every diary whose `project_root` matches `project_root`, most
133    /// recently updated first. Used by skillify to mine a project's decisions
134    /// and insights across all its agents (#290).
135    /// Reads at most [`MAX_PROJECT_DIARY_FILES`] diary files
136    /// ([`Self::load_all_for_project_bounded`]).
137    pub fn load_all_for_project(project_root: &str) -> Vec<AgentDiary> {
138        Self::load_all_for_project_bounded(project_root, MAX_PROJECT_DIARY_FILES)
139    }
140
141    /// [`Self::load_all_for_project`] reading at most `max_files` diary files
142    /// (the current partition's first, then the others, by name within a
143    /// directory). Symlinked partitions and files and files over
144    /// [`MAX_DIARY_FILE_BYTES`] are skipped before anything is read.
145    pub fn load_all_for_project_bounded(project_root: &str, max_files: usize) -> Vec<AgentDiary> {
146        let mut diaries: Vec<AgentDiary> = Vec::new();
147        // The current partition first: its diary supersedes an older one.
148        for (_, path) in diary_files(&search_dirs(project_root))
149            .into_iter()
150            .take(max_files)
151        {
152            if let Some(diary) = read_diary(&path)
153                && same_root(&diary.project_root, project_root)
154                && !diaries.iter().any(|known| known.agent_id == diary.agent_id)
155            {
156                diaries.push(diary);
157            }
158        }
159        diaries.sort_by_key(|d| std::cmp::Reverse(d.updated_at));
160        diaries
161    }
162
163    /// Every diary on this machine (all partitions and the shared directory
164    /// of releases before 3.11.5), one per agent and project (the newest
165    /// copy wins), newest first (ties: agent id, project). Reads at most
166    /// `max_files` diary files (the most recently written) and skips
167    /// symlinks and files over [`MAX_DIARY_FILE_BYTES`].
168    pub fn load_all(max_files: usize) -> Vec<AgentDiary> {
169        let Ok(base) = diary_dir() else {
170            return Vec::new();
171        };
172        let mut dirs = vec![base.clone()];
173        dirs.extend(partitions(&base));
174        let mut files = diary_files(&dirs);
175        files.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
176        files.truncate(max_files);
177        let mut newest: std::collections::BTreeMap<(String, String), AgentDiary> =
178            std::collections::BTreeMap::new();
179        for (_, path) in files {
180            let Some(diary) = read_diary(&path) else {
181                continue;
182            };
183            let key = (diary.agent_id.clone(), diary.project_root.clone());
184            match newest.get(&key) {
185                Some(known) if known.updated_at >= diary.updated_at => {}
186                _ => {
187                    newest.insert(key, diary);
188                }
189            }
190        }
191        let mut diaries: Vec<AgentDiary> = newest.into_values().collect();
192        diaries.sort_by(|a, b| {
193            b.updated_at
194                .cmp(&a.updated_at)
195                .then_with(|| a.agent_id.cmp(&b.agent_id))
196                .then_with(|| a.project_root.cmp(&b.project_root))
197        });
198        diaries
199    }
200}
201
202/// The largest diary file any load reads (100 entries of ordinary agent
203/// notes stay far below it).
204pub const MAX_DIARY_FILE_BYTES: u64 = 1024 * 1024;
205
206/// The most diary files [`AgentDiary::load_all_for_project`] reads.
207pub const MAX_PROJECT_DIARY_FILES: usize = 2000;
208
209/// The partition directories in `base`, by name. A symlink is no partition.
210fn partitions(base: &std::path::Path) -> Vec<PathBuf> {
211    let Ok(entries) = std::fs::read_dir(base) else {
212        return Vec::new();
213    };
214    let mut dirs: Vec<PathBuf> = entries
215        .flatten()
216        .filter(|entry| entry.file_type().is_ok_and(|t| t.is_dir()))
217        .map(|entry| entry.path())
218        .collect();
219    dirs.sort();
220    dirs
221}
222
223/// The diary files in `dirs` (in `dirs` order, by name within a directory)
224/// with their modification time: regular `*.json` files of at most
225/// [`MAX_DIARY_FILE_BYTES`], never a symlink. Nothing is read.
226fn diary_files(dirs: &[PathBuf]) -> Vec<(std::time::SystemTime, PathBuf)> {
227    let mut files = Vec::new();
228    for dir in dirs {
229        let Ok(entries) = std::fs::read_dir(dir) else {
230            continue;
231        };
232        let mut found: Vec<(std::time::SystemTime, PathBuf)> = entries
233            .flatten()
234            .filter_map(|entry| {
235                let path = entry.path();
236                if path.extension().and_then(|e| e.to_str()) != Some("json") {
237                    return None;
238                }
239                let meta = std::fs::symlink_metadata(&path).ok()?;
240                (meta.is_file() && meta.len() <= MAX_DIARY_FILE_BYTES)
241                    .then(|| (meta.modified().unwrap_or(std::time::UNIX_EPOCH), path))
242            })
243            .collect();
244        found.sort_by(|a, b| a.1.cmp(&b.1));
245        files.extend(found);
246    }
247    files
248}
249
250/// The diary in `path`: opened without following a symlink (the opened
251/// file is checked, so a swap after listing is refused too) and read only
252/// when it is a regular file of at most [`MAX_DIARY_FILE_BYTES`].
253fn read_diary(path: &std::path::Path) -> Option<AgentDiary> {
254    use std::io::Read;
255    if path.extension().and_then(|e| e.to_str()) != Some("json") {
256        return None;
257    }
258    let mut options = std::fs::OpenOptions::new();
259    options.read(true);
260    #[cfg(unix)]
261    {
262        use std::os::unix::fs::OpenOptionsExt;
263        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
264    }
265    #[cfg(not(unix))]
266    {
267        if !std::fs::symlink_metadata(path).ok()?.is_file() {
268            return None;
269        }
270    }
271    let file = options.open(path).ok()?;
272    let meta = file.metadata().ok()?;
273    if !meta.is_file() || meta.len() > MAX_DIARY_FILE_BYTES {
274        return None;
275    }
276    let mut text = String::new();
277    file.take(MAX_DIARY_FILE_BYTES + 1)
278        .read_to_string(&mut text)
279        .ok()?;
280    if text.len() as u64 > MAX_DIARY_FILE_BYTES {
281        return None;
282    }
283    serde_json::from_str(&text).ok()
284}
285
286fn same_root(stored: &str, requested: &str) -> bool {
287    use crate::core::pathutil::{normalize_tool_path, safe_canonicalize_bounded};
288    let canonical = |root: &str| safe_canonicalize_bounded(std::path::Path::new(root), 2000);
289    normalize_tool_path(stored).trim_end_matches('/')
290        == normalize_tool_path(requested).trim_end_matches('/')
291        || canonical(stored) == canonical(requested)
292}
293
294/// Where a diary of `project_root` may be: its current partition first, then
295/// every other partition (an identity change moved the hash), then the shared
296/// directory of releases before 3.11.5. The stored root decides membership.
297fn search_dirs(project_root: &str) -> Vec<PathBuf> {
298    let (Ok(current), Ok(base)) = (partition_dir(project_root), diary_dir()) else {
299        return Vec::new();
300    };
301    // A symlinked partition is never searched, the current one included.
302    let mut dirs: Vec<PathBuf> = std::fs::symlink_metadata(&current)
303        .is_ok_and(|meta| meta.is_dir())
304        .then(|| current.clone())
305        .into_iter()
306        .collect();
307    dirs.extend(partitions(&base).into_iter().filter(|dir| *dir != current));
308    dirs.push(base);
309    dirs
310}
311
312fn partition_dir(project_root: &str) -> Result<PathBuf, String> {
313    Ok(diary_dir()?.join(crate::core::project_hash::hash_project_root(project_root)))
314}
315
316impl std::fmt::Display for DiaryEntryType {
317    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318        match self {
319            DiaryEntryType::Discovery => write!(f, "discovery"),
320            DiaryEntryType::Decision => write!(f, "decision"),
321            DiaryEntryType::Blocker => write!(f, "blocker"),
322            DiaryEntryType::Progress => write!(f, "progress"),
323            DiaryEntryType::Insight => write!(f, "insight"),
324        }
325    }
326}
327
328fn diary_dir() -> Result<PathBuf, String> {
329    let dir = crate::core::data_dir::lean_ctx_data_dir()?;
330    Ok(dir.join("agents").join("diaries"))
331}
332
333fn sanitize_filename(name: &str) -> String {
334    name.chars()
335        .map(|c| {
336            if c.is_alphanumeric() || c == '-' || c == '_' {
337                c
338            } else {
339                '_'
340            }
341        })
342        .collect()
343}