Skip to main content

speccoder_core/
scope.rs

1//! Task scope as a reported finding: which changed paths a task's line did
2//! not name. Never a gate — a task line is prose, and a list of paths in
3//! it is a hint, not a contract.
4
5use serde::{Deserialize, Serialize};
6
7/// What an attempt changed beyond the paths its task names.
8#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
9pub struct ScopeFinding {
10    /// The task names at least one path.
11    pub stated: bool,
12    /// The paths the task names.
13    pub named: Vec<String>,
14    /// Changed paths outside them.
15    pub outside: Vec<String>,
16}
17
18/// Paths a task line names: backticked spans, and bare tokens with a `/`
19/// or a file extension (`src/lib.rs`, `README.md`, `tests/`).
20#[must_use]
21pub fn named_paths(text: &str) -> Vec<String> {
22    paths_in(text, true)
23}
24
25/// The backticked paths of a task line only: what it names on purpose
26/// (`input/output` in its prose is no path).
27#[must_use]
28pub fn quoted_paths(text: &str) -> Vec<String> {
29    paths_in(text, false)
30}
31
32/// Top directories of a machine, not of a repository.
33const SYSTEM_ROOTS: &[&str] = &[
34    "tmp",
35    "dev",
36    "usr",
37    "etc",
38    "var",
39    "bin",
40    "sbin",
41    "opt",
42    "home",
43    "Users",
44    "proc",
45    "sys",
46    "private",
47    "root",
48    "lib",
49    "Library",
50    "System",
51    "Applications",
52    "Volumes",
53    "mnt",
54    "srv",
55];
56
57fn paths_in(text: &str, bare: bool) -> Vec<String> {
58    let mut out: Vec<String> = Vec::new();
59    let mut push = |raw: &str| {
60        let t = raw
61            .trim_matches(|c: char| matches!(c, '(' | ')' | '"' | '\'' | '[' | ']' | '<' | '>'))
62            .trim_end_matches(['.', ',', ';', ':', '!', '?']);
63        let t = t.strip_prefix("./").unwrap_or(t);
64        // `/specs/001-x/plan.md`: Spec Kit writes repository paths from the
65        // root; `/tmp/…` or `/dev/null` is the machine's, never named.
66        let t = t
67            .strip_prefix('/')
68            .filter(|r| {
69                !r.starts_with('/')
70                    && !SYSTEM_ROOTS.contains(&r.split('/').next().unwrap_or_default())
71            })
72            .unwrap_or(t);
73        if looks_like_path(t) && !out.iter().any(|p| p == t) {
74            out.push(t.to_owned());
75        }
76    };
77    let mut rest = text;
78    while let Some(start) = rest.find('`') {
79        let Some(len) = rest[start + 1..].find('`') else {
80            break;
81        };
82        push(&rest[start + 1..start + 1 + len]);
83        rest = &rest[start + 2 + len..];
84    }
85    if bare {
86        for token in text.split_whitespace().filter(|t| !t.contains('`')) {
87            push(token);
88        }
89    }
90    out
91}
92
93fn looks_like_path(t: &str) -> bool {
94    if t.is_empty() || t.contains("://") || t.contains(' ') || t.starts_with('/') {
95        return false;
96    }
97    if t.contains('/') {
98        return t.chars().any(char::is_alphanumeric);
99    }
100    // `name.ext`: an extension of letters, as files have (`v1.2` is not one).
101    t.rsplit_once('.').is_some_and(|(stem, ext)| {
102        !stem.is_empty()
103            && (1..=5).contains(&ext.len())
104            && ext.chars().all(|c| c.is_ascii_alphabetic())
105    })
106}
107
108/// Changed paths not covered by `named` (exact path, a directory prefix, or
109/// a `*` glob), except `exempt` ones (speccoder's own acceptance tests).
110#[must_use]
111pub fn finding(named: &[String], changed: &[String], exempt: &[String]) -> ScopeFinding {
112    let covers = |n: &str, p: &str| {
113        let dir = n.trim_end_matches('/');
114        p == n || p.starts_with(&format!("{dir}/")) || (n.contains('*') && glob(n, p))
115    };
116    ScopeFinding {
117        stated: !named.is_empty(),
118        named: named.to_vec(),
119        outside: if named.is_empty() {
120            Vec::new()
121        } else {
122            changed
123                .iter()
124                .filter(|p| !exempt.contains(p) && !named.iter().any(|n| covers(n, p)))
125                .cloned()
126                .collect()
127        },
128    }
129}
130
131/// `*` matches within a path segment, `**` across segments.
132fn glob(pattern: &str, path: &str) -> bool {
133    fn go(p: &[u8], s: &[u8]) -> bool {
134        match p.split_first() {
135            None => s.is_empty(),
136            Some((b'*', rest)) if rest.first() == Some(&b'*') => {
137                let rest = rest.get(1..).unwrap_or_default();
138                let rest = rest.strip_prefix(b"/").unwrap_or(rest);
139                (0..=s.len()).any(|i| go(rest, &s[i..]))
140            }
141            Some((b'*', rest)) => (0..=s.len())
142                .take_while(|&i| i == 0 || s[i - 1] != b'/')
143                .any(|i| go(rest, &s[i..])),
144            Some((c, rest)) => s.first() == Some(c) && go(rest, &s[1..]),
145        }
146    }
147    go(pattern.as_bytes(), path.as_bytes())
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn reads_paths_from_a_task_line() {
156        assert_eq!(
157            named_paths("[US1] Implement Service in src/services/x.py (depends on T012)"),
158            ["src/services/x.py"]
159        );
160        assert_eq!(
161            named_paths("Document `--bye` in README.md, and update `docs/`."),
162            ["docs/", "README.md"]
163        );
164        assert_eq!(
165            named_paths("Scaffold `/specs/001-x/contracts/` from /specs/001-x/plan.md"),
166            ["specs/001-x/contracts/", "specs/001-x/plan.md"]
167        );
168        assert!(named_paths("Write the log to /tmp/run.log, not `/dev/null`").is_empty());
169        assert!(named_paths("Bump to v1.2 and say hi").is_empty());
170        assert!(named_paths("See https://example.com/x for details").is_empty());
171    }
172
173    #[test]
174    fn lists_changes_outside_the_named_paths() {
175        let named = vec![
176            "src/lib.rs".to_owned(),
177            "docs/".to_owned(),
178            "src/**/*.snap".to_owned(),
179        ];
180        let changed: Vec<String> = [
181            "src/lib.rs",
182            "docs/a/b.md",
183            "src/util.rs",
184            "src/x/y.snap",
185            "tests/acceptance_t1.rs",
186        ]
187        .map(str::to_owned)
188        .to_vec();
189        let f = finding(&named, &changed, &["tests/acceptance_t1.rs".to_owned()]);
190        assert!(f.stated);
191        assert_eq!(f.outside, ["src/util.rs"]);
192        let none = finding(&[], &changed, &[]);
193        assert!(!none.stated && none.outside.is_empty());
194    }
195}