lean-ctx-engine 3.12.13

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
use lean_ctx_time::UtcDateTime;
use std::path::{Path, PathBuf};

pub(crate) fn escape_xml_attr(value: &str) -> String {
    value
        .replace('&', "&")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

pub(crate) fn file_stem_search_pattern(path: &str) -> String {
    Path::new(path)
        .file_stem()
        .and_then(|s| s.to_str())
        .map(str::trim)
        .filter(|s| !s.is_empty() && s.chars().any(char::is_alphanumeric))
        .unwrap_or("")
        .to_string()
}

pub(crate) fn parent_dir_slash(path: &str) -> String {
    Path::new(path)
        .parent()
        .and_then(|p| p.to_str())
        .map_or_else(
            || "./".to_string(),
            |p| {
                let norm = p.replace('\\', "/");
                let trimmed = norm.trim_end_matches('/');
                if trimmed.is_empty() {
                    "./".to_string()
                } else {
                    format!("{trimmed}/")
                }
            },
        )
}

pub(crate) fn sessions_dir() -> Option<PathBuf> {
    crate::core::data_dir::lean_ctx_data_dir()
        .ok()
        .map(|d| d.join("sessions"))
}

pub(crate) fn generate_session_id() -> String {
    static COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
    let now = UtcDateTime::now();
    // Keep the sortable date/time prefix while separating numeric seconds from
    // microseconds with a letter. A hyphen made this prefix look like a
    // Luhn-valid payment-card number to content admission.
    let ts = now.format("%Y%m%d-%H%M%S").to_string();
    let micros = now.timestamp_subsec_micros();
    let seq = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    // The session file name is also its storage key. Include the MCP process ID
    // so concurrently launched servers cannot share or overwrite state.
    format!("{ts}u{micros:06}p{}s{seq}", std::process::id())
}

/// A session identity generated by this Engine, structurally validated so
/// policy code can treat it as metadata rather than caller-provided prose.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct EngineSessionId<'a>(&'a str);

impl<'a> EngineSessionId<'a> {
    pub(crate) fn as_str(self) -> &'a str {
        self.0
    }
}

/// Parse the current or legacy Engine session ID format. Arbitrary strings do
/// not receive the metadata treatment.
pub(crate) fn parse_engine_session_id(id: &str) -> Option<EngineSessionId<'_>> {
    let bytes = id.as_bytes();
    if !(26..=44).contains(&bytes.len())
        || bytes[8] != b'-'
        || !matches!(bytes[15], b'-' | b'u')
        || bytes[22] != b'p'
    {
        return None;
    }
    if !bytes[..8].iter().all(u8::is_ascii_digit)
        || !bytes[9..15].iter().all(u8::is_ascii_digit)
        || !bytes[16..22].iter().all(u8::is_ascii_digit)
    {
        return None;
    }

    lean_ctx_time::parse_date(&id[..8], "%Y%m%d").ok()?;
    let hour = id[9..11].parse::<i8>().ok()?;
    let minute = id[11..13].parse::<i8>().ok()?;
    let second = id[13..15].parse::<i8>().ok()?;
    let micros = id[16..22].parse::<i32>().ok()?;
    lean_ctx_time::Time::new(hour, minute, second, micros * 1_000).ok()?;

    let (pid, sequence) = id[23..].split_once('s')?;
    if pid.is_empty()
        || sequence.is_empty()
        || !pid.bytes().all(|byte| byte.is_ascii_digit())
        || !sequence.bytes().all(|byte| byte.is_ascii_digit())
        || pid.starts_with('0')
        || (sequence.len() > 1 && sequence.starts_with('0'))
        || !pid.parse::<u32>().is_ok_and(|value| value > 0)
        || sequence.parse::<u32>().is_err()
    {
        return None;
    }
    Some(EngineSessionId(id))
}

pub(crate) fn shorten_path(path: &str) -> String {
    let parts: Vec<&str> = path.split('/').collect();
    if parts.len() <= 2 {
        return path.to_string();
    }
    let last_two: Vec<&str> = parts.iter().rev().take(2).copied().collect();
    format!("…/{}/{}", last_two[1], last_two[0])
}

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

    #[test]
    fn session_id_is_qualified_by_process() {
        let id = generate_session_id();
        assert!(id.contains(&format!("p{}s", std::process::id())));
        assert_eq!(id.as_bytes()[8], b'-');
        assert!(id[..8].bytes().all(|byte| byte.is_ascii_digit()));
        assert!(id[9..15].bytes().all(|byte| byte.is_ascii_digit()));
        assert_eq!(id.as_bytes()[15], b'u');
        assert!(parse_engine_session_id(&id).is_some());
        assert!(!id.contains('/') && !id.contains('\\'));
    }

    #[test]
    fn engine_session_id_parser_preserves_legacy_shape_without_accepting_free_text() {
        // This valid legacy generated ID contains a Luhn-valid date/time run.
        assert!(parse_engine_session_id("20261004-123406-123456p43210s0").is_some());
        assert!(parse_engine_session_id("20261004-123406u123456p43210s0").is_some());
        for invalid in [
            "20260230-123406-123456p43210s0",
            "20261004-246006u123456p43210s0",
            "20261004-123406u123456px43210s0",
            "20261004-123406u123456p43210s",
            "20261004-123406u123456p43210s0/other",
            "20261004-123406u123456p043210s0",
            "20261004-123406u123456p43210s00",
            "list-boundary",
        ] {
            assert!(parse_engine_session_id(invalid).is_none(), "{invalid}");
        }
        assert!(
            parse_engine_session_id(&format!("20261004-123406u123456p{}1s0", "0".repeat(100)))
                .is_none()
        );
    }
}