Skip to main content

speccoder_runtime/attest/
branch.rs

1//! `speccoder-verify check` and `speccoder attest verify --branch`: every
2//! ticked task of the units a branch touches, mapped to the commit that
3//! carries its evidence and checked with `attest verify`'s own rules
4//! ([`super::verify::object`]), plus what only a branch can show: a tick
5//! with no evidence at all, a task line edited after its tick, a cited
6//! requirement changed since, a commit a squash merge lost.
7//!
8//! Everything is read from git objects of the repository at the given
9//! head, never from a working tree, and trust comes only from the caller:
10//! a key the branch itself declares is never trusted.
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::path::{Path, PathBuf};
14
15use serde_json::{Value, json};
16use speccoder_core::predicate::TaskVerificationV0;
17use speccoder_core::verify_branch::{
18    self, Anchor, BranchReport, BranchTotals, Conclusion, Mode, SkippedTask, Tick, TickKind,
19    TickOutcome, TickReport, Unverifiable,
20};
21use speccoder_core::{
22    CommandData, CommandResult, CommandStatus, ObjectVerification, TraceRow, VerifyOutcome,
23};
24
25use super::verify::{Context, Target, Trust};
26use super::{notes, statement};
27use crate::format::Adapter;
28use crate::git::Git;
29
30/// Field and record separators for `git log` output.
31const FS: char = '\u{1f}';
32const RS: char = '\u{1e}';
33
34/// Where the verifier's SSH trust comes from.
35#[derive(Debug, Clone)]
36pub enum AllowedSigners {
37    /// A file on the verifier's machine.
38    File(PathBuf),
39    /// A file read from git at a revision (`<rev>:<path>`): in CI, the base
40    /// branch's, never the head's.
41    Rev {
42        /// The revision (the base).
43        rev: String,
44        /// The repository path.
45        path: String,
46    },
47}
48
49impl AllowedSigners {
50    /// `<rev>:<path>`, as `--allowed-signers-rev` takes it.
51    ///
52    /// # Errors
53    ///
54    /// No `:` separating a revision and a path.
55    pub fn parse_rev(spec: &str) -> Result<Self, String> {
56        match spec.split_once(':') {
57            Some((rev, path)) if !rev.is_empty() && !path.is_empty() => Ok(Self::Rev {
58                rev: rev.to_owned(),
59                path: path.to_owned(),
60            }),
61            _ => Err(format!(
62                "--allowed-signers-rev takes <rev>:<path>, e.g. origin/main:.github/speccoder/allowed_signers (got `{spec}`)"
63            )),
64        }
65    }
66}
67
68/// What a branch check is asked.
69#[derive(Debug, Clone)]
70pub struct Options {
71    /// The commit to check (`HEAD` by default).
72    pub head: String,
73    /// The branch it is compared with; units touched since their merge
74    /// base are checked. `None`: every unit.
75    pub base: Option<String>,
76    /// Every unit, whatever the base.
77    pub all: bool,
78    /// SSH trust.
79    pub allowed_signers: Option<AllowedSigners>,
80    /// The Sigstore certificate identity.
81    pub identity: Option<String>,
82    /// The Sigstore OIDC issuer.
83    pub issuer: Option<String>,
84    /// Unsigned evidence is unverifiable (default).
85    pub require_signed: bool,
86    /// `regression_only` and `attested` fail too.
87    pub require_verified: bool,
88}
89
90impl Default for Options {
91    fn default() -> Self {
92        Self {
93            head: "HEAD".to_owned(),
94            base: None,
95            all: false,
96            allowed_signers: None,
97            identity: None,
98            issuer: None,
99            require_signed: true,
100            require_verified: false,
101        }
102    }
103}
104
105/// A check that could not start.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct Refusal {
108    /// How it ends.
109    pub status: CommandStatus,
110    /// Why, and what to do.
111    pub message: String,
112}
113
114impl Refusal {
115    /// A check that could not read what it checks: an error (exit 1), never
116    /// `neutral`.
117    fn internal(what: impl std::fmt::Display) -> Self {
118        Self::new(
119            CommandStatus::Error,
120            format!("the check could not read the branch: {what}; nothing was verified"),
121        )
122    }
123
124    fn new(status: CommandStatus, message: impl Into<String>) -> Self {
125        Self {
126            status,
127            message: message.into(),
128        }
129    }
130}
131
132/// The refusal when the caller gave no trust.
133pub const NO_TRUST: &str = "no trust configured: pass --allowed-signers or --certificate-identity/--certificate-oidc-issuer";
134
135/// A finished check: the report and where it was read from.
136#[derive(Debug)]
137pub struct Checked {
138    /// The report.
139    pub report: BranchReport,
140    /// The repository's top level.
141    pub repo: PathBuf,
142    /// The project's path in the repository (`""`, or ending in `/`).
143    pub prefix: String,
144}
145
146/// `speccoder-verify check` / `attest verify --branch` for the repository
147/// containing `start`, as a command result named `command` (payload
148/// `branch_verify`).
149#[must_use]
150pub fn verify(start: &Path, opts: &Options, command: &str) -> CommandResult {
151    match check(start, opts) {
152        Ok(c) => result(command, c.report),
153        Err(r) => CommandResult::new(command, r.status, &r.message),
154    }
155}
156
157/// The report as a command result.
158#[must_use]
159pub fn result(command: &str, report: BranchReport) -> CommandResult {
160    let status = match report.conclusion {
161        Conclusion::Success => CommandStatus::Ok,
162        Conclusion::Failure => CommandStatus::AttestationFailed,
163        Conclusion::Neutral => CommandStatus::NotFound,
164    };
165    let mut message = report.title();
166    if report.accepted_unsigned {
167        message.push_str("; unsigned ticks were accepted (--require-signed=false)");
168    }
169    CommandResult::new(command, status, &message)
170        .with_data(CommandData::BranchVerify(Box::new(report)))
171}
172
173/// Resolves the caller's trust; the temporary directory holds a file read
174/// from git, and must live as long as the trust is used.
175/// With `optional`, no trust is no refusal: signatures go unchecked (a
176/// tour, which shows what is recorded and says so).
177fn trust(
178    top: &Path,
179    opts: &Options,
180    optional: bool,
181) -> Result<(Option<Trust>, Value, Option<tempfile::TempDir>), Refusal> {
182    let sigstore = opts.identity.is_some() && opts.issuer.is_some();
183    if opts.identity.is_some() != opts.issuer.is_some() {
184        return Err(Refusal::new(
185            CommandStatus::UsageError,
186            "--certificate-identity and --certificate-oidc-issuer go together",
187        ));
188    }
189    let mut held = None;
190    let (allowed, source) = match &opts.allowed_signers {
191        None => (None, Value::Null),
192        Some(AllowedSigners::File(p)) => {
193            if !p.is_file() {
194                return Err(Refusal::new(
195                    CommandStatus::UsageError,
196                    format!("--allowed-signers {}: no such file", p.display()),
197                ));
198            }
199            (Some(p.clone()), json!({ "file": p.display().to_string() }))
200        }
201        Some(AllowedSigners::Rev { rev, path }) => {
202            let bytes = Git::at(top)
203                .run(&["show", &format!("{rev}:{path}")])
204                .map_err(|e| {
205                    Refusal::new(
206                        CommandStatus::UsageError,
207                        format!(
208                            "--allowed-signers-rev {rev}:{path}: cannot read it ({})",
209                            e.0
210                        ),
211                    )
212                })?;
213            let dir = tempfile::tempdir().map_err(|e| {
214                Refusal::new(CommandStatus::Error, format!("no temporary directory: {e}"))
215            })?;
216            let file = dir.path().join("allowed_signers");
217            std::fs::write(&file, bytes).map_err(|e| {
218                Refusal::new(CommandStatus::Error, format!("cannot write the trust: {e}"))
219            })?;
220            held = Some(dir);
221            (Some(file), json!({ "rev": rev, "path": path }))
222        }
223    };
224    if allowed.is_none() && !sigstore {
225        if optional {
226            return Ok((
227                None,
228                json!({ "signatures": "not checked: no trust given" }),
229                None,
230            ));
231        }
232        return Err(Refusal::new(CommandStatus::UsageError, NO_TRUST));
233    }
234    let shown = json!({
235        "ssh_allowed_signers": source,
236        "gpg": true,
237        "sigstore": opts.identity.as_ref().map(|i| json!({ "identity": i, "issuer": opts.issuer })),
238    });
239    Ok((
240        Some(Trust {
241            allowed_signers: allowed,
242            identity: opts.identity.clone(),
243            issuer: opts.issuer.clone(),
244        }),
245        shown,
246        held,
247    ))
248}
249
250/// `path` relative to `root`, `/`-separated; `""` for the root itself.
251fn relative(path: &Path, root: &Path) -> Option<String> {
252    let canonical = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
253    let rel = canonical(path)
254        .strip_prefix(canonical(root))
255        .ok()?
256        .to_path_buf();
257    Some(rel.to_string_lossy().replace('\\', "/"))
258}
259
260/// `rel` as a prefix: `""`, or ending in `/`.
261fn as_prefix(rel: &str) -> String {
262    if rel.is_empty() {
263        String::new()
264    } else {
265        format!("{}/", rel.trim_end_matches('/'))
266    }
267}
268
269/// What the history says about tasks, read once: the latest commit
270/// carrying each `<unit>/<task>`'s verdict, and the trailer-only claims in
271/// the checked range.
272struct History {
273    latest: BTreeMap<String, String>,
274    bug_claims: BTreeSet<String>,
275}
276
277fn history(git: &Git, head: &str, base: Option<&str>) -> Result<History, Refusal> {
278    let log = git
279        .run(&[
280            "log",
281            "--grep=^Spec-Task: ",
282            "--format=%H%x1f%(trailers:key=Spec-Task,valueonly)%x1f%(trailers:key=Verdict,valueonly)%x1e",
283            head,
284        ])
285        .map(|b| String::from_utf8_lossy(&b).into_owned())
286        .map_err(|e| Refusal::internal(format!("git log {head}: {}", e.0)))?;
287    let in_range: Option<BTreeSet<String>> = base
288        .map(|b| {
289            git.run(&["rev-list", &format!("{b}..{head}")])
290                .map(|o| {
291                    String::from_utf8_lossy(&o)
292                        .lines()
293                        .map(str::to_owned)
294                        .collect()
295                })
296                .map_err(|e| Refusal::internal(format!("git rev-list {b}..{head}: {}", e.0)))
297        })
298        .transpose()?;
299    let mut latest = BTreeMap::new();
300    let mut bug_claims = BTreeSet::new();
301    for record in log.split(RS) {
302        let f: Vec<&str> = record.trim().split(FS).collect();
303        let [commit, task, verdict] = f[..] else {
304            continue;
305        };
306        let (task, verdict) = (task.trim(), verdict.trim());
307        if task.is_empty() || verdict.is_empty() {
308            continue;
309        }
310        if task.contains("/bug:") && in_range.as_ref().is_none_or(|r| r.contains(commit)) {
311            bug_claims.insert(task.to_owned());
312        }
313        latest
314            .entry(task.to_owned())
315            .or_insert_with(|| commit.to_owned());
316    }
317    Ok(History { latest, bug_claims })
318}
319
320/// Noted commits not reachable from `head`, by the task their
321/// task-verification names (`<unit>/<task>`): evidence a squash or rebase
322/// merge left behind.
323fn unreachable_evidence(
324    git: &Git,
325    repo: &Path,
326    head: &str,
327) -> Result<BTreeMap<String, String>, Refusal> {
328    let reachable: BTreeSet<String> = git
329        .run(&["rev-list", head])
330        .map(|o| {
331            String::from_utf8_lossy(&o)
332                .lines()
333                .map(str::to_owned)
334                .collect()
335        })
336        .map_err(|e| Refusal::internal(format!("git rev-list {head}: {}", e.0)))?;
337    let noted = notes::try_noted(repo)
338        .map_err(|e| Refusal::internal(format!("git notes list: {}", e.0)))?;
339    let mut out = BTreeMap::new();
340    for commit in noted {
341        if reachable.contains(&commit) {
342            continue;
343        }
344        for s in crate::evidence::statements(repo, &commit) {
345            if s["predicateType"] == statement::TASK_VERIFICATION
346                && let Some(name) = s["subject"][0]["name"].as_str()
347            {
348                out.insert(name.to_owned(), commit.clone());
349            }
350        }
351    }
352    Ok(out)
353}
354
355/// The changed paths between `base` and `head`. A diff git cannot make is
356/// an error: an empty list would touch no unit, and check nothing.
357fn changed(git: &Git, base: &str, head: &str) -> Result<Vec<String>, Refusal> {
358    git.run(&["diff", "--name-only", "-z", base, head])
359        .map(|o| crate::git::nul_fields(&o))
360        .map_err(|e| Refusal::internal(format!("git diff {base} {head}: {}", e.0)))
361}
362
363/// Whether `rev` holds a spec project at `start_rel` (read as the head is).
364fn project_at(top: &Path, rev: &str, start_rel: &str) -> Result<bool, Refusal> {
365    let dir = super::tree::intent_tops(top, rev)
366        .and_then(|tops| super::tree::materialize(top, rev, Some(&tops)))
367        .map_err(Refusal::internal)?;
368    let at = dir.path().join(start_rel);
369    Ok(crate::format::at(&at).inspect(&at, None).is_some())
370}
371
372/// One unit's ticks at the head.
373struct Unit {
374    name: String,
375    dir: String,
376    ticks: Vec<Tick>,
377    skipped: Vec<SkippedTask>,
378}
379
380/// One unit's ticks; a unit the project lists but this cannot read is an
381/// error, never a unit left out.
382fn unit(
383    format: &dyn Adapter,
384    project: &Path,
385    name: &str,
386    prefix: &str,
387    skips: &BTreeSet<String>,
388) -> Result<Unit, Refusal> {
389    let f = format
390        .inspect(project, Some(name))
391        .and_then(|snap| snap.feature)
392        .ok_or_else(|| Refusal::internal(format!("the unit {name} cannot be read at the head")))?;
393    let mut ticks = Vec::new();
394    let mut skipped = Vec::new();
395    if let Some(tasks) = &f.tasks {
396        let text = std::fs::read_to_string(project.join(&tasks.path))
397            .map_err(|e| Refusal::internal(format!("{prefix}{}: {e}", tasks.path)))?;
398        let lines: Vec<&str> = text.lines().collect();
399        for t in &tasks.tasks {
400            if !t.done {
401                if skips.contains(&format!("{name}/{}", t.id)) {
402                    skipped.push(SkippedTask {
403                        feature: name.to_owned(),
404                        task: t.id.clone(),
405                    });
406                }
407                continue;
408            }
409            let line = usize::try_from(t.line)
410                .ok()
411                .and_then(|l| l.checked_sub(1))
412                .and_then(|i| lines.get(i))
413                .copied()
414                .unwrap_or_default();
415            ticks.push(Tick {
416                feature: name.to_owned(),
417                task: t.id.clone(),
418                title: t.title.clone(),
419                kind: TickKind::Tick,
420                anchor: Anchor {
421                    path: format!("{prefix}{}", tasks.path),
422                    line: t.line,
423                },
424                line_sha256: Some(crate::integrity::sha256_hex(&crate::integrity::untick(
425                    line.as_bytes(),
426                ))),
427                claim_sha256: None,
428            });
429        }
430    }
431    Ok(Unit {
432        name: name.to_owned(),
433        dir: f.feature.dir,
434        ticks,
435        skipped,
436    })
437}
438
439/// The trailer-only task `claim` (`<unit>/bug:<slug>`) as the head holds
440/// it: anchored on its home's file (the first Expected line), its claim the
441/// triad's digest; `None` when the home cannot be read.
442fn trailer_only(format: &dyn Adapter, project: &Path, prefix: &str, claim: &str) -> Option<Tick> {
443    let (unit, task) = claim.rsplit_once('/')?;
444    // The claim comes from a commit's trailer (an untrusted pull request
445    // writes those): only a slug, and only the unit that slug's bug is.
446    let slug = task
447        .strip_prefix("bug:")
448        .filter(|s| speccoder_core::bug::valid_slug(s))?;
449    let home = format.bug_unit(project).ok().filter(|h| h.kind.native())?;
450    if format.bug_dir(&home, slug).map(|(_, u)| u).as_deref() != Some(unit) {
451        return None;
452    }
453    let read = format.read_bug(project, &home, slug).ok()?;
454    let triad = speccoder_core::bug::Triad::new(
455        read.current.first().map_or("", String::as_str),
456        &read.expected,
457        &read.unchanged,
458        crate::integrity::sha256_hex,
459    )
460    .ok()?;
461    let text = std::fs::read_to_string(project.join(&read.file)).unwrap_or_default();
462    let line = text
463        .lines()
464        .position(|l| l.contains("Expected:"))
465        .and_then(|i| u32::try_from(i + 1).ok())
466        .unwrap_or(1);
467    Some(Tick {
468        feature: unit.to_owned(),
469        task: task.to_owned(),
470        title: read.title.clone().unwrap_or_else(|| triad.title()),
471        kind: TickKind::TrailerOnly,
472        anchor: Anchor {
473            path: format!("{prefix}{}", read.file),
474            line,
475        },
476        line_sha256: None,
477        claim_sha256: Some(triad.digest),
478    })
479}
480
481/// The skipped tasks' refs, as `<unit>/<task>`.
482fn skips(git: &Git) -> Result<BTreeSet<String>, Refusal> {
483    git.run(&[
484        "for-each-ref",
485        "--format=%(refname)",
486        &format!("{}/", notes::SKIPPED),
487    ])
488    .map(|o| {
489        String::from_utf8_lossy(&o)
490            .lines()
491            .filter_map(|r| r.strip_prefix(&format!("{}/", notes::SKIPPED)))
492            // `bug:<slug>` is kept as `bug%3A<slug>` (no `:` in a ref).
493            .map(|r| r.replace("%3A", ":").replace("%25", "%"))
494            .collect()
495    })
496    .map_err(|e| Refusal::internal(format!("git for-each-ref {}: {}", notes::SKIPPED, e.0)))
497}
498
499/// A reason's line: `trailer Spec-Task: expected …, found …`.
500fn detail(v: &ObjectVerification) -> Option<String> {
501    let r = v.reasons.first()?;
502    Some(match (&r.field, &r.expected, &r.found) {
503        (Some(field), Some(e), Some(f)) => format!("{} {field}: expected {e}, found {f}", r.code),
504        (_, _, Some(f)) => format!("{}: {f}", r.code),
505        _ => r.code.clone(),
506    })
507}
508
509/// The tick's outcome from its commit's verification, the head's task line
510/// and the typed predicate.
511fn outcome_of(
512    tick: &Tick,
513    commit: &str,
514    v: ObjectVerification,
515    statements: &[Value],
516    require_signed: bool,
517) -> TickReport {
518    let mut r = TickReport {
519        tick: tick.clone(),
520        commit: Some(commit.to_owned()),
521        outcome: TickOutcome::Evidenced,
522        verdict: v.verdict.clone(),
523        reason: None,
524        detail: None,
525        signer: v.signer.clone(),
526        decider: None,
527        stale: Vec::new(),
528        stale_anchor: None,
529        newer_fields: Vec::new(),
530        verification: None,
531    };
532    let unverifiable = |r: &mut TickReport, reason: Unverifiable, detail: Option<String>| {
533        r.outcome = TickOutcome::Unverifiable;
534        r.reason = Some(reason);
535        r.detail = detail;
536    };
537    // A predicate of another major version is not one this verifier reads.
538    let other = statements.iter().find_map(|s| {
539        s["predicateType"]
540            .as_str()
541            .filter(|t| t.starts_with("https://speccoder.dev/task-verification/"))
542            .filter(|t| *t != statement::TASK_VERIFICATION)
543    });
544    let tv = statements
545        .iter()
546        .find(|s| s["predicateType"] == statement::TASK_VERIFICATION)
547        .map(|s| serde_json::from_value::<TaskVerificationV0>(s["predicate"].clone()));
548    match v.outcome {
549        VerifyOutcome::Ok => {}
550        VerifyOutcome::Unsigned if !require_signed => {}
551        o => {
552            let reason = Unverifiable::of(o).unwrap_or(Unverifiable::Malformed);
553            match other {
554                Some(t) if tv.is_none() => unverifiable(
555                    &mut r,
556                    Unverifiable::Malformed,
557                    Some(format!("predicate {t} not supported by this verifier")),
558                ),
559                _ => unverifiable(&mut r, reason, detail(&v)),
560            }
561        }
562    }
563    if r.outcome == TickOutcome::Evidenced {
564        match tv {
565            Some(Ok(tv)) => {
566                // A trailer-only task has no line: its claim is anchored on
567                // the bug's triad, as the verified predicate (the one the
568                // signature check covered) records it — never another
569                // envelope of the note.
570                let triad = tv
571                    .bug
572                    .as_ref()
573                    .and_then(|b| b["triad_sha256"].as_str().map(str::to_owned));
574                let agree = statements
575                    .iter()
576                    .filter(|s| s["predicateType"] == statement::TASK_VERIFICATION)
577                    .all(|s| s["predicate"]["bug"]["triad_sha256"].as_str() == triad.as_deref());
578                let anchored = match tick.kind {
579                    TickKind::Tick => Some(&tv.task.line_hash) == tick.line_sha256.as_ref(),
580                    TickKind::TrailerOnly => triad.is_some() && agree,
581                };
582                if tick.kind == TickKind::TrailerOnly && triad.is_some() && !agree {
583                    unverifiable(
584                        &mut r,
585                        Unverifiable::Mismatch,
586                        Some(
587                            "the note's task-verification statements name different triads"
588                                .to_owned(),
589                        ),
590                    );
591                } else if !anchored {
592                    unverifiable(
593                        &mut r,
594                        Unverifiable::Mismatch,
595                        Some("the task line changed since its tick: task.line_hash differs from the line at the head".to_owned()),
596                    );
597                }
598                // The triad read at the head against the one the fix was judged on.
599                if r.outcome == TickOutcome::Evidenced
600                    && tick.kind == TickKind::TrailerOnly
601                    && triad.as_deref() != tick.claim_sha256.as_deref()
602                {
603                    r.outcome = TickOutcome::Stale;
604                    r.stale_anchor = Some(tick.anchor.clone());
605                    r.detail = Some(
606                        "the bug's triad changed since its fix: the verdict is for the earlier words"
607                            .to_owned(),
608                    );
609                }
610                r.newer_fields = tv.newer_fields();
611                r.decider = tv.decider.map(|d| d.by);
612            }
613            Some(Err(e)) => unverifiable(
614                &mut r,
615                Unverifiable::Malformed,
616                Some(format!("the predicate is not task-verification v0: {e}")),
617            ),
618            None => unverifiable(
619                &mut r,
620                Unverifiable::Mismatch,
621                Some("no task-verification statement".to_owned()),
622            ),
623        }
624    }
625    if v.outcome == VerifyOutcome::Unsigned && require_signed {
626        r.detail =
627            Some("the statements are not signed (sign with `speccoder attest sign`)".to_owned());
628    }
629    r.verification = Some(v);
630    r
631}
632
633/// A tick no reachable commit carries evidence for.
634fn without_commit(tick: &Tick, lost: Option<&String>) -> TickReport {
635    let (reason, detail) = match lost {
636        Some(c) => (
637            Unverifiable::CommitUnreachable,
638            format!(
639                "its evidence is on {} — not reachable from the head (a squash or rebase merge?); merge with a merge commit to keep it",
640                &c[..c.len().min(12)]
641            ),
642        ),
643        None => (
644            Unverifiable::TickedWithoutEvidence,
645            "no commit carries this task's verdict (ticked by hand?)".to_owned(),
646        ),
647    };
648    TickReport {
649        tick: tick.clone(),
650        commit: None,
651        outcome: TickOutcome::Unverifiable,
652        verdict: None,
653        reason: Some(reason),
654        detail: Some(detail),
655        signer: None,
656        decider: None,
657        stale: Vec::new(),
658        stale_anchor: None,
659        newer_fields: Vec::new(),
660        verification: None,
661    }
662}
663
664/// The 1-based line of `text` holding `line` (trimmed), if any.
665fn line_of(text: &str, line: &str) -> Option<u32> {
666    let want = line.trim();
667    text.lines()
668        .position(|l| l.trim() == want)
669        .and_then(|i| u32::try_from(i + 1).ok())
670}
671
672/// Marks evidenced ticks whose cited requirements changed between their
673/// commit and the head as stale.
674fn mark_stale(
675    top: &Path,
676    format: &dyn Adapter,
677    project: &Path,
678    prefix: &str,
679    unit_dir: &str,
680    head: &str,
681    reports: &mut [TickReport],
682) {
683    let asked: Vec<(&str, Option<&str>)> = reports
684        .iter()
685        .map(|r| {
686            (
687                r.tick.title.as_str(),
688                r.commit
689                    .as_deref()
690                    .filter(|_| r.outcome == TickOutcome::Evidenced),
691            )
692        })
693        .collect();
694    let Some(found) = crate::drift::at(top, format, unit_dir, prefix, head, &asked) else {
695        return;
696    };
697    let spec = format
698        .requirements_file()
699        .map(|f| format!("{}/{f}", unit_dir.trim_end_matches('/')));
700    let spec_text = spec
701        .as_ref()
702        .and_then(|s| std::fs::read_to_string(project.join(s)).ok())
703        .unwrap_or_default();
704    for (r, drift) in reports.iter_mut().zip(found) {
705        let Some(drift) = drift.filter(|d| !d.requirements.is_empty()) else {
706            continue;
707        };
708        r.outcome = TickOutcome::Stale;
709        r.stale_anchor = drift.requirements.iter().find_map(|d| {
710            let now = d.now.as_deref()?;
711            Some(Anchor {
712                path: format!("{prefix}{}", spec.as_deref()?),
713                line: line_of(&spec_text, now)?,
714            })
715        });
716        r.detail = Some(format!(
717            "{} changed since the tick: the verdict is for the earlier wording",
718            drift
719                .requirements
720                .iter()
721                .map(|d| d.id.as_str())
722                .collect::<Vec<_>>()
723                .join(", ")
724        ));
725        r.stale = drift.requirements;
726    }
727}
728
729/// The word a trace row shows for a tick.
730fn word(r: &TickReport) -> String {
731    match r.outcome {
732        TickOutcome::Evidenced => r.verdict.clone().unwrap_or_default(),
733        TickOutcome::Stale => "stale".to_owned(),
734        TickOutcome::Unverifiable => "unverifiable".to_owned(),
735        TickOutcome::Regressed => "regressed".to_owned(),
736    }
737}
738
739/// Requirement → task → verdict rows for one unit (a requirement no tick
740/// cites is a row of its own), then the scenario/test rows the signed
741/// `trace[]` of each evidenced tick holds.
742fn trace(
743    requirements: &[(String, String)],
744    reports: &[TickReport],
745    signed: &BTreeMap<String, Vec<Value>>,
746) -> Vec<TraceRow> {
747    let mut rows = Vec::new();
748    for (id, _) in requirements {
749        let citing: Vec<&TickReport> = reports
750            .iter()
751            .filter(|r| super::cites(&r.tick.title, id))
752            .collect();
753        if citing.is_empty() {
754            rows.push(TraceRow {
755                requirement: id.clone(),
756                scenario: None,
757                test: None,
758                task: None,
759                verdict: None,
760                changed: false,
761            });
762        }
763        for r in citing {
764            rows.push(TraceRow {
765                requirement: id.clone(),
766                scenario: None,
767                test: None,
768                task: Some(r.tick.task.clone()),
769                verdict: Some(word(r)),
770                changed: r.stale.iter().any(|d| d.id == *id),
771            });
772        }
773    }
774    for r in reports {
775        for row in signed.get(&r.tick.task).into_iter().flatten() {
776            let Some(test) = row["test"].as_str() else {
777                continue;
778            };
779            rows.push(TraceRow {
780                requirement: row["requirement"].as_str().unwrap_or("—").to_owned(),
781                scenario: row["scenario"].as_str().map(str::to_owned),
782                test: Some(test.to_owned()),
783                task: Some(r.tick.task.clone()),
784                verdict: Some(word(r)),
785                changed: false,
786            });
787        }
788    }
789    rows
790}
791
792/// Checks the ticks of the units the branch touches.
793///
794/// # Errors
795///
796/// Not a git repository, a revision that does not resolve, or no trust.
797pub fn check(start: &Path, opts: &Options) -> Result<Checked, Refusal> {
798    run(start, opts, None)
799}
800
801/// One task of `feature` at the head, for its tour: checked with the
802/// caller's trust when given, else read as recorded (signatures not
803/// checked, said in its detail). The report holds that tick alone, or none.
804///
805/// # Errors
806///
807/// As [`check`], except that no trust is no refusal.
808pub fn locate(start: &Path, opts: &Options, feature: &str, task: &str) -> Result<Checked, Refusal> {
809    let opts = Options {
810        all: true,
811        base: None,
812        ..opts.clone()
813    };
814    run(start, &opts, Some((feature, Some(task))))
815}
816
817/// Every tick of `feature` at `head`, read as recorded (no trust, no
818/// signature checked): what `pr`'s body tours show before a maintainer's
819/// verifier checks them.
820///
821/// # Errors
822///
823/// Not a git repository, or `head` does not resolve.
824pub fn recorded(start: &Path, head: &str, feature: &str) -> Result<Checked, Refusal> {
825    let opts = Options {
826        head: head.to_owned(),
827        all: true,
828        ..Options::default()
829    };
830    run(start, &opts, Some((feature, None)))
831}
832
833/// The tasks of `feature` closed on `head`: ticked there, with the commit
834/// reachable from it that carries the task's verdict — `(task, commit)`.
835/// What `pr` publishes held-out sets for; read as recorded, no trust.
836#[must_use]
837pub fn closed(start: &Path, head: &str, feature: &str) -> Vec<(String, String)> {
838    recorded(start, head, feature)
839        .map(|c| {
840            c.report
841                .ticks
842                .into_iter()
843                .filter_map(|t| t.commit.map(|c| (t.tick.task, c)))
844                .collect()
845        })
846        .unwrap_or_default()
847}
848
849/// The statements' own word, when there is no trust to check signatures
850/// with: what [`super::verify::object`] would say short of them.
851fn as_recorded(commit: &str, task: &str, statements: &[Value]) -> ObjectVerification {
852    let tv = statements
853        .iter()
854        .find(|s| s["predicateType"] == statement::TASK_VERIFICATION);
855    ObjectVerification {
856        object: commit.to_owned(),
857        kind: "task".to_owned(),
858        task: task.to_owned(),
859        verdict: tv.and_then(|s| s["predicate"]["verdict"].as_str().map(str::to_owned)),
860        outcome: if statements.is_empty() {
861            VerifyOutcome::Missing
862        } else {
863            VerifyOutcome::Ok
864        },
865        reasons: Vec::new(),
866        signer: None,
867        statements: statements.len(),
868        same_tree_as: None,
869    }
870}
871
872#[allow(clippy::too_many_lines)] // one pass, in the report's order
873fn run(
874    start: &Path,
875    opts: &Options,
876    only: Option<(&str, Option<&str>)>,
877) -> Result<Checked, Refusal> {
878    let top =
879        Git::at(start).toplevel().ok().flatten().ok_or_else(|| {
880            Refusal::new(CommandStatus::GitPrecondition, "not in a git repository")
881        })?;
882    let git = Git::at(&top);
883    let resolve = |rev: &str| {
884        git.line(&[
885            "rev-parse",
886            "--verify",
887            "--quiet",
888            &format!("{rev}^{{commit}}"),
889        ])
890        .ok()
891        .filter(|c| !c.is_empty())
892        .ok_or_else(|| {
893            Refusal::new(
894                CommandStatus::GitPrecondition,
895                format!("{rev} is not a commit here (fetch it first)"),
896            )
897        })
898    };
899    let head = resolve(&opts.head)?;
900    let base = match opts.base.as_deref() {
901        Some(b) => {
902            let b = resolve(b)?;
903            Some(
904                git.line(&["merge-base", &b, &head])
905                    .ok()
906                    .filter(|m| !m.is_empty())
907                    .ok_or_else(|| {
908                        Refusal::new(
909                            CommandStatus::GitPrecondition,
910                            format!("{b} and {head} share no history"),
911                        )
912                    })?,
913            )
914        }
915        None => None,
916    };
917    let (trust, trust_shown, _held) = trust(&top, opts, only.is_some())?;
918    let mode = if opts.all || base.is_none() {
919        Mode::All
920    } else {
921        Mode::Touched
922    };
923    let mut report = BranchReport {
924        head: head.clone(),
925        base: base.clone(),
926        mode,
927        features: Vec::new(),
928        ticks: Vec::new(),
929        skipped: Vec::new(),
930        totals: BranchTotals::default(),
931        conclusion: Conclusion::Neutral,
932        trust: trust_shown,
933        accepted_unsigned: !opts.require_signed,
934        require_verified: opts.require_verified,
935        trace: Vec::new(),
936        share: None,
937        open_no_claim: Vec::new(),
938        not_evaluated: vec![verify_branch::EARLIER_TASK_REGRESSIONS.to_owned()],
939        newer_fields: Vec::new(),
940    };
941    let history = history(
942        &git,
943        &head,
944        base.as_deref().filter(|_| mode == Mode::Touched),
945    )?;
946    let start_rel = relative(start, &top).unwrap_or_default();
947    let dir = super::tree::intent_tops(&top, &head)
948        .and_then(|tops| super::tree::materialize(&top, &head, Some(&tops)))
949        .map_err(Refusal::internal)?;
950    let opened = {
951        let at = dir.path().join(&start_rel);
952        let format = crate::format::at(&at);
953        format.inspect(&at, None).map(|snap| (format, snap))
954    };
955    let Some((format, snap)) = opened else {
956        // Nothing to verify only when there is no project to verify: a head
957        // that drops the project its base (or the trust's revision) holds
958        // has not shown there is nothing to check.
959        let reference = base.clone().or_else(|| match &opts.allowed_signers {
960            Some(AllowedSigners::Rev { rev, .. }) => resolve(rev).ok(),
961            _ => None,
962        });
963        if let Some(r) = reference
964            && project_at(&top, &r, &start_rel)?
965        {
966            return Err(Refusal::new(
967                CommandStatus::AttestationFailed,
968                format!(
969                    "{head} holds no spec project where {r} holds one: the head removes or breaks it, and its ticks cannot be checked"
970                ),
971            ));
972        }
973        report.conclusion = Conclusion::of(&[], opts.require_verified, &report.not_evaluated);
974        return Ok(Checked {
975            report,
976            repo: top,
977            prefix: as_prefix(&start_rel),
978        });
979    };
980    let project = PathBuf::from(&snap.root);
981    let prefix = as_prefix(&relative(&project, dir.path()).unwrap_or_default());
982    let mut units: Vec<&speccoder_core::snapshot::FeatureRef> = snap
983        .features
984        .iter()
985        .filter(|f| only.is_none_or(|(name, _)| f.name == name))
986        .collect();
987    if mode == Mode::Touched
988        && let Some(b) = &base
989    {
990        let paths = changed(&git, b, &head)?;
991        let dirs: Vec<String> = units
992            .iter()
993            .map(|f| format!("{prefix}{}/", f.dir.trim_end_matches('/')))
994            .collect();
995        let policy = crate::tools::policy::Policy::new(&[], &[]).rules(format.rules());
996        // A shared intent file (a constitution) speaks for every unit.
997        let shared = paths.iter().any(|p| {
998            p.strip_prefix(&prefix).is_some_and(|rel| {
999                !dirs.iter().any(|d| p.starts_with(d))
1000                    && policy.write_protected(rel) == Some(crate::tools::paths::Class::Intent)
1001            })
1002        });
1003        if !shared {
1004            units = units
1005                .into_iter()
1006                .zip(&dirs)
1007                .filter(|(_, d)| paths.iter().any(|p| p.starts_with(d.as_str())))
1008                .map(|(f, _)| f)
1009                .collect();
1010        }
1011    }
1012    let skipped = skips(&git)?;
1013    let config_path = crate::verify::find_config(&project)
1014        .and_then(|d| relative(&d, dir.path()))
1015        .map_or_else(
1016            || format!("{prefix}{}", crate::verify::config::FILE),
1017            |d| format!("{}{}", as_prefix(&d), crate::verify::config::FILE),
1018        );
1019    let mut lost: Option<BTreeMap<String, String>> = None;
1020    for f in units {
1021        let mut u = unit(format, &project, &f.name, &prefix, &skipped)?;
1022        if let Some((_, Some(task))) = only {
1023            u.ticks.retain(|t| t.task == task);
1024        }
1025        report.features.push(u.name.clone());
1026        report.skipped.extend(u.skipped);
1027        let tasks_path = u.ticks.first().map(|t| t.anchor.path.clone());
1028        let unchecked = Trust::default();
1029        let cx = Context {
1030            repo: &top,
1031            feature: &u.name,
1032            tasks_path: tasks_path.as_deref(),
1033            config_path: &config_path,
1034            trust: trust.as_ref().unwrap_or(&unchecked),
1035            format: Some(format),
1036        };
1037        let checking = trust.is_some();
1038        // Where the evidence of a tick no reachable commit carries went:
1039        // read once, before the checks, so a git failure is an error.
1040        if lost.is_none()
1041            && u.ticks.iter().any(|t| {
1042                !history
1043                    .latest
1044                    .contains_key(&format!("{}/{}", t.feature, t.task))
1045            })
1046        {
1047            lost = Some(unreachable_evidence(&git, &top, &head)?);
1048        }
1049        // Each commit's check is its own processes; a few side by side.
1050        let width = std::thread::available_parallelism().map_or(4, std::num::NonZero::get);
1051        let mut reports: Vec<TickReport> = Vec::new();
1052        let mut signed: BTreeMap<String, Vec<Value>> = BTreeMap::new();
1053        for chunk in u.ticks.chunks(width.max(1)) {
1054            let done: Vec<(TickReport, Vec<Value>)> = std::thread::scope(|scope| {
1055                let handles: Vec<_> = chunk
1056                    .iter()
1057                    .map(|tick| {
1058                        let commit = history
1059                            .latest
1060                            .get(&format!("{}/{}", tick.feature, tick.task))
1061                            .cloned();
1062                        let cx = &cx;
1063                        scope.spawn(move || {
1064                            let commit = commit?;
1065                            let statements = crate::evidence::statements(cx.repo, &commit);
1066                            if !checking {
1067                                let v = as_recorded(&commit, &tick.task, &statements);
1068                                let mut r = outcome_of(tick, &commit, v, &statements, false);
1069                                if r.outcome == TickOutcome::Evidenced {
1070                                    r.detail = Some(
1071                                        "as recorded: signatures not checked (no trust given)"
1072                                            .to_owned(),
1073                                    );
1074                                }
1075                                return Some((r, statements));
1076                            }
1077                            let v = super::verify::object(
1078                                cx,
1079                                &Target {
1080                                    object: commit.clone(),
1081                                    kind: "task",
1082                                    task: tick.task.clone(),
1083                                },
1084                            );
1085                            Some((
1086                                outcome_of(tick, &commit, v, &statements, opts.require_signed),
1087                                statements,
1088                            ))
1089                        })
1090                    })
1091                    .collect();
1092                handles
1093                    .into_iter()
1094                    .zip(chunk)
1095                    .map(|(h, tick)| match h.join() {
1096                        Ok(Some(done)) => done,
1097                        Ok(None) => (
1098                            without_commit(
1099                                tick,
1100                                lost.as_ref().and_then(|l| {
1101                                    l.get(&format!("{}/{}", tick.feature, tick.task))
1102                                }),
1103                            ),
1104                            Vec::new(),
1105                        ),
1106                        Err(_) => {
1107                            let mut r = without_commit(tick, None);
1108                            r.reason = Some(Unverifiable::Malformed);
1109                            r.detail = Some("the check panicked".to_owned());
1110                            (r, Vec::new())
1111                        }
1112                    })
1113                    .collect()
1114            });
1115            for (r, statements) in done {
1116                let rows: Vec<Value> = statements
1117                    .iter()
1118                    .filter(|s| s["predicateType"] == statement::TASK_VERIFICATION)
1119                    .flat_map(|s| {
1120                        s["predicate"]["trace"]
1121                            .as_array()
1122                            .cloned()
1123                            .unwrap_or_default()
1124                    })
1125                    .collect();
1126                signed.insert(r.tick.task.clone(), rows);
1127                reports.push(r);
1128            }
1129        }
1130        mark_stale(&top, format, &project, &prefix, &u.dir, &head, &mut reports);
1131        let requirements = format.requirement_ids(&project, &u.dir);
1132        report.trace.extend(trace(&requirements, &reports, &signed));
1133        report.ticks.extend(reports);
1134    }
1135    // Trailer-only tasks: a bug of the format's own bug structure, closed by
1136    // its verdict commit and anchored on its triad.
1137    for claim in &history.bug_claims {
1138        let Some(tick) = trailer_only(format, &project, &prefix, claim) else {
1139            // A claim whose home this build cannot read is not proof.
1140            if !report
1141                .not_evaluated
1142                .iter()
1143                .any(|n| n == verify_branch::TRAILER_ONLY_TASKS)
1144            {
1145                report
1146                    .not_evaluated
1147                    .push(verify_branch::TRAILER_ONLY_TASKS.to_owned());
1148            }
1149            continue;
1150        };
1151        if only.is_some_and(|(name, task)| {
1152            tick.feature != name || task.is_some_and(|t| t != tick.task)
1153        }) {
1154            continue;
1155        }
1156        let Some(commit) = history.latest.get(claim).cloned() else {
1157            continue;
1158        };
1159        let statements = crate::evidence::statements(&top, &commit);
1160        let unchecked = Trust::default();
1161        let cx = Context {
1162            repo: &top,
1163            feature: &tick.feature,
1164            tasks_path: None,
1165            config_path: &config_path,
1166            trust: trust.as_ref().unwrap_or(&unchecked),
1167            format: Some(format),
1168        };
1169        let r = if trust.is_some() {
1170            let v = super::verify::object(
1171                &cx,
1172                &Target {
1173                    object: commit.clone(),
1174                    kind: "task",
1175                    task: tick.task.clone(),
1176                },
1177            );
1178            outcome_of(&tick, &commit, v, &statements, opts.require_signed)
1179        } else {
1180            let v = as_recorded(&commit, &tick.task, &statements);
1181            let mut r = outcome_of(&tick, &commit, v, &statements, false);
1182            if r.outcome == TickOutcome::Evidenced {
1183                r.detail = Some("as recorded: signatures not checked (no trust given)".to_owned());
1184            }
1185            r
1186        };
1187        if !report.features.contains(&tick.feature) {
1188            report.features.push(tick.feature.clone());
1189        }
1190        report.ticks.push(r);
1191    }
1192    let mut newer: BTreeSet<String> = BTreeSet::new();
1193    for t in &report.ticks {
1194        newer.extend(t.newer_fields.iter().cloned());
1195    }
1196    report.newer_fields = newer.into_iter().collect();
1197    report.totals = BranchTotals::of(&report.ticks, report.skipped.len());
1198    report.share = verify_branch::share(&report.ticks);
1199    report.conclusion = Conclusion::of(&report.ticks, opts.require_verified, &report.not_evaluated);
1200    Ok(Checked {
1201        report,
1202        repo: top,
1203        prefix,
1204    })
1205}
1206
1207#[cfg(test)]
1208mod tests {
1209    use super::*;
1210
1211    #[test]
1212    fn a_trust_revision_needs_both_parts() {
1213        assert!(matches!(
1214            AllowedSigners::parse_rev("origin/main:.github/speccoder/allowed_signers"),
1215            Ok(AllowedSigners::Rev { rev, path }) if rev == "origin/main" && path == ".github/speccoder/allowed_signers"
1216        ));
1217        assert!(AllowedSigners::parse_rev("main").is_err());
1218        assert!(AllowedSigners::parse_rev(":x").is_err());
1219    }
1220
1221    #[test]
1222    fn the_line_of_a_requirement_is_found_trimmed() {
1223        let text = "# Spec\n\n- **FR-001**: Users MUST log in.\n";
1224        assert_eq!(
1225            line_of(text, "  - **FR-001**: Users MUST log in. "),
1226            Some(3)
1227        );
1228        assert_eq!(line_of(text, "nope"), None);
1229    }
1230
1231    #[test]
1232    fn a_git_failure_is_an_error_never_an_empty_answer() {
1233        let dir = tempfile::tempdir().unwrap();
1234        let run = |args: &[&str]| {
1235            assert!(
1236                std::process::Command::new("git")
1237                    .args(["-c", "user.name=t", "-c", "user.email=t@example.com"])
1238                    .args(["-c", "commit.gpgsign=false"])
1239                    .args(args)
1240                    .current_dir(dir.path())
1241                    .output()
1242                    .unwrap()
1243                    .status
1244                    .success()
1245            );
1246        };
1247        run(&["init", "-q"]);
1248        run(&["commit", "-q", "--allow-empty", "-m", "x"]);
1249        let git = Git::at(dir.path());
1250        // An empty diff would touch no unit and check nothing.
1251        let Err(r) = changed(&git, "no-such-base", "HEAD") else {
1252            panic!("a failed diff was an empty one");
1253        };
1254        assert_eq!(r.status, CommandStatus::Error);
1255        assert!(history(&git, "no-such-head", None).is_err());
1256        assert!(history(&git, "HEAD", Some("no-such-base")).is_err());
1257        assert!(unreachable_evidence(&git, dir.path(), "no-such-head").is_err());
1258        assert!(changed(&git, "HEAD", "HEAD").unwrap().is_empty());
1259    }
1260
1261    #[test]
1262    fn no_trust_is_refused_even_when_unsigned_ticks_are_accepted() {
1263        let dir = tempfile::tempdir().unwrap();
1264        let opts = Options {
1265            require_signed: false,
1266            ..Options::default()
1267        };
1268        let Err(r) = trust(dir.path(), &opts, false) else {
1269            panic!("trusted nothing")
1270        };
1271        assert_eq!(r.message, NO_TRUST);
1272    }
1273}