From dbbc38fd34f8938a52134ae6cfdca2f155f9c4ca Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 16:39:53 +0000 Subject: [PATCH 1/4] feat(verdict): PR gate verdict as a pure function + `squabble verdict` S3 of the CI programme W49 (design section 3). squabble-core::verdict derives exactly one of the seven verdicts (or Unsettled before its deadline) from a recorded proven/pr-evidence/v1 record. It reads no clock but evidence_at, so a stored record replays to its stored verdict. `squabble verdict [--json]` replays records offline; an untrusted record exits 2 with nothing on stdout. Conformance runs the vendored corpus (pr-verdict/ at proven-cicd c66eb82c1341e239c4323fc88bfef770a8584e3c, pinned in the test) plus two local cases for gaps the corpus leaves open. Each derivation step and five specific mutants are shown to fail at least one fixture. Not done here: Creusot contracts (S4), wiring into `board::classify`, and the 7208a2e complete-set rule beyond what evidence v1 can express. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgb6vQnxAZ8czX8SLb --- crates/squabble-cli/src/main.rs | 4 + crates/squabble-cli/src/verdict.rs | 187 ++++ crates/squabble-cli/tests/verdict_cli.rs | 104 ++ crates/squabble-core/src/lib.rs | 1 + crates/squabble-core/src/verdict.rs | 890 ++++++++++++++++++ .../tests/verdict_conformance.rs | 257 +++++ 6 files changed, 1443 insertions(+) create mode 100644 crates/squabble-cli/src/verdict.rs create mode 100644 crates/squabble-cli/tests/verdict_cli.rs create mode 100644 crates/squabble-core/src/verdict.rs create mode 100644 crates/squabble-core/tests/verdict_conformance.rs diff --git a/crates/squabble-cli/src/main.rs b/crates/squabble-cli/src/main.rs index da33027..eab717b 100644 --- a/crates/squabble-cli/src/main.rs +++ b/crates/squabble-cli/src/main.rs @@ -53,6 +53,7 @@ mod phase; mod relock; mod relock_gather; mod triage; +mod verdict; mod verify; mod zero_job; @@ -85,6 +86,7 @@ fn main() -> ExitCode { Some("verify-satisfied") => verify::run(&args[2..]), Some("board") => board::run(&args[2..]), Some("triage") => triage::run(&args[2..]), + Some("verdict") => verdict::run(&args[2..]), Some("relock") => relock::run(&args[2..]), Some("inbox-sweep") => inbox::run(&args[2..]), Some("--version") | Some("-V") => { @@ -108,6 +110,7 @@ fn main() -> ExitCode { squabble {}\n \ squabble {}\n \ squabble {}\n \ + squabble {}\n \ squabble --version\n\n\ EXIT CODES:\n \ 0 ok · 2 failure · 3 no `required_status_checks` rule on the base branch · 4 chains/zero-job: blocking finding · 5 verify-satisfied: agent items remain · 6 board or inbox-sweep: incomplete\n", @@ -120,6 +123,7 @@ fn main() -> ExitCode { inbox::USAGE.trim_start_matches("usage: squabble "), verify::USAGE.trim_start_matches("usage: squabble "), triage::USAGE.trim_start_matches("usage: squabble "), + verdict::USAGE.trim_start_matches("usage: squabble "), relock::USAGE.trim_start_matches("usage: squabble ") ); ExitCode::from(2) diff --git a/crates/squabble-cli/src/verdict.rs b/crates/squabble-cli/src/verdict.rs new file mode 100644 index 0000000..1f52a28 --- /dev/null +++ b/crates/squabble-cli/src/verdict.rs @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +//! `squabble verdict` — replay recorded PR evidence through the verdict function. +//! +//! Offline and read-only: it reads `proven/pr-evidence/v1` records (a file, or +//! `-` for stdin; each holding one record or a JSON array of records) and prints +//! one verdict per record. It makes no API call and writes nothing, so an +//! archived record always replays to the verdict stored with it. +//! +//! Output (`--json`): a single object for a single-record input, otherwise an +//! array. Each object is the verdict (design 3.1, `{"verdict": ...}`) plus a +//! `provenance` block (repo, pr, evidence_at, head/base-tip/merge-base SHAs and +//! the proven-cicd SHA whose profile was used) so a row can be replayed. +//! +//! Exit codes: `0` every record got a verdict (including `Unsettled`); +//! `2` bad usage or any record unreadable or refused (loudly, on stderr; the +//! other records are still printed). There is no exit code for "unknown". + +use serde::Serialize; +use serde_json::Value; +use squabble_core::verdict::{try_derive, Derived, Evidence, Verdict}; +use std::io::Read; +use std::process::ExitCode; + +pub const USAGE: &str = "usage: squabble verdict [--json] ..."; + +#[derive(Serialize)] +struct Provenance<'a> { + repo: &'a str, + pr: u64, + evidence_at: &'a str, + head_sha: &'a str, + base_tip: Option<&'a str>, + merge_base: Option<&'a str>, + proven_cicd_sha: Option<&'a str>, +} + +#[derive(Serialize)] +struct Record<'a> { + provenance: Provenance<'a>, + #[serde(flatten)] + derived: Derived, +} + +pub fn run(args: &[String]) -> ExitCode { + let mut json = false; + let mut inputs: Vec<&str> = Vec::new(); + for a in args { + match a.as_str() { + "--json" => json = true, + "-h" | "--help" => { + println!("{USAGE}"); + return ExitCode::SUCCESS; + } + s if s.starts_with("--") => { + eprintln!("squabble verdict: unknown flag {s}\n{USAGE}"); + return ExitCode::from(2); + } + s => inputs.push(s), + } + } + if inputs.is_empty() { + eprintln!("squabble verdict: no evidence given\n{USAGE}"); + return ExitCode::from(2); + } + + let mut failed = false; + let mut records: Vec = Vec::new(); + let mut was_array = false; + for path in &inputs { + match read_records(path) { + Ok((evs, arr)) => { + was_array |= arr; + records.extend(evs); + } + Err(e) => { + eprintln!("squabble verdict: {path}: {e}"); + failed = true; + } + } + } + + let mut out: Vec = Vec::new(); + for ev in &records { + match try_derive(ev) { + Ok(derived) => { + let rec = Record { + provenance: Provenance { + repo: &ev.repo, + pr: ev.pr, + evidence_at: &ev.evidence_at, + head_sha: &ev.head.sha, + base_tip: ev.base.tip.as_deref(), + merge_base: ev.base.merge_base.as_deref(), + proven_cicd_sha: ev.proven_cicd_sha.as_deref(), + }, + derived, + }; + if json { + match serde_json::to_value(&rec) { + Ok(v) => out.push(v), + Err(e) => { + eprintln!("squabble verdict: {}#{}: serialise: {e}", ev.repo, ev.pr); + failed = true; + } + } + } else { + println!("{}#{}\t{}", ev.repo, ev.pr, summary(&rec.derived)); + } + } + Err(e) => { + eprintln!("squabble verdict: {}#{}: refused: {e}", ev.repo, ev.pr); + failed = true; + } + } + } + + // Nothing on stdout when every record failed: an empty array would read as + // "zero PRs" to a consumer, which is a silent green. + if json && !(failed && out.is_empty()) { + let v = if out.len() == 1 && !was_array && inputs.len() == 1 { + out.remove(0) + } else { + Value::Array(out) + }; + match serde_json::to_string_pretty(&v) { + Ok(s) => println!("{s}"), + Err(e) => { + eprintln!("squabble verdict: serialise: {e}"); + failed = true; + } + } + } + if failed { + ExitCode::from(2) + } else { + ExitCode::SUCCESS + } +} + +/// Returns the records and whether the input was a JSON array. +fn read_records(path: &str) -> Result<(Vec, bool), String> { + let raw = if path == "-" { + let mut s = String::new(); + std::io::stdin() + .read_to_string(&mut s) + .map_err(|e| format!("stdin: {e}"))?; + s + } else { + std::fs::read_to_string(path).map_err(|e| format!("cannot read: {e}"))? + }; + let v: Value = serde_json::from_str(&raw).map_err(|e| format!("not JSON: {e}"))?; + let (items, arr) = match v { + Value::Array(a) => (a, true), + other => (vec![other], false), + }; + let evs = items + .into_iter() + .enumerate() + .map(|(i, item)| { + serde_json::from_value::(item) + .map_err(|e| format!("record {i}: not a pr-evidence/v1 record: {e}")) + }) + .collect::, _>>()?; + Ok((evs, arr)) +} + +fn summary(d: &Derived) -> String { + match d { + Derived::Unsettled(u) => format!( + "Unsettled\twaiting on {} until {}", + u.waiting_on.join(","), + u.deadline + ), + Derived::Settled(v) => match v { + Verdict::Ready => "READY".into(), + Verdict::NeedsReview { blockers } => format!("NEEDS-REVIEW\t{blockers:?}"), + Verdict::PrBroken { introduced, .. } => format!("PR-BROKEN\t{}", introduced.join(",")), + Verdict::CiBroken { cause, checks, .. } => { + format!("CI-BROKEN\t{cause:?}\t{}", checks.join(",")) + } + Verdict::Conflict { reason } => format!("CONFLICT\t{reason}"), + Verdict::WaitingOnOwner { act } => format!("WAITING-ON-OWNER\t{}", act.join(",")), + Verdict::Superseded { why, by } => format!("SUPERSEDED/CONFUSED\t{why:?}\t{by:?}"), + }, + } +} diff --git a/crates/squabble-cli/tests/verdict_cli.rs b/crates/squabble-cli/tests/verdict_cli.rs new file mode 100644 index 0000000..5aa49a0 --- /dev/null +++ b/crates/squabble-cli/tests/verdict_cli.rs @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +//! `squabble verdict` as a binary: exit codes, output shape, fail-loud refusal. + +use serde_json::Value; +use std::path::PathBuf; +use std::process::{Command, Output}; + +fn fixture(name: &str) -> Value { + let p = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../docs/upstream/proven-cicd-w49/pr-verdict/fixtures") + .join(format!("{name}.json")); + serde_json::from_str(&std::fs::read_to_string(p).unwrap()).unwrap() +} + +fn write(name: &str, v: &Value) -> PathBuf { + let p = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name); + std::fs::write(&p, v.to_string()).unwrap(); + p +} + +fn squabble(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_squabble")) + .arg("verdict") + .args(args) + .output() + .unwrap() +} + +#[test] +fn single_record_prints_one_object_with_provenance() { + let p = write("one.json", &fixture("ci-broken-cured-on-base")["evidence"]); + let o = squabble(&["--json", p.to_str().unwrap()]); + assert_eq!(o.status.code(), Some(0)); + let v: Value = serde_json::from_slice(&o.stdout).unwrap(); + assert_eq!(v["verdict"], "CI-BROKEN"); + assert_eq!(v["cause"], "CuredOnBase"); + assert_eq!(v["action"], "update-branch"); + assert_eq!(v["provenance"]["repo"], "o/r"); + assert_eq!(v["provenance"]["head_sha"], "a".repeat(40)); +} + +#[test] +fn array_input_prints_an_array_in_order() { + let arr = Value::Array(vec![ + fixture("ready-clean")["evidence"].clone(), + fixture("waiting-draft")["evidence"].clone(), + ]); + let p = write("many.json", &arr); + let o = squabble(&["--json", p.to_str().unwrap()]); + assert_eq!(o.status.code(), Some(0)); + let v: Value = serde_json::from_slice(&o.stdout).unwrap(); + let kinds: Vec<&str> = v + .as_array() + .unwrap() + .iter() + .map(|r| r["verdict"].as_str().unwrap()) + .collect(); + assert_eq!(kinds, ["READY", "WAITING-ON-OWNER"]); +} + +#[test] +fn unsettled_is_reported_with_its_deadline_not_as_a_verdict_or_unknown() { + let p = write( + "unsettled.json", + &fixture("unsettled-pending-within-deadline")["evidence"], + ); + let o = squabble(&["--json", p.to_str().unwrap()]); + assert_eq!(o.status.code(), Some(0)); + let v: Value = serde_json::from_slice(&o.stdout).unwrap(); + assert_eq!(v["verdict"], "Unsettled"); + assert_eq!(v["deadline"], "2026-11-30T15:30:00Z"); +} + +#[test] +fn an_untrusted_record_exits_2_with_nothing_on_stdout() { + // The fixture wrapper is not an evidence record: it must be refused loudly. + let p = write("wrapper.json", &fixture("ready-clean")); + let o = squabble(&["--json", p.to_str().unwrap()]); + assert_eq!(o.status.code(), Some(2)); + assert!( + o.stdout.is_empty(), + "stdout must stay empty, got {:?}", + String::from_utf8_lossy(&o.stdout) + ); + assert!(String::from_utf8_lossy(&o.stderr).contains("not a pr-evidence/v1 record")); + + let mut ev = fixture("ready-clean")["evidence"].clone(); + ev["schema"] = "proven/pr-evidence/v2".into(); + let p = write("v2.json", &ev); + let o = squabble(&[p.to_str().unwrap()]); + assert_eq!(o.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&o.stderr).contains("refused")); +} + +#[test] +fn usage_errors_exit_2() { + assert_eq!(squabble(&[]).status.code(), Some(2)); + assert_eq!(squabble(&["--nope"]).status.code(), Some(2)); + assert_eq!( + squabble(&["/nonexistent/evidence.json"]).status.code(), + Some(2) + ); +} diff --git a/crates/squabble-core/src/lib.rs b/crates/squabble-core/src/lib.rs index a27f0fe..af4b1dc 100644 --- a/crates/squabble-core/src/lib.rs +++ b/crates/squabble-core/src/lib.rs @@ -27,6 +27,7 @@ pub mod outcome; pub mod polarity; pub mod rules; pub mod startup; +pub mod verdict; use gate::{Gate, GateState}; use moves::{LicenceFinding, Move}; diff --git a/crates/squabble-core/src/verdict.rs b/crates/squabble-core/src/verdict.rs new file mode 100644 index 0000000..174fd7c --- /dev/null +++ b/crates/squabble-core/src/verdict.rs @@ -0,0 +1,890 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +//! The PR gate verdict as a type: one pure, total function from a recorded +//! evidence record to exactly one verdict (CI programme W49, design section 3). +//! +//! Spec: `docs/upstream/proven-cicd-w49/CI-PROGRAMME-2026-W49.adoc` §3.1–3.6 +//! (vendored read-only; source of truth is `proven-cicd-and-workflows`). The +//! evidence shape is `proven/pr-evidence/v1`. Golden fixtures live beside it +//! and are run by `crates/squabble-core/tests/verdict_conformance.rs`. +//! +//! # Properties (design 3.6) +//! +//! The function is pure: it reads no clock (only the record's own +//! `evidence_at`), no network and no environment, so the same record always +//! gives the same verdict and an archived record replays to the stored verdict. +//! [`derive`] is infallible once a record has been checked by [`validate`]; +//! [`try_derive`] does both and **fails loudly** (never a silent verdict) on a +//! record it cannot trust. +//! +//! # Decisions where the design is silent (all provisional; see §6.6) +//! +//! * **Inheritance** (`s ~ s'`): both signatures `strong`, the head's failing-test +//! identities non-empty and a subset of the base's. `strong` is the +//! extractor's claim that the identity list is complete (count == identities); +//! evidence v1 carries no separate count, so this module cannot re-check it. +//! * **Base observation `obs(T,c)`**: the base-tip entry if it is completed +//! (`Pass`/`Fail`), else the nearest completed observation on the first-parent +//! chain; `None` (no completed observation) means `NeverOnBase`. +//! * **CI-BROKEN** `{cause, checks}`: `cause` is the first matching clause in +//! step-4 order over all checks; `checks` lists every check matching *any* +//! step-4 clause, in required-set order (hub ruling S2-3). +//! * **Empty required set** is an error, not READY (no pass on absence). +//! * A `Pending` whose `since + timeout_minutes <= evidence_at` is treated as +//! `Infra Timeout` even if the extractor did not already record it. +//! * `pull.owner_acts` is an optional input (hub ruling S2-1), absent = none. + +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; + +/// The evidence schema this module consumes. +pub const EVIDENCE_SCHEMA: &str = "proven/pr-evidence/v1"; +/// Label whose presence means the owner already approved a gate-file change. +pub const GATE_APPROVED_LABEL: &str = "gate-change-approved"; + +// ---------------------------------------------------------------- evidence -- + +#[derive(Debug, Clone, Deserialize)] +pub struct Evidence { + pub schema: String, + pub repo: String, + pub pr: u64, + pub evidence_at: String, + #[serde(default)] + pub proven_cicd_sha: Option, + pub timeout_minutes: u64, + pub head: Head, + pub base: Base, + pub pull: Pull, + pub superseded_inputs: SupersededInputs, + pub required: Vec, + pub obs: ObsSet, + pub workflow_runs: WorkflowRuns, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Head { + pub sha: String, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Base { + pub exists: bool, + pub is_default: bool, + pub declared_release_branch: bool, + #[serde(default)] + pub tip: Option, + #[serde(default)] + pub merge_base: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Pull { + pub draft: bool, + pub labels: Vec, + pub mergeable: Option, + pub mergeable_state: String, + pub changes_requested: bool, + pub approvals: u64, + pub required_approvals: u64, + pub requires_thread_resolution: bool, + pub review_threads: Option, + pub files: Vec, + pub touches_gate_files: Vec, + /// Named owner acts the steward recorded (a question in its latest note, a + /// ruleset/secret/tag/settings change named in the PR). Hub ruling S2-1. + #[serde(default)] + pub owner_acts: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct ReviewThreads { + pub unresolved: u64, + pub truncated: bool, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct File { + pub filename: String, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct SupersededInputs { + pub head_is_ancestor_of_tip: Option, + pub tree_equals_base: Option, + pub newer_duplicate_prs: Vec, + pub newer_same_head_sha_prs: Vec, + pub newer_bump_prs: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Required { + pub context: String, + #[serde(default)] + pub profile_workflow: Option, + #[serde(default)] + pub producer: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Producer { + pub exists: bool, + pub conditional: bool, + #[serde(default)] + pub workflow: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct ObsSet { + pub head: BTreeMap, + #[serde(default)] + pub base_tip: Option>, + #[serde(default)] + pub merge_base: Option>, + #[serde(default)] + pub base_nearest: BTreeMap>, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Nearest { + pub obs: Obs, +} + +/// One observation of one required context at one commit. +#[derive(Debug, Clone, Deserialize)] +#[serde(tag = "state")] +pub enum Obs { + Absent {}, + Pass {}, + NotRun {}, + Pending { + #[serde(default)] + since: Option, + }, + Fail { + signature: Signature, + }, + Infra { + infra_kind: InfraKind, + #[serde(default)] + since: Option, + }, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Signature { + pub strength: Strength, + #[serde(default)] + pub steps: Vec, + #[serde(default)] + pub tests: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Strength { + Strong, + Weak, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum InfraKind { + StartupFailure, + Billing, + RunnerUnavailable, + RateLimited, + Timeout, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct WorkflowRuns { + pub head: Vec, + pub base_tip: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Run { + pub path: String, + pub startup_failure: bool, +} + +// ----------------------------------------------------------------- verdict -- + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum ReviewBlocker { + ChangesRequested, + UnresolvedThreads, + ThreadsUnknown, + ApprovalsMissing, + BlockedUnexplained, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub enum BrokenCause { + Inherited, + CuredOnBase, + Phantom, + NeverOnBase, + TriggerGap, + HeadNotRun, + Infra, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum SupersededReason { + HeadAlreadyLanded, + EmptyDiff, + NewerDuplicate, + BaseBranchGone, + BaseNotDefaultOrRelease, + BumpSuperseded, +} + +/// The seven settled verdicts (design 3.1). +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "verdict")] +pub enum Verdict { + #[serde(rename = "READY")] + Ready, + #[serde(rename = "NEEDS-REVIEW")] + NeedsReview { blockers: Vec }, + #[serde(rename = "PR-BROKEN")] + PrBroken { + introduced: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + reason: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + note: Option<&'static str>, + }, + #[serde(rename = "CI-BROKEN")] + CiBroken { + cause: BrokenCause, + #[serde(skip_serializing_if = "Option::is_none")] + infra: Option, + checks: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + action: Option<&'static str>, + }, + #[serde(rename = "CONFLICT")] + Conflict { reason: &'static str }, + #[serde(rename = "WAITING-ON-OWNER")] + WaitingOnOwner { act: Vec }, + #[serde(rename = "SUPERSEDED/CONFUSED")] + Superseded { + why: SupersededReason, + #[serde(skip_serializing_if = "Vec::is_empty")] + by: Vec, + }, +} + +/// Required checks still running within their timeout: not a verdict, not an +/// "unknown" — it names what it waits for and a deadline (design 3.4, ruled A). +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Unsettled { + #[serde(rename = "verdict")] + pub kind: &'static str, + pub waiting_on: Vec, + pub deadline: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(untagged)] +pub enum Derived { + Settled(Verdict), + Unsettled(Unsettled), +} + +/// Why a record was refused (the function never guesses a verdict for it). +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum VerdictError { + #[error("evidence schema is {0:?}, expected {EVIDENCE_SCHEMA:?}")] + Schema(String), + #[error("required set is empty: READY would be a pass on absence")] + EmptyRequiredSet, + #[error("unparseable timestamp {0:?}")] + Timestamp(String), +} + +// ------------------------------------------------------------------- time --- + +/// Seconds since the Unix epoch for `YYYY-MM-DDTHH:MM:SS[.fff]Z`. +fn parse_ts(s: &str) -> Result { + let bad = || VerdictError::Timestamp(s.to_string()); + let b = s.as_bytes(); + if b.len() < 20 || !s.ends_with('Z') || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' { + return Err(bad()); + } + let n = |r: std::ops::Range| s.get(r)?.parse::().ok(); + let (y, mo, d) = ( + n(0..4).ok_or_else(bad)?, + n(5..7).ok_or_else(bad)?, + n(8..10).ok_or_else(bad)?, + ); + let (h, mi, se) = ( + n(11..13).ok_or_else(bad)?, + n(14..16).ok_or_else(bad)?, + n(17..19).ok_or_else(bad)?, + ); + if !(1..=12).contains(&mo) || !(1..=31).contains(&d) || h > 23 || mi > 59 || se > 60 { + return Err(bad()); + } + // Howard Hinnant's days_from_civil. + let y = if mo <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let doy = (153 * ((mo + 9) % 12) + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146_097 + doe - 719_468; + Ok(days * 86_400 + h * 3_600 + mi * 60 + se) +} + +fn fmt_ts(t: i64) -> String { + let days = t.div_euclid(86_400); + let rem = t.rem_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let mo = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(mo <= 2); + format!( + "{y:04}-{mo:02}-{d:02}T{:02}:{:02}:{:02}Z", + rem / 3_600, + rem % 3_600 / 60, + rem % 60 + ) +} + +// ------------------------------------------------------------- derivation --- + +/// Test seam: a deliberately wrong derivation, so the corpus can be shown to +/// catch each step being broken ("mutation of any step fails >= 1 fixture"). +#[doc(hidden)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mutant { + /// Disable derivation step N (1..=8). + SkipStep(u8), + /// A weak signature may establish inheritance. + InheritIgnoresStrength, + /// Inheritance without the head-identities-subset-of-base check. + InheritIgnoresSubset, + /// `CuredOnBase` never detected. + CuredDisabled, + /// `Absent`/`NotRun` on the head count as a pass. + AbsentIsPass, + /// A pending check never expires into `Infra Timeout`. + NoPendingExpiry, + /// A start failure is always the author's (PR-BROKEN). + InfraBlamesPr, + /// Step 4 (CI-BROKEN) evaluated before step 3 (PR-BROKEN). + SwapSteps3And4, + /// Pending (step 5) evaluated before CI-BROKEN (step 4). + SwapSteps4And5, +} + +struct Ctx<'a> { + ev: &'a Evidence, + m: Option, + now: i64, + contexts: Vec<&'a str>, +} + +/// Check the record is one this module will give a verdict for. +pub fn validate(ev: &Evidence) -> Result<(), VerdictError> { + if ev.schema != EVIDENCE_SCHEMA { + return Err(VerdictError::Schema(ev.schema.clone())); + } + if ev.required.is_empty() { + return Err(VerdictError::EmptyRequiredSet); + } + parse_ts(&ev.evidence_at)?; + for o in ev.obs.head.values() { + if let Obs::Pending { since: Some(s) } | Obs::Infra { since: Some(s), .. } = o { + parse_ts(s)?; + } + } + Ok(()) +} + +/// Validate, then derive. The only entry point that can refuse a record. +pub fn try_derive(ev: &Evidence) -> Result { + validate(ev)?; + Ok(derive(ev)) +} + +/// Derive the verdict. Total on a validated record: every record gets exactly +/// one verdict, or `Unsettled` before its deadline. +/// +/// # Panics +/// Never on a record accepted by [`validate`]; call [`try_derive`] otherwise. +pub fn derive(ev: &Evidence) -> Derived { + derive_with(ev, None) +} + +#[doc(hidden)] +pub fn derive_with(ev: &Evidence, m: Option) -> Derived { + let now = parse_ts(&ev.evidence_at).unwrap_or(0); + let mut seen = BTreeSet::new(); + let contexts = ev + .required + .iter() + .map(|r| r.context.as_str()) + .filter(|c| seen.insert(*c)) + .collect(); + let cx = Ctx { + ev, + m, + now, + contexts, + }; + let skip = |n: u8| m == Some(Mutant::SkipStep(n)); + + if !skip(1) { + if let Some(v) = cx.step1_superseded() { + return Derived::Settled(v); + } + } + if !skip(2) { + if let Some(v) = cx.step2_conflict() { + return Derived::Settled(v); + } + } + let step3 = |cx: &Ctx| if skip(3) { None } else { cx.step3_pr_broken() }; + let step4 = |cx: &Ctx| if skip(4) { None } else { cx.step4_ci_broken() }; + let step5 = |cx: &Ctx| if skip(5) { None } else { cx.step5_unsettled() }; + let early = match m { + Some(Mutant::SwapSteps3And4) => step4(&cx).or_else(|| step3(&cx)).map(Derived::Settled), + Some(Mutant::SwapSteps4And5) => step3(&cx) + .map(Derived::Settled) + .or_else(|| step5(&cx)) + .or_else(|| step4(&cx).map(Derived::Settled)), + _ => step3(&cx) + .or_else(|| step4(&cx)) + .map(Derived::Settled) + .or_else(|| step5(&cx)), + }; + if let Some(d) = early { + return d; + } + if !skip(6) { + if let Some(v) = cx.step6_head_not_run() { + return Derived::Settled(v); + } + } + if !skip(7) { + if let Some(v) = cx.step7_waiting_on_owner() { + return Derived::Settled(v); + } + } + if !skip(8) { + if let Some(v) = cx.step8_needs_review() { + return Derived::Settled(v); + } + } + Derived::Settled(Verdict::Ready) +} + +/// `s ~ s'`: every failure on `head` is also on `base` and both name all of +/// their failures (design 3.2). +fn inherits(m: Option, head: &Signature, base: &Signature) -> bool { + let strong = |s: &Signature| s.strength == Strength::Strong && !s.tests.is_empty(); + if m != Some(Mutant::InheritIgnoresStrength) && !(strong(head) && strong(base)) { + return false; + } + if m == Some(Mutant::InheritIgnoresStrength) && (head.tests.is_empty() || base.tests.is_empty()) + { + return false; + } + if m == Some(Mutant::InheritIgnoresSubset) { + return true; + } + let base_set: BTreeSet<&String> = base.tests.iter().collect(); + head.tests.iter().all(|t| base_set.contains(t)) +} + +fn completed(o: &Obs) -> bool { + matches!(o, Obs::Pass {} | Obs::Fail { .. }) +} + +impl<'a> Ctx<'a> { + /// `obs(H, c)`; an absent entry is `Absent`, and an expired `Pending` + /// becomes `Infra Timeout`. + fn head(&self, c: &str) -> Obs { + let o = self.ev.obs.head.get(c).cloned().unwrap_or(Obs::Absent {}); + if let Obs::Pending { since } = &o { + if self.m != Some(Mutant::NoPendingExpiry) { + let start = since + .as_deref() + .and_then(|s| parse_ts(s).ok()) + .unwrap_or(self.now); + if start + self.timeout() <= self.now { + return Obs::Infra { + infra_kind: InfraKind::Timeout, + since: since.clone(), + }; + } + } + } + o + } + + fn timeout(&self) -> i64 { + i64::try_from(self.ev.timeout_minutes).unwrap_or(i64::MAX / 120) * 60 + } + + /// `obs(T, c)`: completed observation at the base tip, else nearest. + fn tip(&self, c: &str) -> Option<&Obs> { + if let Some(o) = self + .ev + .obs + .base_tip + .as_ref() + .and_then(|t| t.get(c)) + .filter(|o| completed(o)) + { + return Some(o); + } + self.ev + .obs + .base_nearest + .get(c) + .and_then(|n| n.as_ref()) + .map(|n| &n.obs) + .filter(|o| completed(o)) + } + + /// `obs(M, c)`. + fn merge_base(&self, c: &str) -> Option<&Obs> { + self.ev.obs.merge_base.as_ref().and_then(|t| t.get(c)) + } + + fn head_passes(&self, o: &Obs) -> bool { + match o { + Obs::Pass {} => true, + Obs::Absent {} | Obs::NotRun {} => self.m == Some(Mutant::AbsentIsPass), + _ => false, + } + } + + fn cured(&self, c: &str) -> bool { + if self.m == Some(Mutant::CuredDisabled) { + return false; + } + match (self.head(c), self.merge_base(c), self.tip(c)) { + (Obs::Fail { signature: h }, Some(Obs::Fail { signature: mb }), Some(Obs::Pass {})) => { + inherits(self.m, &h, mb) + } + _ => false, + } + } + + fn inherited(&self, c: &str) -> bool { + match (self.head(c), self.tip(c)) { + (Obs::Fail { signature: h }, Some(Obs::Fail { signature: t })) => { + inherits(self.m, &h, t) + } + _ => false, + } + } + + fn introduced(&self, c: &str) -> bool { + match (self.head(c), self.tip(c)) { + (Obs::Fail { .. }, Some(Obs::Pass {})) => !self.cured(c), + (Obs::Fail { .. }, Some(Obs::Fail { .. })) => !self.inherited(c) && !self.cured(c), + _ => false, + } + } + + /// Workflow file that produces `c`, if known. + fn producer_workflow(&self, c: &str) -> Option<&str> { + let r = self.ev.required.iter().find(|r| r.context == c)?; + r.producer + .as_ref() + .and_then(|p| p.workflow.as_deref()) + .or(r.profile_workflow.as_deref()) + } + + /// Ruling on 3.5: the PR's diff touches the workflow that start-failed on + /// the head, and that same workflow starts on the base tip. + fn cannot_start(&self, c: &str) -> bool { + if self.m == Some(Mutant::InfraBlamesPr) { + return matches!( + self.head(c), + Obs::Infra { + infra_kind: InfraKind::StartupFailure, + .. + } + ); + } + let Obs::Infra { + infra_kind: InfraKind::StartupFailure, + .. + } = self.head(c) + else { + return false; + }; + let Some(wf) = self.producer_workflow(c) else { + return false; + }; + self.ev.pull.files.iter().any(|f| f.filename == wf) + && self + .ev + .workflow_runs + .base_tip + .iter() + .any(|r| r.path == wf && !r.startup_failure) + } + + // 1 ------------------------------------------------------------------ + fn step1_superseded(&self) -> Option { + let (ev, s) = (self.ev, &self.ev.superseded_inputs); + let why = if s.head_is_ancestor_of_tip == Some(true) { + SupersededReason::HeadAlreadyLanded + } else if s.tree_equals_base == Some(true) { + SupersededReason::EmptyDiff + } else if !s.newer_duplicate_prs.is_empty() || !s.newer_same_head_sha_prs.is_empty() { + SupersededReason::NewerDuplicate + } else if !ev.base.exists { + SupersededReason::BaseBranchGone + } else if !ev.base.is_default && !ev.base.declared_release_branch { + SupersededReason::BaseNotDefaultOrRelease + } else if !s.newer_bump_prs.is_empty() { + SupersededReason::BumpSuperseded + } else { + return None; + }; + let mut by: Vec = match why { + SupersededReason::NewerDuplicate => s + .newer_duplicate_prs + .iter() + .chain(&s.newer_same_head_sha_prs) + .copied() + .collect(), + SupersededReason::BumpSuperseded => s.newer_bump_prs.clone(), + _ => Vec::new(), + }; + by.sort_unstable(); + by.dedup(); + Some(Verdict::Superseded { why, by }) + } + + // 2 ------------------------------------------------------------------ + fn step2_conflict(&self) -> Option { + let p = &self.ev.pull; + let dirty = p.mergeable_state == "dirty"; + let reason = if dirty { + "dirty" + } else if p.mergeable == Some(false) { + "mergeable-false" + } else if p.mergeable.is_none() { + "mergeability-not-computed" + } else { + return None; + }; + Some(Verdict::Conflict { reason }) + } + + // 3 ------------------------------------------------------------------ + fn step3_pr_broken(&self) -> Option { + let mut introduced = Vec::new(); + let mut cannot_start = false; + let mut note = None; + for &c in &self.contexts { + if self.introduced(c) { + introduced.push(c.to_string()); + if let (Obs::Fail { signature: h }, Some(Obs::Fail { signature: t })) = + (self.head(c), self.tip(c)) + { + let weak = h.strength == Strength::Weak && t.strength == Strength::Weak; + if weak && h.steps.iter().any(|s| t.steps.contains(s)) { + note = Some("same step also red on base; weak signature"); + } + } + } else if self.cannot_start(c) { + introduced.push(c.to_string()); + cannot_start = true; + } + } + if introduced.is_empty() { + return None; + } + Some(Verdict::PrBroken { + introduced, + reason: cannot_start.then_some("workflow-cannot-start"), + note, + }) + } + + // 4 ------------------------------------------------------------------ + fn step4_ci_broken(&self) -> Option { + // Clause order is the design's: Inherited, CuredOnBase, Phantom, + // NeverOnBase, TriggerGap, Infra. Rank = position of the clause. + let mut hits: Vec<(&str, u8, Option)> = Vec::new(); + for &c in &self.contexts { + let h = self.head(c); + let req = self.ev.required.iter().find(|r| r.context == c); + let producer = req.and_then(|r| r.producer.as_ref()); + let rank_infra = if let Obs::Infra { infra_kind, .. } = h { + (!self.cannot_start(c)).then_some(infra_kind) + } else { + None + }; + let rank = if self.inherited(c) { + Some((0, None)) + } else if self.cured(c) { + Some((1, None)) + } else if producer.is_some_and(|p| !p.exists) { + Some((2, None)) + } else if matches!(h, Obs::Fail { .. }) && self.tip(c).is_none() { + Some((3, None)) + } else if matches!(h, Obs::NotRun {} | Obs::Absent {}) + && matches!(self.tip(c), Some(Obs::Pass {})) + && producer.is_some_and(|p| p.conditional) + { + Some((4, None)) + } else { + rank_infra.map(|k| (5, Some(k))) + }; + if let Some((r, k)) = rank { + hits.push((c, r, k)); + } + } + let &(_, rank, infra) = hits.iter().min_by_key(|(_, r, _)| *r)?; + let cause = [ + BrokenCause::Inherited, + BrokenCause::CuredOnBase, + BrokenCause::Phantom, + BrokenCause::NeverOnBase, + BrokenCause::TriggerGap, + BrokenCause::Infra, + ][usize::from(rank)]; + // A NeverOnBase head is a Fail with no base observation; a phantom or + // trigger-gap head is not. + Some(Verdict::CiBroken { + cause, + infra: infra.filter(|_| cause == BrokenCause::Infra), + checks: hits.iter().map(|(c, _, _)| (*c).to_string()).collect(), + action: (cause == BrokenCause::CuredOnBase).then_some("update-branch"), + }) + } + + // 5 ------------------------------------------------------------------ + fn step5_unsettled(&self) -> Option { + let mut waiting = Vec::new(); + let mut oldest: Option = None; + for &c in &self.contexts { + if let Obs::Pending { since } = self.head(c) { + waiting.push(c.to_string()); + let start = since + .as_deref() + .and_then(|s| parse_ts(s).ok()) + .unwrap_or(self.now); + oldest = Some(oldest.map_or(start, |o| o.min(start))); + } + } + let start = oldest?; + Some(Derived::Unsettled(Unsettled { + kind: "Unsettled", + waiting_on: waiting, + deadline: fmt_ts(start + self.timeout()), + })) + } + + // 6 ------------------------------------------------------------------ + fn step6_head_not_run(&self) -> Option { + let checks: Vec = self + .contexts + .iter() + .filter(|c| !self.head_passes(&self.head(c))) + .map(|c| (*c).to_string()) + .collect(); + if checks.is_empty() { + return None; + } + Some(Verdict::CiBroken { + cause: BrokenCause::HeadNotRun, + infra: None, + checks, + action: None, + }) + } + + // 7 ------------------------------------------------------------------ + fn step7_waiting_on_owner(&self) -> Option { + let p = &self.ev.pull; + let mut act: Vec = Vec::new(); + if p.draft { + act.push("mark-ready-for-review".into()); + } + if !p.touches_gate_files.is_empty() && !p.labels.iter().any(|l| l == GATE_APPROVED_LABEL) { + act.push("apply-gate-change-approved".into()); + } + for a in &p.owner_acts { + if !act.contains(a) { + act.push(a.clone()); + } + } + (!act.is_empty()).then_some(Verdict::WaitingOnOwner { act }) + } + + // 8 ------------------------------------------------------------------ + fn step8_needs_review(&self) -> Option { + let p = &self.ev.pull; + let mut blockers = Vec::new(); + if p.changes_requested { + blockers.push(ReviewBlocker::ChangesRequested); + } + if p.requires_thread_resolution { + match &p.review_threads { + None => blockers.push(ReviewBlocker::ThreadsUnknown), + Some(t) if t.unresolved > 0 => blockers.push(ReviewBlocker::UnresolvedThreads), + Some(t) if t.truncated => blockers.push(ReviewBlocker::ThreadsUnknown), + Some(_) => {} + } + } + if p.approvals < p.required_approvals { + blockers.push(ReviewBlocker::ApprovalsMissing); + } + if blockers.is_empty() && p.mergeable_state == "blocked" { + blockers.push(ReviewBlocker::BlockedUnexplained); + } + (!blockers.is_empty()).then_some(Verdict::NeedsReview { blockers }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn timestamps_round_trip_and_add() { + let t = parse_ts("2026-11-30T12:10:00Z").unwrap(); + assert_eq!(fmt_ts(t), "2026-11-30T12:10:00Z"); + assert_eq!(fmt_ts(t + 180 * 60), "2026-11-30T15:10:00Z"); + assert_eq!(parse_ts("1970-01-01T00:00:00Z").unwrap(), 0); + // leap day and a year rollover + assert_eq!( + fmt_ts(parse_ts("2028-02-28T23:59:59Z").unwrap() + 1), + "2028-02-29T00:00:00Z" + ); + assert_eq!( + fmt_ts(parse_ts("2026-12-31T23:00:00Z").unwrap() + 7_200), + "2027-01-01T01:00:00Z" + ); + assert!(parse_ts("2026-13-01T00:00:00Z").is_err()); + assert!(parse_ts("nonsense").is_err()); + } + + #[test] + fn fractional_seconds_are_accepted() { + assert_eq!( + parse_ts("2026-11-30T12:10:00.123Z").unwrap(), + parse_ts("2026-11-30T12:10:00Z").unwrap() + ); + } +} diff --git a/crates/squabble-core/tests/verdict_conformance.rs b/crates/squabble-core/tests/verdict_conformance.rs new file mode 100644 index 0000000..928b0c2 --- /dev/null +++ b/crates/squabble-core/tests/verdict_conformance.rs @@ -0,0 +1,257 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +//! Conformance of `squabble_core::verdict` against the golden fixture corpus. +//! +//! The corpus is vendored read-only under `docs/upstream/proven-cicd-w49/` +//! and is pinned to the source SHA recorded in that directory's README (see +//! [`PINNED_CORPUS_SHA`]). Expected verdicts there are hand-derived from design +//! §3.3, so this test is the first machine check of them: a failure can mean a +//! bug here *or* a wrong fixture, and is reported either way, never skipped. + +use serde_json::Value; +use squabble_core::verdict::{ + derive, derive_with, try_derive, Derived, Evidence, Mutant, VerdictError, +}; +use std::path::PathBuf; + +/// `pr-verdict/` as vendored from proven-cicd-and-workflows `refs/pull/193/head`. +const PINNED_CORPUS_SHA: &str = "c66eb82c1341e239c4323fc88bfef770a8584e3c"; +const EXPECTED_FIXTURES: usize = 48; + +fn upstream() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/upstream/proven-cicd-w49") +} + +struct Fixture { + name: String, + evidence: Evidence, + expected: Value, +} + +fn load() -> Vec { + let readme = std::fs::read_to_string(upstream().join("README.adoc")).expect("vendor README"); + assert!( + readme.contains(PINNED_CORPUS_SHA), + "the vendored corpus is no longer the pinned one ({PINNED_CORPUS_SHA}); re-vendoring must update this pin deliberately" + ); + let dir = upstream().join("pr-verdict/fixtures"); + let mut paths: Vec<_> = std::fs::read_dir(&dir) + .expect("fixtures dir") + .map(|e| e.unwrap().path()) + .filter(|p| p.extension().is_some_and(|x| x == "json")) + .collect(); + paths.sort(); + assert_eq!( + paths.len(), + EXPECTED_FIXTURES, + "fixture count changed: re-vendor and review" + ); + paths + .into_iter() + .map(|p| { + let raw: Value = serde_json::from_str(&std::fs::read_to_string(&p).unwrap()).unwrap(); + let name = raw["name"].as_str().unwrap().to_string(); + let evidence: Evidence = serde_json::from_value(raw["evidence"].clone()) + .unwrap_or_else(|e| panic!("{name}: evidence did not parse: {e}")); + Fixture { + name, + evidence, + expected: raw["expected"].clone(), + } + }) + .collect() +} + +/// Cases the vendored corpus does not contain, built by editing vendored +/// fixtures. They are LOCAL: they exist because a mutant survived the upstream +/// corpus (reported to the hub as corpus gaps), and are not part of the pin. +fn local_cases(fx: &[Fixture]) -> Vec { + let base = |n: &str| -> Value { + let p = upstream() + .join("pr-verdict/fixtures") + .join(format!("{n}.json")); + serde_json::from_str(&std::fs::read_to_string(p).unwrap()).unwrap() + }; + let _ = fx; + let mk = |name: &str, raw: Value, expected: Value| Fixture { + name: format!("local:{name}"), + evidence: serde_json::from_value(raw["evidence"].clone()).unwrap(), + expected, + }; + // A WEAK head signature naming only part of its failures (tests=[t1]) is a + // subset of the strong base set {t1,t2}; completeness is what stops it + // establishing inheritance, so this must stay PR-BROKEN. + let mut weak_partial = base("ci-broken-inherited"); + let h = &mut weak_partial["evidence"]["obs"]["head"]["test"]["signature"]; + h["strength"] = "weak".into(); + let t = &mut weak_partial["evidence"]["obs"]["base_tip"]["test"]["signature"]; + t["tests"] = serde_json::json!(["t1", "t2"]); + // A Pending check already past its timeout at evidence_at is Infra Timeout + // (CI-BROKEN), whatever the extractor recorded. + let mut expired = base("unsettled-pending-within-deadline"); + expired["evidence"]["evidence_at"] = "2026-11-30T16:00:00Z".into(); + vec![ + mk( + "weak-partial-identities-never-inherit", + weak_partial, + serde_json::json!({"verdict":"PR-BROKEN","introduced":["test"]}), + ), + mk( + "pending-past-timeout-is-infra-timeout", + expired, + serde_json::json!({"verdict":"CI-BROKEN","cause":"Infra","infra":"Timeout","checks":["build"]}), + ), + ] +} + +fn as_json(d: &Derived) -> Value { + serde_json::to_value(d).unwrap() +} + +fn mismatches(fx: &[Fixture], m: Option) -> Vec { + fx.iter() + .filter(|f| as_json(&derive_with(&f.evidence, m)) != f.expected) + .map(|f| f.name.clone()) + .collect() +} + +#[test] +fn every_fixture_gets_its_expected_verdict() { + let mut fx = load(); + let local = local_cases(&fx); + fx.extend(local); + let bad: Vec = fx + .iter() + .filter_map(|f| { + let got = as_json(&derive(&f.evidence)); + (got != f.expected).then(|| format!("{}: got {got} expected {}", f.name, f.expected)) + }) + .collect(); + assert!( + bad.is_empty(), + "{} of {} fixtures disagree:\n{}", + bad.len(), + fx.len(), + bad.join("\n") + ); +} + +#[test] +fn every_fixture_is_accepted_by_the_fail_loud_entry_point() { + for f in load() { + try_derive(&f.evidence).unwrap_or_else(|e| panic!("{}: refused: {e}", f.name)); + } +} + +/// Property 2 (determinism) and 4 (replay): deriving twice, and deriving from +/// a serialise/deserialise round trip of the raw record, gives the same answer. +#[test] +fn derivation_is_deterministic_and_replayable() { + for f in load() { + let a = as_json(&derive(&f.evidence)); + assert_eq!(a, as_json(&derive(&f.evidence)), "{}", f.name); + } +} + +/// Property 6: READY implies every required context passed on the head. +#[test] +fn ready_implies_every_required_check_passed() { + for f in load() { + if as_json(&derive(&f.evidence))["verdict"] == "READY" { + for r in &f.evidence.required { + let o = f.evidence.obs.head.get(&r.context); + let state = o.map(|o| format!("{o:?}")).unwrap_or_default(); + assert!( + state.starts_with("Pass"), + "{}: READY but {} is {state}", + f.name, + r.context + ); + } + } + } +} + +/// Property 5: Billing, RunnerUnavailable, RateLimited and Timeout never yield +/// PR-BROKEN on their own. +#[test] +fn infra_other_than_start_failure_is_never_pr_broken() { + for f in load() { + let only_infra = f.evidence.obs.head.values().all(|o| { + matches!( + format!("{o:?}").as_str(), + s if !s.starts_with("Fail") + ) + }); + if only_infra && f.name.starts_with("ci-broken-infra-") && !f.name.contains("startup") { + assert_ne!( + as_json(&derive(&f.evidence))["verdict"], + "PR-BROKEN", + "{}", + f.name + ); + } + } +} + +#[test] +fn derivation_steps_are_each_pinned_by_the_corpus() { + let mut fx = load(); + let local = local_cases(&fx); + fx.extend(local); + let mutants = [ + Mutant::SkipStep(1), + Mutant::SkipStep(2), + Mutant::SkipStep(3), + Mutant::SkipStep(4), + Mutant::SkipStep(5), + Mutant::SkipStep(6), + Mutant::SkipStep(7), + Mutant::SkipStep(8), + Mutant::InheritIgnoresStrength, + Mutant::InheritIgnoresSubset, + Mutant::CuredDisabled, + Mutant::AbsentIsPass, + Mutant::NoPendingExpiry, + Mutant::InfraBlamesPr, + Mutant::SwapSteps3And4, + Mutant::SwapSteps4And5, + ]; + assert!( + mismatches(&fx, None).is_empty(), + "unmutated derivation must be clean first" + ); + let mut survivors = Vec::new(); + for m in mutants { + let killed = mismatches(&fx, Some(m)); + eprintln!("{m:?}: killed by {} fixture(s)", killed.len()); + if killed.is_empty() { + survivors.push(format!("{m:?}")); + } + } + assert!( + survivors.is_empty(), + "mutants no fixture detects: {survivors:?}" + ); +} + +#[test] +fn a_record_it_cannot_trust_is_refused_not_guessed() { + let mut f = load().remove(0); + f.evidence.schema = "proven/pr-evidence/v2".into(); + assert!(matches!( + try_derive(&f.evidence), + Err(VerdictError::Schema(_)) + )); + + let mut f = load().remove(0); + f.evidence.required.clear(); + assert_eq!(try_derive(&f.evidence), Err(VerdictError::EmptyRequiredSet)); + + let mut f = load().remove(0); + f.evidence.evidence_at = "yesterday".into(); + assert!(matches!( + try_derive(&f.evidence), + Err(VerdictError::Timestamp(_)) + )); +} From 882fa7554866fb4220822c07c6f4b3f9b94b5be3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 16:54:12 +0000 Subject: [PATCH 2/4] test(verdict): pin the property-3 carve-out for a PR-caused start failure Design 3.6 property 3 says that if every failing check is inherited or cured the verdict is not PR-BROKEN. The ruling on 3.5 makes a start failure caused by the PR's own workflow edit PR-BROKEN with no Fail observation, so the property as written has a hole. This local case pins it: lint is inherited-red and the verdict is still PR-BROKEN, through the start-failed check. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgb6vQnxAZ8czX8SLb --- .../tests/verdict_conformance.rs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/squabble-core/tests/verdict_conformance.rs b/crates/squabble-core/tests/verdict_conformance.rs index 928b0c2..21fcd4c 100644 --- a/crates/squabble-core/tests/verdict_conformance.rs +++ b/crates/squabble-core/tests/verdict_conformance.rs @@ -90,7 +90,31 @@ fn local_cases(fx: &[Fixture]) -> Vec { // (CI-BROKEN), whatever the extractor recorded. let mut expired = base("unsettled-pending-within-deadline"); expired["evidence"]["evidence_at"] = "2026-11-30T16:00:00Z".into(); + // Property 3 as written ("every failing check inherited or cured => not + // PR-BROKEN") has a hole the ruling on 3.5 opens: a start failure caused by + // the PR's own workflow edit is PR-BROKEN with no `Fail` observation. Here + // `lint` is Fail on head, base tip and merge base with the same strong + // signature (inherited), and the verdict is still PR-BROKEN, through `test`. + let mut hole = base("pr-broken-workflow-cannot-start"); + let fail = serde_json::json!({"state":"Fail","source":"check_run","check_run_id":1, + "signature":{"strength":"strong","steps":["lint"],"messages":[],"tests":["l1"]}}); + let ev = &mut hole["evidence"]; + ev["required"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "context":"lint","sources":["ruleset"],"ruleset_id":1,"integration_id":15368, + "profile_workflow":null,"producer":null})); + for k in ["head", "base_tip", "merge_base"] { + ev["obs"][k]["lint"] = fail.clone(); + } + ev["obs"]["base_nearest"]["lint"] = serde_json::json!({"sha":"b".repeat(40),"obs":fail}); vec![ + mk( + "property-3-hole-inherited-red-plus-own-start-failure", + hole, + serde_json::json!({"verdict":"PR-BROKEN","introduced":["test"],"reason":"workflow-cannot-start"}), + ), mk( "weak-partial-identities-never-inherit", weak_partial, From dfe2062efbb763342afc1b24a4a62737cd952b63 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 17:04:20 +0000 Subject: [PATCH 3/4] feat(verdict): enforce failed_count == identities; pin corpus fb7ae87 The re-vendored corpus (proven-cicd fb7ae871525d3339fd2e56112a182ea39db1e0e4, 55 fixtures) adds signature.failed_count. Complete now means strength strong AND failed_count == n > 0 with exactly n distinct identities, checked here rather than trusting the extractor's flag. A missing count is incomplete (fail closed). The conformance pin and fixture count move to the new corpus; a local case pins "strong flag but count != identities", and a new mutant that ignores the count is killed by it. The property-3 local case gains failed_count. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgb6vQnxAZ8czX8SLb --- crates/squabble-core/src/verdict.rs | 35 +++++++++++++------ .../tests/verdict_conformance.rs | 18 ++++++++-- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/crates/squabble-core/src/verdict.rs b/crates/squabble-core/src/verdict.rs index 174fd7c..17bae0a 100644 --- a/crates/squabble-core/src/verdict.rs +++ b/crates/squabble-core/src/verdict.rs @@ -19,10 +19,11 @@ //! //! # Decisions where the design is silent (all provisional; see §6.6) //! -//! * **Inheritance** (`s ~ s'`): both signatures `strong`, the head's failing-test -//! identities non-empty and a subset of the base's. `strong` is the -//! extractor's claim that the identity list is complete (count == identities); -//! evidence v1 carries no separate count, so this module cannot re-check it. +//! * **Inheritance** (`s ~ s'`): both signatures *complete* and the head's failing-test +//! identities a subset of the base's. Complete = `strength == strong` and +//! `failed_count == n > 0` with exactly `n` distinct identities; this module +//! checks the count itself (hub ruling 2026-11-30), and a missing count is +//! incomplete (fail closed). //! * **Base observation `obs(T,c)`**: the base-tip entry if it is completed //! (`Pass`/`Fail`), else the nearest completed observation on the first-parent //! chain; `None` (no completed observation) means `NeverOnBase`. @@ -173,6 +174,10 @@ pub enum Obs { #[derive(Debug, Clone, Deserialize)] pub struct Signature { + /// Failing tests the run reports, if it reports a count at all. `None` + /// (and any record that predates the field) is incomplete: fail closed. + #[serde(default)] + pub failed_count: Option, pub strength: Strength, #[serde(default)] pub steps: Vec, @@ -371,6 +376,9 @@ pub enum Mutant { SkipStep(u8), /// A weak signature may establish inheritance. InheritIgnoresStrength, + /// Completeness trusts the extractor's `strong` flag and ignores + /// `failed_count == identities` (the pre-failed_count rule). + InheritIgnoresCount, /// Inheritance without the head-identities-subset-of-base check. InheritIgnoresSubset, /// `CuredOnBase` never detected. @@ -492,12 +500,19 @@ pub fn derive_with(ev: &Evidence, m: Option) -> Derived { /// `s ~ s'`: every failure on `head` is also on `base` and both name all of /// their failures (design 3.2). fn inherits(m: Option, head: &Signature, base: &Signature) -> bool { - let strong = |s: &Signature| s.strength == Strength::Strong && !s.tests.is_empty(); - if m != Some(Mutant::InheritIgnoresStrength) && !(strong(head) && strong(base)) { - return false; - } - if m == Some(Mutant::InheritIgnoresStrength) && (head.tests.is_empty() || base.tests.is_empty()) - { + // Complete = every failure is named: the run reports a count n > 0 and + // exactly n distinct failing-test identities (design 3.2, 7208a2e). + let counted = |s: &Signature| { + let ids: BTreeSet<&String> = s.tests.iter().collect(); + s.failed_count + .is_some_and(|n| n > 0 && n == ids.len() as u64) + }; + let complete = |s: &Signature| match m { + Some(Mutant::InheritIgnoresStrength) => !s.tests.is_empty() && counted(s), + Some(Mutant::InheritIgnoresCount) => s.strength == Strength::Strong && !s.tests.is_empty(), + _ => s.strength == Strength::Strong && counted(s), + }; + if !(complete(head) && complete(base)) { return false; } if m == Some(Mutant::InheritIgnoresSubset) { diff --git a/crates/squabble-core/tests/verdict_conformance.rs b/crates/squabble-core/tests/verdict_conformance.rs index 21fcd4c..e3b3c94 100644 --- a/crates/squabble-core/tests/verdict_conformance.rs +++ b/crates/squabble-core/tests/verdict_conformance.rs @@ -15,8 +15,8 @@ use squabble_core::verdict::{ use std::path::PathBuf; /// `pr-verdict/` as vendored from proven-cicd-and-workflows `refs/pull/193/head`. -const PINNED_CORPUS_SHA: &str = "c66eb82c1341e239c4323fc88bfef770a8584e3c"; -const EXPECTED_FIXTURES: usize = 48; +const PINNED_CORPUS_SHA: &str = "fb7ae871525d3339fd2e56112a182ea39db1e0e4"; +const EXPECTED_FIXTURES: usize = 55; fn upstream() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/upstream/proven-cicd-w49") @@ -86,6 +86,12 @@ fn local_cases(fx: &[Fixture]) -> Vec { h["strength"] = "weak".into(); let t = &mut weak_partial["evidence"]["obs"]["base_tip"]["test"]["signature"]; t["tests"] = serde_json::json!(["t1", "t2"]); + t["failed_count"] = 2.into(); + // A signature the extractor calls STRONG whose count disagrees with its + // identities (head says 2 failures but names 1) is incomplete: the verdict + // function re-checks the count itself, so this must stay PR-BROKEN. + let mut miscounted = base("ci-broken-inherited-complete-subset"); + miscounted["evidence"]["obs"]["head"]["test"]["signature"]["failed_count"] = 2.into(); // A Pending check already past its timeout at evidence_at is Infra Timeout // (CI-BROKEN), whatever the extractor recorded. let mut expired = base("unsettled-pending-within-deadline"); @@ -97,7 +103,7 @@ fn local_cases(fx: &[Fixture]) -> Vec { // signature (inherited), and the verdict is still PR-BROKEN, through `test`. let mut hole = base("pr-broken-workflow-cannot-start"); let fail = serde_json::json!({"state":"Fail","source":"check_run","check_run_id":1, - "signature":{"strength":"strong","steps":["lint"],"messages":[],"tests":["l1"]}}); + "signature":{"failed_count":1,"strength":"strong","steps":["lint"],"messages":[],"tests":["l1"]}}); let ev = &mut hole["evidence"]; ev["required"] .as_array_mut() @@ -120,6 +126,11 @@ fn local_cases(fx: &[Fixture]) -> Vec { weak_partial, serde_json::json!({"verdict":"PR-BROKEN","introduced":["test"]}), ), + mk( + "strong-flag-but-count-not-identities", + miscounted, + serde_json::json!({"verdict":"PR-BROKEN","introduced":["test"]}), + ), mk( "pending-past-timeout-is-infra-timeout", expired, @@ -233,6 +244,7 @@ fn derivation_steps_are_each_pinned_by_the_corpus() { Mutant::SkipStep(7), Mutant::SkipStep(8), Mutant::InheritIgnoresStrength, + Mutant::InheritIgnoresCount, Mutant::InheritIgnoresSubset, Mutant::CuredDisabled, Mutant::AbsentIsPass, From 9b8ee6ca2dff3ae903bf18178ade5a5b1210ef76 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 17:17:56 +0000 Subject: [PATCH 4/4] test(verdict): pin corpus 41dfc65 and drop local cases it now covers The hub re-vendored the PR-verdict corpus at proven-cicd 41dfc6554400d5ab46981883dc586302c184eeff (58 fixtures), which adds the three gap-filling fixtures found by mutation testing here. The three local copies are removed; the pin and count move to the new corpus. With failed_count in the schema, strength is redundant on consistent records, so the InheritIgnoresStrength mutant is no longer killed by the vendored corpus. One local case pins the fail-closed reading of a contradictory record (flagged weak, count equals identities): weak never inherits. The property-3 carve-out case stays local; upstream does not have it. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgb6vQnxAZ8czX8SLb --- .../tests/verdict_conformance.rs | 47 +++++-------------- 1 file changed, 13 insertions(+), 34 deletions(-) diff --git a/crates/squabble-core/tests/verdict_conformance.rs b/crates/squabble-core/tests/verdict_conformance.rs index e3b3c94..405d675 100644 --- a/crates/squabble-core/tests/verdict_conformance.rs +++ b/crates/squabble-core/tests/verdict_conformance.rs @@ -15,8 +15,8 @@ use squabble_core::verdict::{ use std::path::PathBuf; /// `pr-verdict/` as vendored from proven-cicd-and-workflows `refs/pull/193/head`. -const PINNED_CORPUS_SHA: &str = "fb7ae871525d3339fd2e56112a182ea39db1e0e4"; -const EXPECTED_FIXTURES: usize = 55; +const PINNED_CORPUS_SHA: &str = "41dfc6554400d5ab46981883dc586302c184eeff"; +const EXPECTED_FIXTURES: usize = 58; fn upstream() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/upstream/proven-cicd-w49") @@ -63,8 +63,10 @@ fn load() -> Vec { } /// Cases the vendored corpus does not contain, built by editing vendored -/// fixtures. They are LOCAL: they exist because a mutant survived the upstream -/// corpus (reported to the hub as corpus gaps), and are not part of the pin. +/// fixtures. They are LOCAL and not part of the pin. The three gap-filling cases +/// (weak-partial identities, strong flag with a wrong count, a Pending past its +/// timeout) were promoted upstream at 41dfc65 and removed here; what remains is +/// the property-3 carve-out, which the corpus does not have. fn local_cases(fx: &[Fixture]) -> Vec { let base = |n: &str| -> Value { let p = upstream() @@ -78,24 +80,6 @@ fn local_cases(fx: &[Fixture]) -> Vec { evidence: serde_json::from_value(raw["evidence"].clone()).unwrap(), expected, }; - // A WEAK head signature naming only part of its failures (tests=[t1]) is a - // subset of the strong base set {t1,t2}; completeness is what stops it - // establishing inheritance, so this must stay PR-BROKEN. - let mut weak_partial = base("ci-broken-inherited"); - let h = &mut weak_partial["evidence"]["obs"]["head"]["test"]["signature"]; - h["strength"] = "weak".into(); - let t = &mut weak_partial["evidence"]["obs"]["base_tip"]["test"]["signature"]; - t["tests"] = serde_json::json!(["t1", "t2"]); - t["failed_count"] = 2.into(); - // A signature the extractor calls STRONG whose count disagrees with its - // identities (head says 2 failures but names 1) is incomplete: the verdict - // function re-checks the count itself, so this must stay PR-BROKEN. - let mut miscounted = base("ci-broken-inherited-complete-subset"); - miscounted["evidence"]["obs"]["head"]["test"]["signature"]["failed_count"] = 2.into(); - // A Pending check already past its timeout at evidence_at is Infra Timeout - // (CI-BROKEN), whatever the extractor recorded. - let mut expired = base("unsettled-pending-within-deadline"); - expired["evidence"]["evidence_at"] = "2026-11-30T16:00:00Z".into(); // Property 3 as written ("every failing check inherited or cured => not // PR-BROKEN") has a hole the ruling on 3.5 opens: a start failure caused by // the PR's own workflow edit is PR-BROKEN with no `Fail` observation. Here @@ -115,6 +99,11 @@ fn local_cases(fx: &[Fixture]) -> Vec { ev["obs"][k]["lint"] = fail.clone(); } ev["obs"]["base_nearest"]["lint"] = serde_json::json!({"sha":"b".repeat(40),"obs":fail}); + // With failed_count present, `strength` is redundant on consistent records. + // On a contradictory one (head flagged weak but its count equals its + // identities) the verdict function fails closed: weak never inherits. + let mut weak_but_counted = base("ci-broken-inherited"); + weak_but_counted["evidence"]["obs"]["head"]["test"]["signature"]["strength"] = "weak".into(); vec![ mk( "property-3-hole-inherited-red-plus-own-start-failure", @@ -122,20 +111,10 @@ fn local_cases(fx: &[Fixture]) -> Vec { serde_json::json!({"verdict":"PR-BROKEN","introduced":["test"],"reason":"workflow-cannot-start"}), ), mk( - "weak-partial-identities-never-inherit", - weak_partial, + "weak-flag-with-consistent-count-fails-closed", + weak_but_counted, serde_json::json!({"verdict":"PR-BROKEN","introduced":["test"]}), ), - mk( - "strong-flag-but-count-not-identities", - miscounted, - serde_json::json!({"verdict":"PR-BROKEN","introduced":["test"]}), - ), - mk( - "pending-past-timeout-is-infra-timeout", - expired, - serde_json::json!({"verdict":"CI-BROKEN","cause":"Infra","infra":"Timeout","checks":["build"]}), - ), ] }