Skip to main content

kmp_embedded/
data_dir.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3
4use kmp_domain::PortError;
5
6/// Explicit data directory override (ADR-012 rule 1).
7pub const DATA_DIR_ENV: &str = "KMP_MCP_DATA_DIR";
8
9const PROJECT_DIR_NAME: &str = ".kernel";
10
11/// Where a project keeps the committed copy of its memory, relative to the
12/// project root.
13///
14/// The store itself (`.kernel/`) is machine state and is auto-gitignored. A
15/// bundle is the event log in one text file, which is a different thing: it
16/// belongs to the repository the same way a migration or a fixture does, so
17/// memory branches, reviews and reverts with the code that produced it.
18///
19/// The path is a convention rather than a setting so that `export` and
20/// `import` with no argument mean the same thing in every checkout, and so a
21/// reviewer knows where to look.
22pub const PROJECT_BUNDLE_PATH: &str = ".kmp/memory.jsonl";
23
24/// Where the data directory came from — logged at startup so the winning
25/// resolution rule is always visible.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum ResolvedDataDir {
28    /// `KMP_MCP_DATA_DIR` was set.
29    Explicit(PathBuf),
30    /// `<project-root>/.kernel/`, project root found by walking up to `.git`.
31    Project(PathBuf),
32    /// Per-user fallback under the platform data dir.
33    UserDefault(PathBuf),
34}
35
36impl ResolvedDataDir {
37    pub fn path(&self) -> &Path {
38        match self {
39            Self::Explicit(path) | Self::Project(path) | Self::UserDefault(path) => path,
40        }
41    }
42
43    pub fn rule_name(&self) -> &'static str {
44        match self {
45            Self::Explicit(_) => "env",
46            Self::Project(_) => "project",
47            Self::UserDefault(_) => "user",
48        }
49    }
50}
51
52/// ADR-012 resolution: env override > project `.kernel/` > per-user default.
53/// Pure function for testability; `resolve_data_dir_from_env` feeds it from
54/// the process environment.
55pub fn resolve_data_dir(
56    env_override: Option<&str>,
57    working_dir: &Path,
58    user_data_home: &Path,
59) -> ResolvedDataDir {
60    resolve_with_project_marker(env_override, working_dir, user_data_home, |candidate| {
61        candidate.join(".git").exists()
62    })
63}
64
65fn resolve_with_project_marker(
66    env_override: Option<&str>,
67    working_dir: &Path,
68    user_data_home: &Path,
69    is_project_root: impl Fn(&Path) -> bool,
70) -> ResolvedDataDir {
71    if let Some(explicit) = env_override
72        .map(str::trim)
73        .filter(|value| !value.is_empty())
74    {
75        return ResolvedDataDir::Explicit(PathBuf::from(explicit));
76    }
77
78    let mut current = Some(working_dir);
79    while let Some(candidate) = current {
80        if is_project_root(candidate) {
81            return ResolvedDataDir::Project(candidate.join(PROJECT_DIR_NAME));
82        }
83        current = candidate.parent();
84    }
85
86    ResolvedDataDir::UserDefault(user_data_home.join("kmp").join("default"))
87}
88
89/// The conventional bundle path for the project `data_dir` belongs to.
90///
91/// Only a project-scoped store has one: an explicit `KMP_MCP_DATA_DIR` or the
92/// per-user default has no repository to be committed to, and guessing one
93/// would put memory somewhere the operator did not choose.
94pub fn project_bundle_path(resolved: &ResolvedDataDir) -> Option<PathBuf> {
95    match resolved {
96        ResolvedDataDir::Project(path) => path
97            .parent()
98            .map(|project_root| project_root.join(PROJECT_BUNDLE_PATH)),
99        ResolvedDataDir::Explicit(_) | ResolvedDataDir::UserDefault(_) => None,
100    }
101}
102
103/// Resolves from the process environment and prepares the directory. Every
104/// data directory gets the same safety skeleton, regardless of whether it was
105/// discovered from a project, supplied explicitly, or created by migration.
106pub fn resolve_data_dir_from_env() -> Result<ResolvedDataDir, PortError> {
107    let env_override = std::env::var(DATA_DIR_ENV).ok();
108    let working_dir = std::env::current_dir().map_err(|error| {
109        PortError::Unavailable(format!(
110            "embedded kernel could not resolve the working directory: {error}"
111        ))
112    })?;
113    let user_data_home = std::env::var("XDG_DATA_HOME")
114        .map(PathBuf::from)
115        .ok()
116        .filter(|path| !path.as_os_str().is_empty())
117        .or_else(|| {
118            std::env::var("HOME")
119                .ok()
120                .map(|home| PathBuf::from(home).join(".local").join("share"))
121        })
122        .ok_or_else(|| {
123            PortError::Unavailable(
124                "embedded kernel could not resolve a user data directory \
125                 (neither XDG_DATA_HOME nor HOME is set)"
126                    .to_string(),
127            )
128        })?;
129
130    let resolved = resolve_data_dir(env_override.as_deref(), &working_dir, &user_data_home);
131    prepare_data_dir(&resolved)?;
132    Ok(resolved)
133}
134
135fn prepare_data_dir(resolved: &ResolvedDataDir) -> Result<(), PortError> {
136    ensure_data_dir_skeleton(resolved.path())
137}
138
139/// Creates the non-store part of a KMP data directory.
140///
141/// Fresh startup, `migrate`, and `share-memory` all call this function. The
142/// self-ignore file is deliberately installed even for an explicit path: an
143/// operator can put such a path inside a repository, and the store must not
144/// start appearing in `git status` merely because it arrived through a
145/// migration rather than first startup. Existing files are never replaced.
146pub fn ensure_data_dir_skeleton(path: &Path) -> Result<(), PortError> {
147    fs::create_dir_all(path).map_err(|error| {
148        PortError::Unavailable(format!(
149            "embedded kernel could not create data dir `{}`: {error}",
150            path.display()
151        ))
152    })?;
153
154    let gitignore = path.join(".gitignore");
155    if !gitignore.exists() {
156        fs::write(&gitignore, "*\n").map_err(|error| {
157            PortError::Unavailable(format!(
158                "embedded kernel could not write `{}`: {error}",
159                gitignore.display()
160            ))
161        })?;
162    }
163    let logs = path.join("logs");
164    fs::create_dir_all(&logs).map_err(|error| {
165        PortError::Unavailable(format!(
166            "embedded kernel could not create log dir `{}`: {error}",
167            logs.display()
168        ))
169    })?;
170    Ok(())
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn only_a_project_store_has_a_conventional_bundle_path() {
179        let project = ResolvedDataDir::Project(PathBuf::from("/repo/.kernel"));
180        assert_eq!(
181            project_bundle_path(&project),
182            Some(PathBuf::from("/repo/.kmp/memory.jsonl")),
183            "the bundle sits beside the store's project root, not inside the store"
184        );
185
186        // Neither of these belongs to a repository, and picking one for them
187        // would write memory somewhere nobody chose.
188        assert_eq!(
189            project_bundle_path(&ResolvedDataDir::Explicit(PathBuf::from("/tmp/dir"))),
190            None
191        );
192        assert_eq!(
193            project_bundle_path(&ResolvedDataDir::UserDefault(PathBuf::from("/home/u/kmp"))),
194            None
195        );
196    }
197
198    #[test]
199    fn env_override_wins_over_everything() {
200        let resolved = resolve_data_dir(
201            Some("/explicit/dir"),
202            Path::new("/some/project"),
203            Path::new("/home/u/.local/share"),
204        );
205        assert_eq!(
206            resolved,
207            ResolvedDataDir::Explicit(PathBuf::from("/explicit/dir"))
208        );
209        assert_eq!(resolved.rule_name(), "env");
210    }
211
212    #[test]
213    fn blank_env_override_is_ignored() {
214        let resolved = resolve_with_project_marker(
215            Some("  "),
216            Path::new("/anywhere"),
217            Path::new("/data"),
218            |_| false,
219        );
220        assert_eq!(resolved.rule_name(), "user");
221    }
222
223    #[test]
224    fn project_root_is_found_by_walking_up_to_git() {
225        let temp = tempfile::tempdir().expect("tempdir");
226        let nested = temp.path().join("workspace").join("src");
227        std::fs::create_dir_all(&nested).expect("nested dirs");
228        std::fs::create_dir_all(temp.path().join("workspace").join(".git")).expect("git dir");
229
230        let resolved = resolve_data_dir(None, &nested, Path::new("/data"));
231        assert_eq!(
232            resolved,
233            ResolvedDataDir::Project(temp.path().join("workspace").join(".kernel"))
234        );
235    }
236
237    #[test]
238    fn no_project_falls_back_to_user_data_dir() {
239        let resolved = resolve_with_project_marker(
240            None,
241            Path::new("/anywhere/nested"),
242            Path::new("/home/u/.local/share"),
243            |_| false,
244        );
245        assert_eq!(
246            resolved,
247            ResolvedDataDir::UserDefault(PathBuf::from("/home/u/.local/share/kmp/default"))
248        );
249    }
250
251    #[test]
252    fn project_dir_preparation_writes_self_ignoring_gitignore() {
253        let temp = tempfile::tempdir().expect("tempdir");
254        let kernel_dir = temp.path().join(".kernel");
255        let resolved = ResolvedDataDir::Project(kernel_dir.clone());
256
257        prepare_data_dir(&resolved).expect("prepare");
258
259        let gitignore = std::fs::read_to_string(kernel_dir.join(".gitignore")).expect("gitignore");
260        assert_eq!(gitignore, "*\n");
261        assert!(kernel_dir.join("logs").is_dir());
262    }
263
264    #[test]
265    fn explicit_and_migrated_dirs_get_the_same_non_destructive_skeleton() {
266        let temp = tempfile::tempdir().expect("tempdir");
267        let data_dir = temp.path().join("destination");
268
269        ensure_data_dir_skeleton(&data_dir).expect("prepare explicit destination");
270        assert_eq!(
271            std::fs::read_to_string(data_dir.join(".gitignore")).expect("gitignore"),
272            "*\n"
273        );
274        assert!(data_dir.join("logs").is_dir());
275
276        std::fs::write(data_dir.join(".gitignore"), "keep-me\n").expect("custom ignore");
277        ensure_data_dir_skeleton(&data_dir).expect("prepare again");
278        assert_eq!(
279            std::fs::read_to_string(data_dir.join(".gitignore")).expect("custom gitignore"),
280            "keep-me\n",
281            "the skeleton never overwrites an operator-owned ignore file"
282        );
283    }
284}