diff --git a/bots/sillybot/Cargo.lock b/bots/sillybot/Cargo.lock new file mode 100644 index 00000000..751c2c97 --- /dev/null +++ b/bots/sillybot/Cargo.lock @@ -0,0 +1,416 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sillybot" +version = "0.1.0" +dependencies = [ + "clap", + "serde", + "serde_json", + "tempfile", + "toml", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "toml" +version = "1.2.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.7+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/bots/sillybot/Cargo.toml b/bots/sillybot/Cargo.toml new file mode 100644 index 00000000..5dd6addd --- /dev/null +++ b/bots/sillybot/Cargo.toml @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: MPL-2.0 +[package] +name = "sillybot" +version = "0.1.0" +edition = "2021" +license = "MPL-2.0" +authors = ["Jonathan D.A. Jewell "] +description = "Thin adapter running docudactyl docs-ingest and recon-silly-ation reconcile at pinned commits and reporting docs findings to gitbot-fleet" +repository = "https://github.com/hyperpolymath/gitbot-fleet" +keywords = ["documentation", "audit", "gitbot-fleet"] +categories = ["development-tools"] + +[lib] +name = "sillybot" +path = "src/lib.rs" + +[[bin]] +name = "sillybot" +path = "src/main.rs" + +[dependencies] +clap = { version = "4.6.1", features = ["derive"] } +serde = { version = "1.0.228", features = ["derive"] } +serde_json = "1.0.150" +tempfile = "3.27.0" +toml = "1.1.2" diff --git a/bots/sillybot/canon/pin.toml b/bots/sillybot/canon/pin.toml new file mode 100644 index 00000000..c0888e27 --- /dev/null +++ b/bots/sillybot/canon/pin.toml @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: MPL-2.0 +# +# The ONE commit of each engine sillybot accepts. sillybot runs two external +# tools and owns no checking logic (sillybot spec v0, owner ruling DP5): +# +# docudactyl `docs-ingest` repo tree -> reconcile-input/v0 bundle +# recon-silly-ation `reconcile` bundles -> findings/v0 +# +# Neither tool prints its own source commit yet, so sillybot cannot check the +# binary against this pin at run time the way ponsbot does. The pin is what +# the build step (fleet wiring, DP12) must build. Until a tool stamps its +# commit, a drifted binary is a known gap, recorded here and in lib.rs. +# +# Provenance: docudactyl main after #96 and #97 (docs-ingest and its review +# fixes); recon-silly-ation main after #83 (reconcile v0) and #85 (design). +# +# To re-pin: change a commit and `pinned`, rebuild that tool there, run +# `cargo test` in bots/sillybot. + +[ingest] +repo = "hyperpolymath/docudactyl" +commit = "f8ed65f0979b6bb12cd9e2258bed993e2d0e9d7c" +pinned = "2026-11-27" + +[reconcile] +repo = "hyperpolymath/recon-silly-ation" +commit = "6b306c6e3ef2825f685817a206951f204a1b75de" +pinned = "2026-11-27" diff --git a/bots/sillybot/src/cli.rs b/bots/sillybot/src/cli.rs new file mode 100644 index 00000000..dcb98197 --- /dev/null +++ b/bots/sillybot/src/cli.rs @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: MPL-2.0 +//! CLI: `sillybot [--format text|json] scan --path DIR [--base REV] [--repo OWNER/NAME]`. + +use clap::{Parser, Subcommand}; +use std::path::PathBuf; + +/// Sillybot: gitbot-fleet adapter for docs consistency checks. +#[derive(Parser, Debug)] +#[command(name = "sillybot", version)] +#[command( + about = "Runs docudactyl docs-ingest and recon-silly-ation reconcile at pinned commits and reports docs findings to gitbot-fleet" +)] +#[command( + long_about = "Sillybot exports HEAD (and --base, if given) of a git repository into a \ + private temporary directory, runs docs-ingest and reconcile on it, and prints the \ + findings. It never writes into the scanned tree. Report-only. Exit codes: 0 ran, no \ + blocking finding; 1 ran, at least one blocking finding; 2 error; 3 not run (a tool is \ + not installed, or no prose file changed against --base). On 2 and 3 the JSON output is \ + an object {status, reason}, never a findings array. Tools are found through \ + SILLYBOT_DOCS_INGEST and SILLYBOT_RECONCILE, else on PATH as docs-ingest and reconcile." +)] +pub struct Cli { + #[command(subcommand)] + pub command: Command, + + /// Output format (text, json). + #[arg(short, long, default_value = "text", global = true)] + pub format: OutputFormat, +} + +/// Output format for results. +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum OutputFormat { + Text, + Json, +} + +#[derive(Subcommand, Debug)] +pub enum Command { + /// Scan a git repository's HEAD and print the docs findings. + Scan { + /// Repository directory to scan (a git work tree). + #[arg(long, default_value = ".")] + path: PathBuf, + + /// Base revision. Findings already present at the base are reported + /// as inherited (info), and the scan is skipped when no prose file + /// changed. + #[arg(long)] + base: Option, + + /// Repository name OWNER/NAME. Defaults to the GitHub origin remote. + #[arg(long)] + repo: Option, + + /// Pull request number passed through to reconcile. + #[arg(long, default_value_t = 0)] + pr: u64, + + /// Seconds the whole scan may run before sillybot reports an error. + #[arg(long, default_value_t = 300)] + timeout: u64, + }, +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::CommandFactory; + + #[test] + fn test_cli_parses() { + Cli::command().debug_assert(); + } +} diff --git a/bots/sillybot/src/lib.rs b/bots/sillybot/src/lib.rs new file mode 100644 index 00000000..540608eb --- /dev/null +++ b/bots/sillybot/src/lib.rs @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Sillybot: a thin adapter that runs two pinned external tools and reports +//! docs-consistency findings to the gitbot-fleet report-back driver. +//! +//! - docudactyl `docs-ingest` turns a repository revision into a +//! reconcile-input/v0 bundle, +//! - recon-silly-ation `reconcile` turns one or two bundles into findings/v0. +//! +//! Nothing of either tool's logic lives here (sillybot spec v0, owner ruling +//! DP5). The adapter only +//! - exports the revisions it scans into a private temporary directory with +//! `git archive`, so it never reads a dirty work tree and never writes into +//! the scanned tree ([`runner`]), +//! - maps the tools' failures to a status that is never a pass, +//! - maps findings/v0 to the fleet finding shape ([`translator`]). +//! +//! Known gap: neither tool stamps its source commit in its output, so the +//! pins in `canon/pin.toml` cannot be checked at run time ([`pin`]). + +pub mod cli; +pub mod pin; +pub mod runner; +pub mod translator; diff --git a/bots/sillybot/src/main.rs b/bots/sillybot/src/main.rs new file mode 100644 index 00000000..d7e8ec03 --- /dev/null +++ b/bots/sillybot/src/main.rs @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: MPL-2.0 +//! sillybot entry point. See `lib.rs` and `cli.rs`. +//! +//! Output contract for `--format json` (what the report-back driver reads): +//! - ran: a JSON array of findings (possibly empty), exit 0 (no blocking +//! finding) or 1 (at least one blocking finding), +//! - error: `{"status":"error","reason":"..."}`, exit 2, +//! - not run: `{"status":"not_run","reason":"..."}`, exit 3. +//! +//! Nothing here ever prints an empty array for a scan that did not run. + +use clap::Parser; +use sillybot::cli::{Cli, Command, OutputFormat}; +use sillybot::runner::{scan, Outcome, Request}; +use sillybot::{pin, translator}; +use std::process::ExitCode; +use std::time::Duration; + +fn main() -> ExitCode { + let cli = Cli::parse(); + let Command::Scan { + path, + base, + repo, + pr, + timeout, + } = cli.command; + if let Err(e) = pin::pinned() { + return report_not_ran( + "error", + &format!("canon/pin.toml is malformed: {e}"), + cli.format, + 2, + ); + } + let req = Request { + path, + base, + repo, + pr, + timeout: Duration::from_secs(timeout.max(1)), + }; + match scan(&req) { + Outcome::Ran(doc) => match translator::translate_report(&doc) { + Ok(findings) => print_findings(&findings, cli.format), + Err(e) => report_not_ran( + "error", + &format!("reconcile output is unusable: {e}"), + cli.format, + 2, + ), + }, + Outcome::Error(reason) => report_not_ran("error", &reason, cli.format, 2), + Outcome::NotRun(reason) => report_not_ran("not_run", &reason, cli.format, 3), + } +} + +fn print_findings(findings: &[translator::Finding], format: OutputFormat) -> ExitCode { + match format { + OutputFormat::Json => match serde_json::to_string_pretty(findings) { + Ok(s) => println!("{s}"), + Err(e) => return report_not_ran("error", &e.to_string(), format, 2), + }, + OutputFormat::Text => { + if findings.is_empty() { + println!("No docs findings."); + } + for f in findings { + println!( + "{}:{} [{}] {} {}", + f.file, f.line, f.rule_id, f.severity, f.message + ); + } + } + } + if findings.iter().any(|f| f.blocking) { + ExitCode::from(1) + } else { + ExitCode::SUCCESS + } +} + +fn report_not_ran(status: &str, reason: &str, format: OutputFormat, code: u8) -> ExitCode { + match format { + OutputFormat::Json => { + println!( + "{}", + serde_json::json!({ "status": status, "reason": reason }) + ) + } + OutputFormat::Text => println!("sillybot: {status}: {reason}"), + } + eprintln!("sillybot: {status}: {reason}"); + ExitCode::from(code) +} diff --git a/bots/sillybot/src/pin.rs b/bots/sillybot/src/pin.rs new file mode 100644 index 00000000..001de2ea --- /dev/null +++ b/bots/sillybot/src/pin.rs @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: MPL-2.0 +//! The pinned engine commits, compiled in from `canon/pin.toml`. + +use serde::Deserialize; + +const PIN_TOML: &str = include_str!("../canon/pin.toml"); + +/// Both pins. +#[derive(Debug, Clone, Deserialize)] +pub struct Pins { + pub ingest: Source, + pub reconcile: Source, +} + +/// One `[table]` of `canon/pin.toml`. +#[derive(Debug, Clone, Deserialize)] +pub struct Source { + pub repo: String, + pub commit: String, + pub pinned: String, +} + +/// The pins, parsed from the compiled-in `canon/pin.toml`. A malformed file +/// is reported as an error by the caller, never a panic. +pub fn pinned() -> Result { + toml::from_str(PIN_TOML) +} + +/// True for a full 40-hex lowercase commit. +pub fn is_full_commit(s: &str) -> bool { + s.len() == 40 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pins_are_full_commits() -> Result<(), toml::de::Error> { + let p = pinned()?; + assert!(is_full_commit(&p.ingest.commit)); + assert!(is_full_commit(&p.reconcile.commit)); + assert_eq!(p.ingest.repo, "hyperpolymath/docudactyl"); + assert_eq!(p.reconcile.repo, "hyperpolymath/recon-silly-ation"); + Ok(()) + } +} diff --git a/bots/sillybot/src/runner.rs b/bots/sillybot/src/runner.rs new file mode 100644 index 00000000..75471990 --- /dev/null +++ b/bots/sillybot/src/runner.rs @@ -0,0 +1,357 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Run docs-ingest and reconcile on a git repository, never writing into it. +//! +//! Each revision is exported with `git archive` into a private temporary +//! directory, ingested there, and the bundles are handed to reconcile. The +//! scanned tree is only read by `git`, with hooks and fsmonitor switched off. +//! Every failure maps to `Error` or `NotRun`; nothing here turns a failed run +//! into an empty findings list. + +use std::ffi::OsString; +use std::fs::File; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use serde_json::Value; + +/// What happened. +#[derive(Debug)] +pub enum Outcome { + /// Both tools ran. The value is reconcile's findings/v0 document. + Ran(Value), + /// The scan failed. The reason is for the report. + Error(String), + /// The scan was not run (a tool is missing, or no prose changed). + NotRun(String), +} + +/// Inputs for one scan. +#[derive(Debug, Clone)] +pub struct Request { + pub path: PathBuf, + pub base: Option, + pub repo: Option, + pub pr: u64, + pub timeout: Duration, +} + +/// The prose formats docs-ingest parses (docudactyl `formatOf`). +pub fn is_prose(path: &str) -> bool { + let lower = path.to_ascii_lowercase(); + [".adoc", ".asciidoc", ".asc", ".md", ".markdown"] + .iter() + .any(|e| lower.ends_with(e)) +} + +/// OWNER/NAME with GitHub's name characters only. +pub fn valid_repo(s: &str) -> bool { + let mut parts = s.split('/'); + let ok = |p: Option<&str>| { + p.is_some_and(|p| { + !p.is_empty() + && p != "." + && p != ".." + && p.bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) + }) + }; + ok(parts.next()) && ok(parts.next()) && parts.next().is_none() +} + +/// OWNER/NAME from a remote URL: the last two path segments, `.git` dropped. +pub fn repo_from_url(url: &str) -> Option { + let url = url.trim().trim_end_matches('/'); + let url = url.strip_suffix(".git").unwrap_or(url); + let tail = url.rsplit(['/', ':']).take(2).collect::>(); + if tail.len() != 2 { + return None; + } + let r = format!("{}/{}", tail[1], tail[0]); + valid_repo(&r).then_some(r) +} + +/// A tool from its environment variable, else from PATH. +fn find_tool(env: &str, name: &str) -> Option { + if let Some(p) = std::env::var_os(env).filter(|p| !p.is_empty()) { + let p = PathBuf::from(p); + return p.is_file().then_some(p); + } + std::env::split_paths(&std::env::var_os("PATH")?) + .map(|d| d.join(name)) + .find(|p| p.is_file()) +} + +struct Clock { + deadline: Instant, +} + +impl Clock { + fn left(&self) -> Result { + self.deadline + .checked_duration_since(Instant::now()) + .filter(|d| !d.is_zero()) + .ok_or_else(|| "timed out".to_string()) + } +} + +/// Run a command with stdout and stderr in files under `tmp`, killing it at +/// the deadline. Returns stdout on exit 0, else an error with stderr's tail. +fn run(mut cmd: Command, tmp: &Path, tag: &str, clock: &Clock) -> Result, String> { + let out_p = tmp.join(format!("{tag}.out")); + let err_p = tmp.join(format!("{tag}.err")); + let out = File::create(&out_p).map_err(|e| format!("{tag}: {e}"))?; + let err = File::create(&err_p).map_err(|e| format!("{tag}: {e}"))?; + cmd.stdin(Stdio::null()) + .stdout(Stdio::from(out)) + .stderr(Stdio::from(err)); + let mut child = cmd + .spawn() + .map_err(|e| format!("{tag}: cannot start: {e}"))?; + let status = loop { + match child.try_wait() { + Ok(Some(s)) => break s, + Ok(None) => {} + Err(e) => return Err(format!("{tag}: {e}")), + } + if clock.left().is_err() { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("{tag}: timed out")); + } + std::thread::sleep(Duration::from_millis(20)); + }; + if status.success() { + std::fs::read(&out_p).map_err(|e| format!("{tag}: {e}")) + } else { + // Keep stderr on disk for local/debug inspection, but do not surface it + // in user-facing error strings to avoid leaking sensitive diagnostics. + Err(format!("{tag}: exited with {status}")) + } +} + +/// `git` with repository hooks and fsmonitor switched off. +fn git(repo: &Path) -> Command { + let mut c = Command::new("git"); + c.arg("-C") + .arg(repo) + .args([ + "-c", + "core.fsmonitor=false", + "-c", + "core.hooksPath=/dev/null", + ]) + .env("GIT_TERMINAL_PROMPT", "0"); + c +} + +fn git_text(repo: &Path, args: &[&str], tmp: &Path, clock: &Clock) -> Result { + let mut c = git(repo); + c.args(args); + let out = run(c, tmp, "git", clock)?; + String::from_utf8(out).map_err(|_| "git: output is not UTF-8".to_string()) +} + +/// Resolve a revision to its full commit id. +fn resolve(repo: &Path, rev: &str, tmp: &Path, clock: &Clock) -> Result { + if rev.is_empty() || rev.starts_with('-') || rev.chars().any(char::is_control) { + return Err(format!("bad revision {rev:?}")); + } + let spec = format!("{rev}^{{commit}}"); + let sha = git_text( + repo, + &[ + "rev-parse", + "--verify", + "--quiet", + "--end-of-options", + &spec, + ], + tmp, + clock, + ) + .map_err(|_| format!("revision {rev:?} is not a commit in this repository"))?; + let sha = sha.trim().to_string(); + if crate::pin::is_full_commit(&sha) { + Ok(sha) + } else { + Err(format!( + "revision {rev:?} did not resolve to a SHA-1 commit id" + )) + } +} + +/// NUL-separated names from git, refusing names docs-ingest's newline lists +/// cannot carry. +fn nul_names(raw: &str) -> Result, String> { + let names: Vec = raw + .split('\0') + .filter(|n| !n.is_empty()) + .map(str::to_string) + .collect(); + if names.iter().any(|n| n.contains('\n') || n.contains('\r')) { + return Err("a file name contains a line break; docs-ingest cannot list it".into()); + } + Ok(names) +} + +/// Export `sha` to `tmp//`, write its file list, and run docs-ingest. +/// Returns the bundle's path. +fn ingest( + req_path: &Path, + ingest_bin: &Path, + repo: &str, + sha: &str, + tag: &str, + tmp: &Path, + clock: &Clock, +) -> Result { + let tree = tmp.join(tag); + std::fs::create_dir(&tree).map_err(|e| format!("{tag}: {e}"))?; + let tar = tmp.join(format!("{tag}.tar")); + let mut c = git(req_path); + c.args(["archive", "--format=tar", "-o"]).arg(&tar).arg(sha); + run(c, tmp, &format!("{tag}-archive"), clock)?; + let mut c = Command::new("tar"); + c.arg("-xf").arg(&tar).arg("-C").arg(&tree); + run(c, tmp, &format!("{tag}-untar"), clock)?; + + let names = nul_names(&git_text( + req_path, + &["ls-tree", "-r", "-z", "--name-only", sha], + tmp, + clock, + )?)?; + let list = tmp.join(format!("{tag}.files")); + std::fs::write(&list, names.join("\n") + "\n").map_err(|e| format!("{tag}: {e}"))?; + + let mut c = Command::new(ingest_bin); + c.args(["--repo", repo, "--rev", sha, "--root"]) + .arg(&tree) + .arg("--files") + .arg(&list); + let bundle = run(c, tmp, &format!("{tag}-ingest"), clock)?; + let out = tmp.join(format!("{tag}.json")); + std::fs::write(&out, bundle).map_err(|e| format!("{tag}: {e}"))?; + Ok(out) +} + +/// Run one scan. +pub fn scan(req: &Request) -> Outcome { + let clock = Clock { + deadline: Instant::now() + req.timeout, + }; + let Some(ingest_bin) = find_tool("SILLYBOT_DOCS_INGEST", "docs-ingest") else { + return Outcome::NotRun("docs-ingest is not installed (set SILLYBOT_DOCS_INGEST)".into()); + }; + let Some(reconcile_bin) = find_tool("SILLYBOT_RECONCILE", "reconcile") else { + return Outcome::NotRun("reconcile is not installed (set SILLYBOT_RECONCILE)".into()); + }; + match scan_with(req, &ingest_bin, &reconcile_bin, &clock) { + Ok(o) => o, + Err(e) => Outcome::Error(e), + } +} + +fn scan_with( + req: &Request, + ingest_bin: &Path, + reconcile_bin: &Path, + clock: &Clock, +) -> Result { + let tmpdir = tempfile::Builder::new() + .prefix("sillybot-") + .tempdir() + .map_err(|e| format!("cannot make a temporary directory: {e}"))?; + let tmp = tmpdir.path(); + + let repo = match &req.repo { + Some(r) if valid_repo(r) => r.clone(), + Some(r) => return Err(format!("--repo {r:?} is not OWNER/NAME")), + None => git_text( + &req.path, + &["config", "--get", "remote.origin.url"], + tmp, + clock, + ) + .ok() + .and_then(|u| repo_from_url(&u)) + .ok_or("no --repo given and the origin remote does not name OWNER/NAME")?, + }; + + let head = resolve(&req.path, "HEAD", tmp, clock)?; + let base = match &req.base { + Some(b) => Some(resolve(&req.path, b, tmp, clock)?), + None => None, + }; + + if let Some(b) = &base { + let changed = nul_names(&git_text( + &req.path, + &["diff", "--no-renames", "--name-only", "-z", b, &head], + tmp, + clock, + )?)?; + if !changed.iter().any(|n| is_prose(n)) { + return Ok(Outcome::NotRun(format!( + "no prose file changed between {} and {}", + &b[..12], + &head[..12] + ))); + } + } + + let head_json = ingest(&req.path, ingest_bin, &repo, &head, "head", tmp, clock)?; + let base_json = match &base { + Some(b) => Some(ingest(&req.path, ingest_bin, &repo, b, "base", tmp, clock)?), + None => None, + }; + + let mut c = Command::new(reconcile_bin); + c.arg("--head").arg(&head_json); + if let Some(b) = &base_json { + c.arg("--base").arg(b); + } + c.arg("--pr").arg(OsString::from(req.pr.to_string())); + let out = run(c, tmp, "reconcile", clock)?; + let doc: Value = + serde_json::from_slice(&out).map_err(|e| format!("reconcile: output is not JSON: {e}"))?; + Ok(Outcome::Ran(doc)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prose_matches_docs_ingest_formats() { + for p in ["README.adoc", "a/b.md", "x.MARKDOWN", "y.asc", "z.asciidoc"] { + assert!(is_prose(p), "{p}"); + } + for p in ["src/main.rs", "README", "md", "a.mdx"] { + assert!(!is_prose(p), "{p}"); + } + } + + #[test] + fn repo_names_from_remotes() { + assert_eq!( + repo_from_url("https://github.com/hyperpolymath/docudactyl.git").as_deref(), + Some("hyperpolymath/docudactyl") + ); + assert_eq!( + repo_from_url("git@github.com:hyperpolymath/gitbot-fleet").as_deref(), + Some("hyperpolymath/gitbot-fleet") + ); + assert_eq!(repo_from_url("nothing"), None); + assert!(!valid_repo("a/b/c")); + assert!(!valid_repo("../b")); + assert!(!valid_repo("a b/c")); + } + + #[test] + fn names_with_line_breaks_are_refused() { + assert_eq!(nul_names("a.md\0b.md\0").unwrap(), vec!["a.md", "b.md"]); + assert!(nul_names("a\nb.md\0").is_err()); + } +} diff --git a/bots/sillybot/src/translator.rs b/bots/sillybot/src/translator.rs new file mode 100644 index 00000000..2b864c3a --- /dev/null +++ b/bots/sillybot/src/translator.rs @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Translate findings/v0 (reconcile's output) into the fleet's finding shape. +//! +//! Mapping (sillybot spec v0): +//! - `path` to `file` (repo-relative, no `./`); every finding carries one, +//! - `span.start.line` to `line`, +//! - `class` to `rule_id` as `SB-`, +//! - `severity` unchanged (`error`, `warning`, `info`), +//! - `message` unchanged, +//! - an inherited finding (`introduced: false`) is capped at `info`, so the +//! grid's change-scope grading never blocks on it. Its own severity stays in +//! `reconcile_severity`. +//! +//! A report that does not match this shape is rejected as a whole: one bad +//! finding means the report is not trusted, so nothing is silently dropped. + +use serde::Serialize; +use serde_json::Value; + +/// One finding as printed on stdout. +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +pub struct Finding { + pub rule_id: String, + /// Fleet word the grid grades: `error`, `warning` or `info`. + pub severity: String, + /// reconcile's own severity, unchanged. + pub reconcile_severity: String, + pub file: String, + pub line: u64, + pub message: String, + /// False when the finding was already present at the base revision. + pub introduced: bool, + /// True only for an introduced `error`. + pub blocking: bool, + /// reconcile's stable finding id. + pub id: String, +} + +fn str_field<'a>(v: &'a Value, key: &str, i: usize) -> Result<&'a str, String> { + v.get(key) + .and_then(Value::as_str) + .ok_or_else(|| format!("finding {i}: missing string field '{key}'")) +} + +/// A safe repo-relative path: not empty, not absolute, no `..` or empty +/// component, no control characters. A leading `./` is dropped. +fn clean_path(p: &str) -> Option { + let p = p.strip_prefix("./").unwrap_or(p); + if p.is_empty() || p.starts_with('/') || p.chars().any(char::is_control) { + return None; + } + if p.split('/').any(|c| c.is_empty() || c == "." || c == "..") { + return None; + } + Some(p.to_string()) +} + +/// Translate a whole findings/v0 document. +pub fn translate_report(report: &Value) -> Result, String> { + let list = report + .get("findings") + .and_then(Value::as_array) + .ok_or("reconcile output has no 'findings' array")?; + list.iter() + .enumerate() + .map(|(i, f)| translate_one(f, i)) + .collect() +} + +fn translate_one(f: &Value, i: usize) -> Result { + let class = str_field(f, "class", i)?; + if class.is_empty() + || !class + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + { + return Err(format!( + "finding {i}: class '{class}' is not a lowercase slug" + )); + } + let sev = str_field(f, "severity", i)?; + if !matches!(sev, "error" | "warning" | "info") { + return Err(format!("finding {i}: unknown severity '{sev}'")); + } + let file = clean_path(str_field(f, "path", i)?) + .ok_or_else(|| format!("finding {i}: path is not a safe repo-relative path"))?; + let line = f + .pointer("/span/start/line") + .and_then(Value::as_u64) + .filter(|&l| l >= 1) + .ok_or_else(|| format!("finding {i}: span.start.line must be a positive integer"))?; + let message = str_field(f, "message", i)?.to_string(); + let introduced = f + .get("introduced") + .and_then(Value::as_bool) + .ok_or_else(|| format!("finding {i}: missing boolean field 'introduced'"))?; + let id = str_field(f, "id", i)?.to_string(); + let severity = if introduced { sev } else { "info" }; + Ok(Finding { + rule_id: format!("SB-{class}"), + severity: severity.to_string(), + reconcile_severity: sev.to_string(), + file, + line, + message, + introduced, + blocking: introduced && sev == "error", + id, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn finding(introduced: bool, sev: &str, path: &str) -> Value { + json!({ + "class": "dead-internal-link", "severity": sev, "path": path, + "span": {"start": {"line": 5, "col": 1}, "end": {"line": 5, "col": 20}}, + "message": "m", "introduced": introduced, "id": "abc", "tool": "sillybot" + }) + } + + #[test] + fn introduced_error_blocks() { + let out = translate_report(&json!({"findings": [finding(true, "error", "README.adoc")]})) + .unwrap(); + assert_eq!(out[0].rule_id, "SB-dead-internal-link"); + assert_eq!(out[0].severity, "error"); + assert_eq!(out[0].line, 5); + assert!(out[0].blocking); + } + + #[test] + fn inherited_is_capped_at_info() { + let out = translate_report(&json!({"findings": [finding(false, "error", "./docs/a.md")]})) + .unwrap(); + assert_eq!(out[0].severity, "info"); + assert_eq!(out[0].reconcile_severity, "error"); + assert_eq!(out[0].file, "docs/a.md"); + assert!(!out[0].blocking); + } + + #[test] + fn bad_paths_reject_the_report() { + for p in [ + "", + "/etc/passwd", + "../x.md", + "a//b.md", + "a/./b.md", + "a\nb.md", + ] { + assert!( + translate_report(&json!({"findings": [finding(true, "error", p)]})).is_err(), + "{p:?} accepted" + ); + } + } + + #[test] + fn missing_fields_reject_the_report() { + let mut f = finding(true, "error", "a.md"); + f.as_object_mut().unwrap().remove("introduced"); + assert!(translate_report(&json!({"findings": [f]})).is_err()); + assert!(translate_report(&json!({"findings": [finding(true, "fatal", "a.md")]})).is_err()); + assert!(translate_report(&json!({})).is_err()); + } +} diff --git a/bots/sillybot/tests/adapter_test.rs b/bots/sillybot/tests/adapter_test.rs new file mode 100644 index 00000000..af0e7e3d --- /dev/null +++ b/bots/sillybot/tests/adapter_test.rs @@ -0,0 +1,266 @@ +// SPDX-License-Identifier: MPL-2.0 +//! End-to-end tests of the sillybot binary with stub tools. +//! +//! The stubs stand in for docs-ingest and reconcile so these tests need +//! neither Zig toolchain. They check the exit-code and JSON contract, the +//! base handling, and that the scanned tree is left untouched. + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const BIN: &str = env!("CARGO_BIN_EXE_sillybot"); + +fn sh(dir: &Path, args: &[&str]) { + let st = Command::new("git") + .arg("-C") + .arg(dir) + .args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"]) + .args(["-c", "commit.gpgsign=false"]) + .args(args) + .output() + .expect("git runs"); + assert!(st.status.success(), "git {args:?}: {st:?}"); +} + +/// A repo with README.adoc and src/a.rs, origin set to a GitHub URL. +fn repo() -> tempfile::TempDir { + let d = tempfile::tempdir().unwrap(); + sh(d.path(), &["init", "-q", "-b", "main"]); + fs::write(d.path().join("README.adoc"), "= T\n\nlink:gone.adoc[x]\n").unwrap(); + fs::create_dir(d.path().join("src")).unwrap(); + fs::write(d.path().join("src/a.rs"), "fn main() {}\n").unwrap(); + sh(d.path(), &["add", "."]); + sh(d.path(), &["commit", "-q", "-m", "one"]); + sh( + d.path(), + &[ + "remote", + "add", + "origin", + "https://github.com/acme/widgets.git", + ], + ); + d +} + +fn head(dir: &Path) -> String { + let o = Command::new("git") + .arg("-C") + .arg(dir) + .args(["rev-parse", "HEAD"]) + .output() + .unwrap(); + String::from_utf8(o.stdout).unwrap().trim().to_string() +} + +fn script(dir: &Path, name: &str, body: &str) -> PathBuf { + let p = dir.join(name); + fs::write( + &p, + format!("#!/usr/bin/env bash\nset -euo pipefail\n{body}\n"), + ) + .unwrap(); + fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap(); + p +} + +/// Stub docs-ingest: checks its arguments, records them, prints a bundle. +fn stub_ingest(tools: &Path) -> PathBuf { + let log = tools.join("ingest.log"); + script( + tools, + "docs-ingest", + &format!( + r#"echo "$@" >> '{}' +[[ "$1" == --repo && "$3" == --rev && "$5" == --root && "$7" == --files ]] +test -f "$6/README.adoc" +grep -qx README.adoc "$8" +echo '{{"schema":"reconcile-input/v0","repo":"'"$2"'","rev":"'"$4"'","files":[],"docs":[]}}'"#, + log.display() + ), + ) +} + +const FINDINGS: &str = r#"{"findings":[ + {"class":"dead-internal-link","severity":"error","path":"README.adoc", + "span":{"start":{"line":3,"col":1},"end":{"line":3,"col":18}}, + "message":"Link target 'gone.adoc' is not in the repository.", + "introduced":true,"id":"f1","tool":"sillybot","evidence":[]}, + {"class":"dead-anchor","severity":"warning","path":"README.adoc", + "span":{"start":{"line":1,"col":1},"end":{"line":1,"col":3}}, + "message":"old","introduced":false,"id":"f2","tool":"sillybot","evidence":[]}]}"#; + +fn stub_reconcile(tools: &Path, body: &str) -> PathBuf { + script(tools, "reconcile", body) +} + +fn run(dir: &Path, ingest: Option<&Path>, reconcile: Option<&Path>, extra: &[&str]) -> Output { + let mut c = Command::new(BIN); + c.args(["--format", "json", "scan", "--path"]) + .arg(dir) + .args(extra); + c.env("PATH", "/usr/bin:/bin"); + match ingest { + Some(p) => c.env("SILLYBOT_DOCS_INGEST", p), + None => c.env("SILLYBOT_DOCS_INGEST", "/nonexistent/docs-ingest"), + }; + match reconcile { + Some(p) => c.env("SILLYBOT_RECONCILE", p), + None => c.env("SILLYBOT_RECONCILE", "/nonexistent/reconcile"), + }; + c.output().unwrap() +} + +fn json(o: &Output) -> serde_json::Value { + serde_json::from_slice(&o.stdout).unwrap_or_else(|e| panic!("{e}: {o:?}")) +} + +/// Every file under `dir` with its contents, .git included. +fn snapshot(dir: &Path) -> Vec<(PathBuf, Vec)> { + let mut out = Vec::new(); + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + for e in fs::read_dir(&d).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + stack.push(p); + } else { + out.push((p.clone(), fs::read(&p).unwrap())); + } + } + } + out.sort(); + out +} + +#[test] +fn missing_tool_is_not_run() { + let r = repo(); + let o = run(r.path(), None, None, &[]); + assert_eq!(o.status.code(), Some(3)); + assert_eq!(json(&o)["status"], "not_run"); +} + +#[test] +fn ran_maps_findings_and_leaves_the_tree_alone() { + let r = repo(); + let tools = tempfile::tempdir().unwrap(); + let ing = stub_ingest(tools.path()); + let rec = stub_reconcile( + tools.path(), + &format!("[[ \"$1\" == --head ]]\ncat <<'J'\n{FINDINGS}\nJ"), + ); + let before = snapshot(r.path()); + let o = run(r.path(), Some(&ing), Some(&rec), &[]); + assert_eq!(o.status.code(), Some(1), "{o:?}"); + let v = json(&o); + assert_eq!(v[0]["rule_id"], "SB-dead-internal-link"); + assert_eq!(v[0]["severity"], "error"); + assert_eq!(v[0]["file"], "README.adoc"); + assert_eq!(v[0]["line"], 3); + assert_eq!(v[1]["severity"], "info"); + assert_eq!(v[1]["reconcile_severity"], "warning"); + assert_eq!(before, snapshot(r.path()), "scanned tree changed"); + let log = fs::read_to_string(tools.path().join("ingest.log")).unwrap(); + assert!(log.contains("--repo acme/widgets"), "{log}"); + assert!(log.contains(&head(r.path())), "{log}"); +} + +#[test] +fn base_without_prose_change_is_not_run() { + let r = repo(); + let base = head(r.path()); + fs::write(r.path().join("src/a.rs"), "fn main() { }\n").unwrap(); + sh(r.path(), &["commit", "-qam", "code only"]); + let tools = tempfile::tempdir().unwrap(); + let ing = stub_ingest(tools.path()); + let rec = stub_reconcile(tools.path(), "exit 9"); + let o = run(r.path(), Some(&ing), Some(&rec), &["--base", &base]); + assert_eq!(o.status.code(), Some(3), "{o:?}"); + assert_eq!(json(&o)["status"], "not_run"); +} + +#[test] +fn base_with_prose_change_passes_both_bundles() { + let r = repo(); + let base = head(r.path()); + fs::write(r.path().join("README.adoc"), "= T\n\nchanged\n").unwrap(); + sh(r.path(), &["commit", "-qam", "docs"]); + let tools = tempfile::tempdir().unwrap(); + let ing = stub_ingest(tools.path()); + let rec = stub_reconcile( + tools.path(), + "[[ \"$1\" == --head && \"$3\" == --base && \"$5\" == --pr && \"$6\" == 7 ]]\necho '{\"findings\":[]}'", + ); + let o = run( + r.path(), + Some(&ing), + Some(&rec), + &["--base", &base, "--pr", "7"], + ); + assert_eq!(o.status.code(), Some(0), "{o:?}"); + assert_eq!(json(&o), serde_json::json!([])); + let log = fs::read_to_string(tools.path().join("ingest.log")).unwrap(); + assert!(log.contains(&base), "base not ingested: {log}"); +} + +#[test] +fn tool_failure_is_an_error_not_a_pass() { + let r = repo(); + let tools = tempfile::tempdir().unwrap(); + let ing = stub_ingest(tools.path()); + let rec = stub_reconcile(tools.path(), "echo boom >&2; exit 2"); + let o = run(r.path(), Some(&ing), Some(&rec), &[]); + assert_eq!(o.status.code(), Some(2)); + let v = json(&o); + assert_eq!(v["status"], "error"); + assert!(v["reason"].as_str().unwrap().contains("boom")); +} + +#[test] +fn unusable_output_is_an_error() { + let r = repo(); + let tools = tempfile::tempdir().unwrap(); + let ing = stub_ingest(tools.path()); + for body in [ + "echo not-json", + "echo '{}'", + r#"echo '{"findings":[{"class":"x"}]}'"#, + ] { + let rec = stub_reconcile(tools.path(), body); + let o = run(r.path(), Some(&ing), Some(&rec), &[]); + assert_eq!(o.status.code(), Some(2), "{body}: {o:?}"); + assert_eq!(json(&o)["status"], "error"); + } +} + +#[test] +fn bad_base_and_repo_are_errors() { + let r = repo(); + let tools = tempfile::tempdir().unwrap(); + let ing = stub_ingest(tools.path()); + let rec = stub_reconcile(tools.path(), "echo '{\"findings\":[]}'"); + for extra in [ + &["--base", "--upload-pack=x"][..], + &["--base", "nope"][..], + &["--repo", "a/b/c"][..], + ] { + let o = run(r.path(), Some(&ing), Some(&rec), extra); + assert_eq!(o.status.code(), Some(2), "{extra:?}: {o:?}"); + } +} + +#[test] +fn timeout_is_an_error() { + let r = repo(); + let tools = tempfile::tempdir().unwrap(); + let ing = stub_ingest(tools.path()); + let rec = stub_reconcile(tools.path(), "sleep 30"); + let start = std::time::Instant::now(); + let o = run(r.path(), Some(&ing), Some(&rec), &["--timeout", "1"]); + assert_eq!(o.status.code(), Some(2)); + assert!(json(&o)["reason"].as_str().unwrap().contains("timed out")); + assert!(start.elapsed().as_secs() < 10); +}