Skip to main content

strands/storage/
local_file_storage.rs

1//! Local filesystem storage.
2
3use std::fmt;
4use std::io::{self, ErrorKind};
5use std::path::{Component, Path, PathBuf};
6use std::sync::Arc;
7
8use async_trait::async_trait;
9
10use super::search::{KeywordSearchStrategy, SearchStrategy, StorageSearchResult};
11use super::{Storage, normalize_key, normalize_prefix, sort_keys};
12use crate::error::{Error, Result, StorageError};
13use crate::sandbox::Sandbox;
14
15/// Marks the scratch file of an in-progress write; listings skip files whose name contains it.
16const TMP_MARKER: &str = ".__strands_tmp";
17
18/// The default base directory.
19const DEFAULT_BASE_DIR: &str = "./.strands/";
20
21/// Options for [`LocalFileStorage`] (`LocalFileStorageConfig`).
22#[derive(Clone, Default, bon::Builder)]
23pub struct LocalFileStorageConfig {
24    /// A sandbox to route all I/O through instead of the host filesystem; usually set with
25    /// [`LocalFileStorage::for_sandbox`]. Cannot be combined with a search strategy that
26    /// [requires host filesystem access](SearchStrategy::requires_host_fs).
27    pub sandbox: Option<Arc<dyn Sandbox>>,
28    /// Search strategy. When set, writes are indexed and [`LocalFileStorage::search`] delegates to
29    /// it instead of the default keyword scan.
30    pub search_strategy: Option<Arc<dyn SearchStrategy>>,
31}
32
33impl fmt::Debug for LocalFileStorageConfig {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        f.debug_struct("LocalFileStorageConfig")
36            .field("sandbox", &self.sandbox.is_some())
37            .field("search_strategy", &self.search_strategy.is_some())
38            .finish()
39    }
40}
41
42/// [`Storage`] that keeps each key as a file under a base directory (`LocalFileStorage`).
43///
44/// The key's `/` segments map onto directories: key `a/b.json` is the file `<base_dir>/a/b.json`.
45/// Writes are atomic: the bytes go to a scratch sibling that is then renamed over the target, so
46/// a crash mid-write never leaves a partial file. Missing directories are created on write. Bound
47/// to a [`Sandbox`] (see [`for_sandbox`](Self::for_sandbox)), all I/O goes through the sandbox
48/// instead, and atomicity is the sandbox's.
49///
50/// The harness keeps its sessions in `LocalFileStorage::new("./.agent").namespace("sessions")`,
51/// the on-disk layout shared with the other Strands harness SDKs.
52///
53/// ```
54/// use strands::storage::{LocalFileStorage, Storage};
55///
56/// # #[tokio::main(flavor = "current_thread")]
57/// # async fn main() -> strands::Result<()> {
58/// # let dir = tempfile::tempdir()?;
59/// # let root = dir.path().join(".agent");
60/// let sessions = LocalFileStorage::new(&root).namespace("sessions")?;
61/// sessions.write("abc/scopes/agent/default/snapshots/snapshot_latest.json", b"{}").await?;
62/// assert!(root.join("sessions/abc/scopes/agent/default/snapshots/snapshot_latest.json").is_file());
63/// # Ok(())
64/// # }
65/// ```
66#[derive(Clone)]
67pub struct LocalFileStorage {
68    base_dir: PathBuf,
69    namespaced: bool,
70    search_strategy: Option<Arc<dyn SearchStrategy>>,
71    sandbox: Option<Arc<dyn Sandbox>>,
72}
73
74impl LocalFileStorage {
75    /// Storage rooted at `base_dir`, using the default keyword search.
76    pub fn new(base_dir: impl AsRef<Path>) -> Self {
77        Self {
78            base_dir: base_dir.as_ref().components().collect(),
79            namespaced: false,
80            search_strategy: None,
81            sandbox: None,
82        }
83    }
84
85    /// Storage rooted at `base_dir`, with options.
86    ///
87    /// # Errors
88    ///
89    /// When `config` combines a sandbox with a search strategy that requires host filesystem
90    /// access.
91    pub fn with_config(base_dir: impl AsRef<Path>, config: LocalFileStorageConfig) -> Result<Self> {
92        if config.sandbox.is_some()
93            && let Some(strategy) = config
94                .search_strategy
95                .as_ref()
96                .filter(|strategy| strategy.requires_host_fs())
97        {
98            return Err(Error::other(format!(
99                "{} requires host filesystem access and cannot be used with a sandbox",
100                strategy.name()
101            )));
102        }
103        Ok(Self {
104            sandbox: config.sandbox,
105            search_strategy: config.search_strategy,
106            ..Self::new(base_dir)
107        })
108    }
109
110    /// A storage with the same base directory whose I/O goes through `sandbox`.
111    ///
112    /// Storage already bound to a sandbox comes back unchanged. A search strategy that requires
113    /// host filesystem access is dropped with a warning, falling back to the keyword scan, which
114    /// reads through the sandbox.
115    #[must_use]
116    pub fn for_sandbox(&self, sandbox: Arc<dyn Sandbox>) -> Self {
117        if self.sandbox.is_some() {
118            return self.clone();
119        }
120        let mut search_strategy = self.search_strategy.clone();
121        if let Some(strategy) = search_strategy.as_ref().filter(|strategy| strategy.requires_host_fs()) {
122            tracing::warn!(
123                "strategy=<{}> | search strategy requires host filesystem access and is not compatible with sandboxed storage | falling back to keyword search",
124                strategy.name()
125            );
126            search_strategy = None;
127        }
128        Self {
129            sandbox: Some(sandbox),
130            search_strategy,
131            namespaced: false,
132            base_dir: self.base_dir.clone(),
133        }
134    }
135
136    /// The root directory of this storage, with repeated and trailing separators removed.
137    #[must_use]
138    pub fn base_dir(&self) -> &Path {
139        &self.base_dir
140    }
141
142    /// A storage rooted at the `prefix` subdirectory, sharing this storage's search strategy.
143    ///
144    /// # Errors
145    ///
146    /// Returns a [`StorageError`] when the prefix contains a backslash, a `..` segment, or a
147    /// segment the platform does not read as one plain name (a Windows drive prefix).
148    pub fn namespace(&self, prefix: &str) -> Result<Self> {
149        let normalized = normalize_prefix(prefix)?;
150        let base_dir = join_segments(&self.base_dir, &normalized, "prefix", prefix)?;
151        Ok(Self {
152            base_dir,
153            namespaced: true,
154            search_strategy: self.search_strategy.clone(),
155            sandbox: self.sandbox.clone(),
156        })
157    }
158
159    /// Searches the stored files with the configured strategy or the default keyword scan.
160    ///
161    /// # Errors
162    ///
163    /// Returns the strategy's error, or a [`StorageError`] when the keyword scan cannot list.
164    pub async fn search(&self, query: &str) -> Result<Vec<StorageSearchResult>> {
165        match &self.search_strategy {
166            Some(strategy) => strategy.search(self, query).await,
167            None => KeywordSearchStrategy.search(self, query).await,
168        }
169    }
170
171    fn path_for(&self, normalized: &str, key: &str) -> Result<PathBuf> {
172        join_segments(&self.base_dir, normalized, "key", key)
173    }
174
175    /// The sandbox path of `relative` under the base directory (`/`-joined, as sandboxes may be
176    /// remote).
177    fn sandbox_path(&self, relative: &str) -> String {
178        let base = self.base_dir.to_string_lossy();
179        let base = base.trim_end_matches('/');
180        if relative.is_empty() {
181            base.to_owned()
182        } else {
183            format!("{base}/{relative}")
184        }
185    }
186
187    /// Every file key under the sandbox directory `dir`, whose key is `key_prefix`.
188    async fn walk_sandbox(&self, sandbox: &dyn Sandbox, dir: String, key_prefix: String) -> Result<Vec<String>> {
189        let mut found = Vec::new();
190        let mut pending = vec![(dir, key_prefix)];
191        while let Some((dir, prefix)) = pending.pop() {
192            let entries = match sandbox.list_files(&dir).await {
193                Ok(entries) => entries,
194                Err(error) if is_sandbox_not_found(&error) => continue,
195                Err(error) => {
196                    let message = format!("Failed to list sandbox storage under '{prefix}'");
197                    return Err(StorageError::new(message).with_source(error).into());
198                }
199            };
200            for entry in entries {
201                let is_dir = entry.is_dir == Some(true);
202                if !is_dir && entry.name.contains(TMP_MARKER) {
203                    continue;
204                }
205                let child_key = if prefix.is_empty() {
206                    entry.name.clone()
207                } else {
208                    format!("{prefix}/{}", entry.name)
209                };
210                if is_dir {
211                    pending.push((format!("{dir}/{}", entry.name), child_key));
212                } else {
213                    found.push(child_key);
214                }
215            }
216        }
217        Ok(found)
218    }
219
220    /// Every file key under `dir`, whose key is `key_prefix`; a missing directory has none.
221    async fn walk(&self, dir: PathBuf, key_prefix: String) -> Result<Vec<String>> {
222        let mut found = Vec::new();
223        let mut pending = vec![(dir, key_prefix)];
224        while let Some((dir, prefix)) = pending.pop() {
225            let entries = match read_dir_entries(&dir).await {
226                Ok(entries) => entries,
227                Err(error) if is_not_found(&error) => continue,
228                Err(error) => {
229                    let message = format!("Failed to list local storage under '{prefix}'");
230                    return Err(StorageError::new(message).with_source(error).into());
231                }
232            };
233            for (name, is_dir) in entries {
234                if !is_dir && name.contains(TMP_MARKER) {
235                    continue;
236                }
237                let child_key = if prefix.is_empty() {
238                    name.clone()
239                } else {
240                    format!("{prefix}/{name}")
241                };
242                if is_dir {
243                    pending.push((dir.join(&name), child_key));
244                } else {
245                    found.push(child_key);
246                }
247            }
248        }
249        Ok(found)
250    }
251}
252
253impl Default for LocalFileStorage {
254    /// Storage rooted at `./.strands/`.
255    fn default() -> Self {
256        Self::new(DEFAULT_BASE_DIR)
257    }
258}
259
260impl fmt::Debug for LocalFileStorage {
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        f.debug_struct("LocalFileStorage")
263            .field("base_dir", &self.base_dir)
264            .field("search_strategy", &self.search_strategy.is_some())
265            .field("sandbox", &self.sandbox.is_some())
266            .finish_non_exhaustive()
267    }
268}
269
270/// `base` with each `/` segment of `normalized` pushed in turn. A segment that the platform reads
271/// as more than one plain name (a Windows drive prefix such as `C:`) would make the push replace
272/// `base`, so it is rejected.
273fn join_segments(base: &Path, normalized: &str, kind: &str, original: &str) -> Result<PathBuf> {
274    let mut path = base.to_path_buf();
275    for segment in normalized.split('/').filter(|segment| !segment.is_empty()) {
276        let mut components = Path::new(segment).components();
277        let plain = matches!(
278            (components.next(), components.next()),
279            (Some(Component::Normal(_) | Component::CurDir), None)
280        );
281        if !plain {
282            let message = format!("Invalid storage {kind} '{original}': '{segment}' is not a plain path segment");
283            return Err(StorageError::new(message).into());
284        }
285        path.push(segment);
286    }
287    Ok(path)
288}
289
290/// A missing path, or a path through a file (`ENOENT`, `ENOTDIR`).
291fn is_not_found(error: &io::Error) -> bool {
292    matches!(error.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory)
293}
294
295/// Whether a sandbox error reports a missing path.
296fn is_sandbox_not_found(error: &Error) -> bool {
297    match error {
298        Error::SandboxPathNotFound(_) => true,
299        Error::Other(source) => source.downcast_ref::<io::Error>().is_some_and(is_not_found),
300        _ => false,
301    }
302}
303
304/// The names of `dir`'s entries and whether each is a directory (symlinks are not followed).
305async fn read_dir_entries(dir: &Path) -> io::Result<Vec<(String, bool)>> {
306    let mut entries = tokio::fs::read_dir(dir).await?;
307    let mut found = Vec::new();
308    while let Some(entry) = entries.next_entry().await? {
309        let is_dir = entry.file_type().await?.is_dir();
310        found.push((entry.file_name().to_string_lossy().into_owned(), is_dir));
311    }
312    Ok(found)
313}
314
315fn scratch_path(path: &Path) -> PathBuf {
316    let mut scratch = path.as_os_str().to_owned();
317    scratch.push(format!("{TMP_MARKER}_{}", uuid::Uuid::new_v4()));
318    PathBuf::from(scratch)
319}
320
321async fn write_atomically(path: &Path, scratch: &Path, data: &[u8]) -> io::Result<()> {
322    if let Some(parent) = path.parent() {
323        tokio::fs::create_dir_all(parent).await?;
324    }
325    tokio::fs::write(scratch, data).await?;
326    tokio::fs::rename(scratch, path).await
327}
328
329#[async_trait]
330impl Storage for LocalFileStorage {
331    async fn write(&self, key: &str, data: &[u8]) -> Result<()> {
332        let normalized = normalize_key(key)?;
333        if let Some(sandbox) = &self.sandbox {
334            let path = self.sandbox_path(&normalized);
335            return sandbox.write_file(&path, data).await.map_err(|error| {
336                let message = format!("Failed to write '{normalized}' to sandbox storage");
337                StorageError::new(message).with_source(error).into()
338            });
339        }
340        let path = self.path_for(&normalized, key)?;
341        let scratch = scratch_path(&path);
342        if let Err(error) = write_atomically(&path, &scratch, data).await {
343            tokio::fs::remove_file(&scratch).await.ok();
344            let message = format!("Failed to write '{normalized}' to local storage");
345            return Err(StorageError::new(message).with_source(error).into());
346        }
347        if let Some(strategy) = &self.search_strategy {
348            strategy.index(self, &normalized, data).await?;
349        }
350        Ok(())
351    }
352
353    async fn read(&self, key: &str) -> Result<Option<Vec<u8>>> {
354        let normalized = normalize_key(key)?;
355        if let Some(sandbox) = &self.sandbox {
356            return match sandbox.read_file(&self.sandbox_path(&normalized)).await {
357                Ok(bytes) => Ok(Some(bytes)),
358                Err(error) if is_sandbox_not_found(&error) => Ok(None),
359                Err(error) => {
360                    let message = format!("Failed to read '{normalized}' from sandbox storage");
361                    Err(StorageError::new(message).with_source(error).into())
362                }
363            };
364        }
365        match tokio::fs::read(self.path_for(&normalized, key)?).await {
366            Ok(bytes) => Ok(Some(bytes)),
367            Err(error) if is_not_found(&error) => Ok(None),
368            Err(error) => {
369                let message = format!("Failed to read '{normalized}' from local storage");
370                Err(StorageError::new(message).with_source(error).into())
371            }
372        }
373    }
374
375    async fn delete(&self, key: &str) -> Result<()> {
376        let normalized = normalize_key(key)?;
377        if let Some(sandbox) = &self.sandbox {
378            return match sandbox.remove_file(&self.sandbox_path(&normalized)).await {
379                Ok(()) => Ok(()),
380                Err(error) if is_sandbox_not_found(&error) => Ok(()),
381                Err(error) => {
382                    let message = format!("Failed to delete '{normalized}' from sandbox storage");
383                    Err(StorageError::new(message).with_source(error).into())
384                }
385            };
386        }
387        match tokio::fs::remove_file(self.path_for(&normalized, key)?).await {
388            Ok(()) => Ok(()),
389            Err(error) if is_not_found(&error) => Ok(()),
390            Err(error) => {
391                let message = format!("Failed to delete '{normalized}' from local storage");
392                Err(StorageError::new(message).with_source(error).into())
393            }
394        }
395    }
396
397    async fn list(&self, prefix: &str) -> Result<Vec<String>> {
398        let normalized = normalize_prefix(prefix)?;
399        let dir_portion = normalized.rfind('/').map_or("", |slash| &normalized[..slash]);
400        let mut keys = match &self.sandbox {
401            Some(sandbox) => {
402                self.walk_sandbox(sandbox.as_ref(), self.sandbox_path(dir_portion), dir_portion.to_owned())
403                    .await?
404            }
405            None => {
406                let start_dir = join_segments(&self.base_dir, dir_portion, "prefix", prefix)?;
407                self.walk(start_dir, dir_portion.to_owned()).await?
408            }
409        };
410        keys.retain(|key| key.starts_with(&normalized));
411        sort_keys(&mut keys);
412        Ok(keys)
413    }
414
415    fn namespace(&self, prefix: &str) -> Option<Result<Arc<dyn Storage>>> {
416        Some(Self::namespace(self, prefix).map(|scoped| Arc::new(scoped) as Arc<dyn Storage>))
417    }
418
419    async fn search(&self, query: &str) -> Option<Result<Vec<StorageSearchResult>>> {
420        Some(Self::search(self, query).await)
421    }
422
423    fn storage_type(&self) -> &str {
424        "LocalFileStorage"
425    }
426
427    fn is_namespaced(&self) -> bool {
428        self.namespaced
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use std::sync::Mutex;
435
436    use tempfile::TempDir;
437
438    use super::*;
439    use crate::sandbox::NotASandboxLocalEnvironment;
440
441    fn setup() -> (TempDir, PathBuf, LocalFileStorage) {
442        let dir = tempfile::tempdir().unwrap();
443        let base = dir.path().join("strands-test");
444        let storage = LocalFileStorage::new(&base);
445        (dir, base, storage)
446    }
447
448    #[tokio::test]
449    async fn round_trips_bytes() {
450        let (_dir, _base, storage) = setup();
451        storage.write("test/file.txt", b"hello world").await.unwrap();
452        assert_eq!(
453            storage.read("test/file.txt").await.unwrap(),
454            Some(b"hello world".to_vec())
455        );
456    }
457
458    #[tokio::test]
459    async fn creates_nested_directories() {
460        let (_dir, base, storage) = setup();
461        storage.write("deep/nested/path/file.bin", &[1, 2, 3]).await.unwrap();
462        assert!(base.join("deep/nested/path/file.bin").is_file());
463    }
464
465    #[tokio::test]
466    async fn overwrites_existing_values() {
467        let (_dir, _base, storage) = setup();
468        storage.write("key", b"first").await.unwrap();
469        storage.write("key", b"second").await.unwrap();
470        assert_eq!(storage.read("key").await.unwrap(), Some(b"second".to_vec()));
471    }
472
473    #[tokio::test]
474    async fn returns_null_for_missing_keys() {
475        let (_dir, _base, storage) = setup();
476        assert_eq!(storage.read("nonexistent/key").await.unwrap(), None);
477    }
478
479    #[tokio::test]
480    async fn writes_atomically_via_tmp_file() {
481        let (_dir, base, storage) = setup();
482        storage.write("atomic/test", &[1]).await.unwrap();
483        assert_eq!(std::fs::read(base.join("atomic/test")).unwrap(), [1]);
484        assert!(!base.join("atomic/test.tmp").exists());
485        let names: Vec<String> = std::fs::read_dir(base.join("atomic"))
486            .unwrap()
487            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
488            .collect();
489        assert_eq!(names, ["test"]);
490    }
491
492    #[cfg(unix)]
493    #[tokio::test]
494    async fn cleans_up_tmp_file_on_rename_failure() {
495        use std::os::unix::fs::PermissionsExt;
496
497        let (_dir, base, storage) = setup();
498        let dir = base.join("readonly");
499        std::fs::create_dir_all(&dir).unwrap();
500        std::fs::write(dir.join("target"), "original").unwrap();
501        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap();
502
503        let result = storage.write("readonly/target", &[1]).await;
504        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
505
506        let error = result.unwrap_err();
507        assert_eq!(error.to_string(), "Failed to write 'readonly/target' to local storage");
508        assert!(std::error::Error::source(&error).is_some());
509        let leftovers = std::fs::read_dir(&dir)
510            .unwrap()
511            .filter(|entry| {
512                entry
513                    .as_ref()
514                    .unwrap()
515                    .file_name()
516                    .to_string_lossy()
517                    .contains(TMP_MARKER)
518            })
519            .count();
520        assert_eq!(leftovers, 0);
521    }
522
523    #[tokio::test]
524    async fn cleans_up_tmp_file_when_the_target_is_a_directory() {
525        let (_dir, base, storage) = setup();
526        std::fs::create_dir_all(base.join("taken/child")).unwrap();
527        let error = storage.write("taken", &[1]).await.unwrap_err();
528        assert_eq!(error.to_string(), "Failed to write 'taken' to local storage");
529        let leftovers = std::fs::read_dir(&base)
530            .unwrap()
531            .filter(|entry| {
532                entry
533                    .as_ref()
534                    .unwrap()
535                    .file_name()
536                    .to_string_lossy()
537                    .contains(TMP_MARKER)
538            })
539            .count();
540        assert_eq!(leftovers, 0);
541    }
542
543    #[tokio::test]
544    async fn rejects_keys_containing_backslashes() {
545        let (_dir, _base, storage) = setup();
546        let error = storage.write("foo\\bar", &[1]).await.unwrap_err();
547        assert!(error.to_string().contains("backslashes are not allowed"), "{error}");
548    }
549
550    #[tokio::test]
551    async fn rejects_backslash_path_traversal() {
552        let (_dir, _base, storage) = setup();
553        let error = storage.read("foo\\..\\..\\etc\\passwd").await.unwrap_err();
554        assert!(error.to_string().contains("backslashes are not allowed"), "{error}");
555    }
556
557    #[tokio::test]
558    async fn rejects_dot_dot_path_traversal() {
559        let (_dir, _base, storage) = setup();
560        let error = storage.write("../escaped", &[1]).await.unwrap_err();
561        assert_eq!(
562            error.to_string(),
563            "Invalid storage key '../escaped': '..' path segments are not allowed"
564        );
565    }
566
567    #[tokio::test]
568    async fn removes_an_existing_key() {
569        let (_dir, _base, storage) = setup();
570        storage.write("deleteme", &[1]).await.unwrap();
571        storage.delete("deleteme").await.unwrap();
572        assert_eq!(storage.read("deleteme").await.unwrap(), None);
573    }
574
575    #[tokio::test]
576    async fn is_a_no_op_for_missing_keys() {
577        let (_dir, _base, storage) = setup();
578        storage.delete("nonexistent").await.unwrap();
579        storage.write("file", &[1]).await.unwrap();
580        storage.delete("file/child").await.unwrap();
581    }
582
583    #[tokio::test]
584    async fn lists_keys_under_a_prefix() {
585        let (_dir, _base, storage) = setup();
586        storage.write("sessions/a/data.json", &[1]).await.unwrap();
587        storage.write("sessions/b/data.json", &[2]).await.unwrap();
588        storage.write("memory/notes.json", &[3]).await.unwrap();
589        assert_eq!(
590            storage.list("sessions/").await.unwrap(),
591            ["sessions/a/data.json", "sessions/b/data.json"]
592        );
593    }
594
595    #[tokio::test]
596    async fn returns_all_keys_for_empty_prefix() {
597        let (_dir, _base, storage) = setup();
598        storage.write("a", &[1]).await.unwrap();
599        storage.write("b", &[2]).await.unwrap();
600        assert_eq!(storage.list("").await.unwrap(), ["a", "b"]);
601    }
602
603    #[tokio::test]
604    async fn returns_empty_array_when_base_directory_does_not_exist() {
605        let dir = tempfile::tempdir().unwrap();
606        let fresh = LocalFileStorage::new(dir.path().join("nonexistent"));
607        assert!(fresh.list("").await.unwrap().is_empty());
608        assert!(fresh.list("deep/prefix/").await.unwrap().is_empty());
609    }
610
611    #[tokio::test]
612    async fn excludes_scratch_files() {
613        let (_dir, base, storage) = setup();
614        storage.write("real", &[1]).await.unwrap();
615        std::fs::write(base.join("leftover.__strands_tmp"), "garbage").unwrap();
616        assert_eq!(storage.list("").await.unwrap(), ["real"]);
617    }
618
619    #[tokio::test]
620    async fn does_not_exclude_user_tmp_files() {
621        let (_dir, _base, storage) = setup();
622        storage.write("notes.tmp", &[1]).await.unwrap();
623        assert!(storage.list("").await.unwrap().contains(&"notes.tmp".to_owned()));
624    }
625
626    #[tokio::test]
627    async fn returns_keys_sorted_lexicographically() {
628        let (_dir, _base, storage) = setup();
629        for key in ["c", "a", "b/z", "b/a"] {
630            storage.write(key, &[1]).await.unwrap();
631        }
632        assert_eq!(storage.list("").await.unwrap(), ["a", "b/a", "b/z", "c"]);
633    }
634
635    #[tokio::test]
636    async fn matches_a_partial_last_segment() {
637        let (_dir, _base, storage) = setup();
638        for key in ["sessions/abc/x", "sessions/abd/y", "sessions/b/z", "sessionsx"] {
639            storage.write(key, &[1]).await.unwrap();
640        }
641        assert_eq!(
642            storage.list("sessions/ab").await.unwrap(),
643            ["sessions/abc/x", "sessions/abd/y"]
644        );
645        assert_eq!(
646            storage.list("sessions").await.unwrap(),
647            ["sessions/abc/x", "sessions/abd/y", "sessions/b/z", "sessionsx"]
648        );
649    }
650
651    #[tokio::test]
652    async fn returns_a_local_file_storage_instance_rooted_at_the_subdirectory() {
653        let (_dir, base, storage) = setup();
654        let namespaced = storage.namespace("sub/dir").unwrap();
655        namespaced.write("file.txt", &[1, 2, 3]).await.unwrap();
656        assert_eq!(namespaced.read("file.txt").await.unwrap(), Some(vec![1, 2, 3]));
657        assert_eq!(namespaced.list("").await.unwrap(), ["file.txt"]);
658        assert!(base.join("sub/dir/file.txt").is_file());
659        assert!(Storage::is_namespaced(&namespaced));
660        assert_eq!(namespaced.storage_type(), "LocalFileStorage");
661    }
662
663    #[tokio::test]
664    async fn isolates_keys_from_the_parent_storage() {
665        let (_dir, _base, storage) = setup();
666        let namespaced = storage.namespace("isolated").unwrap();
667        storage.write("root.txt", &[1]).await.unwrap();
668        namespaced.write("child.txt", &[2]).await.unwrap();
669        let parent_keys = storage.list("").await.unwrap();
670        assert!(parent_keys.contains(&"root.txt".to_owned()));
671        assert!(!parent_keys.contains(&"child.txt".to_owned()));
672        assert_eq!(namespaced.list("").await.unwrap(), ["child.txt"]);
673    }
674
675    #[test]
676    fn exposes_base_dir_pointing_to_the_subdirectory() {
677        let (_dir, base, storage) = setup();
678        assert_eq!(storage.namespace("nested").unwrap().base_dir(), base.join("nested"));
679        assert_eq!(storage.namespace("nested/").unwrap().base_dir(), base.join("nested"));
680    }
681
682    #[test]
683    fn base_dir_collapses_separators_and_defaults_to_dot_strands() {
684        assert_eq!(LocalFileStorage::new("/tmp//a/").base_dir(), Path::new("/tmp/a"));
685        assert_eq!(LocalFileStorage::new("/").base_dir(), Path::new("/"));
686        assert_eq!(LocalFileStorage::default().base_dir(), Path::new("./.strands"));
687        assert!(!Storage::is_ephemeral(&LocalFileStorage::default()));
688    }
689
690    #[derive(Default)]
691    struct Recording {
692        indexed: Mutex<Vec<(String, Vec<u8>)>>,
693        queries: Mutex<Vec<String>>,
694    }
695
696    #[async_trait]
697    impl SearchStrategy for Recording {
698        async fn index(&self, _storage: &dyn Storage, key: &str, data: &[u8]) -> Result<()> {
699            self.indexed.lock().unwrap().push((key.to_owned(), data.to_vec()));
700            Ok(())
701        }
702
703        async fn search(&self, _storage: &dyn Storage, query: &str) -> Result<Vec<StorageSearchResult>> {
704            self.queries.lock().unwrap().push(query.to_owned());
705            Ok(vec![StorageSearchResult::new("hit.txt", 1.0)])
706        }
707    }
708
709    fn config(strategy: &Arc<Recording>) -> LocalFileStorageConfig {
710        LocalFileStorageConfig::builder()
711            .search_strategy(Arc::clone(strategy) as Arc<dyn SearchStrategy>)
712            .build()
713    }
714
715    #[tokio::test]
716    async fn indexes_writes_and_delegates_search_to_a_search_strategy_from_config() {
717        let (_dir, base, _storage) = setup();
718        let strategy = Arc::new(Recording::default());
719        let configured = LocalFileStorage::with_config(&base, config(&strategy)).unwrap();
720        configured.write("a.txt", &[1]).await.unwrap();
721        assert_eq!(*strategy.indexed.lock().unwrap(), [("a.txt".to_owned(), vec![1])]);
722        assert_eq!(
723            configured.search("query").await.unwrap(),
724            [StorageSearchResult::new("hit.txt", 1.0)]
725        );
726        assert_eq!(*strategy.queries.lock().unwrap(), ["query"]);
727    }
728
729    #[tokio::test]
730    async fn carries_a_search_strategy_from_config_through_namespace() {
731        let (_dir, base, _storage) = setup();
732        let strategy = Arc::new(Recording::default());
733        let configured = LocalFileStorage::with_config(&base, config(&strategy)).unwrap();
734        configured.search("one").await.unwrap();
735        configured.namespace("sub").unwrap().search("two").await.unwrap();
736        assert_eq!(*strategy.queries.lock().unwrap(), ["one", "two"]);
737    }
738
739    #[tokio::test]
740    async fn uses_the_keyword_scan_without_a_strategy() {
741        let (_dir, _base, storage) = setup();
742        storage.write("auth.md", b"OAuth2 authentication flow").await.unwrap();
743        let results = storage.search("authentication").await.unwrap();
744        assert_eq!(results.iter().map(|r| r.key.as_str()).collect::<Vec<_>>(), ["auth.md"]);
745    }
746
747    #[tokio::test]
748    async fn reports_read_failures_other_than_a_missing_key() {
749        let (_dir, base, storage) = setup();
750        std::fs::create_dir_all(base.join("folder")).unwrap();
751        let error = storage.read("folder").await.unwrap_err();
752        assert_eq!(error.to_string(), "Failed to read 'folder' from local storage");
753        assert_eq!(error.name(), "StorageError");
754    }
755
756    /// Records the paths it writes, and reads and lists through the host.
757    #[derive(Default)]
758    struct WriteRecording {
759        writes: Mutex<Vec<String>>,
760        missing_reads: bool,
761    }
762
763    #[async_trait]
764    impl Sandbox for WriteRecording {
765        fn execute_streaming(
766            &self,
767            command: &str,
768            options: crate::sandbox::ExecuteOptions,
769        ) -> crate::sandbox::ExecutionStream {
770            crate::sandbox::default_sandbox().execute_streaming(command, options)
771        }
772
773        fn execute_code_streaming(
774            &self,
775            code: &str,
776            language: &str,
777            options: crate::sandbox::ExecuteOptions,
778        ) -> crate::sandbox::ExecutionStream {
779            crate::sandbox::default_sandbox().execute_code_streaming(code, language, options)
780        }
781
782        async fn read_file(&self, path: &str) -> Result<Vec<u8>> {
783            if self.missing_reads {
784                return Err(crate::SandboxPathNotFoundError::new(path).into());
785            }
786            crate::sandbox::default_sandbox().read_file(path).await
787        }
788
789        async fn write_file(&self, path: &str, content: &[u8]) -> Result<()> {
790            self.writes.lock().unwrap().push(path.to_owned());
791            crate::sandbox::default_sandbox().write_file(path, content).await
792        }
793
794        async fn remove_file(&self, path: &str) -> Result<()> {
795            crate::sandbox::default_sandbox().remove_file(path).await
796        }
797
798        async fn list_files(&self, path: &str) -> Result<Vec<crate::sandbox::FileInfo>> {
799            crate::sandbox::default_sandbox().list_files(path).await
800        }
801    }
802
803    /// A strategy that declares it needs the host filesystem.
804    struct HostIndexStrategy;
805
806    #[async_trait]
807    impl SearchStrategy for HostIndexStrategy {
808        fn requires_host_fs(&self) -> bool {
809            true
810        }
811
812        fn name(&self) -> &str {
813            "HostIndexStrategy"
814        }
815
816        async fn search(&self, _storage: &dyn Storage, _query: &str) -> Result<Vec<StorageSearchResult>> {
817            Ok(Vec::new())
818        }
819    }
820
821    fn sandboxed(
822        base: &Path,
823        sandbox: Arc<dyn Sandbox>,
824        strategy: Option<Arc<dyn SearchStrategy>>,
825    ) -> Result<LocalFileStorage> {
826        LocalFileStorage::with_config(
827            base,
828            LocalFileStorageConfig {
829                sandbox: Some(sandbox),
830                search_strategy: strategy,
831            },
832        )
833    }
834
835    #[tokio::test]
836    async fn routes_io_through_a_sandbox_from_config() {
837        let (_dir, base, _storage) = setup();
838        let sandbox = Arc::new(WriteRecording::default());
839        let configured = sandboxed(&base, sandbox.clone(), None).unwrap();
840        configured.write("a.txt", &[1]).await.unwrap();
841        assert_eq!(*sandbox.writes.lock().unwrap(), [format!("{}/a.txt", base.display())]);
842        assert_eq!(configured.read("a.txt").await.unwrap(), Some(vec![1]));
843        assert_eq!(configured.list("").await.unwrap(), ["a.txt"]);
844        configured.delete("a.txt").await.unwrap();
845        configured.delete("a.txt").await.unwrap();
846        assert_eq!(configured.read("a.txt").await.unwrap(), None);
847    }
848
849    #[tokio::test]
850    async fn treats_sandbox_path_not_found_error_from_the_sandbox_as_a_missing_key() {
851        let (_dir, base, _storage) = setup();
852        let sandbox = Arc::new(WriteRecording {
853            missing_reads: true,
854            ..WriteRecording::default()
855        });
856        let storage = sandboxed(&base, sandbox, None).unwrap();
857        assert_eq!(storage.read("missing.txt").await.unwrap(), None);
858        assert!(storage.list("no-such-dir/").await.unwrap().is_empty());
859    }
860
861    #[tokio::test]
862    async fn accepts_a_sandbox_and_search_strategy() {
863        let (_dir, base, _storage) = setup();
864        let sandbox = Arc::new(WriteRecording::default());
865        let strategy = Arc::new(Recording::default());
866        let storage = sandboxed(&base, sandbox.clone(), Some(strategy.clone())).unwrap();
867        storage.write("a.txt", &[1]).await.unwrap();
868        assert_eq!(sandbox.writes.lock().unwrap().len(), 1);
869        storage.search("query").await.unwrap();
870        assert_eq!(*strategy.queries.lock().unwrap(), ["query"]);
871    }
872
873    #[tokio::test]
874    async fn carries_a_search_strategy_from_config_through_for_sandbox_and_namespace() {
875        let (_dir, base, _storage) = setup();
876        let strategy = Arc::new(Recording::default());
877        let configured = LocalFileStorage::with_config(&base, config(&strategy)).unwrap();
878        configured
879            .for_sandbox(Arc::new(NotASandboxLocalEnvironment::new()))
880            .search("one")
881            .await
882            .unwrap();
883        configured.namespace("sub").unwrap().search("two").await.unwrap();
884        assert_eq!(*strategy.queries.lock().unwrap(), ["one", "two"]);
885    }
886
887    #[test]
888    fn rejects_a_host_filesystem_strategy_passed_with_a_sandbox_in_config() {
889        let error = sandboxed(
890            Path::new("/tmp/x"),
891            Arc::new(NotASandboxLocalEnvironment::new()),
892            Some(Arc::new(HostIndexStrategy)),
893        )
894        .unwrap_err();
895        assert_eq!(
896            error.to_string(),
897            "HostIndexStrategy requires host filesystem access and cannot be used with a sandbox"
898        );
899    }
900
901    #[tokio::test]
902    async fn accepts_a_sandbox_safe_strategy_passed_with_a_sandbox() {
903        let (_dir, base, _storage) = setup();
904        let strategy = Arc::new(Recording::default());
905        let storage = sandboxed(
906            &base,
907            Arc::new(NotASandboxLocalEnvironment::new()),
908            Some(strategy.clone()),
909        )
910        .unwrap();
911        storage.search("query").await.unwrap();
912        assert_eq!(strategy.queries.lock().unwrap().len(), 1);
913    }
914
915    #[tokio::test]
916    async fn drops_a_host_filesystem_strategy_in_for_sandbox_and_falls_back_to_keyword_search() {
917        let (_dir, base, _storage) = setup();
918        let host = LocalFileStorage::with_config(
919            &base,
920            LocalFileStorageConfig::builder()
921                .search_strategy(Arc::new(HostIndexStrategy) as Arc<dyn SearchStrategy>)
922                .build(),
923        )
924        .unwrap();
925        let (bound, logs) =
926            crate::test_support::capture_logs(|| host.for_sandbox(Arc::new(NotASandboxLocalEnvironment::new())));
927        assert!(logs.contains(
928            "strategy=<HostIndexStrategy> | search strategy requires host filesystem access and is not compatible with sandboxed storage | falling back to keyword search"
929        ), "{logs}");
930        bound.write("auth.md", b"OAuth2 authentication flow").await.unwrap();
931        let results = bound.search("authentication").await.unwrap();
932        assert_eq!(results.iter().map(|r| r.key.as_str()).collect::<Vec<_>>(), ["auth.md"]);
933    }
934
935    #[tokio::test]
936    async fn keeps_a_sandbox_safe_strategy_in_for_sandbox() {
937        let (_dir, base, _storage) = setup();
938        let strategy = Arc::new(Recording::default());
939        let bound = LocalFileStorage::with_config(&base, config(&strategy))
940            .unwrap()
941            .for_sandbox(Arc::new(NotASandboxLocalEnvironment::new()));
942        bound.search("query").await.unwrap();
943        assert_eq!(strategy.queries.lock().unwrap().len(), 1);
944    }
945
946    #[test]
947    fn returns_storage_already_bound_to_a_sandbox_unchanged() {
948        let sandbox: Arc<dyn Sandbox> = Arc::new(NotASandboxLocalEnvironment::new());
949        let bound = LocalFileStorage::new("/tmp/x").for_sandbox(sandbox.clone());
950        let again = bound.for_sandbox(Arc::new(NotASandboxLocalEnvironment::new()));
951        assert!(Arc::ptr_eq(again.sandbox.as_ref().unwrap(), &sandbox));
952    }
953
954    fn files_under(dir: &Path) -> Vec<PathBuf> {
955        let mut found = Vec::new();
956        for entry in std::fs::read_dir(dir).unwrap() {
957            let path = entry.unwrap().path();
958            if path.is_dir() {
959                found.extend(files_under(&path));
960            } else {
961                found.push(path);
962            }
963        }
964        found
965    }
966
967    #[tokio::test]
968    async fn keeps_every_write_under_the_base_directory() {
969        let (dir, base, storage) = setup();
970        for key in [
971            "/etc/abs_probe",
972            "./dot",
973            "a/./b",
974            "a/.../b",
975            "~/home_probe",
976            "C:/win",
977            "C:x",
978        ] {
979            let written = storage.write(key, b"v").await;
980            // Windows rejects a drive prefix and strips the trailing dots that make `...` a name.
981            if cfg!(windows) && (key.starts_with("C:") || key.contains("/.../")) {
982                assert!(written.is_err(), "{key}");
983            } else {
984                written.unwrap();
985            }
986        }
987        for key in ["../x", "a/../../x", "a\\b", ".", ".."] {
988            assert!(storage.write(key, b"v").await.is_err(), "{key}");
989        }
990        let outside: Vec<PathBuf> = files_under(dir.path())
991            .into_iter()
992            .filter(|path| !path.starts_with(&base))
993            .collect();
994        assert!(outside.is_empty(), "{outside:?}");
995    }
996
997    #[test]
998    fn rejects_a_segment_that_is_not_one_plain_name() {
999        let base = Path::new("base");
1000        assert_eq!(
1001            join_segments(base, "a/./b", "key", "a/./b").unwrap(),
1002            Path::new("base/a/./b")
1003        );
1004        if cfg!(windows) {
1005            for key in ["C:/win", "C:x"] {
1006                let error = join_segments(base, key, "key", key).unwrap_err();
1007                assert!(
1008                    error.to_string().starts_with(&format!("Invalid storage key '{key}'")),
1009                    "{error}"
1010                );
1011            }
1012        }
1013    }
1014}