From 4b9298693fffb0f5b9ad478a1b4733dbbdc57560 Mon Sep 17 00:00:00 2001 From: Hakula Chen Date: Tue, 1 Dec 2026 19:39:25 +0800 Subject: [PATCH] feat(ox-core): add per-project memory directory support --- crates/ox-core/src/lib.rs | 1 + crates/ox-core/src/memory.rs | 608 +++++++++++++++++++++++++++++++++++ docs/README.md | 1 + docs/reference/memory.md | 37 +++ 4 files changed, 647 insertions(+) create mode 100644 crates/ox-core/src/memory.rs create mode 100644 docs/reference/memory.md diff --git a/crates/ox-core/src/lib.rs b/crates/ox-core/src/lib.rs index 7364d8a43..57fd66d86 100644 --- a/crates/ox-core/src/lib.rs +++ b/crates/ox-core/src/lib.rs @@ -6,6 +6,7 @@ pub mod client; pub mod config; pub mod frontmatter; pub mod hooks; +pub mod memory; pub mod message; pub mod plugin; pub mod prompt; diff --git a/crates/ox-core/src/memory.rs b/crates/ox-core/src/memory.rs new file mode 100644 index 000000000..e67ab5d74 --- /dev/null +++ b/crates/ox-core/src/memory.rs @@ -0,0 +1,608 @@ +//! Per-project Markdown memory directory and bounded prompt-index formatting. + +use std::ffi::OsString; +use std::fmt::Write as _; +use std::fs; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; + +use thiserror::Error; + +/// File name of the per-project memory index. +pub const INDEX_FILENAME: &str = "MEMORY.md"; + +/// Default maximum number of lines included from [`INDEX_FILENAME`] in a prompt section. +pub const DEFAULT_MAX_PROMPT_LINES: usize = 200; + +/// Default maximum number of bytes included from [`INDEX_FILENAME`] in a prompt section. +pub const DEFAULT_MAX_PROMPT_BYTES: usize = 8 * 1024; + +const MAX_SLUG_LEN: usize = 48; +const FNV1A_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; +const FNV1A_PRIME: u64 = 0x0000_0100_0000_01b3; + +/// Errors returned while resolving, reading, or writing project memory files. +#[derive(Debug, Error)] +pub enum MemoryError { + /// Neither `XDG_DATA_HOME` nor `HOME` was set when resolving the default memory root. + #[error("cannot determine memory directory: set XDG_DATA_HOME or HOME")] + MissingDataDir, + + /// Topic name is empty, reserved, or contains disallowed path characters. + #[error("invalid memory topic name: {name:?}")] + InvalidTopicName { + /// Raw topic name provided by the caller. + name: String, + }, + + /// Failed to create the project memory directory. + #[error("failed to create memory directory {path}: {source}")] + CreateDir { + /// Directory path that could not be created. + path: PathBuf, + /// Underlying I/O error. + source: std::io::Error, + }, + + /// Failed to list files in the project memory directory. + #[error("failed to read memory directory {path}: {source}")] + ReadDir { + /// Directory path that could not be read. + path: PathBuf, + /// Underlying I/O error. + source: std::io::Error, + }, + + /// Failed to read a memory file. + #[error("failed to read memory file {path}: {source}")] + ReadFile { + /// File path that could not be read. + path: PathBuf, + /// Underlying I/O error. + source: std::io::Error, + }, + + /// Failed to write a memory file. + #[error("failed to write memory file {path}: {source}")] + WriteFile { + /// File path that could not be written. + path: PathBuf, + /// Underlying I/O error. + source: std::io::Error, + }, + + /// Failed to delete a memory file. + #[error("failed to delete memory file {path}: {source}")] + DeleteFile { + /// File path that could not be deleted. + path: PathBuf, + /// Underlying I/O error. + source: std::io::Error, + }, +} + +/// Metadata for a Markdown file stored in a project memory directory. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MemoryEntry { + /// File name within the memory directory (for example `MEMORY.md` or `architecture.md`). + pub name: String, + /// Full path to the Markdown file. + pub path: PathBuf, + /// Whether this entry is the [`INDEX_FILENAME`] index file. + pub is_index: bool, +} + +/// Resolves the default root directory for all project memories. +/// +/// Uses `$XDG_DATA_HOME/ox/memory` when `XDG_DATA_HOME` is non-empty, falling back to +/// `$HOME/.local/share/ox/memory`. +pub fn default_memory_root() -> Result { + memory_root_from(std::env::var_os("XDG_DATA_HOME"), std::env::var_os("HOME")) +} + +fn memory_root_from( + xdg_data_home: Option, + home: Option, +) -> Result { + if let Some(dir) = xdg_data_home.filter(|value| !value.is_empty()) { + return Ok(PathBuf::from(dir).join("ox").join("memory")); + } + + if let Some(dir) = home.filter(|value| !value.is_empty()) { + return Ok(PathBuf::from(dir) + .join(".local") + .join("share") + .join("ox") + .join("memory")); + } + + Err(MemoryError::MissingDataDir) +} + +/// Derives a deterministic, filesystem-safe key for `project_root`. +/// +/// Canonicalizes `project_root` when it exists on disk so symlinks and relative paths resolve +/// to the same key. The key combines a sanitized directory-name slug with a 64-bit FNV-1a hash +/// of the normalized path to avoid collisions and keep directory names bounded. +pub fn project_key(project_root: impl AsRef) -> String { + let path = project_root.as_ref(); + let normalized = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + let raw = normalized.to_string_lossy(); + let hash = fnv1a_64(raw.as_bytes()); + + let slug = normalized + .file_name() + .and_then(|name| name.to_str()) + .map(sanitize_slug) + .filter(|slug| !slug.is_empty()) + .unwrap_or_else(|| "project".to_string()); + + format!("{slug}-{hash:016x}") +} + +fn sanitize_slug(input: &str) -> String { + let mut out = String::with_capacity(input.len().min(MAX_SLUG_LEN)); + let mut prev_dash = false; + + for ch in input.chars() { + if out.len() >= MAX_SLUG_LEN { + break; + } + + if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' { + out.push(ch.to_ascii_lowercase()); + prev_dash = false; + } else if !prev_dash && !out.is_empty() { + out.push('-'); + prev_dash = true; + } + } + + out.trim_matches('-').to_string() +} + +fn fnv1a_64(bytes: &[u8]) -> u64 { + let mut hash = FNV1A_OFFSET_BASIS; + for &byte in bytes { + hash ^= u64::from(byte); + hash = hash.wrapping_mul(FNV1A_PRIME); + } + hash +} + +fn normalize_topic_filename(name: &str) -> Result { + let trimmed = name.trim(); + let stem = trimmed.strip_suffix(".md").unwrap_or(trimmed); + + let is_valid = !stem.is_empty() + && !stem.eq_ignore_ascii_case("memory") + && stem + .chars() + .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_'); + + if !is_valid { + return Err(MemoryError::InvalidTopicName { + name: name.to_string(), + }); + } + + Ok(format!("{stem}.md")) +} + +/// Manages the per-project Markdown memory directory. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MemoryStore { + dir: PathBuf, +} + +impl MemoryStore { + /// Opens a store for `project_root` under [`default_memory_root`]. + pub fn for_project(project_root: impl AsRef) -> Result { + let root = default_memory_root()?; + Ok(Self::for_project_in(root, project_root)) + } + + /// Opens a store for `project_root` under an explicit `memory_root` directory. + pub fn for_project_in(memory_root: impl AsRef, project_root: impl AsRef) -> Self { + let key = project_key(project_root); + Self::at_dir(memory_root.as_ref().join(key)) + } + + /// Opens a store backed directly by `dir`. + pub fn at_dir(dir: impl Into) -> Self { + Self { dir: dir.into() } + } + + /// Returns the project memory directory path. + pub fn dir(&self) -> &Path { + &self.dir + } + + /// Returns the path to [`INDEX_FILENAME`] within this store. + pub fn index_path(&self) -> PathBuf { + self.dir.join(INDEX_FILENAME) + } + + /// Returns the validated path for a topic Markdown file. + /// + /// Accepts topic names with or without a `.md` suffix (for example `architecture` or + /// `architecture.md`). Rejects empty names, path separators, non-identifier characters, and + /// the reserved `MEMORY` index name. + pub fn topic_path(&self, name: &str) -> Result { + let filename = normalize_topic_filename(name)?; + Ok(self.dir.join(filename)) + } + + /// Reads [`INDEX_FILENAME`], returning `Ok(None)` if it does not exist. + pub fn read_index(&self) -> Result, MemoryError> { + read_optional_file(&self.index_path()) + } + + /// Writes `content` to [`INDEX_FILENAME`], creating the memory directory if needed. + pub fn write_index(&self, content: &str) -> Result<(), MemoryError> { + self.ensure_dir()?; + let path = self.index_path(); + fs::write(&path, content).map_err(|source| MemoryError::WriteFile { path, source }) + } + + /// Reads a topic Markdown file, returning `Ok(None)` if it does not exist. + pub fn read_topic(&self, name: &str) -> Result, MemoryError> { + let path = self.topic_path(name)?; + read_optional_file(&path) + } + + /// Writes `content` to a topic Markdown file, creating the memory directory if needed. + pub fn write_topic(&self, name: &str, content: &str) -> Result { + let path = self.topic_path(name)?; + self.ensure_dir()?; + fs::write(&path, content).map_err(|source| MemoryError::WriteFile { + path: path.clone(), + source, + })?; + Ok(path) + } + + /// Deletes a topic Markdown file, returning `Ok(true)` if it existed or `Ok(false)` if not. + pub fn delete_topic(&self, name: &str) -> Result { + let path = self.topic_path(name)?; + match fs::remove_file(&path) { + Ok(()) => Ok(true), + Err(err) if err.kind() == ErrorKind::NotFound => Ok(false), + Err(source) => Err(MemoryError::DeleteFile { path, source }), + } + } + + /// Lists Markdown memory files in this store. + /// + /// Returns an empty list if the memory directory does not exist. [`INDEX_FILENAME`] appears + /// first when present, followed by topic files sorted by file name. + pub fn list_entries(&self) -> Result, MemoryError> { + let read_dir = match fs::read_dir(&self.dir) { + Ok(entries) => entries, + Err(err) if err.kind() == ErrorKind::NotFound => return Ok(Vec::new()), + Err(source) => { + return Err(MemoryError::ReadDir { + path: self.dir.clone(), + source, + }); + } + }; + + let mut entries = Vec::new(); + for item in read_dir { + let entry = item.map_err(|source| MemoryError::ReadDir { + path: self.dir.clone(), + source, + })?; + let path = entry.path(); + if !path.is_file() { + continue; + } + let Some(name) = path.file_name().and_then(|value| value.to_str()) else { + continue; + }; + if !path + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("md")) + { + continue; + } + + entries.push(MemoryEntry { + is_index: name == INDEX_FILENAME, + name: name.to_string(), + path, + }); + } + + entries.sort_by(|left, right| { + right + .is_index + .cmp(&left.is_index) + .then_with(|| left.name.cmp(&right.name)) + }); + + Ok(entries) + } + + /// Formats a bounded [`INDEX_FILENAME`] snippet for system prompt injection. + /// + /// Returns `None` when [`INDEX_FILENAME`] is missing, blank, or unreadable. + pub fn prompt_section(&self) -> Option { + self.prompt_section_bounded(DEFAULT_MAX_PROMPT_LINES, DEFAULT_MAX_PROMPT_BYTES) + .ok() + .flatten() + } + + /// Formats a [`INDEX_FILENAME`] snippet bounded by `max_lines` and `max_bytes`. + /// + /// Returns `Ok(None)` when [`INDEX_FILENAME`] does not exist or contains only whitespace. + pub fn prompt_section_bounded( + &self, + max_lines: usize, + max_bytes: usize, + ) -> Result, MemoryError> { + let Some(raw) = self.read_index()? else { + return Ok(None); + }; + let trimmed = raw.trim(); + if trimmed.is_empty() { + return Ok(None); + } + + let (snippet, truncated) = truncate_snippet(trimmed, max_lines, max_bytes); + let mut rendered = format!( + "# Project Memory\n\nMemory directory: `{}`\n\n{snippet}", + self.dir.display() + ); + + if truncated { + let _ = write!( + rendered, + "\n\n[Truncated: read `{}` for remaining entries.]", + self.index_path().display() + ); + } + + Ok(Some(rendered)) + } + + fn ensure_dir(&self) -> Result<(), MemoryError> { + fs::create_dir_all(&self.dir).map_err(|source| MemoryError::CreateDir { + path: self.dir.clone(), + source, + }) + } +} + +fn read_optional_file(path: &Path) -> Result, MemoryError> { + match fs::read_to_string(path) { + Ok(content) => Ok(Some(content)), + Err(err) if err.kind() == ErrorKind::NotFound => Ok(None), + Err(source) => Err(MemoryError::ReadFile { + path: path.to_path_buf(), + source, + }), + } +} + +fn truncate_snippet(content: &str, max_lines: usize, max_bytes: usize) -> (String, bool) { + let mut out = String::new(); + let mut truncated = false; + + for (line_idx, line) in content.lines().enumerate() { + if line_idx >= max_lines { + truncated = true; + break; + } + + let separator_len = usize::from(!out.is_empty()); + if out.len() + separator_len + line.len() > max_bytes { + let remaining = max_bytes.saturating_sub(out.len() + separator_len); + if remaining > 0 { + if separator_len > 0 { + out.push('\n'); + } + let boundary = floor_char_boundary(line, remaining); + out.push_str(&line[..boundary]); + } + truncated = true; + break; + } + + if separator_len > 0 { + out.push('\n'); + } + out.push_str(line); + } + + (out, truncated) +} + +fn floor_char_boundary(text: &str, max_bytes: usize) -> usize { + if max_bytes >= text.len() { + return text.len(); + } + + let mut idx = max_bytes; + while idx > 0 && !text.is_char_boundary(idx) { + idx -= 1; + } + idx +} + +#[cfg(test)] +mod tests { + use indoc::indoc; + use tempfile::TempDir; + + use super::*; + + #[test] + fn memory_root_from_prefers_xdg_data_home() { + let root = memory_root_from( + Some(OsString::from("/custom/data")), + Some(OsString::from("/home/alice")), + ) + .unwrap(); + + assert_eq!(root, PathBuf::from("/custom/data/ox/memory")); + } + + #[test] + fn memory_root_from_falls_back_to_home() { + let root = + memory_root_from(Some(OsString::new()), Some(OsString::from("/home/alice"))).unwrap(); + + assert_eq!(root, PathBuf::from("/home/alice/.local/share/ox/memory")); + } + + #[test] + fn memory_root_from_errors_when_both_missing() { + let err = memory_root_from(None, None).unwrap_err(); + assert!(matches!(err, MemoryError::MissingDataDir)); + } + + #[test] + fn project_key_is_deterministic_and_sanitized() { + let first = project_key("/tmp/My Project! 2026"); + let second = project_key("/tmp/My Project! 2026"); + let other = project_key("/tmp/other-project"); + + assert_eq!(first, second); + assert_ne!(first, other); + assert!(first.starts_with("my-project-2026-")); + assert!( + first + .chars() + .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_') + ); + } + + #[test] + fn project_key_uses_fallback_slug_for_root_path() { + let key = project_key("/"); + assert!(key.starts_with("project-")); + } + + #[test] + fn topic_path_validates_and_normalizes_names() { + let store = MemoryStore::at_dir("/tmp/ox-memory-test"); + + assert_eq!( + store.topic_path("architecture").unwrap(), + PathBuf::from("/tmp/ox-memory-test/architecture.md") + ); + assert_eq!( + store.topic_path("build_notes.md").unwrap(), + PathBuf::from("/tmp/ox-memory-test/build_notes.md") + ); + + for invalid in ["", " ", "MEMORY", "memory.md", "../escape", "a/b", "a b"] { + assert!( + matches!( + store.topic_path(invalid), + Err(MemoryError::InvalidTopicName { .. }) + ), + "expected {invalid:?} to be rejected" + ); + } + } + + #[test] + fn read_and_write_index_and_topics() { + let temp = TempDir::new().unwrap(); + let store = MemoryStore::for_project_in(temp.path(), "/workspace/oxide-code"); + + assert_eq!(store.read_index().unwrap(), None); + assert_eq!(store.read_topic("architecture").unwrap(), None); + + let index = indoc! {" + # Memory Index + + - [Architecture](architecture.md) + "}; + store.write_index(index).unwrap(); + assert_eq!(store.read_index().unwrap().as_deref(), Some(index)); + + let topic = indoc! {" + # Architecture + + Workspace crates stay small and decoupled. + "}; + let written = store.write_topic("architecture", topic).unwrap(); + assert_eq!(written, store.dir().join("architecture.md")); + assert_eq!( + store.read_topic("architecture.md").unwrap().as_deref(), + Some(topic) + ); + + assert!(store.delete_topic("architecture").unwrap()); + assert!(!store.delete_topic("architecture").unwrap()); + assert_eq!(store.read_topic("architecture").unwrap(), None); + } + + #[test] + fn list_entries_returns_index_first_then_sorted_topics() { + let temp = TempDir::new().unwrap(); + let store = MemoryStore::at_dir(temp.path().join("proj")); + + assert_eq!(store.list_entries().unwrap(), Vec::new()); + + store.write_topic("zeta", "# Zeta\n").unwrap(); + store.write_topic("alpha", "# Alpha\n").unwrap(); + store.write_index("# Index\n").unwrap(); + fs::write(store.dir().join("notes.txt"), "ignored").unwrap(); + + let entries = store.list_entries().unwrap(); + let names: Vec<&str> = entries.iter().map(|entry| entry.name.as_str()).collect(); + assert_eq!(names, vec!["MEMORY.md", "alpha.md", "zeta.md"]); + assert!(entries[0].is_index); + assert!(!entries[1].is_index); + assert!(!entries[2].is_index); + } + + #[test] + fn prompt_section_returns_none_when_missing_or_blank() { + let temp = TempDir::new().unwrap(); + let store = MemoryStore::at_dir(temp.path().join("empty")); + + assert_eq!(store.prompt_section(), None); + + store.write_index(" \n\t\n").unwrap(); + assert_eq!(store.prompt_section(), None); + } + + #[test] + fn prompt_section_renders_index_and_bounds_lines_and_bytes() { + let temp = TempDir::new().unwrap(); + let store = MemoryStore::at_dir(temp.path().join("proj")); + let index = indoc! {" + - line 1 + - line 2 + - line 3 + "}; + store.write_index(index).unwrap(); + + let full = store.prompt_section().unwrap(); + assert!(full.contains("# Project Memory")); + assert!(full.contains("- line 1\n- line 2\n- line 3")); + assert!(!full.contains("[Truncated:")); + + let line_bounded = store.prompt_section_bounded(2, 1024).unwrap().unwrap(); + assert!(line_bounded.contains("- line 1\n- line 2")); + assert!(!line_bounded.contains("- line 3")); + assert!(line_bounded.contains("[Truncated:")); + + let byte_bounded = store.prompt_section_bounded(10, 12).unwrap().unwrap(); + assert!(byte_bounded.contains("- line 1\n- l")); + assert!(byte_bounded.contains("[Truncated:")); + } + + #[test] + fn truncate_snippet_respects_utf8_boundaries() { + let (snippet, truncated) = truncate_snippet("你好世界", 10, 5); + assert!(truncated); + assert_eq!(snippet, "你"); + } +} diff --git a/docs/README.md b/docs/README.md index df9433b2b..469d89ee7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -21,6 +21,7 @@ Documentation for `oxide-code` (`ox`) is organized into three user-facing bucket | [Configuration](reference/configuration.md) | `config.toml` schema for providers, credentials, and model entries | | [Hooks](reference/hooks.md) | Out-of-process command hooks, lifecycle events, and error policy | | [MCP Plugin](reference/mcp-plugin.md) | `ox-plugin-mcp` stdio and Streamable HTTP MCP bridge configuration | +| [Memory](reference/memory.md) | Per-project Markdown memory directory and prompt index injection | | [Models](reference/models.md) | Data-driven model catalog TOML schema and tier profiles | | [Skills](reference/skills.md) | `SKILL.md` discovery roots, frontmatter schema, and `load_skill` | | [Statusline](reference/statusline.md) | Built-in statusline segments and external ANSI command protocol | diff --git a/docs/reference/memory.md b/docs/reference/memory.md new file mode 100644 index 000000000..638d490a6 --- /dev/null +++ b/docs/reference/memory.md @@ -0,0 +1,37 @@ +# Project Memory + +`ox-core` provides a per-project Markdown memory directory through `MemoryStore`. Each project receives a deterministic directory containing a `MEMORY.md` index and topic Markdown files, along with bounded prompt-section formatting for system prompt injection. + +## Directory Layout + +Project memories live under `$XDG_DATA_HOME/ox/memory//`, falling back to `$HOME/.local/share/ox/memory//` when `XDG_DATA_HOME` is unset or empty. Callers and tests can override the root with `MemoryStore::for_project_in` or bind directly to a directory with `MemoryStore::at_dir`. + +```text +$XDG_DATA_HOME/ox/memory// + MEMORY.md # index loaded into the system prompt + architecture.md # topic file + conventions.md # topic file +``` + +`project_key(project_root)` canonicalizes `project_root` when it exists on disk, then builds `-` from a sanitized ASCII directory-name slug (up to 48 characters) and a 16-hex-character 64-bit FNV-1a hash of the normalized path. This keeps directory names deterministic, bounded, and safe across filesystems. + +## Reading, Writing, and Listing + +`MemoryStore` supports index and topic operations without creating the directory until the first write: + +| Method | Behavior | +| ---------------------------- | ----------------------------------------------------------------------------- | +| `read_index()` | Reads `MEMORY.md`, returning `Ok(None)` when missing | +| `write_index(content)` | Creates the memory directory if needed and writes `MEMORY.md` | +| `read_topic(name)` | Reads `.md`, returning `Ok(None)` when missing | +| `write_topic(name, content)` | Creates the memory directory if needed, writes `.md`, returns its path | +| `delete_topic(name)` | Removes `.md`, returning `Ok(true)` if removed or `Ok(false)` if absent | +| `list_entries()` | Lists regular `.md` files with `MEMORY.md` first, then topics sorted by name | + +Topic names accept an optional `.md` suffix and must consist of ASCII alphanumeric characters, `-`, or `_`. Empty names, path separators, and the reserved `MEMORY` index name are rejected with `MemoryError::InvalidTopicName`. + +## System Prompt Injection + +Use `MemoryStore::prompt_section()` to render a bounded `# Project Memory` snippet from `MEMORY.md` for `SystemPromptBuilder`. It returns `None` when `MEMORY.md` is missing or whitespace-only. + +By default, `prompt_section()` caps the included index at `DEFAULT_MAX_PROMPT_LINES` (200 lines) and `DEFAULT_MAX_PROMPT_BYTES` (8 KiB), respecting UTF-8 character boundaries. When truncated, the rendered section appends a notice pointing to the full `MEMORY.md` path. Use `prompt_section_bounded(max_lines, max_bytes)` for custom limits.