1use 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
27const MAX_FILE_BYTES: usize = 1_000_000;
29const MAX_TREE_FILES: usize = 5_000;
31
32pub fn cmd_decisions(args: &[String]) {
33 let code = run(args);
34 if code != 0 {
35 std::process::exit(code);
36 }
37}
38
39fn run(args: &[String]) -> i32 {
40 let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
41 let action = args.first().map_or("help", String::as_str);
42 let rest = args.get(1..).unwrap_or_default();
43 match action {
44 "list" | "ls" => {
45 let (path, symbol) = (flag(rest, "--path"), flag(rest, "--symbol"));
46 let root = project_root(&cwd);
47 println!(
48 "{}",
49 decisions::query_text(&root, path.as_deref(), symbol.as_deref())
50 );
51 0
52 }
53 "show" => show(&cwd, rest),
54 "check" => match parse_mode(rest) {
55 Ok(mode) => {
56 let report = check(&project_root(&cwd), &mode);
57 print!("{}", report.stdout);
58 eprint!("{}", report.stderr);
59 report.code
60 }
61 Err(e) => {
62 eprintln!("lean-ctx decisions check: {e}\n{USAGE}");
63 2
64 }
65 },
66 "new" => new(&cwd, rest),
67 "help" | "--help" | "-h" => {
68 println!("{USAGE}");
69 0
70 }
71 other => {
72 eprintln!("lean-ctx decisions: unknown command `{other}`\n{USAGE}");
73 2
74 }
75 }
76}
77
78fn flag(args: &[String], name: &str) -> Option<String> {
79 let mut it = args.iter();
80 while let Some(a) = it.next() {
81 if a == name {
82 return it.next().cloned();
83 }
84 if let Some(v) = a.strip_prefix(name).and_then(|r| r.strip_prefix('=')) {
85 return Some(v.to_string());
86 }
87 }
88 None
89}
90
91fn project_root(cwd: &Path) -> PathBuf {
93 decisions::find_root(cwd)
94 .or_else(|| {
95 git(cwd, &["rev-parse", "--show-toplevel"])
96 .ok()
97 .map(|s| PathBuf::from(s.trim()))
98 })
99 .unwrap_or_else(|| cwd.to_path_buf())
100}
101
102fn show(cwd: &Path, rest: &[String]) -> i32 {
103 let Some(id) = rest.first() else {
104 eprintln!("{USAGE}");
105 return 2;
106 };
107 let root = project_root(cwd);
108 let set = decisions::load(&root);
109 if let Some(d) = set.get(id) {
110 print!("{}", decisions::describe(&set, d));
111 0
112 } else {
113 eprintln!(
114 "No decision `{id}` in {}",
115 root.join(DECISIONS_DIR).display()
116 );
117 1
118 }
119}
120
121fn new(cwd: &Path, rest: &[String]) -> i32 {
122 let Some(slug) = rest.first().filter(|s| !s.starts_with("--")) else {
123 eprintln!("{USAGE}");
124 return 2;
125 };
126 let Some(id) = decisions::id_from_slug(slug) else {
127 eprintln!("`{slug}` has no letters or digits to build an id from");
128 return 2;
129 };
130 let title = flag(rest, "--title").unwrap_or_else(|| slug.clone());
131 let root = project_root(cwd);
132 let dir = root.join(DECISIONS_DIR);
133 let file = dir.join(format!("{id}.toml"));
134 let today = chrono::Local::now().format("%Y-%m-%d").to_string();
135 let written = std::fs::create_dir_all(&dir).and_then(|()| {
136 use std::io::Write;
137 std::fs::OpenOptions::new()
138 .write(true)
139 .create_new(true)
140 .open(&file)?
141 .write_all(decisions::scaffold(&id, &title, &today).as_bytes())
142 });
143 match written {
144 Ok(()) => {
145 println!(
146 "Created {DECISIONS_DIR}/{id}.toml. Fill in statement, rationale, source, scope \
147 and checks; `lean-ctx decisions check` validates every record."
148 );
149 0
150 }
151 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
152 eprintln!("{DECISIONS_DIR}/{id}.toml exists; edit it or pick another slug");
153 1
154 }
155 Err(e) => {
156 eprintln!("cannot write {}: {e}", file.display());
157 2
158 }
159 }
160}
161
162#[derive(Debug, PartialEq, Eq)]
165enum Mode {
166 Worktree,
168 Staged,
170 Rev(String, String),
172 Diff(String),
174}
175
176fn parse_mode(rest: &[String]) -> Result<Mode, String> {
177 if let Some(range) = flag(rest, "--rev") {
178 let (a, b) = match range.split_once("..") {
179 Some((a, b)) => (a.trim_end_matches('.'), b.trim_start_matches('.')),
180 None => (range.as_str(), ""),
181 };
182 if a.is_empty() {
183 return Err(format!("--rev `{range}` names no base"));
184 }
185 let b = if b.is_empty() { "HEAD" } else { b };
186 return Ok(Mode::Rev(a.to_string(), b.to_string()));
187 }
188 if let Some(file) = flag(rest, "--diff") {
189 return Ok(Mode::Diff(file));
190 }
191 if rest.iter().any(|a| a == "--staged" || a == "--cached") {
192 return Ok(Mode::Staged);
193 }
194 match rest.first() {
195 Some(other) => Err(format!("unknown argument `{other}`")),
196 None => Ok(Mode::Worktree),
197 }
198}
199
200#[derive(Debug, Default, PartialEq, Eq)]
202struct Change {
203 path: String,
204 renamed_from: Option<String>,
206 before: Option<String>,
208 after: Option<String>,
210 line_map: Option<Vec<usize>>,
212}
213
214struct Report {
215 stdout: String,
216 stderr: String,
217 code: i32,
218}
219
220fn check(root: &Path, mode: &Mode) -> Report {
221 let mut report = Report {
222 stdout: String::new(),
223 stderr: String::new(),
224 code: 0,
225 };
226 let set = match mode {
227 Mode::Rev(a, _) => base_set(root, a),
228 _ => Ok(std::sync::Arc::unwrap_or_clone(decisions::load(root))),
229 };
230 let set = match set {
231 Ok(set) => set,
232 Err(e) => {
233 report.stderr = format!("lean-ctx decisions check: {e}\n");
234 report.code = 2;
235 return report;
236 }
237 };
238 for e in &set.errors {
239 report
240 .stderr
241 .push_str(&format!("invalid record (not applied): {e}\n"));
242 }
243 if set.decisions.is_empty() {
244 report.stdout = format!("decisions check: no decisions in {DECISIONS_DIR}\n");
245 report.code = if set.errors.is_empty() { 0 } else { 2 };
246 return report;
247 }
248 let changes = match mode {
249 Mode::Diff(file) => read_diff(file).map(|t| (parse_unified_diff(&t), 0)),
250 _ => git_changes(root, mode),
251 };
252 let (changes, skipped) = match changes {
253 Ok(c) => c,
254 Err(e) => {
255 report
256 .stderr
257 .push_str(&format!("lean-ctx decisions check: {e}\n"));
258 report.code = 2;
259 return report;
260 }
261 };
262 let tree: OnceCell<Vec<String>> = OnceCell::new();
263 let rev_other = |d: &Decision, c: &Check, exclude: &str| match mode {
264 Mode::Rev(_, b) => tree_contains(root, b, &tree, d, c, exclude),
265 Mode::Diff(_) => decisions::check::worktree_other_files(root, d, c, ""),
267 _ => decisions::check::worktree_other_files(root, d, c, exclude),
268 };
269 let mut violations: Vec<Violation> = Vec::new();
270 for ch in &changes {
271 violations.extend(violations_of(&set, ch, &rev_other));
272 }
273 for v in &violations {
274 report.stdout.push_str(&v.render());
275 report.stdout.push('\n');
276 }
277 let skipped_note = if skipped > 0 {
278 format!(", {skipped} skipped (binary or over {MAX_FILE_BYTES} bytes)")
279 } else {
280 String::new()
281 };
282 let summary = format!(
283 "decisions check: {} violation(s) in {} changed file(s){skipped_note}\n",
284 violations.len(),
285 changes.len()
286 );
287 if violations.is_empty() {
288 report.stdout.push_str(&summary);
289 report.code = if set.errors.is_empty() { 0 } else { 2 };
290 } else {
291 report.stderr.push_str(&summary);
292 report.code = 1;
293 }
294 report
295}
296
297fn violations_of(set: &DecisionSet, ch: &Change, other: OtherFiles<'_>) -> Vec<Violation> {
298 let eval = |before: Option<&str>| {
299 decisions::evaluate_change_with(set, &ch.path, before, ch.after.as_deref(), other)
300 };
301 let mut out = eval(ch.before.as_deref());
302 if ch
303 .renamed_from
304 .as_deref()
305 .is_some_and(|from| from != ch.path)
306 && ch.after.is_some()
307 {
308 out.extend(
310 eval(None)
311 .into_iter()
312 .filter(|v| v.kind == CheckKind::ForbidPath),
313 );
314 }
315 if let Some(map) = &ch.line_map {
316 for v in &mut out {
317 v.line = v.line.and_then(|l| map.get(l.saturating_sub(1)).copied());
318 }
319 }
320 out
321}
322
323fn base_set(root: &Path, rev: &str) -> Result<DecisionSet, String> {
325 let listing = git(
326 root,
327 &[
328 "ls-tree",
329 "-z",
330 "--name-only",
331 rev,
332 "--",
333 &format!("{DECISIONS_DIR}/"),
334 ],
335 )?;
336 let records = listing
337 .split('\0')
338 .filter(|p| Path::new(p).extension().is_some_and(|e| e == "toml"))
339 .map(|p| {
340 let text = blob(root, &format!("{rev}:{p}"))
341 .ok_or_else(|| "unreadable at the base commit".to_string());
342 (p.to_string(), text)
343 })
344 .collect();
345 Ok(decisions::from_records(root, records))
346}
347
348fn tree_contains(
350 root: &Path,
351 rev: &str,
352 tree: &OnceCell<Vec<String>>,
353 d: &Decision,
354 c: &Check,
355 exclude: &str,
356) -> bool {
357 let Some(re) = c.regex() else {
358 return true;
359 };
360 let files = tree.get_or_init(|| {
361 git(root, &["ls-tree", "-r", "-z", "--name-only", rev])
362 .map(|s| {
363 s.split('\0')
364 .filter(|p| !p.is_empty())
365 .map(str::to_string)
366 .collect()
367 })
368 .unwrap_or_default()
369 });
370 if files.is_empty() {
371 return true;
372 }
373 let mut seen = 0usize;
374 for f in files {
375 if f == exclude || !c.covers(d, f) {
376 continue;
377 }
378 seen += 1;
379 if seen > MAX_TREE_FILES {
380 return true;
381 }
382 if blob(root, &format!("{rev}:{f}")).is_some_and(|t| re.is_match(&t)) {
383 return true;
384 }
385 }
386 false
387}
388
389fn git(dir: &Path, args: &[&str]) -> Result<String, String> {
390 let out = Command::new("git")
391 .arg("-C")
392 .arg(dir)
393 .args(args)
394 .output()
395 .map_err(|e| format!("git: {e}"))?;
396 if !out.status.success() {
397 return Err(format!(
398 "git {}: {}",
399 args.join(" "),
400 String::from_utf8_lossy(&out.stderr).trim()
401 ));
402 }
403 String::from_utf8(out.stdout)
404 .map_err(|_| format!("git {}: output is not UTF-8", args.join(" ")))
405}
406
407fn blob(root: &Path, spec: &str) -> Option<String> {
409 let out = Command::new("git")
410 .arg("-C")
411 .arg(root)
412 .args(["cat-file", "blob", spec])
413 .output()
414 .ok()?;
415 (out.status.success() && out.stdout.len() <= MAX_FILE_BYTES)
416 .then(|| String::from_utf8(out.stdout).ok())
417 .flatten()
418}
419
420fn read_disk(root: &Path, rel: &str) -> Option<String> {
421 let path = root.join(rel);
422 let len = std::fs::metadata(&path).ok()?.len();
423 (len <= MAX_FILE_BYTES as u64)
424 .then(|| std::fs::read_to_string(path).ok())
425 .flatten()
426}
427
428fn parse_name_status(z: &str) -> Vec<(char, Option<String>, String)> {
430 let mut out = Vec::new();
431 let mut it = z.split('\0').filter(|s| !s.is_empty());
432 while let Some(status) = it.next() {
433 let kind = status.chars().next().unwrap_or('M');
434 if matches!(kind, 'R' | 'C') {
435 if let (Some(from), Some(to)) = (it.next(), it.next()) {
436 out.push((kind, Some(from.to_string()), to.to_string()));
437 }
438 } else if let Some(p) = it.next() {
439 out.push((kind, None, p.to_string()));
440 }
441 }
442 out
443}
444
445fn git_changes(root: &Path, mode: &Mode) -> Result<(Vec<Change>, usize), String> {
447 let (base, mut entries) = match mode {
448 Mode::Worktree => {
449 let mut e =
450 parse_name_status(&git(root, &["diff", "--name-status", "-z", "-M", "HEAD"])?);
451 let untracked = git(root, &["ls-files", "-z", "--others", "--exclude-standard"])?;
452 e.extend(
453 untracked
454 .split('\0')
455 .filter(|p| !p.is_empty())
456 .map(|p| ('A', None, p.to_string())),
457 );
458 ("HEAD".to_string(), e)
459 }
460 Mode::Staged => (
461 "HEAD".to_string(),
462 parse_name_status(&git(
463 root,
464 &["diff", "--cached", "--name-status", "-z", "-M", "HEAD"],
465 )?),
466 ),
467 Mode::Rev(a, b) => (
468 a.clone(),
469 parse_name_status(&git(root, &["diff", "--name-status", "-z", "-M", a, b])?),
470 ),
471 Mode::Diff(_) => return Ok((Vec::new(), 0)),
472 };
473 entries.sort_by(|x, y| x.2.cmp(&y.2));
474 let mut changes = Vec::new();
475 let mut skipped = 0usize;
476 for (kind, from, path) in entries {
477 if matches!(kind, 'D' | 'U') {
478 continue;
479 }
480 let after = match mode {
481 Mode::Worktree => read_disk(root, &path),
482 Mode::Staged => blob(root, &format!(":{path}")),
483 Mode::Rev(_, b) => blob(root, &format!("{b}:{path}")),
484 Mode::Diff(_) => None,
485 };
486 let before = match kind {
487 'A' | 'C' => Some(None),
488 _ => {
489 let old = from.as_deref().unwrap_or(&path);
490 blob(root, &format!("{base}:{old}")).map(Some)
491 }
492 };
493 let (Some(after), Some(before)) = (after, before) else {
494 skipped += 1;
495 continue;
496 };
497 changes.push(Change {
498 renamed_from: from.filter(|_| kind == 'R'),
499 path,
500 before,
501 after: Some(after),
502 line_map: None,
503 });
504 }
505 Ok((changes, skipped))
506}
507
508fn read_diff(file: &str) -> Result<String, String> {
509 if file == "-" {
510 let mut text = String::new();
511 std::io::Read::read_to_string(&mut std::io::stdin(), &mut text)
512 .map_err(|e| format!("stdin: {e}"))?;
513 Ok(text)
514 } else {
515 std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))
516 }
517}
518
519fn diff_path(header: &str, prefix: &str) -> Option<String> {
520 let p = header.split('\t').next().unwrap_or(header).trim();
521 (p != "/dev/null").then(|| p.strip_prefix(prefix).unwrap_or(p).to_string())
522}
523
524fn parse_unified_diff(text: &str) -> Vec<Change> {
528 let mut out: Vec<Change> = Vec::new();
529 let mut old: Option<Option<String>> = None;
530 let mut cur: Option<(Change, usize)> = None;
531 let lines: Vec<&str> = text.lines().collect();
532 for (i, &line) in lines.iter().enumerate() {
533 let header = lines.get(i + 1).is_some_and(|n| n.starts_with("+++ "));
535 if line.starts_with("diff ") {
536 out.extend(cur.take().map(|(c, _)| c));
537 old = None;
538 } else if let Some(h) = line.strip_prefix("--- ").filter(|_| header) {
539 out.extend(cur.take().map(|(c, _)| c));
540 old = Some(diff_path(h, "a/"));
541 } else if let (Some(h), Some(from)) = (line.strip_prefix("+++ "), old.clone()) {
542 let to = diff_path(h, "b/");
543 let path = to.clone().or_else(|| from.clone()).unwrap_or_default();
544 cur = Some((
545 Change {
546 renamed_from: from
547 .clone()
548 .filter(|f| Some(f) != to.as_ref() && to.is_some()),
549 path,
550 before: from.map(|_| String::new()),
551 after: to.map(|_| String::new()),
552 line_map: Some(Vec::new()),
553 },
554 1,
555 ));
556 old = None;
557 } else if let Some(h) = line.strip_prefix("@@ ") {
558 if let Some((_, next)) = cur.as_mut() {
559 *next = h
560 .split_whitespace()
561 .find_map(|t| t.strip_prefix('+'))
562 .and_then(|t| t.split(',').next()?.parse().ok())
563 .unwrap_or(1);
564 }
565 } else if let Some((c, next)) = cur.as_mut() {
566 let (tag, body) = line.split_at(line.len().min(1));
567 let push_after = |c: &mut Change, next: &mut usize| {
568 if let Some(a) = c.after.as_mut() {
569 a.push_str(body);
570 a.push('\n');
571 if let Some(m) = c.line_map.as_mut() {
572 m.push(*next);
573 }
574 }
575 *next += 1;
576 };
577 match tag {
578 "+" => push_after(c, next),
579 "-" => {
580 if let Some(b) = c.before.as_mut() {
581 b.push_str(body);
582 b.push('\n');
583 }
584 }
585 " " | "" => {
586 if let Some(b) = c.before.as_mut() {
587 b.push_str(body);
588 b.push('\n');
589 }
590 push_after(c, next);
591 }
592 _ => {}
593 }
594 }
595 }
596 out.extend(cur.map(|(c, _)| c));
597 out
598}
599
600#[cfg(test)]
601mod tests {
602 use super::*;
603
604 #[test]
605 fn modes_parse() {
606 let s = |v: &[&str]| v.iter().map(|x| (*x).to_string()).collect::<Vec<_>>();
607 assert_eq!(parse_mode(&[]), Ok(Mode::Worktree));
608 assert_eq!(parse_mode(&s(&["--staged"])), Ok(Mode::Staged));
609 assert_eq!(
610 parse_mode(&s(&["--rev", "main..HEAD"])),
611 Ok(Mode::Rev("main".into(), "HEAD".into()))
612 );
613 assert_eq!(
614 parse_mode(&s(&["--rev=v1"])),
615 Ok(Mode::Rev("v1".into(), "HEAD".into()))
616 );
617 assert_eq!(parse_mode(&s(&["--diff", "-"])), Ok(Mode::Diff("-".into())));
618 assert!(parse_mode(&s(&["--bogus"])).is_err());
619 }
620
621 #[test]
622 fn name_status_reads_renames() {
623 let z = "M\0src/a.rs\0R087\0old.rs\0new.rs\0A\0b.rs\0";
624 assert_eq!(
625 parse_name_status(z),
626 vec![
627 ('M', None, "src/a.rs".to_string()),
628 ('R', Some("old.rs".to_string()), "new.rs".to_string()),
629 ('A', None, "b.rs".to_string()),
630 ]
631 );
632 }
633
634 #[test]
635 fn unified_diff_maps_hunk_lines() {
636 let diff = "diff --git a/src/a.rs b/src/a.rs\n--- a/src/a.rs\n+++ b/src/a.rs\n\
637 @@ -10,2 +10,3 @@ fn x\n ctx\n-old\n+new1\n+new2\n\
638 diff --git a/n.rs b/n.rs\nnew file mode 100644\n--- /dev/null\n+++ b/n.rs\n\
639 @@ -0,0 +1 @@\n+fresh\n";
640 let changes = parse_unified_diff(diff);
641 assert_eq!(changes.len(), 2);
642 assert_eq!(changes[0].path, "src/a.rs");
643 assert_eq!(changes[0].before.as_deref(), Some("ctx\nold\n"));
644 assert_eq!(changes[0].after.as_deref(), Some("ctx\nnew1\nnew2\n"));
645 assert_eq!(changes[0].line_map.as_deref(), Some(&[10, 11, 12][..]));
646 assert_eq!(changes[1].path, "n.rs");
647 assert_eq!(changes[1].before, None);
648 assert_eq!(changes[1].after.as_deref(), Some("fresh\n"));
649 }
650
651 fn git_ok(root: &Path, args: &[&str]) {
652 let st = Command::new("git")
653 .arg("-C")
654 .arg(root)
655 .args([
656 "-c",
657 "user.name=t",
658 "-c",
659 "user.email=t@example.invalid",
660 "-c",
661 "commit.gpgsign=false",
662 ])
663 .args(args)
664 .output()
665 .expect("git");
666 assert!(
667 st.status.success(),
668 "{args:?}: {}",
669 String::from_utf8_lossy(&st.stderr)
670 );
671 }
672
673 #[test]
674 fn rev_check_uses_base_decisions_and_flags_introduced_violations() {
675 let tmp = tempfile::tempdir().unwrap();
676 let root = tmp.path();
677 git_ok(root, &["init", "-q", "-b", "main"]);
678 let dir = root.join(DECISIONS_DIR);
679 std::fs::create_dir_all(&dir).unwrap();
680 std::fs::write(
681 dir.join("dec-no-print.toml"),
682 "id = \"dec-no-print\"\ntitle = \"No println\"\nstatement = \"Use tracing.\"\n\
683 status = \"active\"\ndecided_by = \"team\"\ndecided_at = \"2026-11-12\"\n\
684 [scope]\npaths = [\"src/**\"]\n\
685 [[check]]\nkind = \"forbid_regex\"\npattern = \"println!\"\nmessage = \"use tracing\"\n",
686 )
687 .unwrap();
688 std::fs::create_dir_all(root.join("src")).unwrap();
689 std::fs::write(root.join("src/a.rs"), "fn a() { println!(\"legacy\"); }\n").unwrap();
690 git_ok(root, &["add", "-A"]);
691 git_ok(root, &["commit", "-q", "-m", "base"]);
692 std::fs::write(
694 root.join("src/b.rs"),
695 "fn b() {\n println!(\"new\");\n}\n",
696 )
697 .unwrap();
698 std::fs::remove_file(dir.join("dec-no-print.toml")).unwrap();
699 git_ok(root, &["add", "-A"]);
700 git_ok(root, &["commit", "-q", "-m", "change"]);
701 let report = check(root, &Mode::Rev("HEAD~1".into(), "HEAD".into()));
702 assert_eq!(report.code, 1, "{}{}", report.stdout, report.stderr);
703 assert_eq!(
704 report.stdout,
705 "dec-no-print (No println) at src/b.rs:2 [forbid_regex]: use tracing\n"
706 );
707 let clean = check(root, &Mode::Worktree);
709 assert_eq!(clean.code, 0, "{}{}", clean.stdout, clean.stderr);
710 }
711}