Skip to main content

lean_ctx_ext/core/decisions/
parse.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Strict parser for one `.leanctx/decisions/<id>.toml` record.
3//!
4//! Unknown keys are errors (a misspelt `scope.path` must not silently widen a
5//! decision to the whole repo), and so are invalid globs and regexes: a record
6//! that cannot be checked as written is reported, never half-applied.
7
8use serde::Deserialize;
9
10use super::{Check, CheckKind, Decision, RecordEvidence, Status};
11
12#[derive(Deserialize)]
13#[serde(deny_unknown_fields)]
14struct RawDecision {
15    id: String,
16    title: String,
17    statement: String,
18    #[serde(default)]
19    rationale: String,
20    status: RawStatus,
21    #[serde(default)]
22    supersedes: Vec<String>,
23    decided_by: RawDecidedBy,
24    decided_at: RawDate,
25    #[serde(default)]
26    source: Option<RawSource>,
27    #[serde(default)]
28    scope: RawScope,
29    #[serde(default)]
30    evidence: Option<RawEvidence>,
31    #[serde(default, rename = "check")]
32    checks: Vec<RawCheck>,
33}
34
35#[derive(Deserialize, Clone, Copy)]
36#[serde(rename_all = "lowercase")]
37enum RawStatus {
38    Active,
39    Superseded,
40    Revoked,
41}
42
43#[derive(Deserialize, Clone, Copy)]
44#[serde(rename_all = "lowercase")]
45enum RawDecidedBy {
46    Owner,
47    Team,
48    Review,
49}
50
51#[derive(Deserialize)]
52#[serde(untagged)]
53enum RawDate {
54    Text(String),
55    Toml(toml::value::Datetime),
56}
57
58#[derive(Deserialize)]
59#[serde(deny_unknown_fields)]
60struct RawSource {
61    kind: RawSourceKind,
62    #[serde(rename = "ref")]
63    reference: String,
64}
65
66#[derive(Deserialize, Clone, Copy)]
67#[serde(rename_all = "kebab-case")]
68enum RawSourceKind {
69    OwnerAnswer,
70    Review,
71    Mr,
72    Session,
73    Doc,
74    Commit,
75}
76
77/// `[evidence]`: the verbatim history line a record was confirmed from
78/// (`lean-ctx decisions confirm`, contract §38).
79#[derive(Deserialize)]
80#[serde(deny_unknown_fields)]
81struct RawEvidence {
82    commit: String,
83    quote: String,
84    trust: RawTrust,
85}
86
87#[derive(Deserialize, Clone, Copy)]
88#[serde(rename_all = "lowercase")]
89enum RawTrust {
90    Confirmed,
91    Reconstructed,
92}
93
94#[derive(Deserialize, Default)]
95#[serde(deny_unknown_fields)]
96struct RawScope {
97    #[serde(default)]
98    repos: Vec<String>,
99    #[serde(default)]
100    paths: Vec<String>,
101    #[serde(default)]
102    symbols: Vec<String>,
103}
104
105#[derive(Deserialize)]
106#[serde(deny_unknown_fields)]
107struct RawCheck {
108    kind: RawCheckKind,
109    #[serde(default)]
110    paths: Vec<String>,
111    #[serde(default)]
112    pattern: Option<String>,
113    #[serde(default)]
114    message: Option<String>,
115}
116
117#[derive(Deserialize, Clone, Copy)]
118#[serde(rename_all = "snake_case")]
119enum RawCheckKind {
120    ForbidPath,
121    ForbidRegex,
122    RequireRegex,
123}
124
125/// Upper bound for a compiled check regex (bytes of program); a record is
126/// data from the repository and must not make every edit slow.
127const REGEX_SIZE_LIMIT: usize = 1 << 20;
128
129fn valid_id(id: &str) -> bool {
130    let Some(rest) = id.strip_prefix("dec-") else {
131        return false;
132    };
133    !rest.is_empty()
134        && id.len() <= 80
135        && rest.split('-').all(|part| {
136            !part.is_empty()
137                && part
138                    .bytes()
139                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
140        })
141}
142
143/// Strict `YYYY-MM-DD` calendar date, without a date crate.
144fn valid_date(date: &str) -> bool {
145    let b = date.as_bytes();
146    if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
147        return false;
148    }
149    let num = |s: &[u8]| -> Option<u32> {
150        s.iter().try_fold(0u32, |acc, &c| {
151            c.is_ascii_digit().then(|| acc * 10 + u32::from(c - b'0'))
152        })
153    };
154    let (Some(year), Some(month), Some(day)) = (num(&b[0..4]), num(&b[5..7]), num(&b[8..10]))
155    else {
156        return false;
157    };
158    let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
159    let days_in_month = match month {
160        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
161        4 | 6 | 9 | 11 => 30,
162        2 if leap => 29,
163        2 => 28,
164        _ => return false,
165    };
166    (1..=days_in_month).contains(&day)
167}
168
169fn compile_globs(field: &str, globs: &[String]) -> Result<Vec<glob::Pattern>, String> {
170    globs
171        .iter()
172        .enumerate()
173        .map(|(i, g)| {
174            if g.trim().is_empty() {
175                return Err(format!("{field}[{i}]: empty glob"));
176            }
177            if g.starts_with('/') || g.split('/').any(|c| c == "..") {
178                return Err(format!(
179                    "{field}[{i}] \"{g}\": globs are relative to the project root (no leading `/`, no `..`)"
180                ));
181            }
182            glob::Pattern::new(g).map_err(|e| format!("{field}[{i}] \"{g}\": invalid glob: {e}"))
183        })
184        .collect()
185}
186
187fn nonempty_list(field: &str, values: &[String]) -> Result<(), String> {
188    match values.iter().position(|v| v.trim().is_empty()) {
189        Some(i) => Err(format!("{field}[{i}]: empty value")),
190        None => Ok(()),
191    }
192}
193
194fn compile_check(i: usize, raw: RawCheck) -> Result<Check, String> {
195    let kind = match raw.kind {
196        RawCheckKind::ForbidPath => CheckKind::ForbidPath,
197        RawCheckKind::ForbidRegex => CheckKind::ForbidRegex,
198        RawCheckKind::RequireRegex => CheckKind::RequireRegex,
199    };
200    let globs = compile_globs(&format!("check[{i}].paths"), &raw.paths)?;
201    let regex = match (kind, raw.pattern.as_deref()) {
202        (CheckKind::ForbidPath, Some(_)) => {
203            return Err(format!(
204                "check[{i}]: `pattern` is not used by kind forbid_path (it forbids the paths themselves)"
205            ));
206        }
207        (CheckKind::ForbidPath, None) => None,
208        (_, None) => {
209            return Err(format!(
210                "check[{i}]: kind {} requires `pattern`",
211                kind.as_str()
212            ));
213        }
214        (_, Some(p)) => Some(
215            regex::RegexBuilder::new(p)
216                .size_limit(REGEX_SIZE_LIMIT)
217                .build()
218                .map_err(|e| format!("check[{i}].pattern: invalid regex: {e}"))?,
219        ),
220    };
221    if raw.message.as_deref().is_some_and(|m| m.trim().is_empty()) {
222        return Err(format!(
223            "check[{i}].message: empty (omit it to use the statement)"
224        ));
225    }
226    Ok(Check {
227        kind,
228        paths: raw.paths,
229        globs,
230        pattern: raw.pattern,
231        regex,
232        message: raw.message,
233    })
234}
235
236/// Parse and validate one record. `file_stem` must equal the record's `id`;
237/// `rel_file` is kept for reporting. Errors name the offending key.
238pub fn parse_decision(text: &str, file_stem: &str, rel_file: &str) -> Result<Decision, String> {
239    let raw: RawDecision = toml::from_str(text).map_err(|e| {
240        // toml's message already names the key and position; keep it on one line.
241        e.to_string()
242            .split_whitespace()
243            .collect::<Vec<_>>()
244            .join(" ")
245    })?;
246    if !valid_id(&raw.id) {
247        return Err(format!(
248            "id `{}`: must be kebab-case with prefix `dec-` (e.g. dec-no-macos-gate)",
249            raw.id
250        ));
251    }
252    if raw.id != file_stem {
253        return Err(format!(
254            "id `{}` does not match the file name (expected {}.toml)",
255            raw.id, raw.id
256        ));
257    }
258    for (field, value) in [("title", &raw.title), ("statement", &raw.statement)] {
259        if value.trim().is_empty() {
260            return Err(format!("{field}: must not be empty"));
261        }
262    }
263    if let Some(bad) = raw.supersedes.iter().find(|s| !valid_id(s)) {
264        return Err(format!("supersedes: `{bad}` is not a decision id"));
265    }
266    if raw.supersedes.iter().any(|s| s == &raw.id) {
267        return Err("supersedes: a decision cannot supersede itself".to_string());
268    }
269    let decided_at = match raw.decided_at {
270        RawDate::Text(s) => s,
271        RawDate::Toml(d) => d.to_string(),
272    };
273    if !valid_date(&decided_at) {
274        return Err(format!("decided_at `{decided_at}`: expected YYYY-MM-DD"));
275    }
276    let (source_kind, source_ref) = match raw.source {
277        Some(s) => {
278            if s.reference.trim().is_empty() {
279                return Err("source.ref: must not be empty".to_string());
280            }
281            let kind = match s.kind {
282                RawSourceKind::OwnerAnswer => "owner-answer",
283                RawSourceKind::Review => "review",
284                RawSourceKind::Mr => "mr",
285                RawSourceKind::Session => "session",
286                RawSourceKind::Doc => "doc",
287                RawSourceKind::Commit => "commit",
288            };
289            (Some(kind.to_string()), Some(s.reference))
290        }
291        None => (None, None),
292    };
293    let evidence = raw.evidence.map(parse_evidence).transpose()?;
294    nonempty_list("scope.repos", &raw.scope.repos)?;
295    nonempty_list("scope.symbols", &raw.scope.symbols)?;
296    let path_globs = compile_globs("scope.paths", &raw.scope.paths)?;
297    let checks = raw
298        .checks
299        .into_iter()
300        .enumerate()
301        .map(|(i, c)| compile_check(i, c))
302        .collect::<Result<Vec<_>, _>>()?;
303    Ok(Decision {
304        id: raw.id,
305        title: raw.title,
306        statement: raw.statement,
307        rationale: raw.rationale,
308        status: match raw.status {
309            RawStatus::Active => Status::Active,
310            RawStatus::Superseded => Status::Superseded,
311            RawStatus::Revoked => Status::Revoked,
312        },
313        supersedes: raw.supersedes,
314        decided_by: match raw.decided_by {
315            RawDecidedBy::Owner => "owner",
316            RawDecidedBy::Team => "team",
317            RawDecidedBy::Review => "review",
318        }
319        .to_string(),
320        decided_at,
321        source_kind,
322        source_ref,
323        repos: raw.scope.repos,
324        paths: raw.scope.paths,
325        path_globs,
326        symbols: raw.scope.symbols,
327        checks,
328        evidence,
329        file: rel_file.to_string(),
330    })
331}
332
333fn parse_evidence(raw: RawEvidence) -> Result<RecordEvidence, String> {
334    let commit = raw.commit.trim();
335    if !(7..=64).contains(&commit.len()) || !commit.bytes().all(|b| b.is_ascii_hexdigit()) {
336        return Err(format!(
337            "evidence.commit `{}`: expected a commit id (7 to 64 hex digits)",
338            raw.commit
339        ));
340    }
341    if raw.quote.trim().is_empty() || raw.quote.contains(['\n', '\r']) {
342        return Err("evidence.quote: must be one non-empty line".to_string());
343    }
344    Ok(RecordEvidence {
345        commit: commit.to_ascii_lowercase(),
346        quote: raw.quote,
347        trust: match raw.trust {
348            RawTrust::Confirmed => "confirmed",
349            RawTrust::Reconstructed => "reconstructed",
350        }
351        .to_string(),
352    })
353}
354
355/// Fields of a record confirmed from a draft (`lean-ctx decisions confirm`).
356#[derive(Debug, Clone, PartialEq, Eq)]
357pub struct NewRecord {
358    pub id: String,
359    pub title: String,
360    pub statement: String,
361    pub supersedes: Vec<String>,
362    /// `owner`, `team` or `review`.
363    pub decided_by: String,
364    /// `YYYY-MM-DD`.
365    pub decided_at: String,
366    /// `mr` or `commit`.
367    pub source_kind: String,
368    pub source_ref: String,
369    pub evidence: RecordEvidence,
370}
371
372/// A TOML basic string: `\`, `"` and control characters escaped.
373fn toml_str(s: &str) -> String {
374    let mut out = String::with_capacity(s.len() + 2);
375    out.push('"');
376    for c in s.chars() {
377        match c {
378            '\\' => out.push_str("\\\\"),
379            '"' => out.push_str("\\\""),
380            c if c.is_control() => out.push_str(&format!("\\u{:04X}", c as u32)),
381            c => out.push(c),
382        }
383    }
384    out.push('"');
385    out
386}
387
388/// The record text of `r`: deterministic, parses with [`parse_decision`].
389pub fn render_record(r: &NewRecord) -> String {
390    let list = |v: &[String]| v.iter().map(|s| toml_str(s)).collect::<Vec<_>>().join(", ");
391    format!(
392        "id = {}\n\
393         title = {}\n\
394         statement = {}\n\
395         rationale = \"\"\n\
396         status = \"active\"\n\
397         supersedes = [{}]\n\
398         decided_by = {}\n\
399         decided_at = {}\n\
400         \n\
401         [source]\n\
402         kind = {}\n\
403         ref = {}\n\
404         \n\
405         [evidence]                        # verbatim history line (contract §38)\n\
406         commit = {}\n\
407         quote = {}\n\
408         trust = {}\n\
409         \n\
410         [scope]\n\
411         repos = []                        # empty = all\n\
412         paths = []                        # globs; empty = repo-wide\n\
413         symbols = []\n",
414        toml_str(&r.id),
415        toml_str(&r.title),
416        toml_str(&r.statement),
417        list(&r.supersedes),
418        toml_str(&r.decided_by),
419        toml_str(&r.decided_at),
420        toml_str(&r.source_kind),
421        toml_str(&r.source_ref),
422        toml_str(&r.evidence.commit),
423        toml_str(&r.evidence.quote),
424        toml_str(&r.evidence.trust),
425    )
426}
427
428/// A fresh record for `lean-ctx decisions new` that parses as written.
429pub fn scaffold(id: &str, title: &str, today: &str) -> String {
430    // A TOML basic string: escape `\` and `"`, fold line breaks and other
431    // control characters into spaces so the record stays one parsable line.
432    let title: String = title
433        .chars()
434        .map(|c| if c.is_control() { ' ' } else { c })
435        .collect::<String>()
436        .replace('\\', "\\\\")
437        .replace('"', "\\\"");
438    format!(
439        "id = \"{id}\"\n\
440         title = \"{title}\"\n\
441         statement = \"{title}.\"\n\
442         rationale = \"\"\n\
443         status = \"active\"                 # active | superseded | revoked\n\
444         supersedes = []                   # ids\n\
445         decided_by = \"team\"              # owner | team | review\n\
446         decided_at = \"{today}\"\n\
447         \n\
448         [source]                          # where it was decided\n\
449         kind = \"doc\"                      # owner-answer | review | mr | session | doc\n\
450         ref = \".leanctx/decisions/{id}.toml\"\n\
451         \n\
452         [scope]\n\
453         repos = []                        # empty = all\n\
454         paths = []                        # globs; empty = repo-wide\n\
455         symbols = []\n\
456         \n\
457         # Optional, machine-checkable; may be several.\n\
458         # [[check]]\n\
459         # kind = \"forbid_regex\"           # forbid_path | forbid_regex | require_regex\n\
460         # paths = [\"src/**\"]\n\
461         # pattern = \"(?m)^.*TODO\"\n\
462         # message = \"why this is not allowed\"\n"
463    )
464}
465
466/// `dec-<slug>` from free text: lower-case ASCII words joined by `-`.
467pub fn id_from_slug(slug: &str) -> Option<String> {
468    let slug = slug.trim().strip_prefix("dec-").unwrap_or(slug.trim());
469    let words: Vec<String> = slug
470        .split(|c: char| !c.is_ascii_alphanumeric())
471        .filter(|w| !w.is_empty())
472        .map(str::to_ascii_lowercase)
473        .collect();
474    let id = format!("dec-{}", words.join("-"));
475    valid_id(&id).then_some(id)
476}