Skip to main content

arabica_runtime/
long_memory.rs

1use std::collections::BTreeMap;
2use std::error::Error;
3use std::fmt::{Display, Formatter};
4use std::fs::{self, DirBuilder, OpenOptions};
5use std::io::Write;
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use arabica_protocol::{ContextEntry, DisclosureLevel};
10use rusqlite::{Connection, OptionalExtension, params};
11use serde::{Deserialize, Serialize};
12
13const GLANCE_LIMIT: usize = 160;
14const OVERVIEW_LIMIT: usize = 1_024;
15const MAX_CONTEXT_PATH_BYTES: usize = 1_024;
16static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
17
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19pub enum LongMemoryErrorKind {
20    InvalidPath,
21    Conflict,
22    Storage,
23}
24
25#[derive(Clone, Debug, Eq, PartialEq)]
26pub struct LongMemoryError {
27    kind: LongMemoryErrorKind,
28    message: String,
29}
30
31impl LongMemoryError {
32    fn invalid_path(message: impl Into<String>) -> Self {
33        Self {
34            kind: LongMemoryErrorKind::InvalidPath,
35            message: message.into(),
36        }
37    }
38
39    fn conflict(message: impl Into<String>) -> Self {
40        Self {
41            kind: LongMemoryErrorKind::Conflict,
42            message: message.into(),
43        }
44    }
45
46    fn storage(message: impl Into<String>) -> Self {
47        Self {
48            kind: LongMemoryErrorKind::Storage,
49            message: message.into(),
50        }
51    }
52
53    pub fn kind(&self) -> LongMemoryErrorKind {
54        self.kind
55    }
56}
57
58impl Display for LongMemoryError {
59    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
60        self.message.fmt(formatter)
61    }
62}
63
64impl Error for LongMemoryError {}
65
66/// Workspace-scoped durable memory.
67///
68/// The in-memory map is the local foundation implementation. A persistent
69/// `LongMemoryStore` adapter can replace it without changing Runtime's
70/// separation from session-derived short memory.
71#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
72pub struct ArchivedMemory {
73    pub memory_id: String,
74    pub content: String,
75    pub content_hash: String,
76}
77
78/// Durable backing contract for recoverable short-memory pointers.
79///
80/// Implementations must make writes idempotent for identical content and
81/// reject attempts to reuse an identifier for different evidence.
82pub trait LongMemoryStore {
83    fn put_archive(
84        &mut self,
85        memory_id: &str,
86        content: String,
87        content_hash: String,
88    ) -> Result<(), LongMemoryError>;
89
90    fn get_archive(&self, memory_id: &str) -> Result<Option<ArchivedMemory>, LongMemoryError>;
91
92    fn contains_archive(&self, memory_id: &str) -> Result<bool, LongMemoryError> {
93        Ok(self.get_archive(memory_id)?.is_some())
94    }
95
96    fn search_archives(
97        &self,
98        query: &str,
99        limit: usize,
100    ) -> Result<Vec<ArchivedMemory>, LongMemoryError>;
101
102    fn archive_count(&self) -> Result<usize, LongMemoryError>;
103}
104
105/// Atomic filesystem archive. Each pointer is stored as one JSON envelope
106/// beneath `root`, preserving the normalized memory-id hierarchy.
107#[derive(Clone, Debug)]
108pub struct FileArchiveStore {
109    root: PathBuf,
110}
111
112impl FileArchiveStore {
113    pub fn open(root: impl Into<PathBuf>) -> Result<Self, LongMemoryError> {
114        let root = root.into();
115        create_private_archive_dir(&root).map_err(|error| {
116            LongMemoryError::storage(format!(
117                "failed to create file archive {}: {error}",
118                root.display()
119            ))
120        })?;
121        Ok(Self { root })
122    }
123
124    pub fn root(&self) -> &Path {
125        &self.root
126    }
127
128    fn archive_path(&self, memory_id: &str) -> Result<PathBuf, LongMemoryError> {
129        let memory_id = normalize_path(memory_id)?;
130        Ok(self.root.join(memory_id))
131    }
132}
133
134impl LongMemoryStore for FileArchiveStore {
135    fn put_archive(
136        &mut self,
137        memory_id: &str,
138        content: String,
139        content_hash: String,
140    ) -> Result<(), LongMemoryError> {
141        let memory_id = normalize_path(memory_id)?;
142        let archive = ArchivedMemory {
143            memory_id: memory_id.clone(),
144            content,
145            content_hash,
146        };
147        let path = self.archive_path(&memory_id)?;
148        if let Some(parent) = path.parent() {
149            create_private_archive_dir(parent).map_err(|error| {
150                LongMemoryError::storage(format!(
151                    "failed to create archive directory {}: {error}",
152                    parent.display()
153                ))
154            })?;
155        }
156        if path.exists() {
157            return verify_existing_archive(self.get_archive(&memory_id)?, &archive);
158        }
159
160        let bytes = serde_json::to_vec(&archive).map_err(|error| {
161            LongMemoryError::storage(format!("failed to encode archive {memory_id}: {error}"))
162        })?;
163        let nonce = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
164        let temp_path = path.with_extension(format!("json.tmp-{}-{nonce}", std::process::id()));
165        let write_result = (|| {
166            let mut options = OpenOptions::new();
167            options.write(true).create_new(true);
168            #[cfg(unix)]
169            {
170                use std::os::unix::fs::OpenOptionsExt;
171                options.mode(0o600);
172            }
173            let mut file = options.open(&temp_path)?;
174            file.write_all(&bytes)?;
175            file.sync_all()?;
176            fs::hard_link(&temp_path, &path)
177        })();
178        let _ = fs::remove_file(&temp_path);
179        match write_result {
180            Ok(()) => Ok(()),
181            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
182                verify_existing_archive(self.get_archive(&memory_id)?, &archive)
183            }
184            Err(error) => Err(LongMemoryError::storage(format!(
185                "failed to persist archive {}: {error}",
186                path.display()
187            ))),
188        }
189    }
190
191    fn get_archive(&self, memory_id: &str) -> Result<Option<ArchivedMemory>, LongMemoryError> {
192        let memory_id = normalize_path(memory_id)?;
193        let path = self.archive_path(&memory_id)?;
194        let bytes = match fs::read(&path) {
195            Ok(bytes) => bytes,
196            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
197            Err(error) => {
198                return Err(LongMemoryError::storage(format!(
199                    "failed to read archive {}: {error}",
200                    path.display()
201                )));
202            }
203        };
204        let archive: ArchivedMemory = serde_json::from_slice(&bytes).map_err(|error| {
205            LongMemoryError::storage(format!(
206                "archive {} is not valid JSON: {error}",
207                path.display()
208            ))
209        })?;
210        if archive.memory_id != memory_id {
211            return Err(LongMemoryError::storage(format!(
212                "archive {} contains mismatched memory id {}",
213                path.display(),
214                archive.memory_id
215            )));
216        }
217        Ok(Some(archive))
218    }
219
220    fn contains_archive(&self, memory_id: &str) -> Result<bool, LongMemoryError> {
221        Ok(self.archive_path(memory_id)?.is_file())
222    }
223
224    fn archive_count(&self) -> Result<usize, LongMemoryError> {
225        count_json_files(&self.root)
226    }
227
228    fn search_archives(
229        &self,
230        query: &str,
231        limit: usize,
232    ) -> Result<Vec<ArchivedMemory>, LongMemoryError> {
233        let mut matches = Vec::new();
234        for path in json_files(&self.root)? {
235            let relative = path.strip_prefix(&self.root).map_err(|error| {
236                LongMemoryError::storage(format!(
237                    "invalid archive path {}: {error}",
238                    path.display()
239                ))
240            })?;
241            let memory_id = relative.to_string_lossy().replace('\\', "/");
242            let archive = self.get_archive(&memory_id)?.ok_or_else(|| {
243                LongMemoryError::storage(format!("archive disappeared during search: {memory_id}"))
244            })?;
245            if archive_matches(&archive, query) {
246                matches.push(archive);
247            }
248        }
249        matches.sort_by(|left, right| left.memory_id.cmp(&right.memory_id));
250        matches.truncate(limit);
251        Ok(matches)
252    }
253}
254
255fn create_private_archive_dir(path: &Path) -> std::io::Result<()> {
256    let mut builder = DirBuilder::new();
257    builder.recursive(true);
258    #[cfg(unix)]
259    {
260        use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
261        builder.mode(0o700);
262        builder.create(path)?;
263        fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
264    }
265    #[cfg(not(unix))]
266    builder.create(path)?;
267    Ok(())
268}
269
270/// SQLite archive with an idempotent primary-key contract.
271#[derive(Debug)]
272pub struct SqliteArchiveStore {
273    path: PathBuf,
274    connection: Connection,
275}
276
277impl SqliteArchiveStore {
278    pub fn open(path: impl Into<PathBuf>) -> Result<Self, LongMemoryError> {
279        let path = path.into();
280        if let Some(parent) = path
281            .parent()
282            .filter(|parent| !parent.as_os_str().is_empty())
283        {
284            fs::create_dir_all(parent).map_err(|error| {
285                LongMemoryError::storage(format!(
286                    "failed to create SQLite archive directory {}: {error}",
287                    parent.display()
288                ))
289            })?;
290        }
291        let connection = Connection::open(&path).map_err(sqlite_error)?;
292        connection
293            .execute_batch(
294                "PRAGMA journal_mode=WAL;\
295                 PRAGMA synchronous=NORMAL;\
296                 CREATE TABLE IF NOT EXISTS runtime_memory_archive (\
297                   memory_id TEXT PRIMARY KEY NOT NULL,\
298                   content TEXT NOT NULL,\
299                   content_hash TEXT NOT NULL\
300                 );",
301            )
302            .map_err(sqlite_error)?;
303        Ok(Self { path, connection })
304    }
305
306    pub fn path(&self) -> &Path {
307        &self.path
308    }
309}
310
311impl LongMemoryStore for SqliteArchiveStore {
312    fn put_archive(
313        &mut self,
314        memory_id: &str,
315        content: String,
316        content_hash: String,
317    ) -> Result<(), LongMemoryError> {
318        let memory_id = normalize_path(memory_id)?;
319        let transaction = self.connection.transaction().map_err(sqlite_error)?;
320        transaction
321            .execute(
322                "INSERT OR IGNORE INTO runtime_memory_archive (memory_id, content, content_hash) \
323                 VALUES (?1, ?2, ?3)",
324                params![memory_id, content, content_hash],
325            )
326            .map_err(sqlite_error)?;
327        let existing = transaction
328            .query_row(
329                "SELECT content, content_hash FROM runtime_memory_archive WHERE memory_id = ?1",
330                params![memory_id],
331                |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
332            )
333            .map_err(sqlite_error)?;
334        if existing != (content, content_hash) {
335            return Err(LongMemoryError::conflict(format!(
336                "SQLite archive id already contains different evidence: {memory_id}"
337            )));
338        }
339        transaction.commit().map_err(sqlite_error)
340    }
341
342    fn get_archive(&self, memory_id: &str) -> Result<Option<ArchivedMemory>, LongMemoryError> {
343        let memory_id = normalize_path(memory_id)?;
344        self.connection
345            .query_row(
346                "SELECT content, content_hash FROM runtime_memory_archive WHERE memory_id = ?1",
347                params![memory_id],
348                |row| {
349                    Ok(ArchivedMemory {
350                        memory_id: memory_id.clone(),
351                        content: row.get(0)?,
352                        content_hash: row.get(1)?,
353                    })
354                },
355            )
356            .optional()
357            .map_err(sqlite_error)
358    }
359
360    fn contains_archive(&self, memory_id: &str) -> Result<bool, LongMemoryError> {
361        let memory_id = normalize_path(memory_id)?;
362        self.connection
363            .query_row(
364                "SELECT EXISTS(SELECT 1 FROM runtime_memory_archive WHERE memory_id = ?1)",
365                params![memory_id],
366                |row| row.get(0),
367            )
368            .map_err(sqlite_error)
369    }
370
371    fn archive_count(&self) -> Result<usize, LongMemoryError> {
372        self.connection
373            .query_row("SELECT COUNT(*) FROM runtime_memory_archive", [], |row| {
374                row.get(0)
375            })
376            .map_err(sqlite_error)
377    }
378
379    fn search_archives(
380        &self,
381        query: &str,
382        limit: usize,
383    ) -> Result<Vec<ArchivedMemory>, LongMemoryError> {
384        let pattern = format!("%{}%", query.trim().to_lowercase());
385        let mut statement = self
386            .connection
387            .prepare(
388                "SELECT memory_id, content, content_hash FROM runtime_memory_archive \
389                 WHERE lower(memory_id) LIKE ?1 OR lower(content) LIKE ?1 \
390                 ORDER BY memory_id LIMIT ?2",
391            )
392            .map_err(sqlite_error)?;
393        let rows = statement
394            .query_map(params![pattern, limit], |row| {
395                Ok(ArchivedMemory {
396                    memory_id: row.get(0)?,
397                    content: row.get(1)?,
398                    content_hash: row.get(2)?,
399                })
400            })
401            .map_err(sqlite_error)?;
402        rows.collect::<Result<Vec<_>, _>>().map_err(sqlite_error)
403    }
404}
405
406#[derive(Debug)]
407enum ArchiveBackend {
408    Memory(BTreeMap<String, ArchivedMemory>),
409    File(FileArchiveStore),
410    Sqlite(SqliteArchiveStore),
411}
412
413impl Default for ArchiveBackend {
414    fn default() -> Self {
415        Self::Memory(BTreeMap::new())
416    }
417}
418
419#[derive(Debug, Default)]
420pub struct LongMemoryManager {
421    entries: BTreeMap<String, String>,
422    archives: ArchiveBackend,
423}
424
425impl LongMemoryManager {
426    pub fn with_file_archive(root: impl Into<PathBuf>) -> Result<Self, LongMemoryError> {
427        Ok(Self {
428            entries: BTreeMap::new(),
429            archives: ArchiveBackend::File(FileArchiveStore::open(root)?),
430        })
431    }
432
433    pub fn with_sqlite_archive(path: impl Into<PathBuf>) -> Result<Self, LongMemoryError> {
434        Ok(Self {
435            entries: BTreeMap::new(),
436            archives: ArchiveBackend::Sqlite(SqliteArchiveStore::open(path)?),
437        })
438    }
439
440    pub fn read(
441        &self,
442        path: &str,
443        disclosure: DisclosureLevel,
444    ) -> Result<Option<ContextEntry>, LongMemoryError> {
445        let path = normalize_path(path)?;
446        Ok(self.entries.get(&path).map(|content| ContextEntry {
447            path,
448            content: disclose(content, disclosure),
449        }))
450    }
451
452    pub fn search(&self, query: &str, disclosure: DisclosureLevel) -> Vec<ContextEntry> {
453        let normalized_query = query.trim().to_lowercase();
454        self.entries
455            .iter()
456            .filter(|(path, content)| {
457                normalized_query.is_empty()
458                    || path.to_lowercase().contains(&normalized_query)
459                    || content.to_lowercase().contains(&normalized_query)
460            })
461            .map(|(path, content)| ContextEntry {
462                path: path.clone(),
463                content: disclose(content, disclosure),
464            })
465            .collect()
466    }
467
468    pub fn entries(&self, disclosure: DisclosureLevel) -> Vec<ContextEntry> {
469        self.search("", disclosure)
470    }
471
472    pub fn update(
473        &mut self,
474        path: String,
475        content: String,
476    ) -> Result<ContextEntry, LongMemoryError> {
477        let path = normalize_path(&path)?;
478        self.entries.insert(path.clone(), content.clone());
479        Ok(ContextEntry { path, content })
480    }
481
482    pub fn delete(&mut self, path: &str) -> Result<Option<String>, LongMemoryError> {
483        let path = normalize_path(path)?;
484        Ok(self.entries.remove(&path).map(|_| path))
485    }
486
487    pub fn archived_count(&self) -> Result<usize, LongMemoryError> {
488        self.archive_count()
489    }
490}
491
492impl LongMemoryStore for LongMemoryManager {
493    fn put_archive(
494        &mut self,
495        memory_id: &str,
496        content: String,
497        content_hash: String,
498    ) -> Result<(), LongMemoryError> {
499        let memory_id = normalize_path(memory_id)?;
500        match &mut self.archives {
501            ArchiveBackend::Memory(archives) => {
502                let archive = ArchivedMemory {
503                    memory_id: memory_id.clone(),
504                    content,
505                    content_hash,
506                };
507                if let Some(existing) = archives.get(&memory_id) {
508                    return verify_existing_archive(Some(existing.clone()), &archive);
509                }
510                archives.insert(memory_id, archive);
511                Ok(())
512            }
513            ArchiveBackend::File(store) => store.put_archive(&memory_id, content, content_hash),
514            ArchiveBackend::Sqlite(store) => store.put_archive(&memory_id, content, content_hash),
515        }
516    }
517
518    fn get_archive(&self, memory_id: &str) -> Result<Option<ArchivedMemory>, LongMemoryError> {
519        match &self.archives {
520            ArchiveBackend::Memory(archives) => {
521                let memory_id = normalize_path(memory_id)?;
522                Ok(archives.get(&memory_id).cloned())
523            }
524            ArchiveBackend::File(store) => store.get_archive(memory_id),
525            ArchiveBackend::Sqlite(store) => store.get_archive(memory_id),
526        }
527    }
528
529    fn contains_archive(&self, memory_id: &str) -> Result<bool, LongMemoryError> {
530        match &self.archives {
531            ArchiveBackend::Memory(archives) => {
532                let memory_id = normalize_path(memory_id)?;
533                Ok(archives.contains_key(&memory_id))
534            }
535            ArchiveBackend::File(store) => store.contains_archive(memory_id),
536            ArchiveBackend::Sqlite(store) => store.contains_archive(memory_id),
537        }
538    }
539
540    fn archive_count(&self) -> Result<usize, LongMemoryError> {
541        match &self.archives {
542            ArchiveBackend::Memory(archives) => Ok(archives.len()),
543            ArchiveBackend::File(store) => store.archive_count(),
544            ArchiveBackend::Sqlite(store) => store.archive_count(),
545        }
546    }
547
548    fn search_archives(
549        &self,
550        query: &str,
551        limit: usize,
552    ) -> Result<Vec<ArchivedMemory>, LongMemoryError> {
553        match &self.archives {
554            ArchiveBackend::Memory(archives) => Ok(archives
555                .values()
556                .filter(|archive| archive_matches(archive, query))
557                .take(limit)
558                .cloned()
559                .collect()),
560            ArchiveBackend::File(store) => store.search_archives(query, limit),
561            ArchiveBackend::Sqlite(store) => store.search_archives(query, limit),
562        }
563    }
564}
565
566fn verify_existing_archive(
567    existing: Option<ArchivedMemory>,
568    requested: &ArchivedMemory,
569) -> Result<(), LongMemoryError> {
570    match existing {
571        Some(existing) if existing == *requested => Ok(()),
572        Some(_) => Err(LongMemoryError::conflict(format!(
573            "archive id already contains different evidence: {}",
574            requested.memory_id
575        ))),
576        None => Err(LongMemoryError::storage(format!(
577            "archive appeared concurrently but could not be read: {}",
578            requested.memory_id
579        ))),
580    }
581}
582
583fn count_json_files(root: &Path) -> Result<usize, LongMemoryError> {
584    Ok(json_files(root)?.len())
585}
586
587fn json_files(root: &Path) -> Result<Vec<PathBuf>, LongMemoryError> {
588    let mut files = Vec::new();
589    let mut pending = vec![root.to_path_buf()];
590    while let Some(directory) = pending.pop() {
591        let entries = fs::read_dir(&directory).map_err(|error| {
592            LongMemoryError::storage(format!(
593                "failed to list archive directory {}: {error}",
594                directory.display()
595            ))
596        })?;
597        for entry in entries {
598            let entry = entry.map_err(|error| {
599                LongMemoryError::storage(format!("failed to inspect archive entry: {error}"))
600            })?;
601            let file_type = entry.file_type().map_err(|error| {
602                LongMemoryError::storage(format!(
603                    "failed to inspect archive entry {}: {error}",
604                    entry.path().display()
605                ))
606            })?;
607            if file_type.is_dir() {
608                pending.push(entry.path());
609            } else if file_type.is_file()
610                && entry.path().extension().and_then(|value| value.to_str()) == Some("json")
611            {
612                files.push(entry.path());
613            }
614        }
615    }
616    Ok(files)
617}
618
619fn archive_matches(archive: &ArchivedMemory, query: &str) -> bool {
620    let query = query.trim().to_lowercase();
621    query.is_empty()
622        || archive.memory_id.to_lowercase().contains(&query)
623        || archive.content.to_lowercase().contains(&query)
624}
625
626fn sqlite_error(error: rusqlite::Error) -> LongMemoryError {
627    LongMemoryError::storage(format!("SQLite archive failed: {error}"))
628}
629
630fn normalize_path(path: &str) -> Result<String, LongMemoryError> {
631    let path = path.trim();
632    if path.is_empty() {
633        return Err(LongMemoryError::invalid_path(
634            "long-memory path must not be empty",
635        ));
636    }
637    if path.len() > MAX_CONTEXT_PATH_BYTES {
638        return Err(LongMemoryError::invalid_path(format!(
639            "long-memory path must be at most {MAX_CONTEXT_PATH_BYTES} bytes"
640        )));
641    }
642    if path.chars().any(char::is_control) {
643        return Err(LongMemoryError::invalid_path(
644            "long-memory path must not contain control characters",
645        ));
646    }
647    if path.contains('\\') {
648        return Err(LongMemoryError::invalid_path(
649            "long-memory paths use forward slashes",
650        ));
651    }
652    if path == "/" {
653        return Ok(path.to_owned());
654    }
655
656    let path = path.trim_matches('/');
657    let mut segments = Vec::new();
658    for segment in path.split('/') {
659        if segment.is_empty() {
660            return Err(LongMemoryError::invalid_path(
661                "long-memory path must not contain empty segments",
662            ));
663        }
664        if matches!(segment, "." | "..") {
665            return Err(LongMemoryError::invalid_path(
666                "long-memory path must not contain '.' or '..' segments",
667            ));
668        }
669        segments.push(segment);
670    }
671    Ok(segments.join("/"))
672}
673
674fn disclose(content: &str, level: DisclosureLevel) -> String {
675    match level {
676        DisclosureLevel::Glance => {
677            let collapsed = content.split_whitespace().collect::<Vec<_>>().join(" ");
678            truncate(&collapsed, GLANCE_LIMIT)
679        }
680        DisclosureLevel::Overview => truncate(content, OVERVIEW_LIMIT),
681        DisclosureLevel::Detail => content.to_owned(),
682    }
683}
684
685fn truncate(value: &str, limit: usize) -> String {
686    if value.chars().count() <= limit {
687        return value.to_owned();
688    }
689
690    let mut truncated: String = value.chars().take(limit.saturating_sub(1)).collect();
691    truncated.push('…');
692    truncated
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698
699    #[test]
700    fn search_matches_paths_and_full_content_case_insensitively() {
701        let mut memory = LongMemoryManager::default();
702        memory
703            .update(
704                "knowledge/Architecture".to_owned(),
705                "Command bus".to_owned(),
706            )
707            .expect("valid path");
708        memory
709            .update(
710                "memory/user".to_owned(),
711                "Prefers concise output".to_owned(),
712            )
713            .expect("valid path");
714
715        assert_eq!(
716            memory.search("architecture", DisclosureLevel::Detail).len(),
717            1
718        );
719        assert_eq!(
720            memory.search("CONCISE", DisclosureLevel::Detail)[0].path,
721            "memory/user"
722        );
723        assert_eq!(memory.entries(DisclosureLevel::Detail).len(), 2);
724    }
725
726    #[test]
727    fn paths_are_canonical_and_cannot_traverse() {
728        let mut memory = LongMemoryManager::default();
729        let entry = memory
730            .update("/knowledge/design/".to_owned(), "content".to_owned())
731            .expect("leading and trailing slashes normalize");
732
733        assert_eq!(entry.path, "knowledge/design");
734        assert_eq!(
735            memory
736                .read("knowledge/design", DisclosureLevel::Detail)
737                .expect("valid path")
738                .expect("entry exists")
739                .content,
740            "content"
741        );
742        assert_eq!(
743            memory
744                .update("knowledge/../secret".to_owned(), "blocked".to_owned())
745                .expect_err("traversal is rejected")
746                .kind(),
747            LongMemoryErrorKind::InvalidPath
748        );
749        assert_eq!(
750            memory.delete("/knowledge/design/").expect("valid path"),
751            Some("knowledge/design".to_owned())
752        );
753    }
754
755    #[test]
756    fn disclosure_is_a_read_projection_not_stored_state() {
757        let mut memory = LongMemoryManager::default();
758        let content = format!("first line\n{}", "detail ".repeat(200));
759        let updated = memory
760            .update("knowledge/long".to_owned(), content.clone())
761            .expect("valid path");
762        assert_eq!(
763            updated.content, content,
764            "mutation facts retain complete content for event replay"
765        );
766
767        let glance = memory
768            .read("knowledge/long", DisclosureLevel::Glance)
769            .expect("valid path")
770            .expect("entry exists");
771        assert!(!glance.content.contains('\n'));
772        assert!(glance.content.chars().count() <= GLANCE_LIMIT);
773
774        assert_eq!(
775            memory
776                .search("first line", DisclosureLevel::Detail)
777                .first()
778                .expect("search result")
779                .content,
780            content
781        );
782    }
783
784    #[test]
785    fn archive_writes_are_idempotent_and_conflicts_are_rejected() {
786        let mut memory = LongMemoryManager::default();
787        memory
788            .put_archive(
789                "runtime-memory/abc/1-2",
790                "exact evidence".to_owned(),
791                "fnv1a64:1234".to_owned(),
792            )
793            .expect("first archive write succeeds");
794        memory
795            .put_archive(
796                "runtime-memory/abc/1-2",
797                "exact evidence".to_owned(),
798                "fnv1a64:1234".to_owned(),
799            )
800            .expect("identical archive write is idempotent");
801
802        let error = memory
803            .put_archive(
804                "runtime-memory/abc/1-2",
805                "different evidence".to_owned(),
806                "fnv1a64:5678".to_owned(),
807            )
808            .expect_err("identifier reuse with different evidence is rejected");
809
810        assert_eq!(error.kind(), LongMemoryErrorKind::Conflict);
811        assert_eq!(memory.archived_count().expect("count succeeds"), 1);
812    }
813
814    #[test]
815    fn archives_do_not_leak_into_normal_long_context_entries() {
816        let mut memory = LongMemoryManager::default();
817        memory
818            .update("knowledge/design".to_owned(), "visible".to_owned())
819            .expect("normal entry is valid");
820        memory
821            .put_archive(
822                "runtime-memory/abc/1-2",
823                "large exact evidence".to_owned(),
824                "fnv1a64:1234".to_owned(),
825            )
826            .expect("archive write succeeds");
827
828        assert_eq!(memory.entries(DisclosureLevel::Detail).len(), 1);
829        assert_eq!(
830            memory
831                .get_archive("runtime-memory/abc/1-2")
832                .expect("valid archive id")
833                .expect("archive exists")
834                .content,
835            "large exact evidence"
836        );
837    }
838
839    #[test]
840    fn file_archive_survives_reopening_and_rejects_conflicts() {
841        let root = unique_test_path("file-archive");
842        {
843            let mut store = FileArchiveStore::open(&root).expect("file archive opens");
844            store
845                .put_archive(
846                    "m/tool/read/file-evidence.json",
847                    "exact file evidence".to_owned(),
848                    "sha256:file".to_owned(),
849                )
850                .expect("archive persists");
851        }
852        let mut reopened = FileArchiveStore::open(&root).expect("file archive reopens");
853        assert_eq!(
854            reopened
855                .get_archive("m/tool/read/file-evidence.json")
856                .expect("archive read succeeds")
857                .expect("archive exists")
858                .content,
859            "exact file evidence"
860        );
861        assert_eq!(reopened.archive_count().expect("count succeeds"), 1);
862        assert_eq!(
863            reopened
864                .search_archives("file evidence", 5)
865                .expect("search succeeds")[0]
866                .memory_id,
867            "m/tool/read/file-evidence.json"
868        );
869        assert_eq!(
870            reopened
871                .put_archive(
872                    "m/tool/read/file-evidence.json",
873                    "different".to_owned(),
874                    "sha256:different".to_owned(),
875                )
876                .expect_err("conflict is rejected")
877                .kind(),
878            LongMemoryErrorKind::Conflict
879        );
880        fs::remove_dir_all(root).expect("test archive cleanup succeeds");
881    }
882
883    #[cfg(unix)]
884    #[test]
885    fn file_archive_keeps_evidence_owner_only() {
886        use std::os::unix::fs::PermissionsExt;
887
888        let root = unique_test_path("private-archive");
889        let mut store = FileArchiveStore::open(&root).expect("file archive opens");
890        store
891            .put_archive(
892                "m/tool/read/evidence.json",
893                "private evidence".to_owned(),
894                "sha256:private".to_owned(),
895            )
896            .expect("archive persists");
897        assert_eq!(
898            fs::metadata(&root).unwrap().permissions().mode() & 0o777,
899            0o700
900        );
901        let path = root.join("m/tool/read/evidence.json");
902        assert_eq!(
903            fs::metadata(path).unwrap().permissions().mode() & 0o777,
904            0o600
905        );
906        fs::remove_dir_all(root).ok();
907    }
908
909    #[test]
910    fn sqlite_archive_survives_reopening_and_is_idempotent() {
911        let root = unique_test_path("sqlite-archive");
912        let path = root.join("runtime-memory.sqlite3");
913        {
914            let mut store = SqliteArchiveStore::open(&path).expect("SQLite archive opens");
915            store
916                .put_archive(
917                    "runtime-memory/sqlite/3-4",
918                    "exact SQLite evidence".to_owned(),
919                    "sha256:sqlite".to_owned(),
920                )
921                .expect("archive persists");
922        }
923        let mut reopened = SqliteArchiveStore::open(&path).expect("SQLite archive reopens");
924        reopened
925            .put_archive(
926                "runtime-memory/sqlite/3-4",
927                "exact SQLite evidence".to_owned(),
928                "sha256:sqlite".to_owned(),
929            )
930            .expect("identical write remains idempotent after restart");
931        assert_eq!(reopened.archive_count().expect("count succeeds"), 1);
932        assert_eq!(
933            reopened
934                .search_archives("SQLite evidence", 5)
935                .expect("search succeeds")[0]
936                .memory_id,
937            "runtime-memory/sqlite/3-4"
938        );
939        assert_eq!(
940            reopened
941                .get_archive("runtime-memory/sqlite/3-4")
942                .expect("archive read succeeds")
943                .expect("archive exists")
944                .content,
945            "exact SQLite evidence"
946        );
947        drop(reopened);
948        fs::remove_dir_all(root).expect("test archive cleanup succeeds");
949    }
950
951    fn unique_test_path(label: &str) -> PathBuf {
952        std::env::temp_dir().join(format!(
953            "structure-{label}-{}-{}",
954            std::process::id(),
955            TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed)
956        ))
957    }
958}