From 8f30563ddaa72b544cc7cbc52dce0b5291f4c52e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 17:36:38 +0000 Subject: [PATCH 1/4] feat(drift): squabble drift, a read-only caller drift comparator (S9) squabble-core::drift compares a repository's workflow callers with the layer-3 templates: a caller is matched by the reusable workflow in its uses: line, the template is rendered with the caller's own pin, and the bytes are compared. Findings: EditedCaller (certain at the latest pin, unknown-cause at an older one, since the template at the old pin is not available), StalePin, NotFullShaPin, LeftoverGuardCaller and MissingLockEntry. Checks that could not run are listed in not_checked and never read as passed. `squabble drift [--json] [--repo DIR] [--templates DIR] [--latest-suite-sha SHA] [--latest-proven-sha SHA]` exits 0 clean, 4 drift found, 2 bad usage or unreadable input. It reads files and writes nothing (tested by snapshotting the repository and the templates before and after). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgb6vQnxAZ8czX8SLb --- crates/squabble-cli/src/drift.rs | 238 +++++++++++ crates/squabble-cli/src/main.rs | 4 + crates/squabble-cli/tests/drift_cli.rs | 298 +++++++++++++ crates/squabble-core/src/drift.rs | 555 +++++++++++++++++++++++++ crates/squabble-core/src/lib.rs | 1 + 5 files changed, 1096 insertions(+) create mode 100644 crates/squabble-cli/src/drift.rs create mode 100644 crates/squabble-cli/tests/drift_cli.rs create mode 100644 crates/squabble-core/src/drift.rs diff --git a/crates/squabble-cli/src/drift.rs b/crates/squabble-cli/src/drift.rs new file mode 100644 index 0000000..7b4186b --- /dev/null +++ b/crates/squabble-cli/src/drift.rs @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +//! `squabble drift` — compare a repository's workflow callers with the layer-3 +//! templates (CI programme W49, S9). +//! +//! Read-only by construction: it lists and reads files under `--repo` and +//! `--templates` and writes nothing, anywhere. The comparison itself is +//! [`squabble_core::drift`]; this module only gathers the inputs. +//! +//! Exit codes: `0` no drift found; `4` drift found (a reportable finding, like +//! `squabble chains`); `2` bad usage or an unreadable input. A clean `0` still +//! carries `not_checked`: read it before treating `0` as "all good". + +use serde::Serialize; +use squabble_core::drift::{analyse, File, Inputs, Report}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +pub const USAGE: &str = "usage: squabble drift [--json] [--repo DIR] [--templates DIR] [--latest-suite-sha SHA] [--latest-proven-sha SHA]"; + +/// Where the vendored templates live, relative to a repository root. +const DEFAULT_TEMPLATES: &str = "docs/upstream/proven-cicd-w49/templates"; +const LOCK: &str = ".github/workflows/actions.lock"; + +#[derive(Serialize)] +struct Out<'a> { + schema: &'static str, + repo: String, + templates: TemplatesInfo, + latest: Latest<'a>, + drift: bool, + #[serde(flatten)] + report: &'a Report, +} + +#[derive(Serialize)] +struct TemplatesInfo { + dir: String, + /// The SHA the templates were taken at, when the vendor README says. + source_sha: Option, +} + +#[derive(Serialize)] +struct Latest<'a> { + suite_sha: Option<&'a str>, + /// Where `suite_sha` came from: `flag`, `templates-readme` (the SHA the vendored + /// templates were taken at, i.e. a branch tip, not a release) or `none`. + suite_sha_source: &'static str, + proven_sha: Option<&'a str>, +} + +struct Args { + json: bool, + repo: PathBuf, + templates: Option, + suite_sha: Option, + proven_sha: Option, +} + +fn parse(args: &[String]) -> Result { + let mut a = Args { + json: false, + repo: PathBuf::from("."), + templates: None, + suite_sha: None, + proven_sha: None, + }; + let mut it = args.iter(); + while let Some(flag) = it.next() { + let mut val = |name: &str| { + it.next() + .cloned() + .ok_or_else(|| format!("{name} needs a value")) + }; + match flag.as_str() { + "--json" => a.json = true, + "--repo" => a.repo = PathBuf::from(val("--repo")?), + "--templates" => a.templates = Some(PathBuf::from(val("--templates")?)), + "--latest-suite-sha" => a.suite_sha = Some(val("--latest-suite-sha")?), + "--latest-proven-sha" => a.proven_sha = Some(val("--latest-proven-sha")?), + other => return Err(format!("unknown argument {other}")), + } + } + Ok(a) +} + +fn read(p: &Path) -> Result { + std::fs::read_to_string(p).map_err(|e| format!("cannot read {}: {e}", p.display())) +} + +/// Files directly in `dir` with a `.yml`/`.yaml` extension, sorted by name. +fn yaml_files(dir: &Path) -> Result, String> { + let mut v: Vec = std::fs::read_dir(dir) + .map_err(|e| format!("cannot list {}: {e}", dir.display()))? + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| { + p.is_file() && matches!(p.extension().and_then(|x| x.to_str()), Some("yml" | "yaml")) + }) + .collect(); + v.sort(); + Ok(v) +} + +/// The SHA after `templates/ and profiles/ from main = ` in the vendor README. +fn vendor_source_sha(templates: &Path) -> Option { + let readme = std::fs::read_to_string(templates.parent()?.join("README.adoc")).ok()?; + let line = readme + .lines() + .find(|l| l.contains("templates/ and profiles/ from main"))?; + let (_, rest) = line.split_once('=')?; + let sha: String = rest + .trim() + .chars() + .take_while(|c| c.is_ascii_hexdigit()) + .collect(); + (sha.len() == 40).then_some(sha) +} + +pub fn run(args: &[String]) -> ExitCode { + let a = match parse(args) { + Ok(a) => a, + Err(e) => { + eprintln!("squabble drift: {e}\n{USAGE}"); + return ExitCode::from(2); + } + }; + match gather_and_report(&a) { + Ok(code) => code, + Err(e) => { + eprintln!("squabble drift: {e}"); + ExitCode::from(2) + } + } +} + +fn gather_and_report(a: &Args) -> Result { + let tdir = a + .templates + .clone() + .unwrap_or_else(|| a.repo.join(DEFAULT_TEMPLATES)); + if !tdir.is_dir() { + return Err(format!( + "templates directory {} does not exist (pass --templates DIR)", + tdir.display() + )); + } + + // Workflow templates only: a template with no top-level `on:` (dependabot.yml) is config, not a workflow. + let mut templates = Vec::new(); + for p in yaml_files(&tdir)? { + let text = read(&p)?; + if text.lines().any(|l| l.starts_with("on:")) { + let name = p + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default() + .to_string(); + templates.push(File { path: name, text }); + } + } + if templates.is_empty() { + return Err(format!("no workflow templates found in {}", tdir.display())); + } + + let wf_dir = a.repo.join(".github/workflows"); + let mut workflows = Vec::new(); + if wf_dir.is_dir() { + for p in yaml_files(&wf_dir)? { + let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + workflows.push(File { + path: format!(".github/workflows/{name}"), + text: read(&p)?, + }); + } + } + let lock = std::fs::read_to_string(a.repo.join(LOCK)).ok(); + + let source_sha = vendor_source_sha(&tdir); + let suite = a.suite_sha.clone().or_else(|| source_sha.clone()); + let suite_source = match (&a.suite_sha, &source_sha) { + (Some(_), _) => "flag", + (None, Some(_)) => "templates-readme", + _ => "none", + }; + let report = analyse(&Inputs { + workflows: &workflows, + templates: &templates, + lock: lock.as_deref(), + latest_suite_sha: suite.as_deref(), + latest_proven_sha: a.proven_sha.as_deref(), + }); + + let drift = report.drifted(); + if a.json { + let out = Out { + schema: "squabble/drift/v1", + repo: a.repo.display().to_string(), + templates: TemplatesInfo { + dir: tdir.display().to_string(), + source_sha, + }, + latest: Latest { + suite_sha: suite.as_deref(), + suite_sha_source: suite_source, + proven_sha: a.proven_sha.as_deref(), + }, + drift, + report: &report, + }; + println!( + "{}", + serde_json::to_string_pretty(&out).map_err(|e| format!("serialise: {e}"))? + ); + } else { + for c in &report.callers { + println!( + "{}\t{}\t{}", + c.file, + c.template, + if c.clean { "clean" } else { "DRIFT" } + ); + } + for f in &report.findings { + println!( + "finding\t{}", + serde_json::to_string(f).map_err(|e| format!("serialise: {e}"))? + ); + } + for n in &report.not_checked { + println!("not-checked\t{n}"); + } + } + Ok(if drift { + ExitCode::from(4) + } else { + ExitCode::SUCCESS + }) +} diff --git a/crates/squabble-cli/src/main.rs b/crates/squabble-cli/src/main.rs index da33027..fe2abe3 100644 --- a/crates/squabble-cli/src/main.rs +++ b/crates/squabble-cli/src/main.rs @@ -45,6 +45,7 @@ mod board; #[cfg(feature = "boj")] mod boj; mod chains; +mod drift; mod fetch; mod fight; mod inbox; @@ -80,6 +81,7 @@ fn main() -> ExitCode { }, Some("fight") => fight::run(&args[2..]), Some("chains") => chains::run(&args[2..]), + Some("drift") => drift::run(&args[2..]), Some("zero-job") => zero_job::run(&args[2..]), Some("phase") => phase::run(&args[2..]), Some("verify-satisfied") => verify::run(&args[2..]), @@ -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 "), + drift::USAGE.trim_start_matches("usage: squabble "), relock::USAGE.trim_start_matches("usage: squabble ") ); ExitCode::from(2) diff --git a/crates/squabble-cli/tests/drift_cli.rs b/crates/squabble-cli/tests/drift_cli.rs new file mode 100644 index 0000000..d4c1bce --- /dev/null +++ b/crates/squabble-cli/tests/drift_cli.rs @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +//! `squabble drift` as a binary, against fixture repositories built at test time +//! from the vendored layer-3 templates (so the fixtures cannot drift from them). + +use serde_json::Value; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const LATEST: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const OLD: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + +fn templates() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/upstream/proven-cicd-w49/templates") +} + +fn template(name: &str) -> String { + std::fs::read_to_string(templates().join(name)).unwrap() +} + +/// A fresh fixture repository holding exactly `files` (path relative to the repo root). +fn repo(case: &str, files: &[(&str, String)]) -> PathBuf { + let root = PathBuf::from(env!("CARGO_TARGET_TMPDIR")) + .join("drift") + .join(case); + let _ = std::fs::remove_dir_all(&root); + for (path, text) in files { + let p = root.join(path); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, text).unwrap(); + } + root +} + +fn drift(repo: &Path, extra: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_squabble")) + .arg("drift") + .arg("--json") + .args(["--repo", repo.to_str().unwrap()]) + .args(["--templates", templates().to_str().unwrap()]) + .args(["--latest-suite-sha", LATEST]) + .args(extra) + .output() + .unwrap() +} + +fn json(o: &Output) -> Value { + serde_json::from_slice(&o.stdout).unwrap_or_else(|e| { + panic!( + "stdout is not JSON ({e}): {}", + String::from_utf8_lossy(&o.stdout) + ) + }) +} + +fn kinds(v: &Value) -> Vec { + v["findings"] + .as_array() + .unwrap() + .iter() + .map(|f| f["kind"].as_str().unwrap().to_string()) + .collect() +} + +fn gate(pin: &str) -> String { + template("ci-gate-caller.yml").replace("__CICD_SUITE_SHA__", pin) +} + +const GATE: &str = ".github/workflows/ci-gate.yml"; + +#[test] +fn a_caller_that_equals_its_rendered_template_at_the_latest_pin_is_clean() { + let r = repo("clean", &[(GATE, gate(LATEST))]); + let o = drift(&r, &[]); + assert_eq!( + o.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&o.stdout) + ); + let v = json(&o); + assert_eq!(v["drift"], false); + assert_eq!(v["callers"][0]["clean"], true); + assert_eq!(v["latest"]["suite_sha_source"], "flag"); +} + +#[test] +fn an_edited_caller_at_the_latest_pin_is_a_certain_edit() { + let r = repo( + "edited", + &[( + GATE, + gate(LATEST).replace("name: CI gate", "name: CI gate (mine)"), + )], + ); + let o = drift(&r, &[]); + assert_eq!(o.status.code(), Some(4)); + let f = &json(&o)["findings"][0]; + assert_eq!(f["kind"], "EditedCaller"); + assert_eq!(f["certainty"], "certain"); + let line = f["first_diff_line"].as_u64().unwrap() as usize; + assert!( + gate(LATEST) + .lines() + .nth(line - 1) + .unwrap() + .starts_with("name: CI gate"), + "line {line}" + ); +} + +#[test] +fn a_stale_pin_with_unedited_bytes_is_only_stale() { + let r = repo("stale", &[(GATE, gate(OLD))]); + let o = drift(&r, &[]); + assert_eq!(o.status.code(), Some(4)); + let v = json(&o); + assert_eq!(kinds(&v), ["StalePin"]); + assert_eq!(v["findings"][0]["pinned"], OLD); + assert_eq!(v["findings"][0]["latest"], LATEST); +} + +#[test] +fn a_stale_and_different_caller_is_not_called_edited_for_certain() { + let r = repo( + "stale-edited", + &[(GATE, gate(OLD).replace("name: CI gate", "name: Other"))], + ); + let v = json(&drift(&r, &[])); + assert!(kinds(&v).contains(&"StalePin".to_string())); + let e = v["findings"] + .as_array() + .unwrap() + .iter() + .find(|f| f["kind"] == "EditedCaller") + .unwrap(); + assert_eq!( + e["certainty"], "unknown-cause", + "an old pin cannot tell an edit from a template change" + ); +} + +#[test] +fn a_retired_guard_caller_is_reported() { + let guard = + "on:\n pull_request_target:\njobs:\n g:\n runs-on: ubuntu-latest\n".to_string(); + let r = repo( + "guard", + &[ + (GATE, gate(LATEST)), + (".github/workflows/ci-gate-tamper-guard-caller.yml", guard), + ], + ); + let o = drift(&r, &[]); + assert_eq!(o.status.code(), Some(4)); + let v = json(&o); + assert_eq!(kinds(&v), ["LeftoverGuardCaller"]); + assert!(v["findings"][0]["reason"] + .as_str() + .unwrap() + .contains("pull_request_target")); +} + +#[test] +fn a_lock_with_no_record_for_a_workflow_is_a_finding_and_a_record_clears_it() { + let lock_without = + "version: 'v0.0.3'\nworkflows:\n '.github/workflows/other.yml': []\n".to_string(); + let lock_with = + "version: 'v0.0.3'\nworkflows:\n '.github/workflows/ci-gate.yml': []\n".to_string(); + let lock = ".github/workflows/actions.lock"; + let v = json(&drift( + &repo( + "lock-missing", + &[(GATE, gate(LATEST)), (lock, lock_without)], + ), + &[], + )); + assert_eq!(kinds(&v), ["MissingLockEntry"]); + assert_eq!(v["findings"][0]["file"], GATE); + let o = drift( + &repo("lock-present", &[(GATE, gate(LATEST)), (lock, lock_with)]), + &[], + ); + assert_eq!(o.status.code(), Some(0)); +} + +#[test] +fn without_a_lock_the_lock_check_is_listed_as_not_run_not_passed() { + let v = json(&drift(&repo("no-lock", &[(GATE, gate(LATEST))]), &[])); + assert_eq!(v["drift"], false); + let nc: Vec<&str> = v["not_checked"] + .as_array() + .unwrap() + .iter() + .map(|s| s.as_str().unwrap()) + .collect(); + assert!( + nc.iter() + .any(|m| m.contains("no .github/workflows/actions.lock")), + "{nc:?}" + ); +} + +#[test] +fn a_branch_pin_is_flagged_and_unedited_bytes_are_not_called_edited() { + let v = json(&drift(&repo("branch", &[(GATE, gate("main"))]), &[])); + assert!(kinds(&v).contains(&"NotFullShaPin".to_string())); + assert!(!kinds(&v).contains(&"EditedCaller".to_string())); +} + +#[test] +fn the_umbrella_caller_is_compared_with_its_own_pin_and_tag() { + let proven = template("proven-caller.yml") + .replace("__PROVEN_SHA__", LATEST) + .replace("__PROVEN_TAG__", "v0.1.2"); + let r = repo("proven", &[(".github/workflows/proven.yml", proven)]); + // Given the latest umbrella pin: clean. Without it: not checked, and said so. + assert_eq!( + drift(&r, &["--latest-proven-sha", LATEST]).status.code(), + Some(0) + ); + let v = json(&drift(&r, &[])); + assert!(v["not_checked"] + .as_array() + .unwrap() + .iter() + .any(|m| m.as_str().unwrap().contains("umbrella"))); + assert!(v["not_checked"] + .as_array() + .unwrap() + .iter() + .any(|m| m.as_str().unwrap().contains("not checked against its SHA"))); +} + +fn snapshot(root: &Path) -> BTreeMap> { + fn walk(dir: &Path, out: &mut BTreeMap>) { + for e in std::fs::read_dir(dir).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + walk(&p, out); + } else { + out.insert(p.clone(), std::fs::read(&p).unwrap()); + } + } + } + let mut m = BTreeMap::new(); + walk(root, &mut m); + m +} + +#[test] +fn it_writes_nothing_to_the_repository_or_the_templates() { + let lock = ".github/workflows/actions.lock"; + let r = repo( + "readonly", + &[ + (GATE, gate(OLD).replace("name: CI gate", "name: X")), + ( + ".github/workflows/ci-gate-tamper-guard-caller.yml", + "on:\n push:\n".into(), + ), + (lock, "workflows:\n".into()), + ], + ); + let (before_repo, before_tpl) = (snapshot(&r), snapshot(&templates())); + let o = drift(&r, &[]); + assert_eq!(o.status.code(), Some(4)); + assert_eq!(snapshot(&r), before_repo, "the repository was modified"); + assert_eq!( + snapshot(&templates()), + before_tpl, + "the templates were modified" + ); +} + +#[test] +fn bad_input_exits_2_with_nothing_on_stdout() { + let r = repo("bad", &[(GATE, gate(LATEST))]); + let o = Command::new(env!("CARGO_BIN_EXE_squabble")) + .args([ + "drift", + "--json", + "--repo", + r.to_str().unwrap(), + "--templates", + "/nonexistent/templates", + ]) + .output() + .unwrap(); + assert_eq!(o.status.code(), Some(2)); + assert!(o.stdout.is_empty()); + let o = Command::new(env!("CARGO_BIN_EXE_squabble")) + .args(["drift", "--nope"]) + .output() + .unwrap(); + assert_eq!(o.status.code(), Some(2)); +} diff --git a/crates/squabble-core/src/drift.rs b/crates/squabble-core/src/drift.rs new file mode 100644 index 0000000..a82be97 --- /dev/null +++ b/crates/squabble-core/src/drift.rs @@ -0,0 +1,555 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) +//! Caller drift: compare a repository's workflow callers with the layer-3 +//! templates (CI programme W49, work package S9, design section 2, layer 5). +//! +//! Pure: it takes file contents and returns findings. It reads no file, makes +//! no call and writes nothing; the CLI gathers the inputs and the caller of this +//! module decides what to do with a finding. It never proposes or applies a fix. +//! +//! # How a caller is compared +//! +//! A template names its reusable workflow in a `uses: /@__PLACEHOLDER__` +//! line. A repository workflow *is that caller* when it has a `uses:` line for +//! the same `/`. The template is rendered by putting the +//! caller's own pin (and, for the umbrella caller, the tag in its trailing +//! comment) where the placeholders are, and the bytes are compared: +//! +//! * equal: clean; +//! * different, and the pin is the latest known pin: the caller was **edited** +//! (the template at that pin *is* the latest template); +//! * different, and the pin is older: the bytes differ from the *latest* +//! template, but whether the caller was edited or the template changed since +//! its pin cannot be told here (the template at the old pin is not +//! available), so the finding says [`Certainty::UnknownCause`] and does not guess. +//! +//! # What is and is not checked +//! +//! Four drift kinds (S9 done-criteria): edited caller, stale pin, leftover +//! guard caller, missing lock entry; plus a pin that is not a full SHA, since +//! it cannot be rendered or compared to a release. What a lock record *contains* +//! is not judged (that is the lock gate's job); only whether a record exists. +//! Anything it could not check is listed in [`Report::not_checked`], never +//! silently passed. + +use serde::Serialize; +use std::collections::BTreeSet; + +/// Placeholder for the suite pin in every gate caller template. +pub const SUITE_SHA: &str = "__CICD_SUITE_SHA__"; +/// Placeholders in the umbrella (`proven.yml`) caller template. +pub const PROVEN_SHA: &str = "__PROVEN_SHA__"; +pub const PROVEN_TAG: &str = "__PROVEN_TAG__"; + +/// A file with its repository-relative path. +#[derive(Debug, Clone)] +pub struct File { + pub path: String, + pub text: String, +} + +/// Everything the comparison needs, already read. +#[derive(Debug, Clone)] +pub struct Inputs<'a> { + /// The repository's `.github/workflows/*.yml|yaml` files. + pub workflows: &'a [File], + /// Templates, by file name (`ci-gate-caller.yml`). + pub templates: &'a [File], + /// `.github/workflows/actions.lock`, if the repository carries one. + pub lock: Option<&'a str>, + /// Newest known suite pin (the SHA the templates were taken at). + pub latest_suite_sha: Option<&'a str>, + /// Newest known umbrella (`proven.yml`) release pin. + pub latest_proven_sha: Option<&'a str>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum Certainty { + /// The pin is the latest, so the template compared against is the right one. + Certain, + /// The pin is older; an edit and a template change since the pin look the same. + UnknownCause, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "kind")] +pub enum Finding { + /// The caller's bytes differ from its template rendered with its own pin. + EditedCaller { + file: String, + template: String, + certainty: Certainty, + /// 1-based first differing line, so a reviewer can start there. + first_diff_line: usize, + }, + /// Rendering is impossible and drift cannot be judged: the pin is a branch, + /// a tag or a short SHA, not a full 40-hex SHA. + NotFullShaPin { + file: String, + template: String, + pin: String, + }, + /// The caller's pin is behind the latest known pin. + StalePin { + file: String, + template: String, + pinned: String, + latest: String, + }, + /// A retired tamper-guard caller is still present. + LeftoverGuardCaller { file: String, reason: String }, + /// The repository carries an `actions.lock` but it has no record for this workflow. + MissingLockEntry { file: String }, +} + +/// What was found for one caller, whether or not it drifted. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct CallerStatus { + pub file: String, + pub template: String, + pub pin: Option, + pub clean: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Report { + pub callers: Vec, + pub findings: Vec, + /// Checks that could not run, with the reason. Never read this as "passed". + pub not_checked: Vec, +} + +impl Report { + pub fn drifted(&self) -> bool { + !self.findings.is_empty() + } +} + +/// One `uses: owner/repo/path@ref # comment` line. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Use { + target: String, + reference: String, + comment: Option, +} + +fn parse_use(line: &str) -> Option { + let rest = line + .trim_start() + .trim_start_matches("- ") + .trim_start() + .strip_prefix("uses:")?; + let rest = rest.trim(); + let (spec, comment) = match rest.split_once(" #") { + Some((s, c)) => (s.trim(), Some(c.trim().to_string())), + None => (rest, None), + }; + let (target, reference) = spec.split_once('@')?; + Some(Use { + target: target.trim().trim_matches(['"', '\'']).to_string(), + reference: reference.trim().trim_matches(['"', '\'']).to_string(), + comment, + }) +} + +fn uses_of(text: &str) -> Vec { + text.lines().filter_map(parse_use).collect() +} + +fn is_full_sha(s: &str) -> bool { + s.len() == 40 + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +/// A template that is a caller: its `uses:` lines carry a placeholder pin. +fn caller_target(template: &str) -> Option { + uses_of(template) + .into_iter() + .find(|u| u.reference.starts_with("__")) + .map(|u| u.target) +} + +fn first_diff_line(a: &str, b: &str) -> usize { + let (mut la, mut lb) = (a.lines(), b.lines()); + let mut n: usize = 0; + loop { + n += 1; + match (la.next(), lb.next()) { + (Some(x), Some(y)) if x == y => continue, + // Same lines throughout but different bytes (e.g. a trailing newline): + // point at the last line. + (None, None) => return n - 1, + _ => return n, + } + } +} + +/// Render `template` with the caller's own pin and tag. +fn render(template: &str, pin: &str, tag: &str) -> String { + template + .replace(SUITE_SHA, pin) + .replace(PROVEN_SHA, pin) + .replace(PROVEN_TAG, tag) +} + +/// The workflow file name of a repository path (`.github/workflows/x.yml` -> `x.yml`). +fn file_name(path: &str) -> &str { + path.rsplit('/').next().unwrap_or(path) +} + +/// Does `.github/workflows/actions.lock` hold a record for `path`? +/// +/// The lock maps each workflow path (quoted, under `workflows:`) to its pins. +/// Only the key's presence is read here, not what it lists. +pub fn lock_has_record(lock: &str, path: &str) -> bool { + lock.lines().any(|l| { + let t = l.trim(); + // A record key is a quoted (or bare) path followed by `:`. + let key = match t.chars().next() { + Some(q @ ('\'' | '"')) => t[1..] + .split_once(q) + .and_then(|(k, rest)| rest.starts_with(':').then_some(k)), + _ => t.split_once(':').map(|(k, _)| k), + }; + key == Some(path) + }) +} + +/// Compare a repository's workflows with the templates. +pub fn analyse(inp: &Inputs) -> Report { + let mut callers = Vec::new(); + let mut findings = Vec::new(); + let mut not_checked = Vec::new(); + + let caller_templates: Vec<(&File, String)> = inp + .templates + .iter() + .filter_map(|t| caller_target(&t.text).map(|target| (t, target))) + .collect(); + + for wf in inp.workflows { + let uses = uses_of(&wf.text); + + // Retired guard caller: by file name, or by calling a tamper-guard reusable. + let guard_by_name = file_name(&wf.path).contains("tamper-guard"); + let guard_by_use = uses.iter().any(|u| u.target.contains("tamper-guard")); + if guard_by_name || guard_by_use { + let trigger = if wf.text.contains("pull_request_target") { + "; it triggers on pull_request_target" + } else { + "" + }; + findings.push(Finding::LeftoverGuardCaller { + file: wf.path.clone(), + reason: format!("retired tamper-guard caller still present{trigger}"), + }); + } + + // Which template, if any, is this workflow a caller of? + for (tpl, target) in &caller_templates { + let mine: Vec<&Use> = uses.iter().filter(|u| &u.target == target).collect(); + let Some(first) = mine.first() else { continue }; + let pin = first.reference.clone(); + let tag = first.comment.clone().unwrap_or_default(); + let mixed = mine.iter().any(|u| u.reference != pin); + + if tpl.text.contains(PROVEN_TAG) { + let msg = format!( + "tag comment of {}: taken from the caller itself, not checked against its SHA", + wf.path + ); + if !not_checked.contains(&msg) { + not_checked.push(msg); + } + } + + let latest = if tpl.text.contains(PROVEN_SHA) { + inp.latest_proven_sha + } else { + inp.latest_suite_sha + }; + let at_latest = latest.is_some_and(|l| l == pin); + let mut clean = true; + + if !is_full_sha(&pin) { + clean = false; + findings.push(Finding::NotFullShaPin { + file: wf.path.clone(), + template: tpl.path.clone(), + pin: pin.clone(), + }); + } + + // The comment tag is only a placeholder for the umbrella template. + let rendered = render(&tpl.text, &pin, &tag); + if rendered != wf.text || mixed { + clean = false; + findings.push(Finding::EditedCaller { + file: wf.path.clone(), + template: tpl.path.clone(), + certainty: if at_latest && !mixed { + Certainty::Certain + } else { + Certainty::UnknownCause + }, + first_diff_line: first_diff_line(&rendered, &wf.text), + }); + } + + match latest { + Some(l) if is_full_sha(&pin) && l != pin => { + clean = false; + findings.push(Finding::StalePin { + file: wf.path.clone(), + template: tpl.path.clone(), + pinned: pin.clone(), + latest: l.to_string(), + }); + } + None => { + let which = if tpl.text.contains(PROVEN_SHA) { + "latest umbrella (proven.yml) pin" + } else { + "latest suite pin" + }; + let msg = format!("stale-pin check for {}: no {which} given", wf.path); + if !not_checked.contains(&msg) { + not_checked.push(msg); + } + } + _ => {} + } + + callers.push(CallerStatus { + file: wf.path.clone(), + template: tpl.path.clone(), + pin: Some(pin), + clean, + }); + } + } + + // Exact-copy templates (no pin placeholder): compared when a workflow of the same name exists. + let caller_names: BTreeSet<&str> = caller_templates + .iter() + .map(|(t, _)| t.path.as_str()) + .collect(); + for tpl in inp + .templates + .iter() + .filter(|t| !caller_names.contains(t.path.as_str())) + { + if let Some(wf) = inp + .workflows + .iter() + .find(|w| file_name(&w.path) == file_name(&tpl.path)) + { + let same = wf.text == tpl.text; + if !same { + findings.push(Finding::EditedCaller { + file: wf.path.clone(), + template: tpl.path.clone(), + certainty: Certainty::UnknownCause, + first_diff_line: first_diff_line(&tpl.text, &wf.text), + }); + } + callers.push(CallerStatus { + file: wf.path.clone(), + template: tpl.path.clone(), + pin: None, + clean: same, + }); + } + } + + // Lock records: only meaningful if the repository carries a lock. + match inp.lock { + Some(lock) => { + for wf in inp.workflows { + if !lock_has_record(lock, &wf.path) { + findings.push(Finding::MissingLockEntry { + file: wf.path.clone(), + }); + } + } + not_checked.push( + "lock record contents: only presence of a record per workflow is checked".into(), + ); + } + None => not_checked + .push("lock records: repository has no .github/workflows/actions.lock".into()), + } + + callers.sort_by(|a, b| a.file.cmp(&b.file)); + findings.sort_by_key(|f| format!("{f:?}")); + Report { + callers, + findings, + not_checked, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SHA_A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const SHA_B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + const TPL: &str = "# header\nname: Gate\njobs:\n gate:\n uses: o/r/.github/workflows/gate.yml@__CICD_SUITE_SHA__ # cicd-suite main\n"; + + fn f(path: &str, text: &str) -> File { + File { + path: path.into(), + text: text.into(), + } + } + + fn run(wf: &str, latest: Option<&str>, lock: Option<&str>) -> Report { + let wfs = [f(".github/workflows/gate.yml", wf)]; + let tpls = [f("gate-caller.yml", TPL)]; + analyse(&Inputs { + workflows: &wfs, + templates: &tpls, + lock, + latest_suite_sha: latest, + latest_proven_sha: None, + }) + } + + #[test] + fn a_caller_equal_to_its_rendered_template_at_the_latest_pin_is_clean() { + let r = run(&TPL.replace(SUITE_SHA, SHA_A), Some(SHA_A), None); + assert!(!r.drifted(), "{:?}", r.findings); + assert!(r.callers[0].clean); + } + + #[test] + fn an_edit_at_the_latest_pin_is_certain() { + let edited = TPL + .replace(SUITE_SHA, SHA_A) + .replace("name: Gate", "name: Gate2"); + let r = run(&edited, Some(SHA_A), None); + assert_eq!( + r.findings, + vec![Finding::EditedCaller { + file: ".github/workflows/gate.yml".into(), + template: "gate-caller.yml".into(), + certainty: Certainty::Certain, + first_diff_line: 2 + }] + ); + } + + #[test] + fn an_old_pin_with_identical_bytes_is_only_stale() { + let r = run(&TPL.replace(SUITE_SHA, SHA_B), Some(SHA_A), None); + assert_eq!(r.findings.len(), 1); + assert!( + matches!(&r.findings[0], Finding::StalePin { pinned, latest, .. } if pinned == SHA_B && latest == SHA_A) + ); + } + + #[test] + fn an_old_pin_with_different_bytes_is_stale_and_edited_of_unknown_cause() { + let r = run( + &TPL.replace(SUITE_SHA, SHA_B) + .replace("name: Gate", "name: X"), + Some(SHA_A), + None, + ); + assert!(r + .findings + .iter() + .any(|x| matches!(x, Finding::StalePin { .. }))); + assert!(r.findings.iter().any(|x| matches!( + x, + Finding::EditedCaller { + certainty: Certainty::UnknownCause, + .. + } + ))); + } + + #[test] + fn a_branch_pin_is_flagged_and_still_compared() { + let r = run(&TPL.replace(SUITE_SHA, "main"), Some(SHA_A), None); + assert!(r + .findings + .iter() + .any(|x| matches!(x, Finding::NotFullShaPin { pin, .. } if pin == "main"))); + assert!( + !r.findings + .iter() + .any(|x| matches!(x, Finding::EditedCaller { .. })), + "unedited bytes must not read as edited" + ); + } + + #[test] + fn two_uses_lines_with_different_pins_are_an_edit() { + let two = format!( + "{} uses: o/r/.github/workflows/gate.yml@{SHA_B} # cicd-suite main\n", + TPL.replace(SUITE_SHA, SHA_A) + ); + let r = run(&two, Some(SHA_A), None); + assert!(r.findings.iter().any(|x| matches!( + x, + Finding::EditedCaller { + certainty: Certainty::UnknownCause, + .. + } + ))); + } + + #[test] + fn without_a_latest_pin_staleness_is_not_checked_and_says_so() { + let r = run(&TPL.replace(SUITE_SHA, SHA_A), None, None); + assert!(!r.drifted()); + assert!( + r.not_checked.iter().any(|m| m.contains("stale-pin check")), + "{:?}", + r.not_checked + ); + } + + #[test] + fn a_lock_without_a_record_for_the_workflow_is_a_finding() { + let lock = "version: 'v0.0.3'\nworkflows:\n '.github/workflows/other.yml': []\n"; + let r = run(&TPL.replace(SUITE_SHA, SHA_A), Some(SHA_A), Some(lock)); + assert_eq!( + r.findings, + vec![Finding::MissingLockEntry { + file: ".github/workflows/gate.yml".into() + }] + ); + let lock = "version: 'v0.0.3'\nworkflows:\n '.github/workflows/gate.yml': []\n"; + assert!(!run(&TPL.replace(SUITE_SHA, SHA_A), Some(SHA_A), Some(lock)).drifted()); + } + + #[test] + fn a_tamper_guard_caller_is_a_leftover_by_name_or_by_use() { + let guard = "on:\n pull_request_target:\njobs:\n g:\n uses: o/r/.github/workflows/ci-gate-tamper-guard.yml@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"; + let wfs = [ + f(".github/workflows/ci-gate-tamper-guard-caller.yml", guard), + f(".github/workflows/x.yml", guard), + ]; + let r = analyse(&Inputs { + workflows: &wfs, + templates: &[], + lock: None, + latest_suite_sha: None, + latest_proven_sha: None, + }); + let guards: Vec<_> = r.findings.iter().filter(|x| matches!(x, Finding::LeftoverGuardCaller { reason, .. } if reason.contains("pull_request_target"))).collect(); + assert_eq!(guards.len(), 2); + } + + #[test] + fn the_lock_reader_matches_a_whole_path_only() { + let lock = "workflows:\n '.github/workflows/gate.yml.bak':\n - 'a/b@c'\n"; + assert!(!lock_has_record(lock, ".github/workflows/gate.yml")); + assert!(lock_has_record(lock, ".github/workflows/gate.yml.bak")); + } +} diff --git a/crates/squabble-core/src/lib.rs b/crates/squabble-core/src/lib.rs index a27f0fe..bbfda27 100644 --- a/crates/squabble-core/src/lib.rs +++ b/crates/squabble-core/src/lib.rs @@ -18,6 +18,7 @@ pub mod admission; pub mod board; pub mod chains; pub mod done; +pub mod drift; pub mod execution; pub mod gate; pub mod inbox; From afbd51e6cda70360155eec15174361c6f4d79900 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 17:39:16 +0000 Subject: [PATCH 2/4] refactor(drift): split analyse into named checks; use method references SonarCloud on #180 raised four findings: three minor (closures that are method references) and one critical (analyse had cognitive complexity 59 against 30). analyse is now a short driver over check_guard, check_caller, check_stale, check_exact_copies and check_lock, collected in a small accumulator. Behaviour is unchanged: the 12 core and 11 binary-level drift tests pass, the workspace is 500 passed / 0 failed, and re-running the six detection mutations fails the same number of tests as before (7, 6, 4, 4, 4, 5). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgb6vQnxAZ8czX8SLb --- crates/squabble-cli/src/drift.rs | 15 +- crates/squabble-core/src/drift.rs | 311 +++++++++++++++++------------- 2 files changed, 183 insertions(+), 143 deletions(-) diff --git a/crates/squabble-cli/src/drift.rs b/crates/squabble-cli/src/drift.rs index 7b4186b..0529410 100644 --- a/crates/squabble-cli/src/drift.rs +++ b/crates/squabble-cli/src/drift.rs @@ -94,7 +94,11 @@ fn yaml_files(dir: &Path) -> Result, String> { .map_err(|e| format!("cannot list {}: {e}", dir.display()))? .filter_map(|e| e.ok().map(|e| e.path())) .filter(|p| { - p.is_file() && matches!(p.extension().and_then(|x| x.to_str()), Some("yml" | "yaml")) + p.is_file() + && matches!( + p.extension().and_then(std::ffi::OsStr::to_str), + Some("yml" | "yaml") + ) }) .collect(); v.sort(); @@ -111,7 +115,7 @@ fn vendor_source_sha(templates: &Path) -> Option { let sha: String = rest .trim() .chars() - .take_while(|c| c.is_ascii_hexdigit()) + .take_while(char::is_ascii_hexdigit) .collect(); (sha.len() == 40).then_some(sha) } @@ -152,7 +156,7 @@ fn gather_and_report(a: &Args) -> Result { if text.lines().any(|l| l.starts_with("on:")) { let name = p .file_name() - .and_then(|n| n.to_str()) + .and_then(std::ffi::OsStr::to_str) .unwrap_or_default() .to_string(); templates.push(File { path: name, text }); @@ -166,7 +170,10 @@ fn gather_and_report(a: &Args) -> Result { let mut workflows = Vec::new(); if wf_dir.is_dir() { for p in yaml_files(&wf_dir)? { - let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + let name = p + .file_name() + .and_then(std::ffi::OsStr::to_str) + .unwrap_or_default(); workflows.push(File { path: format!(".github/workflows/{name}"), text: read(&p)?, diff --git a/crates/squabble-core/src/drift.rs b/crates/squabble-core/src/drift.rs index a82be97..19ac4a3 100644 --- a/crates/squabble-core/src/drift.rs +++ b/crates/squabble-core/src/drift.rs @@ -217,177 +217,210 @@ pub fn lock_has_record(lock: &str, path: &str) -> bool { }) } -/// Compare a repository's workflows with the templates. -pub fn analyse(inp: &Inputs) -> Report { - let mut callers = Vec::new(); - let mut findings = Vec::new(); - let mut not_checked = Vec::new(); +/// Findings, caller statuses and unrun checks collected while analysing. +#[derive(Default)] +struct Acc { + callers: Vec, + findings: Vec, + not_checked: Vec, +} - let caller_templates: Vec<(&File, String)> = inp - .templates - .iter() - .filter_map(|t| caller_target(&t.text).map(|target| (t, target))) - .collect(); +impl Acc { + /// Record a check that could not run, once. + fn skip(&mut self, msg: String) { + if !self.not_checked.contains(&msg) { + self.not_checked.push(msg); + } + } +} - for wf in inp.workflows { - let uses = uses_of(&wf.text); +/// The template's newest-known pin: umbrella callers use the umbrella pin. +fn latest_for<'a>(tpl: &File, inp: &Inputs<'a>) -> Option<&'a str> { + if tpl.text.contains(PROVEN_SHA) { + inp.latest_proven_sha + } else { + inp.latest_suite_sha + } +} - // Retired guard caller: by file name, or by calling a tamper-guard reusable. - let guard_by_name = file_name(&wf.path).contains("tamper-guard"); - let guard_by_use = uses.iter().any(|u| u.target.contains("tamper-guard")); - if guard_by_name || guard_by_use { - let trigger = if wf.text.contains("pull_request_target") { - "; it triggers on pull_request_target" - } else { - "" - }; - findings.push(Finding::LeftoverGuardCaller { +/// A retired tamper-guard caller, by file name or by calling a tamper-guard reusable. +fn check_guard(wf: &File, uses: &[Use], acc: &mut Acc) { + let by_name = file_name(&wf.path).contains("tamper-guard"); + let by_use = uses.iter().any(|u| u.target.contains("tamper-guard")); + if !(by_name || by_use) { + return; + } + let trigger = if wf.text.contains("pull_request_target") { + "; it triggers on pull_request_target" + } else { + "" + }; + acc.findings.push(Finding::LeftoverGuardCaller { + file: wf.path.clone(), + reason: format!("retired tamper-guard caller still present{trigger}"), + }); +} + +/// Stale-pin finding, or a note that it could not be checked. +fn check_stale(wf: &File, tpl: &File, pin: &str, latest: Option<&str>, acc: &mut Acc) -> bool { + match latest { + Some(l) if is_full_sha(pin) && l != pin => { + acc.findings.push(Finding::StalePin { file: wf.path.clone(), - reason: format!("retired tamper-guard caller still present{trigger}"), + template: tpl.path.clone(), + pinned: pin.to_string(), + latest: l.to_string(), }); + false } - - // Which template, if any, is this workflow a caller of? - for (tpl, target) in &caller_templates { - let mine: Vec<&Use> = uses.iter().filter(|u| &u.target == target).collect(); - let Some(first) = mine.first() else { continue }; - let pin = first.reference.clone(); - let tag = first.comment.clone().unwrap_or_default(); - let mixed = mine.iter().any(|u| u.reference != pin); - - if tpl.text.contains(PROVEN_TAG) { - let msg = format!( - "tag comment of {}: taken from the caller itself, not checked against its SHA", - wf.path - ); - if !not_checked.contains(&msg) { - not_checked.push(msg); - } - } - - let latest = if tpl.text.contains(PROVEN_SHA) { - inp.latest_proven_sha + None => { + let which = if tpl.text.contains(PROVEN_SHA) { + "latest umbrella (proven.yml) pin" } else { - inp.latest_suite_sha + "latest suite pin" }; - let at_latest = latest.is_some_and(|l| l == pin); - let mut clean = true; - - if !is_full_sha(&pin) { - clean = false; - findings.push(Finding::NotFullShaPin { - file: wf.path.clone(), - template: tpl.path.clone(), - pin: pin.clone(), - }); - } + acc.skip(format!("stale-pin check for {}: no {which} given", wf.path)); + true + } + _ => true, + } +} - // The comment tag is only a placeholder for the umbrella template. - let rendered = render(&tpl.text, &pin, &tag); - if rendered != wf.text || mixed { - clean = false; - findings.push(Finding::EditedCaller { - file: wf.path.clone(), - template: tpl.path.clone(), - certainty: if at_latest && !mixed { - Certainty::Certain - } else { - Certainty::UnknownCause - }, - first_diff_line: first_diff_line(&rendered, &wf.text), - }); - } +/// One workflow that calls the template's reusable: pin, edit and staleness. +fn check_caller(wf: &File, tpl: &File, mine: &[&Use], inp: &Inputs, acc: &mut Acc) { + let first = mine[0]; + let pin = first.reference.clone(); + let tag = first.comment.clone().unwrap_or_default(); + let mixed = mine.iter().any(|u| u.reference != pin); + let latest = latest_for(tpl, inp); + let at_latest = latest.is_some_and(|l| l == pin); + let mut clean = true; + + if tpl.text.contains(PROVEN_TAG) { + acc.skip(format!( + "tag comment of {}: taken from the caller itself, not checked against its SHA", + wf.path + )); + } - match latest { - Some(l) if is_full_sha(&pin) && l != pin => { - clean = false; - findings.push(Finding::StalePin { - file: wf.path.clone(), - template: tpl.path.clone(), - pinned: pin.clone(), - latest: l.to_string(), - }); - } - None => { - let which = if tpl.text.contains(PROVEN_SHA) { - "latest umbrella (proven.yml) pin" - } else { - "latest suite pin" - }; - let msg = format!("stale-pin check for {}: no {which} given", wf.path); - if !not_checked.contains(&msg) { - not_checked.push(msg); - } - } - _ => {} - } + if !is_full_sha(&pin) { + clean = false; + acc.findings.push(Finding::NotFullShaPin { + file: wf.path.clone(), + template: tpl.path.clone(), + pin: pin.clone(), + }); + } - callers.push(CallerStatus { - file: wf.path.clone(), - template: tpl.path.clone(), - pin: Some(pin), - clean, - }); - } + // The comment tag is only a placeholder for the umbrella template. + let rendered = render(&tpl.text, &pin, &tag); + if rendered != wf.text || mixed { + clean = false; + let certain = at_latest && !mixed; + acc.findings.push(Finding::EditedCaller { + file: wf.path.clone(), + template: tpl.path.clone(), + certainty: if certain { + Certainty::Certain + } else { + Certainty::UnknownCause + }, + first_diff_line: first_diff_line(&rendered, &wf.text), + }); } - // Exact-copy templates (no pin placeholder): compared when a workflow of the same name exists. - let caller_names: BTreeSet<&str> = caller_templates - .iter() - .map(|(t, _)| t.path.as_str()) - .collect(); + clean &= check_stale(wf, tpl, &pin, latest, acc); + acc.callers.push(CallerStatus { + file: wf.path.clone(), + template: tpl.path.clone(), + pin: Some(pin), + clean, + }); +} + +/// Templates with no pin placeholder: compared byte for byte with a workflow of the same name. +fn check_exact_copies(inp: &Inputs, caller_names: &BTreeSet<&str>, acc: &mut Acc) { for tpl in inp .templates .iter() .filter(|t| !caller_names.contains(t.path.as_str())) { - if let Some(wf) = inp + let Some(wf) = inp .workflows .iter() .find(|w| file_name(&w.path) == file_name(&tpl.path)) - { - let same = wf.text == tpl.text; - if !same { - findings.push(Finding::EditedCaller { - file: wf.path.clone(), - template: tpl.path.clone(), - certainty: Certainty::UnknownCause, - first_diff_line: first_diff_line(&tpl.text, &wf.text), - }); - } - callers.push(CallerStatus { + else { + continue; + }; + let same = wf.text == tpl.text; + if !same { + acc.findings.push(Finding::EditedCaller { file: wf.path.clone(), template: tpl.path.clone(), - pin: None, - clean: same, + certainty: Certainty::UnknownCause, + first_diff_line: first_diff_line(&tpl.text, &wf.text), }); } + acc.callers.push(CallerStatus { + file: wf.path.clone(), + template: tpl.path.clone(), + pin: None, + clean: same, + }); + } +} + +/// Lock records: only meaningful if the repository carries a lock. +fn check_lock(inp: &Inputs, acc: &mut Acc) { + let Some(lock) = inp.lock else { + acc.skip("lock records: repository has no .github/workflows/actions.lock".into()); + return; + }; + for wf in inp + .workflows + .iter() + .filter(|w| !lock_has_record(lock, &w.path)) + { + acc.findings.push(Finding::MissingLockEntry { + file: wf.path.clone(), + }); } + acc.skip("lock record contents: only presence of a record per workflow is checked".into()); +} + +/// Compare a repository's workflows with the templates. +pub fn analyse(inp: &Inputs) -> Report { + let mut acc = Acc::default(); + let caller_templates: Vec<(&File, String)> = inp + .templates + .iter() + .filter_map(|t| caller_target(&t.text).map(|target| (t, target))) + .collect(); - // Lock records: only meaningful if the repository carries a lock. - match inp.lock { - Some(lock) => { - for wf in inp.workflows { - if !lock_has_record(lock, &wf.path) { - findings.push(Finding::MissingLockEntry { - file: wf.path.clone(), - }); - } + for wf in inp.workflows { + let uses = uses_of(&wf.text); + check_guard(wf, &uses, &mut acc); + for (tpl, target) in &caller_templates { + let mine: Vec<&Use> = uses.iter().filter(|u| &u.target == target).collect(); + if !mine.is_empty() { + check_caller(wf, tpl, &mine, inp, &mut acc); } - not_checked.push( - "lock record contents: only presence of a record per workflow is checked".into(), - ); } - None => not_checked - .push("lock records: repository has no .github/workflows/actions.lock".into()), } - callers.sort_by(|a, b| a.file.cmp(&b.file)); - findings.sort_by_key(|f| format!("{f:?}")); + let caller_names: BTreeSet<&str> = caller_templates + .iter() + .map(|(t, _)| t.path.as_str()) + .collect(); + check_exact_copies(inp, &caller_names, &mut acc); + check_lock(inp, &mut acc); + + acc.callers.sort_by(|a, b| a.file.cmp(&b.file)); + acc.findings.sort_by_key(|f| format!("{f:?}")); Report { - callers, - findings, - not_checked, + callers: acc.callers, + findings: acc.findings, + not_checked: acc.not_checked, } } From 0f2ffcc99e90489493e61d1544eb1f39b7384e96 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 17:43:12 +0000 Subject: [PATCH 3/4] feat(drift): say what StalePin means; label it vendor-time main until releases exist Hub request on #180. Until release tags exist, the default "latest suite pin" is the vendor-time branch tip, so a stale pin only means "behind vendor-time main". The output now carries latest.stale_pin_means, which reads "behind vendor-time main (a branch tip, not a release; no release tags exist yet)" for the default, "behind the pin given with --latest-suite-sha" for a flag, and "not checked" with no pin. Two binary-level tests pin the wording. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgb6vQnxAZ8czX8SLb --- crates/squabble-cli/src/drift.rs | 11 +++++++++++ crates/squabble-cli/tests/drift_cli.rs | 27 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/crates/squabble-cli/src/drift.rs b/crates/squabble-cli/src/drift.rs index 0529410..f5119c2 100644 --- a/crates/squabble-cli/src/drift.rs +++ b/crates/squabble-cli/src/drift.rs @@ -46,6 +46,9 @@ struct Latest<'a> { /// Where `suite_sha` came from: `flag`, `templates-readme` (the SHA the vendored /// templates were taken at, i.e. a branch tip, not a release) or `none`. suite_sha_source: &'static str, + /// What `StalePin` means for this run. Until release tags exist the default is + /// the vendor-time branch tip, so a stale pin is only "behind vendor-time main". + stale_pin_means: &'static str, proven_sha: Option<&'a str>, } @@ -189,6 +192,13 @@ fn gather_and_report(a: &Args) -> Result { (None, Some(_)) => "templates-readme", _ => "none", }; + let stale_means = match suite_source { + "templates-readme" => { + "behind vendor-time main (a branch tip, not a release; no release tags exist yet)" + } + "flag" => "behind the pin given with --latest-suite-sha", + _ => "not checked: no latest suite pin", + }; let report = analyse(&Inputs { workflows: &workflows, templates: &templates, @@ -209,6 +219,7 @@ fn gather_and_report(a: &Args) -> Result { latest: Latest { suite_sha: suite.as_deref(), suite_sha_source: suite_source, + stale_pin_means: stale_means, proven_sha: a.proven_sha.as_deref(), }, drift, diff --git a/crates/squabble-cli/tests/drift_cli.rs b/crates/squabble-cli/tests/drift_cli.rs index d4c1bce..2a22819 100644 --- a/crates/squabble-cli/tests/drift_cli.rs +++ b/crates/squabble-cli/tests/drift_cli.rs @@ -296,3 +296,30 @@ fn bad_input_exits_2_with_nothing_on_stdout() { .unwrap(); assert_eq!(o.status.code(), Some(2)); } + +#[test] +fn without_a_latest_pin_flag_stale_means_behind_vendor_time_main() { + // No --latest-suite-sha: the default comes from the vendor README, a branch tip. + let r = repo("vendor-default", &[(GATE, gate(OLD))]); + let o = Command::new(env!("CARGO_BIN_EXE_squabble")) + .args(["drift", "--json", "--repo", r.to_str().unwrap()]) + .args(["--templates", templates().to_str().unwrap()]) + .output() + .unwrap(); + let v = json(&o); + assert_eq!(v["latest"]["suite_sha_source"], "templates-readme"); + let means = v["latest"]["stale_pin_means"].as_str().unwrap(); + assert!(means.starts_with("behind vendor-time main"), "{means}"); + assert!(means.contains("not a release"), "{means}"); + assert!(kinds(&v).contains(&"StalePin".to_string())); +} + +#[test] +fn with_a_latest_pin_flag_stale_means_behind_that_pin() { + let v = json(&drift(&repo("flag-meaning", &[(GATE, gate(OLD))]), &[])); + assert_eq!(v["latest"]["suite_sha_source"], "flag"); + assert!(v["latest"]["stale_pin_means"] + .as_str() + .unwrap() + .contains("--latest-suite-sha")); +} From 9b0981171e71af7d64a282a564ea743c56c8b164 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 18:07:05 +0000 Subject: [PATCH 4/4] feat(drift): flag a de-onboarded gate caller that still has a lock leaf Owner ruling 2026-11-30 ("keep them out of the lock, follow the template"): gate callers are DE-ONBOARDED from actions.lock. A template says so with the marker "DE-ONBOARDED from actions.lock" (11 vendored templates carry it), and the rule is driven by that text, not a list. De-onboarded means the file's key is present with an empty list ('': []): a missing key is already MissingLockEntry, and the repo's own lock-sync checker treats a missing key as a defect. A gate caller whose key lists any leaf record is the new OnboardedGateCaller finding. The umbrella proven.yml caller has no marker and may keep its leaf. lock_record() reads one workflow's list (absent / empty / leaves). Tests: five core unit tests, three binary-level tests (one data-driven over every marked vendored template, with a leaf and with the empty entry). Mutation check: four mutations of the rule fail 4, 6, 4 and 2 tests. Note for the owner: scripts/check-lock-sync.sh clause 1 requires every uses: to be locked under its own workflow, so the de-onboarded shape fails that gate in this repository. The two rules conflict; this commit only reports. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDgb6vQnxAZ8czX8SLb --- crates/squabble-cli/tests/drift_cli.rs | 103 ++++++++++++++++ crates/squabble-core/src/drift.rs | 157 +++++++++++++++++++++++-- 2 files changed, 249 insertions(+), 11 deletions(-) diff --git a/crates/squabble-cli/tests/drift_cli.rs b/crates/squabble-cli/tests/drift_cli.rs index 2a22819..27b1b31 100644 --- a/crates/squabble-cli/tests/drift_cli.rs +++ b/crates/squabble-cli/tests/drift_cli.rs @@ -323,3 +323,106 @@ fn with_a_latest_pin_flag_stale_means_behind_that_pin() { .unwrap() .contains("--latest-suite-sha")); } + +/// Every vendored template that is a gate caller and says DE-ONBOARDED. +fn de_onboarded_templates() -> Vec<(String, String)> { + let mut v: Vec<(String, String)> = std::fs::read_dir(templates()) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.extension().is_some_and(|x| x == "yml")) + .filter_map(|p| { + let text = std::fs::read_to_string(&p).unwrap(); + (text.contains("DE-ONBOARDED from actions.lock") && text.contains("__CICD_SUITE_SHA__")) + .then(|| (p.file_name().unwrap().to_string_lossy().into_owned(), text)) + }) + .collect(); + v.sort(); + v +} + +fn lock_with(path: &str, body: &str) -> String { + format!("version: 'v0.0.3'\nworkflows:\n '{path}':{body}\n") +} + +#[test] +fn every_de_onboarded_gate_caller_with_a_leaf_record_is_flagged_and_the_empty_entry_is_clean() { + let templates = de_onboarded_templates(); + assert!( + templates.len() >= 10, + "expected the gate caller templates, found {}", + templates.len() + ); + for (name, text) in &templates { + let path = format!(".github/workflows/{}", name.replace("-caller", "")); + let caller = text.replace("__CICD_SUITE_SHA__", LATEST); + let leaf = lock_with( + &path, + &format!("\n - 'hyperpolymath/proven-cicd-and-workflows@{LATEST}'"), + ); + let lock = ".github/workflows/actions.lock"; + + let case = format!("deonb-leaf-{name}"); + let o = drift(&repo(&case, &[(&path, caller.clone()), (lock, leaf)]), &[]); + let v = json(&o); + let f = v["findings"] + .as_array() + .unwrap() + .iter() + .find(|f| f["kind"] == "OnboardedGateCaller") + .unwrap_or_else(|| panic!("{name}: no OnboardedGateCaller in {:?}", kinds(&v))); + assert_eq!(f["file"], path.as_str(), "{name}"); + assert_eq!(o.status.code(), Some(4), "{name}"); + + let case = format!("deonb-empty-{name}"); + let o = drift( + &repo(&case, &[(&path, caller), (lock, lock_with(&path, " []"))]), + &[], + ); + assert_eq!( + o.status.code(), + Some(0), + "{name}: the empty entry must be clean: {:?}", + kinds(&json(&o)) + ); + } +} + +#[test] +fn the_umbrella_caller_is_not_a_de_onboarded_template_and_may_keep_its_leaf() { + let proven = template("proven-caller.yml") + .replace("__PROVEN_SHA__", LATEST) + .replace("__PROVEN_TAG__", "v0.1.2"); + let lock = lock_with( + ".github/workflows/proven.yml", + &format!("\n - 'hyperpolymath/proven-cicd-and-workflows@{LATEST}'"), + ); + let r = repo( + "umbrella-leaf", + &[ + (".github/workflows/proven.yml", proven), + (".github/workflows/actions.lock", lock), + ], + ); + let v = json(&drift(&r, &["--latest-proven-sha", LATEST])); + assert!( + !kinds(&v).contains(&"OnboardedGateCaller".to_string()), + "{:?}", + kinds(&v) + ); +} + +#[test] +fn a_missing_key_is_reported_as_a_missing_entry_not_as_an_onboarded_caller() { + let lock = "version: 'v0.0.3'\nworkflows:\n '.github/workflows/other.yml': []\n".to_string(); + let v = json(&drift( + &repo( + "deonb-absent", + &[ + (GATE, gate(LATEST)), + (".github/workflows/actions.lock", lock), + ], + ), + &[], + )); + assert_eq!(kinds(&v), ["MissingLockEntry"]); +} diff --git a/crates/squabble-core/src/drift.rs b/crates/squabble-core/src/drift.rs index 19ac4a3..7f4f685 100644 --- a/crates/squabble-core/src/drift.rs +++ b/crates/squabble-core/src/drift.rs @@ -101,6 +101,18 @@ pub enum Finding { LeftoverGuardCaller { file: String, reason: String }, /// The repository carries an `actions.lock` but it has no record for this workflow. MissingLockEntry { file: String }, + /// A gate caller whose template says it is DE-ONBOARDED from `actions.lock` + /// (owner ruling 2026-11-30: "keep them out of the lock, follow the template") + /// still has leaf records in the lock. De-onboarded means the file's key is + /// present with an empty list, so a missing key is [`Finding::MissingLockEntry`] + /// instead. NOTE: a repository whose `check-lock-sync.sh` enforces "every + /// `uses:` is locked under its own workflow" will fail that gate on the + /// de-onboarded shape; the two rules conflict until the owner resolves it. + OnboardedGateCaller { + file: String, + template: String, + leaves: Vec, + }, } /// What was found for one caller, whether or not it drifted. @@ -199,22 +211,51 @@ fn file_name(path: &str) -> &str { path.rsplit('/').next().unwrap_or(path) } +/// The marker every de-onboarded template carries in its header comment. +pub const DE_ONBOARDED_MARKER: &str = "DE-ONBOARDED from actions.lock"; + +/// The key of a lock line: a quoted (or bare) path followed by `:`. +fn lock_key(line: &str) -> Option<&str> { + let t = line.trim(); + match t.chars().next() { + Some(q @ ('\'' | '"')) => t[1..] + .split_once(q) + .and_then(|(k, rest)| rest.starts_with(':').then_some(k)), + _ => t.split_once(':').map(|(k, _)| k), + } +} + +/// The leaf records the lock lists for workflow `path`: `None` if the lock has +/// no key for it, `Some(vec![])` for the empty entry (`'': []`), else the +/// listed pins. Only this one workflow's list is read, not what the pins mean. +pub fn lock_record(lock: &str, path: &str) -> Option> { + let indent = |l: &str| l.len() - l.trim_start().len(); + let mut lines = lock.lines(); + let key_line = lines.by_ref().find(|l| lock_key(l) == Some(path))?; + let key_indent = indent(key_line); + let mut leaves = Vec::new(); + for l in lines { + let t = l.trim(); + if t.is_empty() { + continue; + } + // The next key (or any line at the key's own indent or shallower) ends the list. + if indent(l) <= key_indent { + break; + } + if let Some(item) = t.strip_prefix("- ") { + leaves.push(item.trim().trim_matches(['\'', '"']).to_string()); + } + } + Some(leaves) +} + /// Does `.github/workflows/actions.lock` hold a record for `path`? /// /// The lock maps each workflow path (quoted, under `workflows:`) to its pins. /// Only the key's presence is read here, not what it lists. pub fn lock_has_record(lock: &str, path: &str) -> bool { - lock.lines().any(|l| { - let t = l.trim(); - // A record key is a quoted (or bare) path followed by `:`. - let key = match t.chars().next() { - Some(q @ ('\'' | '"')) => t[1..] - .split_once(q) - .and_then(|(k, rest)| rest.starts_with(':').then_some(k)), - _ => t.split_once(':').map(|(k, _)| k), - }; - key == Some(path) - }) + lock_record(lock, path).is_some() } /// Findings, caller statuses and unrun checks collected while analysing. @@ -286,6 +327,27 @@ fn check_stale(wf: &File, tpl: &File, pin: &str, latest: Option<&str>, acc: &mut } } +/// A gate caller whose template is DE-ONBOARDED must have no leaf record in the +/// lock. A missing key is [`Finding::MissingLockEntry`], reported by [`check_lock`]; +/// with no lock at all there is nothing to check (and `check_lock` says so). +fn check_deonboarded(wf: &File, tpl: &File, inp: &Inputs, acc: &mut Acc) -> bool { + let Some(lock) = inp.lock else { return true }; + if !tpl.text.contains(DE_ONBOARDED_MARKER) { + return true; + } + match lock_record(lock, &wf.path) { + Some(leaves) if !leaves.is_empty() => { + acc.findings.push(Finding::OnboardedGateCaller { + file: wf.path.clone(), + template: tpl.path.clone(), + leaves, + }); + false + } + _ => true, + } +} + /// One workflow that calls the template's reusable: pin, edit and staleness. fn check_caller(wf: &File, tpl: &File, mine: &[&Use], inp: &Inputs, acc: &mut Acc) { let first = mine[0]; @@ -330,6 +392,7 @@ fn check_caller(wf: &File, tpl: &File, mine: &[&Use], inp: &Inputs, acc: &mut Ac } clean &= check_stale(wf, tpl, &pin, latest, acc); + clean &= check_deonboarded(wf, tpl, inp, acc); acc.callers.push(CallerStatus { file: wf.path.clone(), template: tpl.path.clone(), @@ -585,4 +648,76 @@ mod tests { assert!(!lock_has_record(lock, ".github/workflows/gate.yml")); assert!(lock_has_record(lock, ".github/workflows/gate.yml.bak")); } + + const DE_TPL: &str = "# DE-ONBOARDED from actions.lock, deliberately\nname: Gate\njobs:\n gate:\n uses: o/r/.github/workflows/gate.yml@__CICD_SUITE_SHA__ # cicd-suite main\n"; + const GATE_PATH: &str = ".github/workflows/gate.yml"; + + fn run_de(template: &str, lock: Option<&str>) -> Report { + let wfs = [f(GATE_PATH, &template.replace(SUITE_SHA, SHA_A))]; + let tpls = [f("gate-caller.yml", template)]; + analyse(&Inputs { + workflows: &wfs, + templates: &tpls, + lock, + latest_suite_sha: Some(SHA_A), + latest_proven_sha: None, + }) + } + + #[test] + fn the_lock_reader_distinguishes_absent_empty_and_leaf_records() { + let lock = "version: 'v0.0.3'\nworkflows:\n '.github/workflows/a.yml': []\n '.github/workflows/b.yml':\n - 'o/r@aaaa'\n - 'p/q@v1'\n '.github/workflows/c.yml':\n - 'x/y@z'\ndependencies:\n 'o/r@aaaa': {}\n"; + assert_eq!(lock_record(lock, ".github/workflows/a.yml"), Some(vec![])); + assert_eq!( + lock_record(lock, ".github/workflows/b.yml"), + Some(vec!["o/r@aaaa".to_string(), "p/q@v1".to_string()]) + ); + assert_eq!( + lock_record(lock, ".github/workflows/c.yml"), + Some(vec!["x/y@z".to_string()]) + ); + assert_eq!(lock_record(lock, ".github/workflows/missing.yml"), None); + assert!(lock_has_record(lock, ".github/workflows/a.yml")); + } + + #[test] + fn a_de_onboarded_gate_caller_with_a_leaf_record_is_a_finding() { + let lock = "workflows:\n '.github/workflows/gate.yml':\n - 'o/r@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'\n"; + let r = run_de(DE_TPL, Some(lock)); + assert_eq!( + r.findings, + vec![Finding::OnboardedGateCaller { + file: GATE_PATH.into(), + template: "gate-caller.yml".into(), + leaves: vec!["o/r@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into()], + }] + ); + assert!(!r.callers[0].clean); + } + + #[test] + fn the_empty_entry_is_the_de_onboarded_shape_and_is_clean() { + let lock = "workflows:\n '.github/workflows/gate.yml': []\n"; + let r = run_de(DE_TPL, Some(lock)); + assert!(!r.drifted(), "{:?}", r.findings); + } + + #[test] + fn an_absent_key_is_a_missing_entry_not_an_onboarded_caller() { + let lock = "workflows:\n '.github/workflows/other.yml': []\n"; + let r = run_de(DE_TPL, Some(lock)); + assert_eq!( + r.findings, + vec![Finding::MissingLockEntry { + file: GATE_PATH.into() + }] + ); + } + + #[test] + fn a_template_without_the_marker_may_keep_its_leaf_record() { + let lock = "workflows:\n '.github/workflows/gate.yml':\n - 'o/r@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'\n"; + let r = run_de(TPL, Some(lock)); + assert!(!r.drifted(), "{:?}", r.findings); + } }