Skip to main content

lean_ctx/core/git/
decision_history.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Draft decisions from the local git history (`lean-ctx decisions suggest`).
3//!
4//! Reads commit and merge-request messages through [`super::run_git`] and
5//! derives *draft* decision records that a human confirms. Nothing here ever
6//! writes into `.leanctx/decisions`: drafts go to the review file
7//! [`REVIEW_DIR`]/[`REVIEW_FILE`] only.
8//!
9//! Each draft carries a trust level:
10//!
11//! * [`Trust::Confirmed`]: the message states the decision explicitly
12//!   (`Decision:` trailer, `Owner decision:` line or a quoted owner answer);
13//!   the verbatim line is kept as evidence.
14//! * [`Trust::Reconstructed`]: derived from policy wording ("never", "no
15//!   longer", "from now on", ...) without an explicit marker.
16//! * [`Trust::Recheck`]: the evidence changed since the last suggestion (the
17//!   quote differs, or the commit is no longer in the history).
18//!
19//! Superseded drafts are detected from reverts (`This reverts commit <sha>`),
20//! `Supersedes:` trailers and a later draft on the same topic with the
21//! opposite polarity.
22//!
23//! [`confirm`] turns one draft into a record in `.leanctx/decisions` when a
24//! human asks for it (`lean-ctx decisions confirm <draft-id>`). The record keeps
25//! the verbatim quote and its commit in `[evidence]`; every later suggestion
26//! re-reads that evidence and reports the record's trust (`re-check` when the
27//! commit left the history or no longer holds the quote) and whether a later
28//! revert, trailer or opposite statement supersedes it (contract §38).
29//!
30//! The output is a deterministic function of the history and the previous
31//! review file: no timestamps, no counters, stable ordering (#498).
32
33use std::collections::{BTreeMap, BTreeSet, HashSet};
34use std::io::Write as _;
35use std::path::Path;
36use std::time::Duration;
37
38use serde::{Deserialize, Serialize};
39
40use crate::core::decisions::{self, NewRecord, RecordEvidence};
41
42/// Review location, relative to the repository root. Deliberately outside
43/// `.leanctx/decisions`, so no loader or sync ever treats a draft as a record.
44pub const REVIEW_DIR: &str = ".leanctx/decisions-review";
45/// The machine-owned review file inside [`REVIEW_DIR`].
46pub const REVIEW_FILE: &str = "suggested.json";
47/// Schema of the review file and of `--json`.
48pub const SCHEMA: &str = "leanctx.decisions-suggest/v1";
49/// Commits scanned by default (most recent first, then put in order).
50pub const DEFAULT_MAX_COMMITS: usize = 1000;
51const GIT_TIMEOUT: Duration = Duration::from_secs(60);
52const MIN_LINE: usize = 12;
53const MAX_LINE: usize = 240;
54
55/// How far a draft can be trusted.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
57#[serde(rename_all = "kebab-case")]
58pub enum Trust {
59    Confirmed,
60    Reconstructed,
61    Recheck,
62}
63
64impl Trust {
65    pub fn label(self) -> &'static str {
66        match self {
67            Trust::Confirmed => "confirmed",
68            Trust::Reconstructed => "reconstructed",
69            Trust::Recheck => "re-check",
70        }
71    }
72}
73
74/// Where a draft comes from.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76pub struct Evidence {
77    /// Full commit id.
78    pub commit: String,
79    /// Author date of the commit (`YYYY-MM-DD`), part of the history.
80    pub date: String,
81    /// `merge-request` when the commit carries a GitLab MR footer, else `commit`.
82    pub kind: String,
83    /// `!<n>` for a merge request, the short commit id otherwise.
84    #[serde(rename = "ref")]
85    pub reference: String,
86    /// The message line, verbatim (trimmed).
87    pub quote: String,
88    /// blake3 of commit + quote: changes when the evidence changes.
89    pub hash: String,
90}
91
92/// One draft decision awaiting human review.
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94pub struct Draft {
95    pub id: String,
96    pub title: String,
97    pub statement: String,
98    /// `draft` or `superseded`. Never `active`: only a human confirms.
99    pub status: String,
100    pub trust: Trust,
101    pub evidence: Evidence,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub recheck_reason: Option<String>,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub superseded_by: Option<String>,
106    #[serde(default, skip_serializing_if = "Vec::is_empty")]
107    pub supersedes: Vec<String>,
108    /// Further commits that repeat the same statement (e.g. an MR merge body).
109    #[serde(default, skip_serializing_if = "Vec::is_empty")]
110    pub also_in: Vec<String>,
111}
112
113/// The review file / `--json` document.
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115pub struct Report {
116    pub schema: String,
117    /// The scanned revision range, e.g. `HEAD` or `v1.0..HEAD`.
118    pub range: String,
119    /// Drafts skipped because `.leanctx/decisions` already has the statement.
120    #[serde(default)]
121    pub already_recorded: Vec<String>,
122    /// Active records that a later revert, `Supersedes:` trailer or opposite
123    /// statement supersedes: re-check them (ids, sorted).
124    #[serde(default)]
125    pub records_superseded: Vec<String>,
126    /// Trust of the active records that carry `[evidence]` or are superseded,
127    /// sorted by id.
128    #[serde(default)]
129    pub records: Vec<RecordTrust>,
130    pub drafts: Vec<Draft>,
131}
132
133/// Trust of one confirmed record, re-read from the history on every run.
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135pub struct RecordTrust {
136    pub id: String,
137    /// Absent for a record without `[evidence]` (written by hand).
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub trust: Option<Trust>,
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub recheck_reason: Option<String>,
142    /// A draft id, or `revert <commit>`.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub superseded_by: Option<String>,
145}
146
147/// What a suggestion needs of one record in `.leanctx/decisions`.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct RecordInfo {
150    pub id: String,
151    pub statement: String,
152    /// `YYYY-MM-DD`.
153    pub decided_at: String,
154    /// In force: status `active` and not superseded by another record.
155    pub active: bool,
156    pub evidence: Option<RecordEvidence>,
157}
158
159/// Options of one suggestion run.
160#[derive(Debug, Clone)]
161pub struct Options {
162    pub since: Option<String>,
163    pub max_commits: usize,
164}
165
166impl Default for Options {
167    fn default() -> Self {
168        Self {
169            since: None,
170            max_commits: DEFAULT_MAX_COMMITS,
171        }
172    }
173}
174
175/// One commit as read from `git log`.
176#[derive(Debug, Clone)]
177pub struct Commit {
178    pub sha: String,
179    pub date: String,
180    pub message: String,
181}
182
183/// Read the commits of `range` (oldest first), at most `max` of them.
184///
185/// Records are NUL-separated (`-z`; git refuses NUL in a message), and the
186/// ids are cross-checked against a plain `--format=%H` listing, so no message
187/// text can forge a commit record (fake id or date).
188pub fn read_commits(root: &Path, range: &str, max: usize) -> Result<Vec<Commit>, String> {
189    let max_arg = format!("--max-count={}", max.max(1));
190    let log = |format: &str, nul: bool| -> Result<String, String> {
191        let mut args = vec!["log", "--no-color", "--no-show-signature", &max_arg];
192        if nul {
193            args.push("-z");
194        }
195        args.extend([format, range, "--"]);
196        super::run_git(&args, root, GIT_TIMEOUT, &[])?.ok_stdout()
197    };
198    let ids: Vec<String> = log("--format=%H", false)?
199        .lines()
200        .map(str::trim)
201        .filter(|l| !l.is_empty())
202        .map(str::to_string)
203        .collect();
204    let out = log("--format=%H%x1f%as%x1f%B", true)?;
205    let mut commits = Vec::with_capacity(ids.len());
206    for chunk in out.split('\0').filter(|c| !c.trim().is_empty()) {
207        let chunk = chunk.trim_start_matches(['\n', '\r']);
208        let mut parts = chunk.splitn(3, '\x1f');
209        let sha = parts.next().unwrap_or("").trim().to_string();
210        let date = parts.next().unwrap_or("").trim().to_string();
211        let message = parts.next().unwrap_or("").to_string();
212        if !is_hex_id(&sha) || !is_iso_date(&date) {
213            return Err(format!(
214                "git log output for {range} did not parse (commit record {})",
215                commits.len() + 1
216            ));
217        }
218        commits.push(Commit { sha, date, message });
219    }
220    if commits.len() != ids.len() || commits.iter().zip(&ids).any(|(c, id)| &c.sha != id) {
221        return Err(format!(
222            "git log output for {range} did not parse: the commit records do not match \
223             the history (did HEAD move? run again)"
224        ));
225    }
226    commits.reverse();
227    Ok(commits)
228}
229
230/// The repository root of `cwd`.
231pub fn repo_root(cwd: &Path) -> Result<std::path::PathBuf, String> {
232    let out =
233        super::run_git(&["rev-parse", "--show-toplevel"], cwd, GIT_TIMEOUT, &[])?.ok_stdout()?;
234    Ok(std::path::PathBuf::from(out.trim()))
235}
236
237/// Run a full suggestion: read history, compare with the previous review
238/// file, and return the new report (not yet written).
239pub fn suggest(root: &Path, opts: &Options) -> Result<Report, String> {
240    let range = match &opts.since {
241        Some(since) => {
242            if since.starts_with('-') {
243                return Err(format!("invalid --since ref: {since}"));
244            }
245            format!("{since}..HEAD")
246        }
247        None => "HEAD".to_string(),
248    };
249    let commits = read_commits(root, &range, opts.max_commits)?;
250    let records = read_records(root);
251    let previous = read_previous(root);
252    let history = GitHistory::load(root);
253    Ok(build_report(
254        &range,
255        &commits,
256        &records,
257        previous.as_ref(),
258        &history,
259    ))
260}
261
262/// What the history says about one commit.
263#[derive(Debug, Clone, PartialEq, Eq)]
264pub enum InHistory {
265    /// In HEAD's history, with its message.
266    Message(String),
267    /// Not in HEAD's history (rewritten or dropped).
268    Gone,
269    /// Git could not answer (error, timeout, shallow clone): keep what was
270    /// known and ask again next run.
271    Unknown,
272}
273
274/// Reachability and messages of commits, as [`build_report`] needs them.
275pub trait History {
276    /// `Some(true|false)` when known, `None` when git could not answer.
277    fn contains(&self, sha: &str) -> Option<bool>;
278    /// The message of `sha` when it is in the history.
279    fn message(&self, sha: &str) -> InHistory;
280}
281
282/// [`History`] of a repository: one `git rev-list HEAD` for reachability,
283/// one `git log -1` per message asked for.
284pub struct GitHistory {
285    root: std::path::PathBuf,
286    /// `None` when `rev-list` failed: every answer is [`InHistory::Unknown`].
287    reachable: Option<HashSet<String>>,
288    /// In a shallow clone a missing commit may be beyond the boundary.
289    shallow: bool,
290}
291
292impl GitHistory {
293    pub fn load(root: &Path) -> Self {
294        let reachable = super::run_git(&["rev-list", "HEAD"], root, GIT_TIMEOUT, &[])
295            .ok()
296            .and_then(|o| o.ok_stdout().ok())
297            .map(|out| {
298                out.lines()
299                    .map(|l| l.trim().to_ascii_lowercase())
300                    .filter(|l| !l.is_empty())
301                    .collect()
302            });
303        let shallow = super::run_git(
304            &["rev-parse", "--is-shallow-repository"],
305            root,
306            GIT_TIMEOUT,
307            &[],
308        )
309        .ok()
310        .and_then(|o| o.ok_stdout().ok())
311        .is_none_or(|out| out.trim() != "false");
312        Self {
313            root: root.to_path_buf(),
314            reachable,
315            shallow,
316        }
317    }
318
319    /// The full id of `sha` when it is reachable.
320    fn resolve(&self, sha: &str) -> Result<Option<String>, ()> {
321        if !is_hex_id(sha) {
322            return Ok(None);
323        }
324        let Some(set) = &self.reachable else {
325            return Err(());
326        };
327        let sha = sha.to_ascii_lowercase();
328        if set.contains(&sha) {
329            return Ok(Some(sha));
330        }
331        if sha.len() < 40 {
332            let mut hits = set.iter().filter(|full| full.starts_with(&sha));
333            if let (Some(full), None) = (hits.next(), hits.next()) {
334                return Ok(Some(full.clone()));
335            }
336        }
337        if self.shallow { Err(()) } else { Ok(None) }
338    }
339}
340
341impl History for GitHistory {
342    fn contains(&self, sha: &str) -> Option<bool> {
343        self.resolve(sha).ok().map(|full| full.is_some())
344    }
345
346    fn message(&self, sha: &str) -> InHistory {
347        match self.resolve(sha) {
348            Err(()) => InHistory::Unknown,
349            Ok(None) => InHistory::Gone,
350            Ok(Some(full)) => match super::run_git(
351                &[
352                    "log",
353                    "-1",
354                    "--no-color",
355                    "--no-show-signature",
356                    "--format=%B",
357                    &full,
358                    "--",
359                ],
360                &self.root,
361                GIT_TIMEOUT,
362                &[],
363            )
364            .ok()
365            .and_then(|o| o.ok_stdout().ok())
366            {
367                Some(m) => InHistory::Message(m),
368                None => InHistory::Unknown,
369            },
370        }
371    }
372}
373
374/// 7 to 64 hex digits.
375fn is_hex_id(s: &str) -> bool {
376    (7..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())
377}
378
379/// A calendar date `YYYY-MM-DD` (month 01-12, day valid for the month).
380pub fn is_iso_date(s: &str) -> bool {
381    let b = s.as_bytes();
382    if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
383        return false;
384    }
385    let num = |r: std::ops::Range<usize>| -> Option<u32> {
386        let part = &s[r];
387        part.bytes()
388            .all(|c| c.is_ascii_digit())
389            .then(|| part.parse().ok())
390            .flatten()
391    };
392    let (Some(year), Some(month), Some(day)) = (num(0..4), num(5..7), num(8..10)) else {
393        return false;
394    };
395    let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
396    let days = match month {
397        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
398        4 | 6 | 9 | 11 => 30,
399        2 if leap => 29,
400        2 => 28,
401        _ => return false,
402    };
403    (1..=days).contains(&day)
404}
405
406/// Whether `message` still yields exactly this (quote, statement, trust).
407fn extracts(message: &str, quote: &str, statement: &str, trust: Trust) -> bool {
408    extract(message)
409        .into_iter()
410        .any(|(q, st, t)| q == quote && st == statement && t == trust)
411}
412
413/// Author date (`YYYY-MM-DD`) of `sha`, read from git.
414fn commit_date(root: &Path, sha: &str) -> Result<String, String> {
415    if !is_hex_id(sha) {
416        return Err(format!("invalid commit id {}", short(sha)));
417    }
418    let out = super::run_git(
419        &["log", "-1", "--no-color", "--format=%as", sha, "--"],
420        root,
421        GIT_TIMEOUT,
422        &[],
423    )?
424    .ok_stdout()?;
425    let date = out.trim();
426    if is_iso_date(date) {
427        Ok(date.to_string())
428    } else {
429        Err(format!(
430            "git could not read the date of commit {}",
431            short(sha)
432        ))
433    }
434}
435
436/// The trust stored in a record's `[evidence]`.
437fn stored_trust(label: &str) -> Trust {
438    if label == Trust::Reconstructed.label() {
439        Trust::Reconstructed
440    } else {
441        Trust::Confirmed
442    }
443}
444
445/// Pure core of [`suggest`]: history in, report out.
446pub fn build_report(
447    range: &str,
448    commits: &[Commit],
449    records: &[RecordInfo],
450    previous: Option<&Report>,
451    history: &dyn History,
452) -> Report {
453    let mut drafts: Vec<Draft> = Vec::new();
454    let mut by_norm: BTreeMap<String, usize> = BTreeMap::new();
455    let mut reverts: Vec<(String, String)> = Vec::new();
456    let mut supersede_refs: Vec<(String, String)> = Vec::new();
457    let mut already: BTreeSet<String> = BTreeSet::new();
458    let mut records_superseded: BTreeSet<String> = BTreeSet::new();
459    let mut record_superseded_by: BTreeMap<String, String> = BTreeMap::new();
460    let record_norms: BTreeMap<String, String> = records
461        .iter()
462        .map(|r| (normalize(&r.statement), r.id.clone()))
463        .collect();
464
465    for commit in commits {
466        if let Some(target) = reverted_commit(&commit.message) {
467            reverts.push((target, commit.sha.clone()));
468        }
469        let (kind, reference) = source_of(commit);
470        let trailer_supersedes = supersedes_trailers(&commit.message);
471        let first_new = drafts.len();
472        for (quote, statement, trust) in extract(&commit.message) {
473            let norm = normalize(&statement);
474            if norm.is_empty() {
475                continue;
476            }
477            if let Some(id) = record_norms.get(&norm) {
478                already.insert(id.clone());
479                continue;
480            }
481            if let Some(&idx) = by_norm.get(&norm) {
482                let d = &mut drafts[idx];
483                if d.evidence.commit != commit.sha && !d.also_in.contains(&commit.sha) {
484                    d.also_in.push(commit.sha.clone());
485                }
486                // An explicit statement later upgrades a reconstructed one;
487                // the evidence moves to that commit, so the quote stays in it.
488                if trust == Trust::Confirmed && d.trust == Trust::Reconstructed {
489                    let old = std::mem::replace(&mut d.evidence.commit, commit.sha.clone());
490                    d.also_in.retain(|c| c != &commit.sha);
491                    if !d.also_in.contains(&old) {
492                        d.also_in.push(old);
493                    }
494                    d.trust = Trust::Confirmed;
495                    // Statement and quote both come from that commit, so
496                    // `confirm` finds the exact extraction there.
497                    d.title = title_of(&statement);
498                    d.statement = statement;
499                    d.evidence.date.clone_from(&commit.date);
500                    d.evidence.kind.clone_from(&kind);
501                    d.evidence.reference.clone_from(&reference);
502                    d.evidence.hash = evidence_hash(&commit.sha, &quote);
503                    d.evidence.quote = quote;
504                }
505                continue;
506            }
507            // Two statements of one commit can share their slug; suffix in
508            // extraction order so ids stay unique and deterministic.
509            let base = draft_id(&statement, &commit.sha);
510            let mut id = base.clone();
511            let mut n = 2;
512            while drafts.iter().any(|d| d.id == id) {
513                id = format!("{base}-{n}");
514                n += 1;
515            }
516            by_norm.insert(norm, drafts.len());
517            drafts.push(Draft {
518                id,
519                title: title_of(&statement),
520                statement,
521                status: "draft".into(),
522                trust,
523                evidence: Evidence {
524                    commit: commit.sha.clone(),
525                    date: commit.date.clone(),
526                    kind: kind.clone(),
527                    reference: reference.clone(),
528                    hash: evidence_hash(&commit.sha, &quote),
529                    quote,
530                },
531                recheck_reason: None,
532                superseded_by: None,
533                supersedes: Vec::new(),
534                also_in: Vec::new(),
535            });
536        }
537        for target in trailer_supersedes {
538            if records.iter().any(|r| r.active && r.id == target) {
539                let by = drafts
540                    .get(first_new)
541                    .map_or_else(|| short(&commit.sha).to_string(), |d| d.id.clone());
542                record_superseded_by.entry(target.clone()).or_insert(by);
543            }
544            if drafts.len() > first_new {
545                for d in &mut drafts[first_new..] {
546                    if !d.supersedes.contains(&target) {
547                        d.supersedes.push(target.clone());
548                    }
549                }
550                supersede_refs.push((target, drafts[first_new].id.clone()));
551            }
552        }
553    }
554
555    // Reverts supersede every draft of the reverted commit.
556    for (target, revert_sha) in &reverts {
557        for d in &mut drafts {
558            if d.superseded_by.is_none() && sha_matches(&d.evidence.commit, target) {
559                d.superseded_by = Some(format!("revert {}", short(revert_sha)));
560            }
561        }
562    }
563    // `Supersedes: <draft id | commit>` trailers.
564    for (target, newer) in &supersede_refs {
565        for d in &mut drafts {
566            if &d.id != newer
567                && d.superseded_by.is_none()
568                && (d.id == *target || sha_matches(&d.evidence.commit, target))
569            {
570                d.superseded_by = Some(newer.clone());
571            }
572        }
573    }
574    // Same topic, opposite polarity, later commit: the later one wins.
575    let topics: Vec<(Vec<String>, bool)> = drafts.iter().map(|d| topic_of(&d.statement)).collect();
576    for later in 1..drafts.len() {
577        let (topic, neg) = &topics[later];
578        if topic.is_empty() {
579            continue;
580        }
581        let newer_id = drafts[later].id.clone();
582        for earlier in 0..later {
583            let (t, n) = &topics[earlier];
584            if t == topic && n != neg && drafts[earlier].superseded_by.is_none() {
585                drafts[earlier].superseded_by = Some(newer_id.clone());
586                if !drafts[later].supersedes.contains(&drafts[earlier].id) {
587                    let id = drafts[earlier].id.clone();
588                    drafts[later].supersedes.push(id);
589                }
590            }
591        }
592    }
593    for d in &mut drafts {
594        if d.superseded_by.is_some() {
595            d.status = "superseded".into();
596        }
597    }
598
599    // Confirmed records: re-read their evidence and look for what replaces them.
600    let mut record_rows: Vec<RecordTrust> = Vec::new();
601    for rec in records.iter().filter(|r| r.active) {
602        let mut superseded_by = record_superseded_by.get(&rec.id).cloned();
603        if superseded_by.is_none()
604            && let Some(ev) = &rec.evidence
605        {
606            superseded_by = reverts
607                .iter()
608                .find(|(target, _)| same_commit(&ev.commit, target))
609                .map(|(_, revert_sha)| format!("revert {}", short(revert_sha)));
610        }
611        if superseded_by.is_none() {
612            let (topic, neg) = topic_of(&rec.statement);
613            if !topic.is_empty()
614                && let Some(d) = drafts.iter_mut().rev().find(|d| {
615                    let (t, n) = topic_of(&d.statement);
616                    d.superseded_by.is_none()
617                        && d.evidence.date.as_str() >= rec.decided_at.as_str()
618                        && t == topic
619                        && n != neg
620                })
621            {
622                if !d.supersedes.contains(&rec.id) {
623                    d.supersedes.push(rec.id.clone());
624                }
625                superseded_by = Some(d.id.clone());
626            }
627        }
628        let (trust, recheck_reason) = match &rec.evidence {
629            None => (None, None),
630            Some(ev) => match history.message(&ev.commit) {
631                // Git could not answer: pass the stored trust on, ask again
632                // next run.
633                InHistory::Unknown => (Some(stored_trust(&ev.trust)), None),
634                InHistory::Gone => (
635                    Some(Trust::Recheck),
636                    Some(format!(
637                        "evidence commit {} is no longer in the history",
638                        short(&ev.commit)
639                    )),
640                ),
641                InHistory::Message(message) if quote_in(&message, &ev.quote) => {
642                    (Some(stored_trust(&ev.trust)), None)
643                }
644                InHistory::Message(_) => (
645                    Some(Trust::Recheck),
646                    Some(format!(
647                        "the quote is no longer in the message of commit {}",
648                        short(&ev.commit)
649                    )),
650                ),
651            },
652        };
653        if superseded_by.is_some() {
654            records_superseded.insert(rec.id.clone());
655        }
656        if trust.is_some() || superseded_by.is_some() {
657            record_rows.push(RecordTrust {
658                id: rec.id.clone(),
659                trust,
660                recheck_reason,
661                superseded_by,
662            });
663        }
664    }
665    record_rows.sort_by(|a, b| a.id.cmp(&b.id));
666
667    // Compare with the last suggestion.
668    if let Some(prev) = previous {
669        let current: BTreeMap<String, usize> = drafts
670            .iter()
671            .enumerate()
672            .map(|(i, d)| (d.id.clone(), i))
673            .collect();
674        for old in &prev.drafts {
675            if let Some(&i) = current.get(&old.id) {
676                let d = &mut drafts[i];
677                if d.evidence.hash != old.evidence.hash {
678                    d.trust = Trust::Recheck;
679                    d.recheck_reason = Some(format!(
680                        "evidence changed since the last suggestion (was: \"{}\")",
681                        old.evidence.quote
682                    ));
683                } else if old.trust == Trust::Recheck {
684                    // Stays flagged until a human clears the review file.
685                    d.trust = Trust::Recheck;
686                    d.recheck_reason.clone_from(&old.recheck_reason);
687                }
688            } else {
689                let norm = normalize(&old.statement);
690                if let Some(id) = record_norms.get(&norm) {
691                    // Confirmed since the last suggestion.
692                    already.insert(id.clone());
693                    continue;
694                }
695                if let Some(&i) = by_norm.get(&norm) {
696                    // The same statement, now drafted from another commit
697                    // (a narrower --since): one draft per statement.
698                    let d = &mut drafts[i];
699                    let c = &old.evidence.commit;
700                    if !same_commit(&d.evidence.commit, c) && !d.also_in.contains(c) {
701                        d.also_in.push(c.clone());
702                        d.also_in.sort();
703                    }
704                    continue;
705                }
706                let mut d = old.clone();
707                // The file is untrusted: the title is derived again.
708                d.title = title_of(&d.statement);
709                // Outside the scanned range: keep it while it is in the
710                // history and its commit still yields this exact draft,
711                // or while git cannot say (asked again next run).
712                match history.message(&old.evidence.commit) {
713                    InHistory::Gone => {
714                        d.trust = Trust::Recheck;
715                        d.recheck_reason = Some(format!(
716                            "evidence commit {} is no longer in the history",
717                            short(&old.evidence.commit)
718                        ));
719                    }
720                    InHistory::Message(m)
721                        if old.trust != Trust::Recheck
722                            && !extracts(&m, &old.evidence.quote, &old.statement, old.trust) =>
723                    {
724                        d.trust = Trust::Recheck;
725                        d.recheck_reason = Some(format!(
726                            "the draft no longer matches commit {}",
727                            short(&old.evidence.commit)
728                        ));
729                    }
730                    InHistory::Message(_) | InHistory::Unknown => {}
731                }
732                by_norm.insert(norm, drafts.len());
733                drafts.push(d);
734            }
735        }
736    }
737
738    drafts.sort_by(|a, b| {
739        a.evidence
740            .date
741            .cmp(&b.evidence.date)
742            .then_with(|| a.id.cmp(&b.id))
743    });
744    Report {
745        schema: SCHEMA.into(),
746        range: range.into(),
747        already_recorded: already.into_iter().collect(),
748        records_superseded: records_superseded.into_iter().collect(),
749        records: record_rows,
750        drafts,
751    }
752}
753
754/// Write `report` to the review file. Refuses a symlinked `.leanctx` or
755/// review directory, so the write cannot escape the repository.
756pub fn write_review(root: &Path, report: &Report) -> Result<std::path::PathBuf, String> {
757    let leanctx = root.join(".leanctx");
758    let dir = root.join(REVIEW_DIR);
759    for p in [&leanctx, &dir] {
760        if let Ok(meta) = std::fs::symlink_metadata(p) {
761            if meta.file_type().is_symlink() || !meta.is_dir() {
762                return Err(format!("{} is not a plain directory", p.display()));
763            }
764        }
765    }
766    std::fs::create_dir_all(&dir).map_err(|e| format!("{REVIEW_DIR}: {e}"))?;
767    let file = dir.join(REVIEW_FILE);
768    if let Ok(meta) = std::fs::symlink_metadata(&file) {
769        if !meta.file_type().is_file() {
770            return Err(format!("{REVIEW_DIR}/{REVIEW_FILE} is not a regular file"));
771        }
772    }
773    // Drafts stay local: the review directory ignores itself. `create_new`
774    // never follows a planted link.
775    let ignore = dir.join(".gitignore");
776    match std::fs::OpenOptions::new()
777        .write(true)
778        .create_new(true)
779        .open(&ignore)
780    {
781        Ok(mut f) => f
782            .write_all(b"# lean-ctx decision drafts stay local (contract \xc2\xa738)\n*\n")
783            .map_err(|e| format!("{}: {e}", ignore.display()))?,
784        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
785        Err(e) => return Err(format!("{}: {e}", ignore.display())),
786    }
787    let body = to_json(report)?;
788    // A fresh, randomly named file (O_EXCL) in the same directory, renamed
789    // over the review file: a planted temp-file link is never written through.
790    let mut tmp = tempfile::Builder::new()
791        .prefix(".suggested.")
792        .suffix(".tmp")
793        .tempfile_in(&dir)
794        .map_err(|e| format!("{REVIEW_DIR}: {e}"))?;
795    tmp.write_all(body.as_bytes())
796        .map_err(|e| format!("{REVIEW_DIR}: {e}"))?;
797    tmp.persist(&file)
798        .map_err(|e| format!("{}: {}", file.display(), e.error))?;
799    Ok(file)
800}
801
802/// Deterministic JSON of a report (pretty, trailing newline).
803pub fn to_json(report: &Report) -> Result<String, String> {
804    serde_json::to_string_pretty(report)
805        .map(|s| s + "\n")
806        .map_err(|e| e.to_string())
807}
808
809fn read_previous(root: &Path) -> Option<Report> {
810    let file = root.join(REVIEW_DIR).join(REVIEW_FILE);
811    let meta = std::fs::symlink_metadata(&file).ok()?;
812    if !meta.file_type().is_file() || meta.len() > 16 * 1024 * 1024 {
813        return None;
814    }
815    let text = std::fs::read_to_string(&file).ok()?;
816    let mut report = serde_json::from_str::<Report>(&text)
817        .ok()
818        .filter(|r| r.schema == SCHEMA)?;
819    // The file sits in the working tree and may come from anyone: keep only
820    // drafts whose ids and commit ids have the shape this module writes.
821    report.drafts.retain(|d| {
822        is_draft_id(&d.id) && is_hex_id(&d.evidence.commit) && is_iso_date(&d.evidence.date)
823    });
824    for d in &mut report.drafts {
825        d.also_in.retain(|c| is_hex_id(c));
826        d.supersedes.retain(|s| is_draft_id(s) || is_hex_id(s));
827    }
828    report.already_recorded.retain(|id| is_draft_id(id));
829    Some(report)
830}
831
832/// `[a-z0-9-]`, at most 128 bytes: the ids drafts and records use.
833fn is_draft_id(s: &str) -> bool {
834    !s.is_empty()
835        && s.len() <= 128
836        && s.bytes()
837            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
838}
839
840/// The records of `.leanctx/decisions` (D1 loader; invalid records are left
841/// out here and reported by `lean-ctx decisions check`).
842pub fn read_records(root: &Path) -> Vec<RecordInfo> {
843    let set = decisions::load(root);
844    set.decisions
845        .iter()
846        .map(|d| RecordInfo {
847            id: d.id.clone(),
848            statement: d.statement.clone(),
849            decided_at: d.decided_at.clone(),
850            active: set.effective_status(d) == decisions::Status::Active,
851            evidence: d.evidence.clone(),
852        })
853        .collect()
854}
855
856/// Whether `message` still holds `quote` as one (trimmed) line.
857fn quote_in(message: &str, quote: &str) -> bool {
858    let quote = quote.trim();
859    !quote.is_empty() && message.lines().any(|l| l.trim() == quote)
860}
861
862/// Two commit ids (full or abbreviated, at least 7 digits) name one commit.
863fn same_commit(a: &str, b: &str) -> bool {
864    let (a, b) = (a.to_ascii_lowercase(), b.to_ascii_lowercase());
865    a.len() >= 7 && b.len() >= 7 && (a.starts_with(&b) || b.starts_with(&a))
866}
867
868/// Options of `lean-ctx decisions confirm`.
869#[derive(Debug, Clone, Default)]
870pub struct ConfirmOptions {
871    /// Record id or slug (`dec-` is added); default: from the statement.
872    pub id: Option<String>,
873    /// `owner`, `team` or `review`; default: `owner` when the quote names the
874    /// owner, else `team`.
875    pub decided_by: Option<String>,
876}
877
878/// What [`confirm`] recorded.
879#[derive(Debug, Clone, PartialEq, Eq)]
880pub struct ConfirmedRecord {
881    pub id: String,
882    /// Root-relative record file.
883    pub file: String,
884    pub trust: Trust,
885    /// Records the new one supersedes.
886    pub supersedes: Vec<String>,
887}
888
889/// Turn draft `draft_id` of the review file into a record in
890/// `.leanctx/decisions` (a human asked for it). Refuses a superseded draft, a
891/// draft flagged `re-check`, and evidence that no longer holds; never
892/// overwrites a record. The draft leaves the review file and its record id
893/// joins `already_recorded`.
894pub fn confirm(
895    root: &Path,
896    draft_id: &str,
897    opts: &ConfirmOptions,
898) -> Result<ConfirmedRecord, String> {
899    let mut report = read_previous(root).ok_or_else(|| {
900        format!("no review file {REVIEW_DIR}/{REVIEW_FILE}: run `lean-ctx decisions suggest` first")
901    })?;
902    let idx = report
903        .drafts
904        .iter()
905        .position(|d| d.id == draft_id)
906        .ok_or_else(|| format!("no draft `{draft_id}` in {REVIEW_DIR}/{REVIEW_FILE}"))?;
907    let draft = report.drafts[idx].clone();
908    if let Some(by) = &draft.superseded_by {
909        return Err(format!(
910            "draft `{draft_id}` is superseded by {by}; confirm the newer decision instead"
911        ));
912    }
913    if draft.trust == Trust::Recheck {
914        return Err(format!(
915            "draft `{draft_id}` needs a re-check ({}); read the commit, then remove \
916             {REVIEW_DIR}/{REVIEW_FILE} and run `lean-ctx decisions suggest` again",
917            draft
918                .recheck_reason
919                .as_deref()
920                .unwrap_or("evidence changed")
921        ));
922    }
923    // Everything below uses the full id git resolved, never the id from the
924    // file (an abbreviated id may also name a branch or tag).
925    let history = GitHistory::load(root);
926    let gone = || {
927        format!(
928            "evidence commit {} is no longer in the history",
929            short(&draft.evidence.commit)
930        )
931    };
932    let unknown = || {
933        format!(
934            "git could not read commit {}; try again",
935            short(&draft.evidence.commit)
936        )
937    };
938    let full = match history.resolve(&draft.evidence.commit) {
939        Ok(Some(full)) => full,
940        Ok(None) => return Err(gone()),
941        Err(()) => return Err(unknown()),
942    };
943    let message = match history.message(&full) {
944        InHistory::Message(m) => m,
945        InHistory::Gone => return Err(gone()),
946        InHistory::Unknown => return Err(unknown()),
947    };
948    if !quote_in(&message, &draft.evidence.quote) {
949        return Err(format!(
950            "the quote is no longer in the message of commit {}",
951            short(&draft.evidence.commit)
952        ));
953    }
954    // The review file is untrusted (contract §38): the commit must yield this
955    // exact (quote, statement, trust) again; date, title and source come from
956    // git, not from the file.
957    if !extracts(
958        &message,
959        &draft.evidence.quote,
960        &draft.statement,
961        draft.trust,
962    ) {
963        return Err(format!(
964            "draft `{draft_id}` does not match commit {}: the quote, statement or trust in \
965             {REVIEW_DIR}/{REVIEW_FILE} differs from the history; run `lean-ctx decisions suggest` again",
966            short(&draft.evidence.commit)
967        ));
968    }
969    let date = commit_date(root, &full)?;
970    let source = Commit {
971        sha: full.clone(),
972        date: date.clone(),
973        message: message.clone(),
974    };
975    let (kind, reference) = source_of(&source);
976    let id = match &opts.id {
977        Some(slug) => decisions::id_from_slug(slug)
978            .ok_or_else(|| format!("`{slug}` has no letters or digits to build an id from"))?,
979        None => record_id_of(&draft.statement).ok_or_else(|| {
980            "no record id can be built from the statement; pass --id <slug>".to_string()
981        })?,
982    };
983    let decided_by = match opts.decided_by.as_deref() {
984        Some(v @ ("owner" | "team" | "review")) => v.to_string(),
985        Some(other) => {
986            return Err(format!(
987                "--decided-by `{other}`: expected owner, team or review"
988            ));
989        }
990        None if draft.evidence.quote.to_ascii_lowercase().contains("owner") => "owner".into(),
991        None => "team".into(),
992    };
993    let set = decisions::load(root);
994    if set.get(&id).is_some() {
995        return Err(format!(
996            "{}/{id}.toml exists; pass another --id",
997            decisions::DECISIONS_DIR
998        ));
999    }
1000    // `supersedes` of the file only narrows what git yields for this commit:
1001    // an edited review file can never retire a record by itself.
1002    let from_git = supersedes_from_git(&message, &draft.statement, &date, &read_records(root));
1003    let mut supersedes: Vec<String> = draft
1004        .supersedes
1005        .iter()
1006        .filter(|s| from_git.contains(*s) && set.get(s).is_some())
1007        .cloned()
1008        .collect();
1009    supersedes.sort();
1010    supersedes.dedup();
1011    let (source_kind, source_ref) = if kind == "merge-request" {
1012        ("mr", reference)
1013    } else {
1014        ("commit", short(&full).to_string())
1015    };
1016    let record = NewRecord {
1017        id: id.clone(),
1018        title: title_of(&draft.statement),
1019        statement: draft.statement.clone(),
1020        supersedes: supersedes.clone(),
1021        decided_by,
1022        decided_at: date,
1023        source_kind: source_kind.into(),
1024        source_ref,
1025        evidence: RecordEvidence {
1026            commit: full.clone(),
1027            quote: draft.evidence.quote.clone(),
1028            trust: draft.trust.label().into(),
1029        },
1030    };
1031    let text = decisions::render_record(&record);
1032    let rel = format!("{}/{id}.toml", decisions::DECISIONS_DIR);
1033    decisions::parse_decision(&text, &id, &rel)
1034        .map_err(|e| format!("the record would not be valid: {e}"))?;
1035    write_record(root, &id, &text)?;
1036
1037    report.drafts.remove(idx);
1038    if !report.already_recorded.contains(&id) {
1039        report.already_recorded.push(id.clone());
1040        report.already_recorded.sort();
1041    }
1042    write_review(root, &report)
1043        .map_err(|e| format!("recorded {rel}, but the review file was not updated: {e}"))?;
1044    Ok(ConfirmedRecord {
1045        id,
1046        file: rel,
1047        trust: draft.trust,
1048        supersedes,
1049    })
1050}
1051
1052/// Records a draft of `message` may supersede, read from git as
1053/// [`build_report`] does: the commit's `Supersedes:` trailers, and active
1054/// records of the same topic and opposite polarity decided on or before `date`.
1055fn supersedes_from_git(
1056    message: &str,
1057    statement: &str,
1058    date: &str,
1059    records: &[RecordInfo],
1060) -> BTreeSet<String> {
1061    let mut out: BTreeSet<String> = supersedes_trailers(message)
1062        .into_iter()
1063        .filter(|t| records.iter().any(|r| &r.id == t))
1064        .collect();
1065    let (topic, neg) = topic_of(statement);
1066    if !topic.is_empty() {
1067        for r in records.iter().filter(|r| r.active) {
1068            let (t, n) = topic_of(&r.statement);
1069            if t == topic && n != neg && date >= r.decided_at.as_str() {
1070                out.insert(r.id.clone());
1071            }
1072        }
1073    }
1074    out
1075}
1076
1077/// `dec-<first words of the statement>`, at most 6 words.
1078fn record_id_of(statement: &str) -> Option<String> {
1079    let normalized = normalize(statement);
1080    let words: Vec<&str> = normalized
1081        .split_whitespace()
1082        .filter(|w| w.is_ascii())
1083        .take(6)
1084        .collect::<Vec<_>>();
1085    let norm = words.join(" ");
1086    decisions::id_from_slug(&norm).or_else(|| {
1087        decisions::id_from_slug(
1088            &norm
1089                .split_whitespace()
1090                .take(3)
1091                .collect::<Vec<_>>()
1092                .join(" "),
1093        )
1094    })
1095}
1096
1097/// Create `<root>/.leanctx/decisions/<id>.toml` (never overwriting), only in
1098/// a records directory that stays inside the project.
1099fn write_record(root: &Path, id: &str, text: &str) -> Result<(), String> {
1100    let leanctx = root.join(".leanctx");
1101    if let Ok(meta) = std::fs::symlink_metadata(&leanctx)
1102        && (meta.file_type().is_symlink() || !meta.is_dir())
1103    {
1104        return Err(format!("{} is not a plain directory", leanctx.display()));
1105    }
1106    decisions::list_records(root)?;
1107    let dir = root.join(decisions::DECISIONS_DIR);
1108    std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", decisions::DECISIONS_DIR))?;
1109    decisions::list_records(root)?;
1110    let file = dir.join(format!("{id}.toml"));
1111    use std::io::Write;
1112    std::fs::OpenOptions::new()
1113        .write(true)
1114        .create_new(true)
1115        .open(&file)
1116        .and_then(|mut f| f.write_all(text.as_bytes()))
1117        .map_err(|e| {
1118            if e.kind() == std::io::ErrorKind::AlreadyExists {
1119                format!(
1120                    "{}/{id}.toml exists; pass another --id",
1121                    decisions::DECISIONS_DIR
1122                )
1123            } else {
1124                format!("{}: {e}", file.display())
1125            }
1126        })
1127}
1128
1129/// Decision lines of one message: (verbatim quote, statement, trust).
1130pub fn extract(message: &str) -> Vec<(String, String, Trust)> {
1131    let mut out = Vec::new();
1132    for raw in message.lines() {
1133        let quote = raw.trim();
1134        // Control characters (escape sequences, record separators) never
1135        // become a quote.
1136        if quote.len() < MIN_LINE
1137            || quote.len() > MAX_LINE
1138            || is_noise(quote)
1139            || quote.chars().any(|c| c.is_control() && c != '\t')
1140        {
1141            continue;
1142        }
1143        let line = quote
1144            .trim_start_matches(['-', '*', '+'])
1145            .trim_start()
1146            .to_string();
1147        if let Some((statement, trust)) = classify(&line) {
1148            let statement = clean_statement(&statement);
1149            if statement.len() >= MIN_LINE {
1150                out.push((quote.to_string(), statement, trust));
1151            }
1152        }
1153    }
1154    out
1155}
1156
1157fn is_noise(line: &str) -> bool {
1158    let lower = line.to_ascii_lowercase();
1159    const SKIP: [&str; 8] = [
1160        "co-authored-by:",
1161        "signed-off-by:",
1162        "reviewed-by:",
1163        "see merge request",
1164        "this reverts commit",
1165        "supersedes:",
1166        "merge branch ",
1167        "#",
1168    ];
1169    SKIP.iter().any(|p| lower.starts_with(p)) || lower.starts_with("revert \"")
1170}
1171
1172fn classify(line: &str) -> Option<(String, Trust)> {
1173    // ASCII lowering keeps byte offsets equal to `line`'s.
1174    let lower = line.to_ascii_lowercase();
1175    for marker in ["decision:", "owner decision:", "decided:"] {
1176        if lower.starts_with(marker) {
1177            let rest = line[marker.len()..].trim();
1178            let statement = quoted(rest).unwrap_or_else(|| rest.to_string());
1179            return Some((statement, Trust::Confirmed));
1180        }
1181    }
1182    // An owner answer quoted after its verb (`Owner answered "…"`). A bare
1183    // `Owner:` line or a quote that merely mentions an owner is not explicit;
1184    // it can still be reconstructed from policy wording below.
1185    const ANSWER: [&str; 5] = [
1186        "owner answered",
1187        "owner decided",
1188        "owner chose",
1189        "owner replied",
1190        "owner said",
1191    ];
1192    if let Some(at) = ANSWER.iter().filter_map(|p| lower.find(p)).min()
1193        && let Some(q) = quoted(&line[at..])
1194    {
1195        return Some((q, Trust::Confirmed));
1196    }
1197    const POLICY: [&str; 9] = [
1198        "never ",
1199        "always ",
1200        "must not ",
1201        "no longer ",
1202        "from now on",
1203        "instead of ",
1204        "we decided",
1205        "decided to ",
1206        "policy: ",
1207    ];
1208    let padded = format!(" {lower}");
1209    if POLICY.iter().any(|p| padded.contains(&format!(" {p}"))) {
1210        return Some((line.to_string(), Trust::Reconstructed));
1211    }
1212    None
1213}
1214
1215/// The first quoted segment ("…", “…”, „…“) of at least [`MIN_LINE`] chars.
1216fn quoted(line: &str) -> Option<String> {
1217    for (open, close) in [
1218        ('"', '"'),
1219        ('\u{201c}', '\u{201d}'),
1220        ('\u{201e}', '\u{201c}'),
1221    ] {
1222        if let Some(start) = line.find(open) {
1223            let after = &line[start + open.len_utf8()..];
1224            if let Some(end) = after.find(close) {
1225                let q = after[..end].trim();
1226                if q.len() >= MIN_LINE {
1227                    return Some(q.to_string());
1228                }
1229            }
1230        }
1231    }
1232    None
1233}
1234
1235fn clean_statement(s: &str) -> String {
1236    let s = s
1237        .trim()
1238        .trim_matches(['"', '\u{201c}', '\u{201d}', '\u{201e}']);
1239    let mut out: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
1240    if let Some(stripped) = out.strip_suffix(['.', ';', ',']) {
1241        out = stripped.to_string();
1242    }
1243    out
1244}
1245
1246fn normalize(s: &str) -> String {
1247    s.to_lowercase()
1248        .chars()
1249        .map(|c| if c.is_alphanumeric() { c } else { ' ' })
1250        .collect::<String>()
1251        .split_whitespace()
1252        .collect::<Vec<_>>()
1253        .join(" ")
1254}
1255
1256const NEGATIONS: [&str; 5] = ["never", "not", "no", "longer", "dont"];
1257const STOP: [&str; 24] = [
1258    "the", "and", "for", "with", "from", "that", "this", "are", "was", "will", "must", "always",
1259    "now", "on", "of", "to", "in", "a", "an", "be", "is", "we", "use", "only",
1260];
1261
1262/// Topic words (sorted, polarity and stop words removed) and negative polarity.
1263fn topic_of(statement: &str) -> (Vec<String>, bool) {
1264    let norm = normalize(&statement.replace('\'', ""));
1265    let mut neg = false;
1266    let mut words = BTreeSet::new();
1267    for w in norm.split_whitespace() {
1268        if NEGATIONS.contains(&w) {
1269            neg = true;
1270        } else if !STOP.contains(&w) && w.len() >= 3 {
1271            words.insert(w.to_string());
1272        }
1273    }
1274    (words.into_iter().collect(), neg)
1275}
1276
1277fn title_of(statement: &str) -> String {
1278    const MAX: usize = 72;
1279    if statement.chars().count() <= MAX {
1280        return statement.to_string();
1281    }
1282    let cut: String = statement.chars().take(MAX - 1).collect();
1283    let cut = cut.rsplit_once(' ').map_or(cut.as_str(), |(a, _)| a);
1284    format!("{cut}…")
1285}
1286
1287fn draft_id(statement: &str, sha: &str) -> String {
1288    let slug: Vec<String> = normalize(statement)
1289        .split_whitespace()
1290        .filter(|w| w.is_ascii())
1291        .take(5)
1292        .map(str::to_string)
1293        .collect();
1294    let slug = if slug.is_empty() {
1295        "decision".to_string()
1296    } else {
1297        slug.join("-")
1298    };
1299    format!("dec-sug-{slug}-{}", &sha[..sha.len().min(7)])
1300}
1301
1302fn evidence_hash(commit: &str, quote: &str) -> String {
1303    let h = blake3::hash(format!("{commit}\n{quote}").as_bytes());
1304    h.to_hex()[..16].to_string()
1305}
1306
1307/// The first 12 characters (char-safe: the value may come from a file).
1308pub fn short(sha: &str) -> &str {
1309    sha.char_indices().nth(12).map_or(sha, |(i, _)| &sha[..i])
1310}
1311
1312fn sha_matches(full: &str, given: &str) -> bool {
1313    given.len() >= 7 && given.chars().all(|c| c.is_ascii_hexdigit()) && full.starts_with(given)
1314}
1315
1316/// `merge-request` + `!N` when the message has a GitLab MR footer.
1317fn source_of(commit: &Commit) -> (String, String) {
1318    for line in commit.message.lines() {
1319        let l = line.trim();
1320        if let Some(rest) = l.strip_prefix("See merge request ") {
1321            if let Some(pos) = rest.rfind('!') {
1322                let n: String = rest[pos + 1..]
1323                    .chars()
1324                    .take_while(char::is_ascii_digit)
1325                    .collect();
1326                if !n.is_empty() {
1327                    return ("merge-request".into(), format!("!{n}"));
1328                }
1329            }
1330        }
1331    }
1332    (
1333        "commit".into(),
1334        commit.sha[..commit.sha.len().min(12)].to_string(),
1335    )
1336}
1337
1338fn reverted_commit(message: &str) -> Option<String> {
1339    message.lines().find_map(|l| {
1340        let rest = l.trim().strip_prefix("This reverts commit ")?;
1341        let sha: String = rest.chars().take_while(char::is_ascii_hexdigit).collect();
1342        (sha.len() >= 7).then_some(sha)
1343    })
1344}
1345
1346fn supersedes_trailers(message: &str) -> Vec<String> {
1347    const KEY: &str = "supersedes:";
1348    let mut out = Vec::new();
1349    for l in message.lines() {
1350        let l = l.trim();
1351        if l.get(..KEY.len())
1352            .is_some_and(|p| p.eq_ignore_ascii_case(KEY))
1353        {
1354            for t in l[KEY.len()..].split([',', ' ']) {
1355                let t = t.trim();
1356                if !t.is_empty() && !out.iter().any(|o| o == t) {
1357                    out.push(t.to_string());
1358                }
1359            }
1360        }
1361    }
1362    out
1363}
1364
1365#[cfg(test)]
1366#[path = "decision_history_tests.rs"]
1367mod tests;