second-brain-core 0.13.5

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
Documentation
use std::fmt;
use std::sync::LazyLock;

use regex::Regex;

pub const ACCEPTED_FORMS: &str = "evidence must be a file location as path:line (src/lib.rs:42), \
     a commit hash of 7 to 40 hex digits, optionally repo@hash, or a command line followed by \
     at least one line of its output";

const MAX_OUTPUT_CHARS: usize = 2_000;

static LOCATION: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?<path>[^\s:]+):(?<line>[1-9][0-9]*)$").unwrap());
static COMMIT: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(?:(?<repo>[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)?)@)?(?<hash>[0-9a-fA-F]{7,40})$")
        .unwrap()
});

/// Why a correction is right: something another agent can check.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Evidence {
    Location { path: String, line: u32 },
    Commit { repo: Option<String>, hash: String },
    CommandOutput { command: String, output: String },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidEvidence;

impl fmt::Display for InvalidEvidence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(ACCEPTED_FORMS)
    }
}

impl std::error::Error for InvalidEvidence {}

impl Evidence {
    pub fn parse(text: &str) -> Result<Self, InvalidEvidence> {
        let lines: Vec<&str> = text
            .lines()
            .map(str::trim_end)
            .filter(|l| !l.trim().is_empty())
            .collect();
        match lines.as_slice() {
            [] => Err(InvalidEvidence),
            [single] => Self::parse_reference(single.trim()),
            [command, output @ ..] => {
                let command = command.trim();
                let command = match command.strip_prefix('$') {
                    Some(rest) if rest.is_empty() || rest.starts_with(char::is_whitespace) => {
                        rest.trim()
                    }
                    _ => command,
                };
                if command.is_empty() {
                    return Err(InvalidEvidence);
                }
                Ok(Self::CommandOutput {
                    command: command.to_string(),
                    output: truncate(&output.join("\n"), MAX_OUTPUT_CHARS),
                })
            }
        }
    }

    fn parse_reference(text: &str) -> Result<Self, InvalidEvidence> {
        if let Some(c) = COMMIT.captures(text) {
            return Ok(Self::Commit {
                repo: c.name("repo").map(|r| r.as_str().to_string()),
                hash: c["hash"].to_ascii_lowercase(),
            });
        }
        if let Some(c) = LOCATION.captures(text)
            && let Ok(line) = c["line"].parse()
        {
            return Ok(Self::Location {
                path: c["path"].to_string(),
                line,
            });
        }
        Err(InvalidEvidence)
    }
}

impl fmt::Display for Evidence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Location { path, line } => write!(f, "{path}:{line}"),
            Self::Commit {
                repo: Some(repo),
                hash,
            } => write!(f, "{repo}@{hash}"),
            Self::Commit { repo: None, hash } => f.write_str(hash),
            Self::CommandOutput { command, output } => write!(f, "$ {command}\n{output}"),
        }
    }
}

fn truncate(text: &str, max: usize) -> String {
    match text.char_indices().nth(max) {
        Some((cut, _)) => text[..cut].to_string(),
        None => text.to_string(),
    }
}

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

    fn location(path: &str, line: u32) -> Evidence {
        Evidence::Location {
            path: path.to_string(),
            line,
        }
    }

    fn commit(repo: Option<&str>, hash: &str) -> Evidence {
        Evidence::Commit {
            repo: repo.map(str::to_string),
            hash: hash.to_string(),
        }
    }

    fn command(command: &str, output: &str) -> Evidence {
        Evidence::CommandOutput {
            command: command.to_string(),
            output: output.to_string(),
        }
    }

    #[test]
    fn accepted_forms_parse_to_their_kind() {
        let cases = [
            ("src/lib.rs:42", location("src/lib.rs", 42)),
            (
                "  crates/core/src/query.rs:7 ",
                location("crates/core/src/query.rs", 7),
            ),
            ("Cargo.toml:1", location("Cargo.toml", 1)),
            ("abc1234", commit(None, "abc1234")),
            ("ABCDEF0123456789", commit(None, "abcdef0123456789")),
            (
                "0123456789abcdef0123456789abcdef01234567",
                commit(None, "0123456789abcdef0123456789abcdef01234567"),
            ),
            ("garden@abc1234", commit(Some("garden"), "abc1234")),
            ("srv/garden@abc1234", commit(Some("srv/garden"), "abc1234")),
            ("cargo test\nok", command("cargo test", "ok")),
            ("$HOME/bin/run\nok", command("$HOME/bin/run", "ok")),
            (
                "$ git log -1\n3b14717 merge\n\nsecond",
                command("git log -1", "3b14717 merge\nsecond"),
            ),
        ];
        for (text, want) in cases {
            assert_eq!(Evidence::parse(text), Ok(want), "{text:?}");
        }
    }

    #[test]
    fn anything_else_is_rejected_naming_the_accepted_forms() {
        let rejected = [
            "",
            "   \n  ",
            "because I said so",
            "abc123",
            "0123456789abcdef0123456789abcdef012345678",
            "src/lib.rs",
            "src/lib.rs:0",
            "src/lib.rs:12:4",
            "my file.rs:3",
            ":12",
            "@abc1234",
            "a b@abc1234",
            "cargo test",
            "$ \noutput",
        ];
        for text in rejected {
            let err = Evidence::parse(text).expect_err(text);
            let message = err.to_string();
            for form in ["path:line", "commit hash", "command line"] {
                assert!(message.contains(form), "{message}");
            }
        }
    }

    #[test]
    fn display_round_trips_through_parse() {
        for text in [
            "src/lib.rs:42",
            "abc1234",
            "garden@abc1234",
            "$ cargo test\nok\nfine",
        ] {
            let parsed = Evidence::parse(text).unwrap();
            assert_eq!(parsed.to_string(), text);
            assert_eq!(Evidence::parse(&parsed.to_string()), Ok(parsed));
        }
    }

    #[test]
    fn long_command_output_is_capped() {
        let output = "x".repeat(MAX_OUTPUT_CHARS + 50);
        let Evidence::CommandOutput { output: kept, .. } =
            Evidence::parse(&format!("make\n{output}")).unwrap()
        else {
            panic!("not command output");
        };
        assert_eq!(kept.chars().count(), MAX_OUTPUT_CHARS);
    }
}