Skip to main content

merry_runtime/durable_memory/
mod.rs

1//! Durable cross-session memory.
2//!
3//! Notes live under `$XDG_DATA_HOME/merry/memory`. The agent reads and writes
4//! them with the ordinary file tools. After a completed user turn, the host
5//! extracts observations and may consolidate them with one-shot dream.
6//! Coordination state is a JSON file beside the notes. There is no vector index.
7
8pub(crate) mod capture;
9pub(crate) mod condense;
10pub(crate) mod dream;
11mod manifest;
12mod paths;
13mod policy;
14pub(crate) mod state;
15
16#[cfg(test)]
17mod tests;
18
19use std::{
20    fs,
21    path::{Path, PathBuf},
22    sync::Arc,
23};
24
25use paths::{MANIFEST_FILE, ensure_scope};
26use policy::{MemoryPathKind, OBSERVATION_MAX_BYTES, TOPIC_MAX_BYTES};
27use thiserror::Error;
28use tokio::sync::Mutex;
29
30pub use paths::MemoryLayout;
31
32const LEASE_SECONDS: u64 = 10 * 60;
33const GLOBAL_HEADING: &str = "Global memory index";
34const WORKSPACE_HEADING: &str = "Workspace memory index";
35
36/// Why a durable-memory operation failed.
37#[derive(Debug, Error)]
38pub enum DurableMemoryError {
39    /// A required path was relative.
40    #[error("{role} must be an absolute path: {path}")]
41    RelativePath {
42        /// What the path was supposed to name.
43        role: &'static str,
44        /// Rejected path.
45        path: PathBuf,
46    },
47    /// `HOME` was missing or relative, so the XDG data home cannot be resolved.
48    #[error("HOME is missing or is not an absolute path")]
49    HomeMissing,
50    /// Filesystem operation failed.
51    #[error("failed to {operation} at {path}: {source}")]
52    Io {
53        /// What was being attempted.
54        operation: &'static str,
55        /// Path involved in the failure.
56        path: PathBuf,
57        /// Source IO error.
58        #[source]
59        source: std::io::Error,
60    },
61    /// The workspace root exists and is not a directory.
62    #[error("workspace root is not a directory: {path}")]
63    WorkspaceNotDirectory {
64        /// Rejected path.
65        path: PathBuf,
66    },
67    /// The coordination file could not be decoded.
68    #[error("memory state at {path} is corrupt: {message}")]
69    CorruptState {
70        /// State file path.
71        path: PathBuf,
72        /// Decoder message.
73        message: String,
74    },
75    /// A memory write violated the filesystem policy.
76    #[error("{message}")]
77    Denied {
78        /// Actionable reason.
79        message: String,
80    },
81}
82
83/// Kind of `apply_patch` change aimed at a memory file.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum MemoryWriteKind {
86    /// Create a file that does not exist yet.
87    Create,
88    /// Replace an existing topic.
89    Update,
90    /// Remove an existing topic.
91    Delete,
92}
93
94/// Open memory store for one workspace, shared by parent and child runtimes.
95#[derive(Debug)]
96pub struct DurableMemory {
97    layout: MemoryLayout,
98    maintenance: Mutex<()>,
99}
100
101impl DurableMemory {
102    /// Creates both scopes and writes their initial indexes.
103    pub fn open(layout: MemoryLayout) -> Result<Arc<Self>, DurableMemoryError> {
104        ensure_scope(layout.global_dir())?;
105        ensure_scope(layout.workspace_dir())?;
106        let memory = Arc::new(Self {
107            layout,
108            maintenance: Mutex::new(()),
109        });
110        memory.refresh_scope(memory.layout.global_dir(), GLOBAL_HEADING)?;
111        memory.refresh_scope(memory.layout.workspace_dir(), WORKSPACE_HEADING)?;
112        Ok(memory)
113    }
114
115    /// Opens the store at the XDG data-home location for `workspace_root`.
116    pub fn open_from_env(workspace_root: &Path) -> Result<Arc<Self>, DurableMemoryError> {
117        Self::open(MemoryLayout::from_env(workspace_root)?)
118    }
119
120    /// Returns the resolved global and workspace directories.
121    #[must_use]
122    pub fn layout(&self) -> &MemoryLayout {
123        &self.layout
124    }
125
126    /// Stable instructions for the provider prefix.
127    ///
128    /// The injected index is separate and belongs in the dynamic segment.
129    #[must_use]
130    pub fn instructions(&self) -> String {
131        let global = self.layout.global_dir().display();
132        let workspace = self.layout.workspace_dir().display();
133        format!(
134            r#"Memory is a user-controlled filesystem knowledge base of what earlier sessions learned. The memory index in `merry_memory_context` lists every topic and any pending observations, so never read or edit MEMORY.md. Before starting work in an area, read the topic files whose titles cover it, and open the paths their `## Files` sections name before listing or searching the tree. Skip memory only for requests with no plausible overlap with past work. The user's instructions in this conversation override memory. A note marked as a past agent decision is a record, not a rule, so verify it against the current tree. When the request conflicts with the situation a note describes, follow the request.
135
136Global memory, shared across workspaces:
137- `{global}/topics/` holds maintained Markdown notes
138- `{global}/observations/_inbox/` holds new Markdown observations
139- `{global}/MEMORY.md` is the generated topic index and is already injected
140
141Workspace memory, specific to this workspace:
142- `{workspace}/topics/` holds maintained Markdown notes
143- `{workspace}/observations/_inbox/` holds new Markdown observations
144- `{workspace}/MEMORY.md` is the generated topic index and is already injected
145
146`topics/` holds durable preferences, conventions, architecture, decisions, recurring workflows, and other facts worth reusing. `observations/_inbox/` holds new observations that may later be consolidated into topics. Paths in the index are relative to the scope root named in its header.
147
148Use `read_file` to read memory files and `apply_patch` to create or edit them. Search with `run_process` when a memory file points at a path you still need to find. Existing files must be read successfully before editing. Writes are allowed only to `.md` files directly under `topics/` or `observations/_inbox/`. Those memory paths stay writable when the workspace itself is read-only. Generated indexes, archives, state files, and other internals are protected.
149
150Remember information when the user explicitly asks, or when it is stable, specific, useful across sessions, and not already available from the repository or its documentation. Do not store secrets, credentials, transient task state, speculative conclusions, or facts that are likely to become stale. A single failed tool call or a guess about the local machine is not an observation. Prefer one focused topic file over duplicating the same fact in several places.
151
152Treat memory as historical context, not current truth. Verify paths, commands, repository state, external facts, and other changeable claims with live tools before relying on them. When live tools and memory disagree, the live tools win."#
153        )
154    }
155
156    /// Renders the global and workspace indexes for one session.
157    ///
158    /// Callers freeze the returned string for the life of the runtime so later
159    /// topic writes do not rewrite the provider prefix.
160    pub fn render_context(&self) -> Result<String, DurableMemoryError> {
161        let global = self.manifest_text(self.layout.global_dir(), GLOBAL_HEADING)?;
162        let workspace = self.manifest_text(self.layout.workspace_dir(), WORKSPACE_HEADING)?;
163        let global_pending = pending_observations(self.layout.global_dir())?;
164        let workspace_pending = pending_observations(self.layout.workspace_dir())?;
165        Ok(manifest::render_injected_context(
166            self.layout.global_dir(),
167            &global,
168            &global_pending,
169            self.layout.workspace_dir(),
170            &workspace,
171            &workspace_pending,
172        ))
173    }
174
175    /// Records a successful read of a topic and snapshots its full bytes.
176    ///
177    /// Observation files, the generated index, and paths outside memory are
178    /// ignored. A snapshot failure is returned to the caller, which should
179    /// keep the file read itself successful.
180    pub fn note_read(&self, path: &Path) -> Result<(), DurableMemoryError> {
181        let Some(classified) = policy::classify(&self.layout, path) else {
182            return Ok(());
183        };
184        let MemoryPathKind::Topic { relative } = classified.kind else {
185            return Ok(());
186        };
187        let bytes = fs::read(&classified.absolute).map_err(|source| DurableMemoryError::Io {
188            operation: "read memory topic for snapshot",
189            path: classified.absolute.clone(),
190            source,
191        })?;
192        let hash = paths::content_hash(&bytes);
193        let key = policy::snapshot_key(&classified.absolute);
194        state::update(&classified.scope_dir, move |state| {
195            state.snapshots.insert(key, hash);
196            *state.topic_reads.entry(relative).or_insert(0) += 1;
197            Ok(())
198        })
199    }
200
201    /// Returns whether `path` is inside a durable-memory scope.
202    ///
203    /// Workspace write scope does not authorize these paths. Callers still use
204    /// [`Self::authorize_write`] for the topic and observation rules.
205    #[must_use]
206    pub fn governs_path(&self, path: &Path) -> bool {
207        policy::classify(&self.layout, path).is_some()
208    }
209
210    /// Allows a patch when `path` is outside memory or the memory write is valid.
211    ///
212    /// Topic updates and deletes require a snapshot from [`Self::note_read`]
213    /// that still matches the current file. The snapshot is not refreshed by
214    /// the write, so the next edit must read the file again.
215    pub fn authorize_write(
216        &self,
217        kind: MemoryWriteKind,
218        path: &Path,
219        byte_len: usize,
220    ) -> Result<(), DurableMemoryError> {
221        let Some(classified) = policy::classify(&self.layout, path) else {
222            return Ok(());
223        };
224        match classified.kind {
225            MemoryPathKind::Protected { reason } => Err(policy::deny(reason)),
226            MemoryPathKind::Observation { .. } => match kind {
227                MemoryWriteKind::Create if byte_len <= OBSERVATION_MAX_BYTES => Ok(()),
228                MemoryWriteKind::Create => {
229                    Err(policy::deny("memory observations are limited to 16 KiB"))
230                }
231                MemoryWriteKind::Update | MemoryWriteKind::Delete => Err(policy::deny(
232                    "observations are immutable; add a new observation or update a topic",
233                )),
234            },
235            MemoryPathKind::Topic { .. } => match kind {
236                MemoryWriteKind::Create if byte_len <= TOPIC_MAX_BYTES => Ok(()),
237                MemoryWriteKind::Create => {
238                    Err(policy::deny("memory topics are limited to 256 KiB"))
239                }
240                MemoryWriteKind::Update if byte_len > TOPIC_MAX_BYTES => {
241                    Err(policy::deny("memory topics are limited to 256 KiB"))
242                }
243                MemoryWriteKind::Update | MemoryWriteKind::Delete => {
244                    self.require_snapshot(&classified)
245                }
246            },
247        }
248    }
249
250    /// Rewrites indexes for scopes touched by a successful memory write.
251    pub fn refresh_after_writes(&self, paths: &[PathBuf]) -> Result<(), DurableMemoryError> {
252        let mut refreshed = Vec::new();
253        for path in paths {
254            let Some(classified) = policy::classify(&self.layout, path) else {
255                continue;
256            };
257            if !matches!(
258                classified.kind,
259                MemoryPathKind::Topic { .. } | MemoryPathKind::Observation { .. }
260            ) {
261                continue;
262            }
263            if refreshed.iter().any(|dir| dir == &classified.scope_dir) {
264                continue;
265            }
266            let heading = self.heading_for(&classified.scope_dir);
267            self.refresh_scope(&classified.scope_dir, heading)?;
268            refreshed.push(classified.scope_dir);
269        }
270        Ok(())
271    }
272
273    pub(crate) fn maintenance(&self) -> &Mutex<()> {
274        &self.maintenance
275    }
276
277    pub(crate) fn captured_turns(&self, session_id: &str) -> Result<u32, DurableMemoryError> {
278        let session_id = session_id.to_owned();
279        state::update(self.layout.workspace_dir(), move |state| {
280            Ok(state.session_turns.get(&session_id).copied().unwrap_or(0))
281        })
282    }
283
284    pub(crate) fn set_captured_turns(
285        &self,
286        session_id: &str,
287        turns: u32,
288    ) -> Result<(), DurableMemoryError> {
289        let session_id = session_id.to_owned();
290        state::update(self.layout.workspace_dir(), move |state| {
291            let entry = state.session_turns.entry(session_id).or_insert(0);
292            if *entry < turns {
293                *entry = turns;
294            }
295            Ok(())
296        })
297    }
298
299    pub(crate) fn try_acquire_lease(&self, owner: &str) -> Result<bool, DurableMemoryError> {
300        let owner = owner.to_owned();
301        let now = state::unix_now();
302        state::update(self.layout.workspace_dir(), move |state| {
303            if let Some(lease) = &state.dream_lease
304                && lease.expires_at > now
305                && lease.owner != owner
306            {
307                return Ok(false);
308            }
309            state.dream_lease = Some(state::DreamLease {
310                owner,
311                expires_at: now.saturating_add(LEASE_SECONDS),
312            });
313            Ok(true)
314        })
315    }
316
317    pub(crate) fn release_lease(&self, owner: &str) -> Result<(), DurableMemoryError> {
318        let owner = owner.to_owned();
319        state::update(self.layout.workspace_dir(), move |state| {
320            if state
321                .dream_lease
322                .as_ref()
323                .is_some_and(|lease| lease.owner == owner)
324            {
325                state.dream_lease = None;
326            }
327            Ok(())
328        })
329    }
330
331    pub(crate) fn scan_inbox(&self) -> Result<dream::InboxScan, DurableMemoryError> {
332        dream::scan_inbox(self.layout.workspace_dir())
333    }
334
335    pub(crate) fn dream_input(
336        &self,
337        claimed: &[dream::ClaimedNote],
338    ) -> Result<String, DurableMemoryError> {
339        dream::render_dream_input(self.layout.workspace_dir(), claimed)
340    }
341
342    pub(crate) fn apply_dream(
343        &self,
344        claimed: &[dream::ClaimedNote],
345        response: &str,
346    ) -> Result<usize, DurableMemoryError> {
347        let count = dream::apply_plan(self.layout.workspace_dir(), claimed, response)?;
348        self.refresh_scope(self.layout.workspace_dir(), WORKSPACE_HEADING)?;
349        Ok(count)
350    }
351
352    pub(crate) fn observation_exists(
353        &self,
354        session_id: &str,
355        from_turn: u32,
356        through_turn: u32,
357    ) -> bool {
358        let name = capture::observation_file_name(session_id, from_turn, through_turn, 1);
359        self.layout
360            .workspace_dir()
361            .join(paths::INBOX_DIR)
362            .join(name)
363            .is_file()
364    }
365
366    pub(crate) fn commit_capture(
367        &self,
368        write: &capture::CaptureWrite<'_>,
369    ) -> Result<(), DurableMemoryError> {
370        if write.observations.is_empty()
371            || capture::first_observation_exists(self.layout.workspace_dir(), write)
372        {
373            return Ok(());
374        }
375        capture::write_observations(self.layout.workspace_dir(), write)?;
376        self.refresh_scope(self.layout.workspace_dir(), WORKSPACE_HEADING)?;
377        Ok(())
378    }
379
380    fn require_snapshot(
381        &self,
382        classified: &policy::ClassifiedPath,
383    ) -> Result<(), DurableMemoryError> {
384        let bytes = fs::read(&classified.absolute).map_err(|source| DurableMemoryError::Io {
385            operation: "read memory file for snapshot check",
386            path: classified.absolute.clone(),
387            source,
388        })?;
389        let hash = paths::content_hash(&bytes);
390        let key = policy::snapshot_key(&classified.absolute);
391        let saved = state::update(&classified.scope_dir, |state| Ok(state.snapshots.clone()))?;
392        match saved.get(&key) {
393            Some(existing) if existing == &hash => Ok(()),
394            Some(_) => Err(policy::deny(
395                "memory file changed since it was read; read_file it again before editing",
396            )),
397            None => Err(policy::deny("read_file the memory file before editing it")),
398        }
399    }
400
401    fn refresh_scope(&self, scope_dir: &Path, heading: &str) -> Result<String, DurableMemoryError> {
402        let reads = state::update(scope_dir, |state| Ok(state.topic_reads.clone()))?;
403        manifest::write_scope_manifest(scope_dir, heading, &reads)
404    }
405
406    fn manifest_text(&self, scope_dir: &Path, heading: &str) -> Result<String, DurableMemoryError> {
407        let path = scope_dir.join(MANIFEST_FILE);
408        match fs::read_to_string(&path) {
409            Ok(text) => Ok(text),
410            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
411                self.refresh_scope(scope_dir, heading)
412            }
413            Err(source) => Err(DurableMemoryError::Io {
414                operation: "read memory index",
415                path,
416                source,
417            }),
418        }
419    }
420
421    fn heading_for(&self, scope_dir: &Path) -> &'static str {
422        if scope_dir == self.layout.global_dir() {
423            GLOBAL_HEADING
424        } else {
425            WORKSPACE_HEADING
426        }
427    }
428}
429
430/// Lists inbox notes that are not topics yet.
431///
432/// An empty inbox returns an empty string so the injected index stays
433/// identical to the on-disk topic index. At most 32 titles are listed.
434fn pending_observations(scope_dir: &Path) -> Result<String, DurableMemoryError> {
435    let scan = dream::scan_inbox(scope_dir)?;
436    if scan.eligible.is_empty() && scan.oversized == 0 {
437        return Ok(String::new());
438    }
439    let mut section = String::from(
440        "\n## Pending observations\n\nThese inbox notes are not topics yet. Read them before treating this scope as empty.\n",
441    );
442    const LISTED: usize = 32;
443    for note in scan.eligible.iter().take(LISTED) {
444        let title = manifest::observation_title(&note.absolute_path);
445        section.push_str(&format!("\n- **{title}** (`{}`)\n", note.relative_path));
446    }
447    let omitted = scan.eligible.len().saturating_sub(LISTED) + scan.oversized;
448    if omitted > 0 {
449        section.push_str(&format!("\n{omitted} more observations are not listed.\n"));
450    }
451    Ok(section)
452}