Skip to main content

lean_ctx_cli/cli/
decisions_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `lean-ctx decisions`: list, show, check and scaffold decision records
3//! (`.leanctx/decisions/*.toml`, docs/internal/decision-layer.md).
4//!
5//! `check` judges a change file by file and reports only what the change
6//! introduces ([`lean_ctx::core::decisions::check`]). With `--rev A..B` the
7//! decisions come from the base `A` (a change cannot weaken the rules it is
8//! judged by) and `require_regex` looks for the pattern in tree `B`.
9
10use std::cell::OnceCell;
11use std::path::{Path, PathBuf};
12use std::process::Command;
13
14use lean_ctx::core::decisions::{
15    self, Check, CheckKind, DECISIONS_DIR, Decision, DecisionSet, OtherFiles, Violation,
16};
17
18const USAGE: &str = "Usage: lean-ctx decisions <command>
19  list [--path P | --symbol S]   decisions in scope (all records by default)
20  show <id>                      one decision in full
21  check [--rev A..B | --staged | --diff FILE|-]
22                                 violations a change introduces (default: working tree
23                                 against HEAD, untracked files included); exit 1 on a
24                                 violation, 2 on invalid records or errors
25  new <slug> [--title T]         scaffold .leanctx/decisions/dec-<slug>.toml
26  suggest [--since REF] [--json] draft decisions from the git history (review file only)
27  confirm <draft-id> [--id SLUG] [--decided-by owner|team|review]
28                                 record a suggested draft with its verbatim evidence";
29
30/// Largest file `check` reads from git or disk; larger ones are skipped.
31const MAX_FILE_BYTES: usize = 1_000_000;
32/// Most files of tree `B` a `require_regex` lookup reads under `--rev`.
33const MAX_TREE_FILES: usize = 5_000;
34
35pub fn cmd_decisions(args: &[String]) {
36    let code = run(args);
37    if code != 0 {
38        std::process::exit(code);
39    }
40}
41
42fn run(args: &[String]) -> i32 {
43    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
44    let action = args.first().map_or("help", String::as_str);
45    let rest = args.get(1..).unwrap_or_default();
46    match action {
47        "list" | "ls" => {
48            let (path, symbol) = (flag(rest, "--path"), flag(rest, "--symbol"));
49            let root = project_root(&cwd);
50            println!(
51                "{}",
52                decisions::query_text(&root, path.as_deref(), symbol.as_deref())
53            );
54            0
55        }
56        "show" => show(&cwd, rest),
57        "check" => match parse_mode(rest) {
58            Ok(mode) => {
59                let report = check(&project_root(&cwd), &mode);
60                print!("{}", report.stdout);
61                eprint!("{}", report.stderr);
62                report.code
63            }
64            Err(e) => {
65                eprintln!("lean-ctx decisions check: {e}\n{USAGE}");
66                2
67            }
68        },
69        "new" => new(&cwd, rest),
70        "help" | "--help" | "-h" => {
71            println!("{USAGE}");
72            0
73        }
74        other => {
75            eprintln!("lean-ctx decisions: unknown command `{other}`\n{USAGE}");
76            2
77        }
78    }
79}
80
81fn flag(args: &[String], name: &str) -> Option<String> {
82    let mut it = args.iter();
83    while let Some(a) = it.next() {
84        if a == name {
85            return it.next().cloned();
86        }
87        if let Some(v) = a.strip_prefix(name).and_then(|r| r.strip_prefix('=')) {
88            return Some(v.to_string());
89        }
90    }
91    None
92}
93
94/// The directory holding `.leanctx/decisions`, else the git top level, else `cwd`.
95fn project_root(cwd: &Path) -> PathBuf {
96    decisions::find_root(cwd)
97        .or_else(|| {
98            git(cwd, &["rev-parse", "--show-toplevel"])
99                .ok()
100                .map(|s| PathBuf::from(s.trim()))
101        })
102        .unwrap_or_else(|| cwd.to_path_buf())
103}
104
105fn show(cwd: &Path, rest: &[String]) -> i32 {
106    let Some(id) = rest.first() else {
107        eprintln!("{USAGE}");
108        return 2;
109    };
110    let root = project_root(cwd);
111    let set = decisions::load(&root);
112    if let Some(d) = set.get(id) {
113        print!("{}", decisions::describe(&set, d));
114        0
115    } else {
116        eprintln!(
117            "No decision `{id}` in {}",
118            root.join(DECISIONS_DIR).display()
119        );
120        1
121    }
122}
123
124fn new(cwd: &Path, rest: &[String]) -> i32 {
125    let Some(slug) = rest.first().filter(|s| !s.starts_with("--")) else {
126        eprintln!("{USAGE}");
127        return 2;
128    };
129    let Some(id) = decisions::id_from_slug(slug) else {
130        eprintln!("`{slug}` has no letters or digits to build an id from");
131        return 2;
132    };
133    let title = flag(rest, "--title").unwrap_or_else(|| slug.clone());
134    let root = project_root(cwd);
135    let dir = root.join(DECISIONS_DIR);
136    let file = dir.join(format!("{id}.toml"));
137    let today = lean_ctx_time::LocalDateTime::now()
138        .format("%Y-%m-%d")
139        .to_string();
140    let written = std::fs::create_dir_all(&dir).and_then(|()| {
141        use std::io::Write;
142        std::fs::OpenOptions::new()
143            .write(true)
144            .create_new(true)
145            .open(&file)?
146            .write_all(decisions::scaffold(&id, &title, &today).as_bytes())
147    });
148    match written {
149        Ok(()) => {
150            println!(
151                "Created {DECISIONS_DIR}/{id}.toml. Fill in statement, rationale, source, scope \
152                 and checks; `lean-ctx decisions check` validates every record."
153            );
154            0
155        }
156        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
157            eprintln!("{DECISIONS_DIR}/{id}.toml exists; edit it or pick another slug");
158            1
159        }
160        Err(e) => {
161            eprintln!("cannot write {}: {e}", file.display());
162            2
163        }
164    }
165}
166
167// ── check ───────────────────────────────────────────────────────────────────
168
169#[derive(Debug, PartialEq, Eq)]
170enum Mode {
171    /// Working tree (and index) against HEAD, untracked files included.
172    Worktree,
173    /// Index against HEAD.
174    Staged,
175    /// Commit `.0` to commit `.1`.
176    Rev(String, String),
177    /// A unified diff from a file, or stdin for `-`.
178    Diff(String),
179}
180
181fn parse_mode(rest: &[String]) -> Result<Mode, String> {
182    if let Some(range) = flag(rest, "--rev") {
183        let (a, b) = match range.split_once("..") {
184            Some((a, b)) => (a.trim_end_matches('.'), b.trim_start_matches('.')),
185            None => (range.as_str(), ""),
186        };
187        if a.is_empty() {
188            return Err(format!("--rev `{range}` names no base"));
189        }
190        let b = if b.is_empty() { "HEAD" } else { b };
191        for side in [a, b] {
192            check_rev_syntax(side).map_err(|e| format!("--rev `{range}`: {e}"))?;
193        }
194        return Ok(Mode::Rev(a.to_string(), b.to_string()));
195    }
196    if let Some(file) = flag(rest, "--diff") {
197        return Ok(Mode::Diff(file));
198    }
199    if rest.iter().any(|a| a == "--staged" || a == "--cached") {
200        return Ok(Mode::Staged);
201    }
202    match rest.first() {
203        Some(other) => Err(format!("unknown argument `{other}`")),
204        None => Ok(Mode::Worktree),
205    }
206}
207
208/// Refuses a revision git could read as an option (`-x`, `--output=…`) or
209/// that carries whitespace or control characters. `resolve_commit` then pins
210/// it to a commit id before any other git command sees it.
211fn check_rev_syntax(rev: &str) -> Result<(), String> {
212    if rev.is_empty() {
213        return Err("empty revision".to_string());
214    }
215    if rev.starts_with('-') {
216        return Err(format!("revision `{rev}` starts with `-`"));
217    }
218    if rev.chars().any(|c| c.is_whitespace() || c.is_control()) {
219        return Err("revision contains whitespace or control characters".to_string());
220    }
221    Ok(())
222}
223
224/// The commit id `rev` names, resolved with `--end-of-options` so git never
225/// reads it as an option.
226fn resolve_commit(root: &Path, rev: &str) -> Result<String, String> {
227    check_rev_syntax(rev)?;
228    let spec = format!("{rev}^{{commit}}");
229    let sha = git(
230        root,
231        &[
232            "rev-parse",
233            "--verify",
234            "--quiet",
235            "--end-of-options",
236            &spec,
237        ],
238    )
239    .map_err(|_| format!("`{rev}` is not a commit"))?;
240    let sha = sha.trim();
241    if sha.is_empty() || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {
242        return Err(format!("`{rev}` is not a commit"));
243    }
244    Ok(sha.to_string())
245}
246
247/// One changed file.
248#[derive(Debug, Default, PartialEq, Eq)]
249struct Change {
250    path: String,
251    /// Source path of a rename.
252    renamed_from: Option<String>,
253    /// `None`: a new (or copied) file.
254    before: Option<String>,
255    /// `None`: a deletion.
256    after: Option<String>,
257    /// Diff mode: new-file line of each line of `after` (hunk text only).
258    line_map: Option<Vec<usize>>,
259}
260
261struct Report {
262    stdout: String,
263    stderr: String,
264    code: i32,
265}
266
267fn check(root: &Path, mode: &Mode) -> Report {
268    let mut report = Report {
269        stdout: String::new(),
270        stderr: String::new(),
271        code: 0,
272    };
273    // Pin both revisions to commit ids: git sees only hex ids from here on.
274    let resolved;
275    let mode = match mode {
276        Mode::Rev(a, b) => {
277            match resolve_commit(root, a).and_then(|a| resolve_commit(root, b).map(|b| (a, b))) {
278                Ok((a, b)) => {
279                    resolved = Mode::Rev(a, b);
280                    &resolved
281                }
282                Err(e) => {
283                    report.stderr = format!("lean-ctx decisions check: {e}\n");
284                    report.code = 2;
285                    return report;
286                }
287            }
288        }
289        other => other,
290    };
291    let set = match mode {
292        Mode::Rev(a, _) => base_set(root, a),
293        _ => Ok(std::sync::Arc::unwrap_or_clone(decisions::load(root))),
294    };
295    let set = match set {
296        Ok(set) => set,
297        Err(e) => {
298            report.stderr = format!("lean-ctx decisions check: {e}\n");
299            report.code = 2;
300            return report;
301        }
302    };
303    for e in &set.errors {
304        report
305            .stderr
306            .push_str(&format!("invalid record (not applied): {e}\n"));
307    }
308    if set.decisions.is_empty() {
309        report.stdout = format!("decisions check: no decisions in {DECISIONS_DIR}\n");
310        report.code = if set.errors.is_empty() { 0 } else { 2 };
311        return report;
312    }
313    let changes = match mode {
314        Mode::Diff(file) => read_diff(file).map(|t| (parse_unified_diff(&t), 0)),
315        _ => git_changes(root, mode),
316    };
317    let (changes, skipped) = match changes {
318        Ok(c) => c,
319        Err(e) => {
320            report
321                .stderr
322                .push_str(&format!("lean-ctx decisions check: {e}\n"));
323            report.code = 2;
324            return report;
325        }
326    };
327    let tree: OnceCell<Vec<String>> = OnceCell::new();
328    let rev_other = |d: &Decision, c: &Check, exclude: &str| match mode {
329        Mode::Rev(_, b) => tree_contains(root, b, &tree, d, c, exclude),
330        // The diff may or may not be applied: look at the changed file too.
331        Mode::Diff(_) => decisions::check::worktree_other_files(root, d, c, ""),
332        _ => decisions::check::worktree_other_files(root, d, c, exclude),
333    };
334    let mut violations: Vec<Violation> = Vec::new();
335    for ch in &changes {
336        violations.extend(violations_of(&set, ch, &rev_other));
337    }
338    for v in &violations {
339        report.stdout.push_str(&v.render());
340        report.stdout.push('\n');
341    }
342    let skipped_note = if skipped > 0 {
343        format!(", {skipped} skipped (binary or over {MAX_FILE_BYTES} bytes)")
344    } else {
345        String::new()
346    };
347    let summary = format!(
348        "decisions check: {} violation(s) in {} changed file(s){skipped_note}\n",
349        violations.len(),
350        changes.len()
351    );
352    if violations.is_empty() {
353        report.stdout.push_str(&summary);
354        report.code = if set.errors.is_empty() { 0 } else { 2 };
355    } else {
356        report.stderr.push_str(&summary);
357        report.code = 1;
358    }
359    report
360}
361
362fn violations_of(set: &DecisionSet, ch: &Change, other: OtherFiles<'_>) -> Vec<Violation> {
363    let eval = |before: Option<&str>| {
364        decisions::evaluate_change_with(set, &ch.path, before, ch.after.as_deref(), other)
365    };
366    let mut out = eval(ch.before.as_deref());
367    if ch
368        .renamed_from
369        .as_deref()
370        .is_some_and(|from| from != ch.path)
371        && ch.after.is_some()
372    {
373        // A rename creates the file at its new path: `forbid_path` judges it new.
374        out.extend(
375            eval(None)
376                .into_iter()
377                .filter(|v| v.kind == CheckKind::ForbidPath),
378        );
379    }
380    if let Some(map) = &ch.line_map {
381        for v in &mut out {
382            v.line = v.line.and_then(|l| map.get(l.saturating_sub(1)).copied());
383        }
384    }
385    out
386}
387
388/// Decisions as recorded in commit `rev`.
389fn base_set(root: &Path, rev: &str) -> Result<DecisionSet, String> {
390    let listing = git(
391        root,
392        &[
393            "ls-tree",
394            "-z",
395            "--name-only",
396            rev,
397            "--",
398            &format!("{DECISIONS_DIR}/"),
399        ],
400    )?;
401    let records = listing
402        .split('\0')
403        .filter(|p| Path::new(p).extension().is_some_and(|e| e == "toml"))
404        .map(|p| {
405            let text = blob(root, &format!("{rev}:{p}"))
406                .ok_or_else(|| "unreadable at the base commit".to_string());
407            (p.to_string(), text)
408        })
409        .collect();
410    Ok(decisions::from_records(root, records))
411}
412
413/// `require_regex` "another file holds it" over git tree `rev`.
414fn tree_contains(
415    root: &Path,
416    rev: &str,
417    tree: &OnceCell<Vec<String>>,
418    d: &Decision,
419    c: &Check,
420    exclude: &str,
421) -> bool {
422    let Some(re) = c.regex() else {
423        return true;
424    };
425    let files = tree.get_or_init(|| {
426        git(root, &["ls-tree", "-r", "-z", "--name-only", rev])
427            .map(|s| {
428                s.split('\0')
429                    .filter(|p| !p.is_empty())
430                    .map(str::to_string)
431                    .collect()
432            })
433            .unwrap_or_default()
434    });
435    if files.is_empty() {
436        return true;
437    }
438    let mut seen = 0usize;
439    for f in files {
440        if f == exclude || !c.covers(d, f) {
441            continue;
442        }
443        seen += 1;
444        if seen > MAX_TREE_FILES {
445            return true;
446        }
447        if blob(root, &format!("{rev}:{f}")).is_some_and(|t| re.is_match(&t)) {
448            return true;
449        }
450    }
451    false
452}
453
454fn git(dir: &Path, args: &[&str]) -> Result<String, String> {
455    let out = Command::new("git")
456        .arg("-C")
457        .arg(dir)
458        .args(args)
459        .output()
460        .map_err(|e| format!("git: {e}"))?;
461    if !out.status.success() {
462        return Err(format!(
463            "git {}: {}",
464            args.join(" "),
465            String::from_utf8_lossy(&out.stderr).trim()
466        ));
467    }
468    String::from_utf8(out.stdout)
469        .map_err(|_| format!("git {}: output is not UTF-8", args.join(" ")))
470}
471
472/// A text blob (`rev:path`, `:path`); `None` when missing, binary or too big.
473fn blob(root: &Path, spec: &str) -> Option<String> {
474    let out = Command::new("git")
475        .arg("-C")
476        .arg(root)
477        .args(["cat-file", "blob", spec])
478        .output()
479        .ok()?;
480    (out.status.success() && out.stdout.len() <= MAX_FILE_BYTES)
481        .then(|| String::from_utf8(out.stdout).ok())
482        .flatten()
483}
484
485fn read_disk(root: &Path, rel: &str) -> Option<String> {
486    let path = root.join(rel);
487    let len = std::fs::metadata(&path).ok()?.len();
488    (len <= MAX_FILE_BYTES as u64)
489        .then(|| std::fs::read_to_string(path).ok())
490        .flatten()
491}
492
493/// `(status, rename/copy source, path)` from `git diff --name-status -z`.
494fn parse_name_status(z: &str) -> Vec<(char, Option<String>, String)> {
495    let mut out = Vec::new();
496    let mut it = z.split('\0').filter(|s| !s.is_empty());
497    while let Some(status) = it.next() {
498        let kind = status.chars().next().unwrap_or('M');
499        if matches!(kind, 'R' | 'C') {
500            if let (Some(from), Some(to)) = (it.next(), it.next()) {
501                out.push((kind, Some(from.to_string()), to.to_string()));
502            }
503        } else if let Some(p) = it.next() {
504            out.push((kind, None, p.to_string()));
505        }
506    }
507    out
508}
509
510/// The changes of a git mode, plus how many files were skipped.
511fn git_changes(root: &Path, mode: &Mode) -> Result<(Vec<Change>, usize), String> {
512    let (base, mut entries) = match mode {
513        Mode::Worktree => {
514            let mut e =
515                parse_name_status(&git(root, &["diff", "--name-status", "-z", "-M", "HEAD"])?);
516            let untracked = git(root, &["ls-files", "-z", "--others", "--exclude-standard"])?;
517            e.extend(
518                untracked
519                    .split('\0')
520                    .filter(|p| !p.is_empty())
521                    .map(|p| ('A', None, p.to_string())),
522            );
523            ("HEAD".to_string(), e)
524        }
525        Mode::Staged => (
526            "HEAD".to_string(),
527            parse_name_status(&git(
528                root,
529                &["diff", "--cached", "--name-status", "-z", "-M", "HEAD"],
530            )?),
531        ),
532        Mode::Rev(a, b) => (
533            a.clone(),
534            parse_name_status(&git(
535                root,
536                &[
537                    "diff",
538                    "--name-status",
539                    "-z",
540                    "-M",
541                    "--end-of-options",
542                    a,
543                    b,
544                    "--",
545                ],
546            )?),
547        ),
548        Mode::Diff(_) => return Ok((Vec::new(), 0)),
549    };
550    entries.sort_by(|x, y| x.2.cmp(&y.2));
551    let mut changes = Vec::new();
552    let mut skipped = 0usize;
553    for (kind, from, path) in entries {
554        if matches!(kind, 'D' | 'U') {
555            continue;
556        }
557        let after = match mode {
558            Mode::Worktree => read_disk(root, &path),
559            Mode::Staged => blob(root, &format!(":{path}")),
560            Mode::Rev(_, b) => blob(root, &format!("{b}:{path}")),
561            Mode::Diff(_) => None,
562        };
563        let before = match kind {
564            'A' | 'C' => Some(None),
565            _ => {
566                let old = from.as_deref().unwrap_or(&path);
567                blob(root, &format!("{base}:{old}")).map(Some)
568            }
569        };
570        let (Some(after), Some(before)) = (after, before) else {
571            skipped += 1;
572            continue;
573        };
574        changes.push(Change {
575            renamed_from: from.filter(|_| kind == 'R'),
576            path,
577            before,
578            after: Some(after),
579            line_map: None,
580        });
581    }
582    Ok((changes, skipped))
583}
584
585fn read_diff(file: &str) -> Result<String, String> {
586    if file == "-" {
587        let mut text = String::new();
588        std::io::Read::read_to_string(&mut std::io::stdin(), &mut text)
589            .map_err(|e| format!("stdin: {e}"))?;
590        Ok(text)
591    } else {
592        std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))
593    }
594}
595
596fn diff_path(header: &str, prefix: &str) -> Option<String> {
597    let p = header.split('\t').next().unwrap_or(header).trim();
598    (p != "/dev/null").then(|| p.strip_prefix(prefix).unwrap_or(p).to_string())
599}
600
601/// Changes from a unified diff. Only the hunks are known, so `before` and
602/// `after` are the hunks' old and new sides (context included) and
603/// `line_map` maps each `after` line back to its line in the new file.
604fn parse_unified_diff(text: &str) -> Vec<Change> {
605    let mut out: Vec<Change> = Vec::new();
606    let mut old: Option<Option<String>> = None;
607    let mut cur: Option<(Change, usize)> = None;
608    let lines: Vec<&str> = text.lines().collect();
609    for (i, &line) in lines.iter().enumerate() {
610        // `--- ` is a file header only right before `+++ ` (else a removed line).
611        let header = lines.get(i + 1).is_some_and(|n| n.starts_with("+++ "));
612        if line.starts_with("diff ") {
613            out.extend(cur.take().map(|(c, _)| c));
614            old = None;
615        } else if let Some(h) = line.strip_prefix("--- ").filter(|_| header) {
616            out.extend(cur.take().map(|(c, _)| c));
617            old = Some(diff_path(h, "a/"));
618        } else if let (Some(h), Some(from)) = (line.strip_prefix("+++ "), old.clone()) {
619            let to = diff_path(h, "b/");
620            let path = to.clone().or_else(|| from.clone()).unwrap_or_default();
621            cur = Some((
622                Change {
623                    renamed_from: from
624                        .clone()
625                        .filter(|f| Some(f) != to.as_ref() && to.is_some()),
626                    path,
627                    before: from.map(|_| String::new()),
628                    after: to.map(|_| String::new()),
629                    line_map: Some(Vec::new()),
630                },
631                1,
632            ));
633            old = None;
634        } else if let Some(h) = line.strip_prefix("@@ ") {
635            if let Some((_, next)) = cur.as_mut() {
636                *next = h
637                    .split_whitespace()
638                    .find_map(|t| t.strip_prefix('+'))
639                    .and_then(|t| t.split(',').next()?.parse().ok())
640                    .unwrap_or(1);
641            }
642        } else if let Some((c, next)) = cur.as_mut() {
643            let (tag, body) = line.split_at(line.len().min(1));
644            let push_after = |c: &mut Change, next: &mut usize| {
645                if let Some(a) = c.after.as_mut() {
646                    a.push_str(body);
647                    a.push('\n');
648                    if let Some(m) = c.line_map.as_mut() {
649                        m.push(*next);
650                    }
651                }
652                *next += 1;
653            };
654            match tag {
655                "+" => push_after(c, next),
656                "-" => {
657                    if let Some(b) = c.before.as_mut() {
658                        b.push_str(body);
659                        b.push('\n');
660                    }
661                }
662                " " | "" => {
663                    if let Some(b) = c.before.as_mut() {
664                        b.push_str(body);
665                        b.push('\n');
666                    }
667                    push_after(c, next);
668                }
669                _ => {}
670            }
671        }
672    }
673    out.extend(cur.map(|(c, _)| c));
674    out
675}
676
677#[cfg(test)]
678mod tests {
679    use super::*;
680
681    #[test]
682    fn modes_parse() {
683        let s = |v: &[&str]| v.iter().map(|x| (*x).to_string()).collect::<Vec<_>>();
684        assert_eq!(parse_mode(&[]), Ok(Mode::Worktree));
685        assert_eq!(parse_mode(&s(&["--staged"])), Ok(Mode::Staged));
686        assert_eq!(
687            parse_mode(&s(&["--rev", "main..HEAD"])),
688            Ok(Mode::Rev("main".into(), "HEAD".into()))
689        );
690        assert_eq!(
691            parse_mode(&s(&["--rev=v1"])),
692            Ok(Mode::Rev("v1".into(), "HEAD".into()))
693        );
694        assert_eq!(parse_mode(&s(&["--diff", "-"])), Ok(Mode::Diff("-".into())));
695        assert!(parse_mode(&s(&["--bogus"])).is_err());
696    }
697
698    #[test]
699    fn name_status_reads_renames() {
700        let z = "M\0src/a.rs\0R087\0old.rs\0new.rs\0A\0b.rs\0";
701        assert_eq!(
702            parse_name_status(z),
703            vec![
704                ('M', None, "src/a.rs".to_string()),
705                ('R', Some("old.rs".to_string()), "new.rs".to_string()),
706                ('A', None, "b.rs".to_string()),
707            ]
708        );
709    }
710
711    #[test]
712    fn unified_diff_maps_hunk_lines() {
713        let diff = "diff --git a/src/a.rs b/src/a.rs\n--- a/src/a.rs\n+++ b/src/a.rs\n\
714                    @@ -10,2 +10,3 @@ fn x\n ctx\n-old\n+new1\n+new2\n\
715                    diff --git a/n.rs b/n.rs\nnew file mode 100644\n--- /dev/null\n+++ b/n.rs\n\
716                    @@ -0,0 +1 @@\n+fresh\n";
717        let changes = parse_unified_diff(diff);
718        assert_eq!(changes.len(), 2);
719        assert_eq!(changes[0].path, "src/a.rs");
720        assert_eq!(changes[0].before.as_deref(), Some("ctx\nold\n"));
721        assert_eq!(changes[0].after.as_deref(), Some("ctx\nnew1\nnew2\n"));
722        assert_eq!(changes[0].line_map.as_deref(), Some(&[10, 11, 12][..]));
723        assert_eq!(changes[1].path, "n.rs");
724        assert_eq!(changes[1].before, None);
725        assert_eq!(changes[1].after.as_deref(), Some("fresh\n"));
726    }
727
728    fn git_ok(root: &Path, args: &[&str]) {
729        let st = Command::new("git")
730            .arg("-C")
731            .arg(root)
732            .args([
733                "-c",
734                "user.name=t",
735                "-c",
736                "user.email=t@example.invalid",
737                "-c",
738                "commit.gpgsign=false",
739            ])
740            .args(args)
741            .output()
742            .expect("git");
743        assert!(
744            st.status.success(),
745            "{args:?}: {}",
746            String::from_utf8_lossy(&st.stderr)
747        );
748    }
749
750    #[test]
751    fn rev_check_uses_base_decisions_and_flags_introduced_violations() {
752        let tmp = tempfile::tempdir().unwrap();
753        let root = tmp.path();
754        git_ok(root, &["init", "-q", "-b", "main"]);
755        let dir = root.join(DECISIONS_DIR);
756        std::fs::create_dir_all(&dir).unwrap();
757        std::fs::write(
758            dir.join("dec-no-print.toml"),
759            "id = \"dec-no-print\"\ntitle = \"No println\"\nstatement = \"Use tracing.\"\n\
760             status = \"active\"\ndecided_by = \"team\"\ndecided_at = \"2026-11-12\"\n\
761             [scope]\npaths = [\"src/**\"]\n\
762             [[check]]\nkind = \"forbid_regex\"\npattern = \"println!\"\nmessage = \"use tracing\"\n",
763        )
764        .unwrap();
765        std::fs::create_dir_all(root.join("src")).unwrap();
766        std::fs::write(root.join("src/a.rs"), "fn a() { println!(\"legacy\"); }\n").unwrap();
767        git_ok(root, &["add", "-A"]);
768        git_ok(root, &["commit", "-q", "-m", "base"]);
769        // The change adds a println and deletes the decision: judged by the base.
770        std::fs::write(
771            root.join("src/b.rs"),
772            "fn b() {\n    println!(\"new\");\n}\n",
773        )
774        .unwrap();
775        std::fs::remove_file(dir.join("dec-no-print.toml")).unwrap();
776        git_ok(root, &["add", "-A"]);
777        git_ok(root, &["commit", "-q", "-m", "change"]);
778        let report = check(root, &Mode::Rev("HEAD~1".into(), "HEAD".into()));
779        assert_eq!(report.code, 1, "{}{}", report.stdout, report.stderr);
780        assert_eq!(
781            report.stdout,
782            "dec-no-print (No println) at src/b.rs:2 [forbid_regex]: use tracing\n"
783        );
784        // The working tree has no decisions any more: nothing to check.
785        let clean = check(root, &Mode::Worktree);
786        assert_eq!(clean.code, 0, "{}{}", clean.stdout, clean.stderr);
787    }
788
789    #[test]
790    fn rev_refuses_option_like_revisions() {
791        let s = |v: &[&str]| v.iter().map(|x| (*x).to_string()).collect::<Vec<_>>();
792        for range in [
793            "HEAD..--output=/tmp/x",
794            "--output=/tmp/x..HEAD",
795            "--output=x..HEAD",
796            "-x",
797            "HEAD..-x",
798            "HEAD.. --output=x",
799            "HEAD..a\nb",
800        ] {
801            assert!(
802                parse_mode(&s(&["--rev", range])).is_err(),
803                "accepted --rev {range:?}"
804            );
805            assert!(
806                parse_mode(&s(&[&format!("--rev={range}")])).is_err(),
807                "accepted --rev={range:?}"
808            );
809        }
810        // `--rev` followed by an option: the option is the (refused) range.
811        assert!(parse_mode(&s(&["--rev", "--output=x"])).is_err());
812    }
813
814    #[test]
815    fn rev_check_with_option_like_revisions_writes_nothing() {
816        let tmp = tempfile::tempdir().unwrap();
817        let root = tmp.path();
818        git_ok(root, &["init", "-q", "-b", "main"]);
819        let dir = root.join(DECISIONS_DIR);
820        std::fs::create_dir_all(&dir).unwrap();
821        std::fs::write(
822            dir.join("dec-x.toml"),
823            "id = \"dec-x\"\ntitle = \"X\"\nstatement = \"S.\"\nstatus = \"active\"\n\
824             decided_by = \"team\"\ndecided_at = \"2026-11-12\"\n[scope]\npaths = [\"**\"]\n\
825             [[check]]\nkind = \"forbid_regex\"\npattern = \"never-matches-here\"\nmessage = \"m\"\n",
826        )
827        .unwrap();
828        git_ok(root, &["add", "-A"]);
829        git_ok(root, &["commit", "-q", "-m", "base"]);
830        let target = root.join("overwritten");
831        let out = format!("--output={}", target.display());
832        // `check` itself refuses even if a caller skips `parse_mode`.
833        for (a, b) in [
834            ("HEAD", out.as_str()),
835            (out.as_str(), "HEAD"),
836            ("-x", "HEAD"),
837            ("HEAD", ""),
838        ] {
839            let report = check(root, &Mode::Rev(a.to_string(), b.to_string()));
840            assert_eq!(
841                report.code, 2,
842                "{a}..{b}: {}{}",
843                report.stdout, report.stderr
844            );
845            assert!(!target.exists(), "{a}..{b} wrote {}", target.display());
846        }
847        // A real range still resolves.
848        let ok = check(root, &Mode::Rev("HEAD".into(), "HEAD".into()));
849        assert_eq!(ok.code, 0, "{}{}", ok.stdout, ok.stderr);
850    }
851}