Skip to main content

second_brain_core/
evidence.rs

1use std::fmt;
2use std::sync::LazyLock;
3
4use regex::Regex;
5
6pub const ACCEPTED_FORMS: &str = "evidence must be a file location as path:line (src/lib.rs:42), \
7     a commit hash of 7 to 40 hex digits, optionally repo@hash, or a command line followed by \
8     at least one line of its output";
9
10const MAX_OUTPUT_CHARS: usize = 2_000;
11
12static LOCATION: LazyLock<Regex> =
13    LazyLock::new(|| Regex::new(r"^(?<path>[^\s:]+):(?<line>[1-9][0-9]*)$").unwrap());
14static COMMIT: LazyLock<Regex> = LazyLock::new(|| {
15    Regex::new(r"^(?:(?<repo>[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)?)@)?(?<hash>[0-9a-fA-F]{7,40})$")
16        .unwrap()
17});
18
19/// Why a correction is right: something another agent can check.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum Evidence {
22    Location { path: String, line: u32 },
23    Commit { repo: Option<String>, hash: String },
24    CommandOutput { command: String, output: String },
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct InvalidEvidence;
29
30impl fmt::Display for InvalidEvidence {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        f.write_str(ACCEPTED_FORMS)
33    }
34}
35
36impl std::error::Error for InvalidEvidence {}
37
38impl Evidence {
39    pub fn parse(text: &str) -> Result<Self, InvalidEvidence> {
40        let lines: Vec<&str> = text
41            .lines()
42            .map(str::trim_end)
43            .filter(|l| !l.trim().is_empty())
44            .collect();
45        match lines.as_slice() {
46            [] => Err(InvalidEvidence),
47            [single] => Self::parse_reference(single.trim()),
48            [command, output @ ..] => {
49                let command = command.trim();
50                let command = match command.strip_prefix('$') {
51                    Some(rest) if rest.is_empty() || rest.starts_with(char::is_whitespace) => {
52                        rest.trim()
53                    }
54                    _ => command,
55                };
56                if command.is_empty() {
57                    return Err(InvalidEvidence);
58                }
59                Ok(Self::CommandOutput {
60                    command: command.to_string(),
61                    output: truncate(&output.join("\n"), MAX_OUTPUT_CHARS),
62                })
63            }
64        }
65    }
66
67    fn parse_reference(text: &str) -> Result<Self, InvalidEvidence> {
68        if let Some(c) = COMMIT.captures(text) {
69            return Ok(Self::Commit {
70                repo: c.name("repo").map(|r| r.as_str().to_string()),
71                hash: c["hash"].to_ascii_lowercase(),
72            });
73        }
74        if let Some(c) = LOCATION.captures(text)
75            && let Ok(line) = c["line"].parse()
76        {
77            return Ok(Self::Location {
78                path: c["path"].to_string(),
79                line,
80            });
81        }
82        Err(InvalidEvidence)
83    }
84}
85
86impl fmt::Display for Evidence {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        match self {
89            Self::Location { path, line } => write!(f, "{path}:{line}"),
90            Self::Commit {
91                repo: Some(repo),
92                hash,
93            } => write!(f, "{repo}@{hash}"),
94            Self::Commit { repo: None, hash } => f.write_str(hash),
95            Self::CommandOutput { command, output } => write!(f, "$ {command}\n{output}"),
96        }
97    }
98}
99
100fn truncate(text: &str, max: usize) -> String {
101    match text.char_indices().nth(max) {
102        Some((cut, _)) => text[..cut].to_string(),
103        None => text.to_string(),
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    fn location(path: &str, line: u32) -> Evidence {
112        Evidence::Location {
113            path: path.to_string(),
114            line,
115        }
116    }
117
118    fn commit(repo: Option<&str>, hash: &str) -> Evidence {
119        Evidence::Commit {
120            repo: repo.map(str::to_string),
121            hash: hash.to_string(),
122        }
123    }
124
125    fn command(command: &str, output: &str) -> Evidence {
126        Evidence::CommandOutput {
127            command: command.to_string(),
128            output: output.to_string(),
129        }
130    }
131
132    #[test]
133    fn accepted_forms_parse_to_their_kind() {
134        let cases = [
135            ("src/lib.rs:42", location("src/lib.rs", 42)),
136            (
137                "  crates/core/src/query.rs:7 ",
138                location("crates/core/src/query.rs", 7),
139            ),
140            ("Cargo.toml:1", location("Cargo.toml", 1)),
141            ("abc1234", commit(None, "abc1234")),
142            ("ABCDEF0123456789", commit(None, "abcdef0123456789")),
143            (
144                "0123456789abcdef0123456789abcdef01234567",
145                commit(None, "0123456789abcdef0123456789abcdef01234567"),
146            ),
147            ("garden@abc1234", commit(Some("garden"), "abc1234")),
148            ("srv/garden@abc1234", commit(Some("srv/garden"), "abc1234")),
149            ("cargo test\nok", command("cargo test", "ok")),
150            ("$HOME/bin/run\nok", command("$HOME/bin/run", "ok")),
151            (
152                "$ git log -1\n3b14717 merge\n\nsecond",
153                command("git log -1", "3b14717 merge\nsecond"),
154            ),
155        ];
156        for (text, want) in cases {
157            assert_eq!(Evidence::parse(text), Ok(want), "{text:?}");
158        }
159    }
160
161    #[test]
162    fn anything_else_is_rejected_naming_the_accepted_forms() {
163        let rejected = [
164            "",
165            "   \n  ",
166            "because I said so",
167            "abc123",
168            "0123456789abcdef0123456789abcdef012345678",
169            "src/lib.rs",
170            "src/lib.rs:0",
171            "src/lib.rs:12:4",
172            "my file.rs:3",
173            ":12",
174            "@abc1234",
175            "a b@abc1234",
176            "cargo test",
177            "$ \noutput",
178        ];
179        for text in rejected {
180            let err = Evidence::parse(text).expect_err(text);
181            let message = err.to_string();
182            for form in ["path:line", "commit hash", "command line"] {
183                assert!(message.contains(form), "{message}");
184            }
185        }
186    }
187
188    #[test]
189    fn display_round_trips_through_parse() {
190        for text in [
191            "src/lib.rs:42",
192            "abc1234",
193            "garden@abc1234",
194            "$ cargo test\nok\nfine",
195        ] {
196            let parsed = Evidence::parse(text).unwrap();
197            assert_eq!(parsed.to_string(), text);
198            assert_eq!(Evidence::parse(&parsed.to_string()), Ok(parsed));
199        }
200    }
201
202    #[test]
203    fn long_command_output_is_capped() {
204        let output = "x".repeat(MAX_OUTPUT_CHARS + 50);
205        let Evidence::CommandOutput { output: kept, .. } =
206            Evidence::parse(&format!("make\n{output}")).unwrap()
207        else {
208            panic!("not command output");
209        };
210        assert_eq!(kept.chars().count(), MAX_OUTPUT_CHARS);
211    }
212}