second-brain-cli 0.13.5

Memory layer for AI coding agents: ingest, recall, and sync across machines
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

/// Markers older than this are pruned, so a session resumed after that long
/// may be asked once more.
const KEEP: Duration = Duration::from_secs(14 * 24 * 60 * 60);

pub(super) const MAX_ID_LEN: usize = 128;

/// Hook ids become file names, so anything but a plain id is refused.
pub(super) fn is_plain_id(id: &str) -> bool {
    !id.is_empty()
        && id.len() <= MAX_ID_LEN
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}

/// One empty file per session a hook has already asked something of, so a
/// request the agent could not satisfy is not repeated on every turn.
pub(super) struct Asked {
    dir: PathBuf,
}

impl Asked {
    pub(super) fn new(data_dir: &Path, hook: &str) -> Self {
        Asked {
            dir: data_dir.join("hooks").join(format!("{hook}-asked")),
        }
    }

    fn marker(&self, session_id: &str) -> Option<PathBuf> {
        is_plain_id(session_id).then(|| self.dir.join(session_id))
    }

    pub(super) fn already(&self, session_id: &str) -> bool {
        self.marker(session_id).is_some_and(|path| path.exists())
    }

    /// False when the ask could not be recorded; the caller then does not
    /// ask, because an unrecorded ask would repeat on every turn.
    pub(super) fn record(&self, session_id: &str, now: SystemTime) -> bool {
        let Some(path) = self.marker(session_id) else {
            return false;
        };
        if let Err(e) = std::fs::create_dir_all(&self.dir).and_then(|()| std::fs::write(&path, b""))
        {
            eprintln!(
                "sb hook: recording the ask in {} failed: {e}",
                self.dir.display()
            );
            return false;
        }
        self.prune(now);
        true
    }

    fn prune(&self, now: SystemTime) {
        let Ok(entries) = std::fs::read_dir(&self.dir) else {
            return;
        };
        for entry in entries.flatten() {
            let stale = entry
                .metadata()
                .and_then(|m| m.modified())
                .is_ok_and(|at| now.duration_since(at).is_ok_and(|age| age > KEEP));
            if stale && let Err(e) = std::fs::remove_file(entry.path()) {
                eprintln!("sb hook: pruning {} failed: {e}", entry.path().display());
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_recorded_session_is_known_and_others_are_not() {
        let dir = tempfile::tempdir().unwrap();
        let asked = Asked::new(dir.path(), "stop");
        assert!(!asked.already("s-1"));
        assert!(asked.record("s-1", SystemTime::now()));
        assert!(asked.already("s-1"));
        assert!(!asked.already("s-2"));
    }

    #[test]
    fn ids_that_are_not_plain_are_never_recorded() {
        let dir = tempfile::tempdir().unwrap();
        let asked = Asked::new(dir.path(), "stop");
        let long = "a".repeat(MAX_ID_LEN + 1);
        for id in ["", "../escape", "a/b", ".", "a b", long.as_str()] {
            assert!(!asked.record(id, SystemTime::now()), "{id:?}");
            assert!(!asked.already(id), "{id:?}");
        }
        assert!(!dir.path().join("hooks").exists());
    }

    #[test]
    fn recording_prunes_markers_older_than_the_keep_window() {
        let dir = tempfile::tempdir().unwrap();
        let asked = Asked::new(dir.path(), "stop");
        let now = SystemTime::now();
        assert!(asked.record("old", now));
        assert!(asked.record("recent", now));
        let marker = |id: &str| {
            std::fs::File::options()
                .write(true)
                .open(asked.dir.join(id))
        };
        marker("old")
            .unwrap()
            .set_modified(now - KEEP - Duration::from_secs(60))
            .unwrap();
        marker("recent")
            .unwrap()
            .set_modified(now - KEEP + Duration::from_secs(60))
            .unwrap();

        assert!(asked.record("new", now));
        assert!(!asked.already("old"));
        assert!(asked.already("recent"));
        assert!(asked.already("new"));
    }
}