Skip to main content

merry_runtime/durable_memory/
paths.rs

1//! XDG data-home layout for durable memory.
2//!
3//! Notes live under `$XDG_DATA_HOME/merry/memory` (default
4//! `$HOME/.local/share/merry/memory`). Coordination state sits beside the
5//! notes so one scope can be committed together. There is no vector index.
6
7use std::{
8    env, fs,
9    path::{Path, PathBuf},
10};
11
12use sha2::{Digest, Sha256};
13
14use super::DurableMemoryError;
15
16pub(crate) const GLOBAL_DIR: &str = "global";
17pub(crate) const WORKSPACES_DIR: &str = "workspaces";
18pub(crate) const TOPICS_DIR: &str = "topics";
19pub(crate) const INBOX_DIR: &str = "observations/_inbox";
20pub(crate) const ARCHIVE_DIR: &str = "archive";
21pub(crate) const MANIFEST_FILE: &str = "MEMORY.md";
22pub(crate) const STATE_FILE: &str = "memory_state.json";
23
24/// Roots for the global scope and one workspace scope.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct MemoryLayout {
27    root: PathBuf,
28    global_dir: PathBuf,
29    workspace_dir: PathBuf,
30    workspace_id: String,
31}
32
33impl MemoryLayout {
34    /// Builds a layout under an explicit memory root.
35    ///
36    /// `memory_root` is the directory that contains `global/` and
37    /// `workspaces/`. `workspace_root` is the project directory whose canonical
38    /// path selects the workspace scope.
39    pub fn at(memory_root: &Path, workspace_root: &Path) -> Result<Self, DurableMemoryError> {
40        if !memory_root.is_absolute() {
41            return Err(DurableMemoryError::RelativePath {
42                role: "memory root",
43                path: memory_root.to_path_buf(),
44            });
45        }
46        let workspace_root = canonical_directory(workspace_root)?;
47        let workspace_id = workspace_id(&workspace_root);
48        let root = memory_root.to_path_buf();
49        Ok(Self {
50            global_dir: root.join(GLOBAL_DIR),
51            workspace_dir: root.join(WORKSPACES_DIR).join(&workspace_id),
52            workspace_id,
53            root,
54        })
55    }
56
57    /// Resolves the layout from `HOME` and `XDG_DATA_HOME`.
58    ///
59    /// An absolute `XDG_DATA_HOME` wins. Otherwise the root is
60    /// `$HOME/.local/share/merry/memory`.
61    pub fn from_env(workspace_root: &Path) -> Result<Self, DurableMemoryError> {
62        Self::at(&Self::memory_root_from_env()?, workspace_root)
63    }
64
65    /// Directory that contains `global/` and `workspaces/`.
66    ///
67    /// An absolute `XDG_DATA_HOME` wins. On Windows, falls back to
68    /// `%LOCALAPPDATA%/merry/memory` or `<home>/AppData/Local/merry/memory`.
69    /// On Unix, falls back to `$HOME/.local/share/merry/memory`.
70    pub fn memory_root_from_env() -> Result<PathBuf, DurableMemoryError> {
71        let home =
72            merry_core::host_paths::user_home_dir().ok_or(DurableMemoryError::HomeMissing)?;
73        let xdg_data_home = env::var_os("XDG_DATA_HOME").map(PathBuf::from);
74        let local_appdata = env::var_os("LOCALAPPDATA").map(PathBuf::from);
75        let data_home = merry_core::host_paths::platform_data_base(
76            &home,
77            xdg_data_home.as_deref(),
78            local_appdata.as_deref(),
79        );
80        Ok(data_home.join("merry").join("memory"))
81    }
82
83    #[must_use]
84    pub fn root(&self) -> &Path {
85        &self.root
86    }
87
88    #[must_use]
89    pub fn global_dir(&self) -> &Path {
90        &self.global_dir
91    }
92
93    #[must_use]
94    pub fn workspace_dir(&self) -> &Path {
95        &self.workspace_dir
96    }
97
98    #[must_use]
99    pub fn workspace_id(&self) -> &str {
100        &self.workspace_id
101    }
102}
103
104pub(crate) fn ensure_scope(scope_dir: &Path) -> Result<(), DurableMemoryError> {
105    for relative in [TOPICS_DIR, INBOX_DIR, ARCHIVE_DIR] {
106        let directory = scope_dir.join(relative);
107        fs::create_dir_all(&directory).map_err(|source| DurableMemoryError::Io {
108            operation: "create memory directory",
109            path: directory,
110            source,
111        })?;
112    }
113    Ok(())
114}
115
116fn canonical_directory(path: &Path) -> Result<PathBuf, DurableMemoryError> {
117    if !path.is_absolute() {
118        return Err(DurableMemoryError::RelativePath {
119            role: "workspace root",
120            path: path.to_path_buf(),
121        });
122    }
123    let canonical = merry_core::host_paths::canonicalize_clean(path).map_err(|source| {
124        DurableMemoryError::Io {
125            operation: "canonicalize workspace root",
126            path: path.to_path_buf(),
127            source,
128        }
129    })?;
130    if !canonical.is_dir() {
131        return Err(DurableMemoryError::WorkspaceNotDirectory { path: canonical });
132    }
133    Ok(canonical)
134}
135
136fn workspace_id(canonical_root: &Path) -> String {
137    let mut hasher = Sha256::new();
138    hasher.update(canonical_root.to_string_lossy().as_bytes());
139    let digest = hasher.finalize();
140    hex_encode(&digest[..8])
141}
142
143pub(crate) fn content_hash(bytes: &[u8]) -> String {
144    let mut hasher = Sha256::new();
145    hasher.update(bytes);
146    hex_encode(&hasher.finalize())
147}
148
149fn hex_encode(bytes: &[u8]) -> String {
150    const HEX: &[u8; 16] = b"0123456789abcdef";
151    let mut encoded = String::with_capacity(bytes.len() * 2);
152    for byte in bytes {
153        encoded.push(HEX[(byte >> 4) as usize] as char);
154        encoded.push(HEX[(byte & 0x0f) as usize] as char);
155    }
156    encoded
157}