Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/squabble-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ mod phase;
mod relock;
mod relock_gather;
mod triage;
mod verdict;
mod verify;
mod zero_job;

Expand Down Expand Up @@ -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") => {
Expand All @@ -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",
Expand All @@ -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)
Expand Down
187 changes: 187 additions & 0 deletions crates/squabble-cli/src/verdict.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) <j.d.a.jewell@open.ac.uk>
//! `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] <evidence.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<Evidence> = 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<Value> = 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<Evidence>, 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::<Evidence>(item)
.map_err(|e| format!("record {i}: not a pr-evidence/v1 record: {e}"))
})
.collect::<Result<Vec<_>, _>>()?;
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:?}"),
},
}
}
104 changes: 104 additions & 0 deletions crates/squabble-cli/tests/verdict_cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) <j.d.a.jewell@open.ac.uk>
//! `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)
);
}
1 change: 1 addition & 0 deletions crates/squabble-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
Loading
Loading