diff --git a/.claude/skills/run-pre-commit-checks/SKILL.md b/.claude/skills/run-pre-commit-checks/SKILL.md index b44b4b70aa..5190779458 100644 --- a/.claude/skills/run-pre-commit-checks/SKILL.md +++ b/.claude/skills/run-pre-commit-checks/SKILL.md @@ -78,12 +78,16 @@ The script runs these steps in order: 5. `cargo run --quiet --package frontmatter-validator --bin frontmatter-validator -- --skill-descriptions` - check of each skill's `description` in the index: whole as YAML reads it (not cut by a `#` comment) and 200 characters or less. See the `add-new-skill` skill's description rules. -6. `cargo machete --with-metadata` - unused dependency check -7. `cargo deny check bans` - workspace layer-boundary dependency check -8. `cargo +nightly fmt --all -- --check` - nightly Rust formatting check -9. `linter all` - all linters (markdown, lychee local links, YAML, TOML, clippy, rustfmt, shellcheck, cspell) -10. `./contrib/dev-tools/checks/lint-containerfile.sh` - hadolint check of the `Containerfile` -11. `cargo test --doc --workspace` - documentation tests +6. `cargo run --quiet --package agent-reply-validator --bin agent-reply-validator -- --all` - + check of the staged content of every agent reply file in the index: every file in an + `agent-replies/` folder or named like a reply file. See the `agent-reply-v1` schema in + `docs/schemas/README.md`. +7. `cargo machete --with-metadata` - unused dependency check +8. `cargo deny check bans` - workspace layer-boundary dependency check +9. `cargo +nightly fmt --all -- --check` - nightly Rust formatting check +10. `linter all` - all linters (markdown, lychee local links, YAML, TOML, clippy, rustfmt, shellcheck, cspell) +11. `./contrib/dev-tools/checks/lint-containerfile.sh` - hadolint check of the `Containerfile` +12. `cargo test --doc --workspace` - documentation tests If the formatter changes the dictionary, the hook exits non-zero before the verification steps. Stage `project-words.txt` and retry the commit. Run the formatter independently with: diff --git a/.dockerignore b/.dockerignore index dc032bc40d..bd4a2513e9 100644 --- a/.dockerignore +++ b/.dockerignore @@ -37,6 +37,7 @@ # never compiled into container test archives. Remove each entry when the crate # leaves the tracker workspace (EPIC #2003 harness-workspace sub-issue). !/contrib/dev-tools/analysis/workspace-coupling/ +!/contrib/dev-tools/checks/agent-reply-validator/ !/contrib/dev-tools/checks/agent-review-report-contract/ !/contrib/dev-tools/checks/ci-gate/ !/contrib/dev-tools/checks/clippy-allow-reasons/ diff --git a/.github/workflows/docs-lint.yaml b/.github/workflows/docs-lint.yaml index ecf3884612..c72a303d4d 100644 --- a/.github/workflows/docs-lint.yaml +++ b/.github/workflows/docs-lint.yaml @@ -81,3 +81,11 @@ jobs: - id: skill-descriptions name: Check Agent Skill Descriptions run: cargo run --quiet --package frontmatter-validator --bin frontmatter-validator -- --skill-descriptions + + # issue: #2904 + # Agents write one JSON reply file per reply in `agent-replies/` of an issue specification + # (D18). The check validates every such file: its place, its name, its content against the + # `agent-reply-v1` schema, and that the name agrees with the content. + - id: agent-replies + name: Check Agent Reply Files + run: cargo run --quiet --package agent-reply-validator --bin agent-reply-validator -- --all diff --git a/Cargo.lock b/Cargo.lock index 53d00ee43f..90cd2895f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,6 +8,21 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "agent-reply-validator" +version = "0.1.0" +dependencies = [ + "clap", + "regex", + "rstest", + "schemars 1.2.3", + "serde", + "serde_json", + "serde_path_to_error", + "tempfile", + "thiserror 2.0.21", +] + [[package]] name = "agent-review-report-contract" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 0e029f5f53..3adbfaeca6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -147,6 +147,7 @@ members = [ ".claude/skills/wait-for-pr-review/tool", "console/tracker-client", "contrib/dev-tools/analysis/workspace-coupling", + "contrib/dev-tools/checks/agent-reply-validator", "contrib/dev-tools/checks/agent-review-report-contract", "contrib/dev-tools/checks/ci-gate", "contrib/dev-tools/checks/clippy-allow-reasons", diff --git a/contrib/dev-tools/checks/agent-reply-validator/Cargo.toml b/contrib/dev-tools/checks/agent-reply-validator/Cargo.toml new file mode 100644 index 0000000000..b6b401a9df --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/Cargo.toml @@ -0,0 +1,28 @@ +[package] +description = "Validates the JSON reply files that AI agents write in agent-replies/ folders." +name = "agent-reply-validator" +publish = false + +authors.workspace = true +edition.workspace = true +rust-version.workspace = true +version = "0.1.0" + +[lints] +workspace = true + +[dependencies] +# No color or suggestion features: every clap message is rendered into an NDJSON record. +clap = { version = "4.6.8", default-features = false, features = [ "derive", "error-context", "help", "std", "usage" ] } +schemars = "1.2.3" +serde = { version = "1", features = [ "derive" ] } +# Keep field order: the NDJSON key order is part of the output contract. +serde_json = { version = "1", features = [ "preserve_order" ] } +serde_path_to_error = "0.1.20" +thiserror = "2" + +[dev-dependencies] +# Checks that the schema patterns accept and reject the same samples as the Rust checks. +regex = "1.13.2" +rstest = "0.28.0" +tempfile = "3" diff --git a/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-schema.rs b/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-schema.rs new file mode 100644 index 0000000000..c60e13145e --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-schema.rs @@ -0,0 +1,49 @@ +//! Writes the `agent-reply-v1` JSON Schema to its tracked path. +//! +//! Run `cargo run --package agent-reply-validator --bin agent-reply-schema`. The file is written +//! in the repository this crate was built from, whatever the working directory. The test +//! `tests/schema.rs` fails when the tracked file differs from the model, so a model change cannot +//! be pushed with a stale schema. +//! +//! Output class `no-stdout-result`: stdout stays empty; one NDJSON record goes to stderr; exit +//! codes are `0` when the file is written, `1` when it cannot be, and `2` for any argument. + +use std::io::{self, Write}; +use std::path::Path; +use std::process::ExitCode; +use std::{env, fs}; + +use agent_reply_validator::schema::{ARTIFACT_PATH, reply_schema_json}; +use serde_json::json; + +fn main() -> ExitCode { + let (record, exit_code) = if env::args_os().len() > 1 { + ( + json!({ + "kind": "usage_error", + "message": "agent-reply-schema takes no arguments", + "exit_code": 2 + }), + 2, + ) + } else { + let artifact = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../..").join(ARTIFACT_PATH); + match fs::write(artifact, reply_schema_json()) { + Ok(()) => (json!({ "kind": "written", "path": ARTIFACT_PATH }), 0), + Err(error) => ( + json!({ + "kind": "runtime_error", + "path": ARTIFACT_PATH, + "message": error.to_string(), + "exit_code": 1 + }), + 1, + ), + } + }; + let mut stderr = io::stderr().lock(); + match writeln!(stderr, "{record}") { + Ok(()) => ExitCode::from(exit_code), + Err(_) => ExitCode::FAILURE, + } +} diff --git a/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-validator/git.rs b/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-validator/git.rs new file mode 100644 index 0000000000..4c93dde7a8 --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-validator/git.rs @@ -0,0 +1,109 @@ +//! Read-only access to the repository that contains the working directory. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// A git repository, addressed by its top-level directory. +#[derive(Debug)] +pub struct Git { + root: PathBuf, +} + +impl Git { + /// Finds the repository that contains `working_directory`. + pub fn discover(working_directory: &Path) -> Result { + let output = run_git(working_directory, &["rev-parse", "--show-toplevel"])?; + let root = String::from_utf8(output).map_err(|error| format!("`git rev-parse` output was not UTF-8: {error}"))?; + + Ok(Self { + root: PathBuf::from(root.trim_end_matches('\n')), + }) + } + + pub fn root(&self) -> &Path { + &self.root + } + + /// The entries of the index: each file's mode and its repository-relative path, as git + /// stores them. The path is bytes, because it need not be UTF-8. + pub fn index_entries(&self) -> Result, String> { + let output = run_git(&self.root, &["ls-files", "--stage", "-z"])?; + output + .split(|byte| *byte == 0) + .filter(|entry| !entry.is_empty()) + .map(IndexEntry::parse) + .collect() + } + + /// The content of a repository-relative path in the index. + pub fn index_content(&self, path: &str) -> Result, String> { + run_git(&self.root, &["show", &format!(":0:{path}")]) + } +} + +/// One entry of `git ls-files --stage -z`: ` \t`. +#[derive(Debug)] +pub struct IndexEntry { + pub mode: String, + pub path: Vec, +} + +impl IndexEntry { + /// The mode git gives a symbolic link. + const SYMBOLIC_LINK_MODE: &'static str = "120000"; + + fn parse(entry: &[u8]) -> Result { + let tab = entry + .iter() + .position(|byte| *byte == b'\t') + .ok_or_else(|| "`git ls-files --stage` printed an entry without a tab".to_owned())?; + let (fields, path) = (&entry[..tab], &entry[tab + 1..]); + let mode = fields + .split(|byte| *byte == b' ') + .next() + .and_then(|mode| std::str::from_utf8(mode).ok()) + .ok_or_else(|| "`git ls-files --stage` printed an entry without a mode".to_owned())?; + Ok(Self { + mode: mode.to_owned(), + path: path.to_vec(), + }) + } + + pub fn is_symbolic_link(&self) -> bool { + self.mode == Self::SYMBOLIC_LINK_MODE + } +} + +/// Variables that can redirect a Git subprocess to a different repository. +/// +/// `GIT_INDEX_FILE` is kept: a pre-commit hook receives it for the index `commit --all`/`--only` prepared. +const GIT_REPOSITORY_REDIRECT_ENVIRONMENT: &[&str] = &[ + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_COMMON_DIR", +]; + +/// `--no-optional-locks` keeps read commands from refreshing the index; `--literal-pathspecs` keeps +/// names from being expanded as globs. +fn run_git(directory: &Path, arguments: &[&str]) -> Result, String> { + let mut command = Command::new("git"); + command.args(["--no-optional-locks", "--literal-pathspecs"]); + command.args(arguments); + command.current_dir(directory); + for variable in GIT_REPOSITORY_REDIRECT_ENVIRONMENT { + command.env_remove(variable); + } + let output = command.output().map_err(|error| format!("could not run `git`: {error}"))?; + + if output.status.success() { + Ok(output.stdout) + } else { + Err(format!( + "`git {}` failed: {}", + arguments.join(" "), + String::from_utf8_lossy(&output.stderr).trim() + )) + } +} diff --git a/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-validator/main.rs b/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-validator/main.rs new file mode 100644 index 0000000000..1cee4befc8 --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-validator/main.rs @@ -0,0 +1,283 @@ +//! Checks agent reply files and reports NDJSON records on stderr. +//! +//! Output class `no-stdout-result`: stdout stays empty; exit codes are `0` when every file is +//! valid, `1` for an invalid file or a runtime failure, and `2` for invalid invocation. + +mod git; +mod record; + +use std::ffi::OsString; +use std::io::{self, Write}; +use std::path::{Component, Path, PathBuf}; +use std::process::ExitCode; +use std::{env, fs}; + +use agent_reply_validator::file::{check_reply_file, is_reply_file_candidate}; +use clap::error::ErrorKind; +use clap::{ArgGroup, Parser}; +use git::Git; +use record::{EXIT_FAILURE, EXIT_SUCCESS, EXIT_USAGE, Record, emit}; + +/// The message for a reply file that is a symbolic link, in either mode. +const SYMBOLIC_LINK: &str = "the file is a symbolic link; a reply file must be a regular file"; + +/// Check agent reply files: their place, name and content, and that the name agrees with the +/// content. +/// +/// There is no `--version`: the tool is built from the workspace it checks, so `--version` is a +/// usage error, exit 2, like any other unknown argument. +#[derive(Debug, Parser)] +#[command( + name = "agent-reply-validator", + group(ArgGroup::new("mode").required(true).args(["paths", "all"])) +)] +struct Arguments { + /// Reply files to check as they are on disk, whatever their names. + paths: Vec, + /// Check, as staged, every file in the index that is in an `agent-replies` folder or is + /// named like a reply file. + #[arg(long)] + all: bool, +} + +fn main() -> ExitCode { + let working_directory = env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + let mut stderr = io::stderr().lock(); + ExitCode::from(run(env::args_os(), &working_directory, &mut stderr)) +} + +/// Runs the command with the program name as the first argument and returns its exit code. +fn run(arguments: impl IntoIterator, working_directory: &Path, stderr: &mut impl Write) -> u8 { + let (records, exit_code) = match Arguments::try_parse_from(arguments) { + Ok(arguments) => match Git::discover(working_directory) { + Ok(git) if arguments.all => check_index(&git), + Ok(git) => check_paths(&git, working_directory, &arguments.paths), + Err(message) => (vec![Record::runtime_error(None, message)], EXIT_FAILURE), + }, + Err(error) if error.kind() == ErrorKind::DisplayHelp => ( + vec![Record::Help { + message: error.to_string().trim_end().to_owned(), + }], + EXIT_SUCCESS, + ), + Err(error) => (vec![Record::usage_error(error.to_string().trim_end())], EXIT_USAGE), + }; + + match emit(&records, stderr) { + Ok(()) => exit_code, + Err(_) => EXIT_FAILURE, + } +} + +/// Checks the staged content of every candidate in the index, so a commit is checked as it will +/// be made. A candidate with merge conflicts has no staged content, so the run stops there with +/// a runtime error. A candidate staged as a symbolic link is rejected, as in path mode: its staged +/// content is the link's target path, not a reply. +fn check_index(git: &Git) -> (Vec, u8) { + let entries = match git.index_entries() { + Ok(entries) => entries, + Err(message) => return (vec![Record::runtime_error(None, message)], EXIT_FAILURE), + }; + let mut checked = Vec::new(); + for entry in entries { + let is_symbolic_link = entry.is_symbolic_link(); + let path = match String::from_utf8(entry.path) { + Ok(path) if is_reply_file_candidate(&path) => path, + Ok(_) => continue, + Err(error) => { + let lossy = String::from_utf8_lossy(error.as_bytes()).into_owned(); + if !is_reply_file_candidate(&lossy) { + continue; + } + return ( + vec![Record::runtime_error(Some(lossy), "the path is not valid UTF-8")], + EXIT_FAILURE, + ); + } + }; + if is_symbolic_link { + return (vec![Record::runtime_error(Some(path), SYMBOLIC_LINK)], EXIT_FAILURE); + } + match git.index_content(&path).map(String::from_utf8) { + Ok(Ok(text)) => checked.push((path, text)), + Ok(Err(_)) => { + return ( + vec![Record::runtime_error(Some(path), "the file is not valid UTF-8")], + EXIT_FAILURE, + ); + } + Err(message) => return (vec![Record::runtime_error(Some(path), message)], EXIT_FAILURE), + } + } + report(&checked) +} + +/// Checks the given files as they are on disk; every one is checked, whatever its name. +/// +/// A symbolic link is rejected: git stores a link as its target's path, so `--all` would read +/// that path, not the content behind it, and the two modes would disagree. +fn check_paths(git: &Git, working_directory: &Path, paths: &[PathBuf]) -> (Vec, u8) { + let root = match fs::canonicalize(git.root()) { + Ok(root) => root, + Err(error) => return (vec![Record::runtime_error(None, error.to_string())], EXIT_FAILURE), + }; + let mut checked = Vec::new(); + for path in paths { + let shown = Some(path.display().to_string()); + let file = working_directory.join(path); + if fs::symlink_metadata(&file).is_ok_and(|metadata| metadata.file_type().is_symlink()) { + return (vec![Record::runtime_error(shown, SYMBOLIC_LINK)], EXIT_FAILURE); + } + let relative = match file.parent().zip(file.file_name()) { + Some((folder, name)) => fs::canonicalize(folder) + .map_err(|error| error.to_string()) + .and_then(|folder| repository_relative(&root, &folder.join(name)).map_err(str::to_owned)), + None => Err("the path does not name a file".to_owned()), + }; + let relative = match relative { + Ok(relative) => relative, + Err(message) => return (vec![Record::runtime_error(shown, message)], EXIT_FAILURE), + }; + match fs::read(&file).map(String::from_utf8) { + Ok(Ok(text)) => checked.push((relative, text)), + Ok(Err(_)) => { + return ( + vec![Record::runtime_error(shown, "the file is not valid UTF-8")], + EXIT_FAILURE, + ); + } + Err(error) => return (vec![Record::runtime_error(shown, error.to_string())], EXIT_FAILURE), + } + } + report(&checked) +} + +/// The records of every problem in the checked files, a summary, and the exit code. +fn report(files: &[(String, String)]) -> (Vec, u8) { + let mut records: Vec = files + .iter() + .flat_map(|(path, text)| { + check_reply_file(path, text) + .into_iter() + .map(|problem| Record::problem(path, problem)) + }) + .collect(); + let problems = records.len(); + records.push(Record::Summary { + files: files.len(), + problems, + }); + (records, if problems == 0 { EXIT_SUCCESS } else { EXIT_FAILURE }) +} + +/// The path of `file` relative to `root`, with `/` separators. `root` is canonical, and so is +/// the folder of `file`. +fn repository_relative(root: &Path, file: &Path) -> Result { + let inside = file.strip_prefix(root).map_err(|_| "the file is not inside the repository")?; + inside + .components() + .map(|component| match component { + Component::Normal(part) => part.to_str().ok_or("the path is not valid UTF-8"), + _ => Err("the file is not inside the repository"), + }) + .collect::, _>>() + .map(|parts| parts.join("/")) +} + +#[cfg(test)] +mod tests { + use std::io::{self, Write}; + use std::path::Path; + + use super::{EXIT_FAILURE, EXIT_SUCCESS, Record, report, repository_relative, run}; + + /// A stderr that refuses every write. + struct FailingWriter; + + impl Write for FailingWriter { + fn write(&mut self, _: &[u8]) -> io::Result { + Err(io::Error::other("stderr is closed")) + } + + fn flush(&mut self) -> io::Result<()> { + Err(io::Error::other("stderr is closed")) + } + } + + #[test] + fn it_should_exit_one_when_the_records_cannot_be_written() { + // Act: `--help` succeeds on its own, so only the failed write can make the run fail. + let exit_code = run( + ["agent-reply-validator", "--help"].map(Into::into), + Path::new("."), + &mut FailingWriter, + ); + + // Assert + assert_eq!(exit_code, EXIT_FAILURE); + } + + #[test] + fn it_should_report_only_an_empty_summary_and_succeed_when_no_file_is_checked() { + // Act + let (records, exit_code) = report(&[]); + + // Assert + assert_eq!(exit_code, EXIT_SUCCESS); + assert!(matches!(records.as_slice(), [Record::Summary { files: 0, problems: 0 }])); + } + + #[test] + fn it_should_report_each_problem_then_the_summary_and_fail_when_a_file_is_invalid() { + // Arrange + let files = [("notes.md".to_owned(), "{}".to_owned())]; + + // Act + let (records, exit_code) = report(&files); + + // Assert: the location, the name and the content of `notes.md` are all wrong. + assert_eq!(exit_code, EXIT_FAILURE); + assert!(matches!( + records.as_slice(), + [ + Record::Problem { .. }, + Record::Problem { .. }, + Record::Problem { .. }, + Record::Summary { files: 1, problems: 3 } + ] + )); + } + + #[test] + fn it_should_join_the_parts_with_slashes_when_the_file_is_inside_the_root() { + // Act + let relative = repository_relative(Path::new("/repo"), Path::new("/repo/docs/agent-replies/x.json")); + + // Assert + assert_eq!(relative, Ok("docs/agent-replies/x.json".to_owned())); + } + + #[test] + fn it_should_reject_the_file_when_it_is_outside_the_root() { + // Act + let relative = repository_relative(Path::new("/repo"), Path::new("/other/x.json")); + + // Assert + assert_eq!(relative, Err("the file is not inside the repository")); + } + + #[cfg(unix)] + #[test] + fn it_should_reject_the_file_when_a_part_of_its_path_is_not_utf8() { + // Arrange + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt; + let file = Path::new("/repo").join(OsStr::from_bytes(b"bad-\xff.json")); + + // Act + let relative = repository_relative(Path::new("/repo"), &file); + + // Assert + assert_eq!(relative, Err("the path is not valid UTF-8")); + } +} diff --git a/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-validator/record.rs b/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-validator/record.rs new file mode 100644 index 0000000000..e70c01f69f --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/src/bin/agent-reply-validator/record.rs @@ -0,0 +1,74 @@ +//! The NDJSON records written to stderr, one JSON object per line. + +use std::io::{self, Write}; + +use agent_reply_validator::file::Problem; +use serde::Serialize; + +pub const EXIT_SUCCESS: u8 = 0; +pub const EXIT_FAILURE: u8 = 1; +pub const EXIT_USAGE: u8 = 2; + +/// One line on stderr. Field order and nullability are the command's output contract. +#[derive(Debug, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Record { + /// One reason a reply file is invalid. + Problem { + path: String, + check: String, + field_path: Option, + message: String, + }, + /// The totals of a run that checked files. + Summary { + files: usize, + problems: usize, + }, + UsageError { + message: String, + exit_code: u8, + }, + RuntimeError { + path: Option, + message: String, + exit_code: u8, + }, + Help { + message: String, + }, +} + +impl Record { + pub fn problem(path: &str, problem: Problem) -> Self { + Self::Problem { + path: path.to_owned(), + check: problem.check.to_string(), + field_path: problem.field_path, + message: problem.message, + } + } + + pub fn usage_error(message: impl Into) -> Self { + Self::UsageError { + message: message.into(), + exit_code: EXIT_USAGE, + } + } + + pub fn runtime_error(path: Option, message: impl Into) -> Self { + Self::RuntimeError { + path, + message: message.into(), + exit_code: EXIT_FAILURE, + } + } +} + +pub fn emit(records: &[Record], stderr: &mut impl Write) -> io::Result<()> { + for record in records { + serde_json::to_writer(&mut *stderr, record)?; + writeln!(stderr)?; + } + stderr.flush() +} diff --git a/contrib/dev-tools/checks/agent-reply-validator/src/file.rs b/contrib/dev-tools/checks/agent-reply-validator/src/file.rs new file mode 100644 index 0000000000..cf5db29494 --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/src/file.rs @@ -0,0 +1,330 @@ +//! The checks of one reply file: where it is, its name, its content, and that the name and the +//! content agree. +//! +//! The checks take the file's repository-relative path and its text, so they read nothing from +//! the disk and every outcome can be tested with plain strings. + +use std::fmt; + +use crate::name::ReplyFileName; +use crate::reply::Reply; + +/// The folder that holds the reply files of one issue specification. +pub const REPLIES_FOLDER: &str = "agent-replies"; + +/// The lifecycle folders of `docs/issues/` that hold issue specifications. +const LIFECYCLE_FOLDERS: [&str; 3] = ["drafts", "open", "closed"]; + +/// One reason a reply file is invalid. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Problem { + /// Which check found it. + pub check: Check, + /// The JSON path of the value at fault, for a problem in the content. + pub field_path: Option, + /// What is wrong. + pub message: String, +} + +/// The checks a reply file goes through. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Check { + /// The file is in the `agent-replies/` folder of an issue specification. + Location, + /// The file name follows `--r.json`. + Name, + /// The content follows the reply format. + Content, + /// The name and the content give the same agent, subject and round. + Agreement, +} + +impl fmt::Display for Check { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::Location => "location", + Self::Name => "name", + Self::Content => "content", + Self::Agreement => "agreement", + }) + } +} + +/// Checks one reply file and returns every problem found; an empty list means the file is valid. +/// +/// `path` is the file's path relative to the repository root, with `/` separators; `text` is +/// its content. The agreement of name and content is checked only when both are valid. +#[must_use] +pub fn check_reply_file(path: &str, text: &str) -> Vec { + let mut problems = Vec::new(); + let (folder, file_name) = path.rsplit_once('/').unwrap_or(("", path)); + + if !is_replies_folder_of_a_specification(folder) { + problems.push(Problem { + check: Check::Location, + field_path: None, + message: format!( + "a reply file must be in `docs/issues/<{}>//{REPLIES_FOLDER}/`", + LIFECYCLE_FOLDERS.join("|") + ), + }); + } + + let name = file_name.parse::().map_err(|error| Problem { + check: Check::Name, + field_path: None, + message: error.to_string(), + }); + let reply = Reply::from_json(text).map_err(|error| Problem { + check: Check::Content, + field_path: Some(error.path), + message: error.message, + }); + + match (name, reply) { + (Ok(name), Ok(reply)) => problems.extend(disagreements(&name, &reply)), + (name, reply) => problems.extend(name.err().into_iter().chain(reply.err())), + } + problems +} + +/// Whether a repository file must pass [`check_reply_file`]. +/// +/// It must when it is in a folder named `agent-replies`, wherever that folder is, or when its name +/// is a reply file name, wherever the file is. So a reply file in the wrong place, and any other +/// file in a replies folder, are reported. +#[must_use] +pub fn is_reply_file_candidate(path: &str) -> bool { + let (folder, file_name) = path.rsplit_once('/').unwrap_or(("", path)); + let folder_name = folder.rsplit('/').next().unwrap_or(folder); + folder_name == REPLIES_FOLDER || file_name.parse::().is_ok() +} + +/// Whether the folder is `docs/issues///agent-replies`. +fn is_replies_folder_of_a_specification(folder: &str) -> bool { + matches!( + folder.split('/').collect::>().as_slice(), + ["docs", "issues", lifecycle, specification, REPLIES_FOLDER] + if LIFECYCLE_FOLDERS.contains(lifecycle) && !matches!(*specification, "" | "." | "..") + ) +} + +/// The fields whose value differs from the file name. +fn disagreements(name: &ReplyFileName, reply: &Reply) -> Vec { + let mismatch = |field: &str, in_name: String, in_content: String| Problem { + check: Check::Agreement, + field_path: Some(field.to_owned()), + message: format!("the file name says `{in_name}` but the field says `{in_content}`"), + }; + let mut problems = Vec::new(); + if name.agent != reply.agent { + problems.push(mismatch("agent", name.agent.to_string(), reply.agent.to_string())); + } + if name.subject != reply.subject { + problems.push(mismatch("subject", name.subject.to_string(), reply.subject.to_string())); + } + if name.round != reply.round { + problems.push(mismatch( + "round", + name.round.number().to_string(), + reply.round.number().to_string(), + )); + } + problems +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + use serde_json::json; + + use super::{Check, Problem, check_reply_file, is_reply_file_candidate}; + + const FOLDER: &str = "docs/issues/open/2904-2003-migrate-custom-agents-to-claude-code/agent-replies"; + + /// A valid reply whose agent, subject and round are the given ones. + fn reply(agent: &str, subject: &str, round: u8) -> String { + json!({ + "schema-version": 1, + "agent": agent, + "model": "claude-opus-5-5", + "subject": subject, + "round": round, + "created-utc": "2026-11-18 17:25", + "verdict": "REVIEW_PASSED", + "summary": "Nothing blocks the task.", + "findings": [], + "questions": [], + "evidence": ["cargo test -q -p agent-reply-validator passed"] + }) + .to_string() + } + + fn checks(problems: &[Problem]) -> Vec { + problems.iter().map(|problem| problem.check).collect() + } + + #[rstest] + #[case::draft("docs/issues/drafts/some-slug/agent-replies")] + #[case::open(FOLDER)] + #[case::closed("docs/issues/closed/2904-2003-migrate-custom-agents-to-claude-code/agent-replies")] + fn it_should_find_no_problem_when_the_file_is_in_a_specification_and_name_and_content_agree(#[case] folder: &str) { + // Arrange + let path = format!("{folder}/task-reviewer-t3-r2.json"); + + // Act + let problems = check_reply_file(&path, &reply("task-reviewer", "t3", 2)); + + // Assert + assert_eq!(problems, vec![]); + } + + #[rstest] + #[case::outside_the_issues("agent-replies/task-reviewer-t3-r2.json")] + #[case::at_the_repository_root("task-reviewer-t3-r2.json")] + #[case::issues_outside_the_documentation("notes/issues/open/2904-slug/agent-replies/task-reviewer-t3-r2.json")] + #[case::folder_with_another_name("docs/issues/open/2904-slug/replies/task-reviewer-t3-r2.json")] + #[case::unknown_lifecycle("docs/issues/archive/2904-slug/agent-replies/task-reviewer-t3-r2.json")] + #[case::directly_in_the_lifecycle_folder("docs/issues/open/agent-replies/task-reviewer-t3-r2.json")] + #[case::empty_specification_folder("docs/issues/open//agent-replies/task-reviewer-t3-r2.json")] + #[case::current_folder_as_specification("docs/issues/open/./agent-replies/task-reviewer-t3-r2.json")] + #[case::parent_folder_as_specification("docs/issues/open/../agent-replies/task-reviewer-t3-r2.json")] + #[case::one_level_too_deep("docs/issues/open/2904-slug/notes/agent-replies/task-reviewer-t3-r2.json")] + #[case::under_another_documentation_folder("docs/refactor-plans/open/a-plan/agent-replies/task-reviewer-t3-r2.json")] + fn it_should_report_only_the_location_when_the_file_is_outside_the_replies_folder_of_a_specification(#[case] path: &str) { + // Act + let problems = check_reply_file(path, &reply("task-reviewer", "t3", 2)); + + // Assert + assert_eq!( + problems, + vec![Problem { + check: Check::Location, + field_path: None, + message: "a reply file must be in `docs/issues///agent-replies/`".to_owned(), + }] + ); + } + + #[test] + fn it_should_report_the_name_and_skip_the_agreement_when_the_name_is_invalid() { + // Arrange + let path = format!("{FOLDER}/task-reviewer-t3-r4.json"); + + // Act + let problems = check_reply_file(&path, &reply("task-reviewer", "t3", 2)); + + // Assert + assert_eq!( + problems, + vec![Problem { + check: Check::Name, + field_path: None, + message: "`4` is not a round: expected a number from 1 to 3, with no leading zero".to_owned(), + }] + ); + } + + #[test] + fn it_should_report_the_content_with_its_path_and_skip_the_agreement_when_the_content_is_invalid() { + // Arrange + let path = format!("{FOLDER}/task-reviewer-t3-r2.json"); + + // Act + let problems = check_reply_file(&path, &reply("task-reviewer", "t3", 9)); + + // Assert: the position at the end of the message depends on the key order, so only the + // reason is compared. + assert_eq!(checks(&problems), vec![Check::Content]); + assert_eq!(problems[0].field_path.as_deref(), Some("round")); + assert!( + problems[0] + .message + .starts_with("invalid value: integer `9`, expected a round number from 1 to 3"), + "unexpected message `{}`", + problems[0].message + ); + } + + #[test] + fn it_should_report_every_problem_when_location_name_and_content_are_all_invalid() { + // Act + let problems = check_reply_file("notes/task-reviewer.json", "{}"); + + // Assert + assert_eq!(checks(&problems), vec![Check::Location, Check::Name, Check::Content]); + } + + #[rstest] + #[case::agent( + reply("implementer", "t3", 2), + "agent", + "the file name says `task-reviewer` but the field says `implementer`" + )] + #[case::subject( + reply("task-reviewer", "pr2942", 2), + "subject", + "the file name says `t3` but the field says `pr2942`" + )] + #[case::round(reply("task-reviewer", "t3", 1), "round", "the file name says `2` but the field says `1`")] + fn it_should_report_the_field_that_disagrees_with_the_name(#[case] text: String, #[case] field: &str, #[case] message: &str) { + // Arrange + let path = format!("{FOLDER}/task-reviewer-t3-r2.json"); + + // Act + let problems = check_reply_file(&path, &text); + + // Assert + assert_eq!( + problems, + vec![Problem { + check: Check::Agreement, + field_path: Some(field.to_owned()), + message: message.to_owned(), + }] + ); + } + + #[test] + fn it_should_report_each_disagreeing_field_when_several_disagree() { + // Arrange + let path = format!("{FOLDER}/task-reviewer-t3-r2.json"); + + // Act + let problems = check_reply_file(&path, &reply("researcher", "pr7", 3)); + + // Assert + let fields: Vec<_> = problems.iter().map(|problem| problem.field_path.as_deref()).collect(); + assert_eq!(fields, vec![Some("agent"), Some("subject"), Some("round")]); + } + + #[test] + fn it_should_report_the_location_and_the_disagreement_when_both_are_wrong() { + // Act + let problems = check_reply_file("task-reviewer-t3-r2.json", &reply("task-reviewer", "t3", 1)); + + // Assert + assert_eq!(checks(&problems), vec![Check::Location, Check::Agreement]); + } + + #[rstest] + #[case::reply_in_its_folder("docs/issues/open/2904-slug/agent-replies/task-reviewer-t3-r2.json", true)] + #[case::other_file_in_a_replies_folder("docs/issues/open/2904-slug/agent-replies/notes.md", true)] + #[case::replies_folder_elsewhere("notes/agent-replies/draft.json", true)] + #[case::reply_name_outside_a_replies_folder("docs/issues/open/2904-slug/implementer-t3-r1.json", true)] + #[case::reply_name_at_the_root("implementer-t3-r1.json", true)] + #[case::other_json_file("docs/schemas/agent-reply-v1.schema.json", false)] + #[case::the_specification("docs/issues/open/2904-slug/ISSUE.md", false)] + #[case::folder_that_only_ends_like_a_replies_folder("docs/old-agent-replies/notes.md", false)] + #[case::replies_folder_higher_up("docs/agent-replies/archive/notes.md", false)] + fn it_should_select_a_file_for_checking_only_when_it_is_in_a_replies_folder_or_named_like_a_reply( + #[case] path: &str, + #[case] selected: bool, + ) { + // Act + let candidate = is_reply_file_candidate(path); + + // Assert + assert_eq!(candidate, selected); + } +} diff --git a/contrib/dev-tools/checks/agent-reply-validator/src/lib.rs b/contrib/dev-tools/checks/agent-reply-validator/src/lib.rs new file mode 100644 index 0000000000..c740b2e69c --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/src/lib.rs @@ -0,0 +1,11 @@ +//! Validation of the JSON reply files that AI agents write. +//! +//! An agent started by the orchestrator records each reply as one JSON file in the +//! `agent-replies/` folder of the issue specification it works on. The file name says which +//! agent replied, about which subject, and in which round; the file content follows the +//! `agent-reply-v1` schema. See decision D18 of issue #2904. + +pub mod file; +pub mod name; +pub mod reply; +pub mod schema; diff --git a/contrib/dev-tools/checks/agent-reply-validator/src/name.rs b/contrib/dev-tools/checks/agent-reply-validator/src/name.rs new file mode 100644 index 0000000000..1b22460877 --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/src/name.rs @@ -0,0 +1,280 @@ +//! The reply file name: `--r.json`. +//! +//! The agent is one of the agents that write reply files; the subject is a task ID of the issue's +//! Implementation Plan in lower case (`t2`) or a pull request (`pr2920`); the round starts at 1 +//! and is at most [`Round::MAX`]. No other name is accepted. + +use std::fmt; +use std::str::FromStr; + +/// The file extension every reply file has. +const EXTENSION: &str = ".json"; + +/// An agent that writes reply files. +/// +/// `pr-review-handler` is not listed: its audit record `PR-REVIEW.md` is its trace. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Agent { + Orchestrator, + Implementer, + TaskReviewer, + PrReviewer, + Researcher, +} + +impl Agent { + /// Every agent, in the order of the agent roster. + pub const ALL: [Self; 5] = [ + Self::Orchestrator, + Self::Implementer, + Self::TaskReviewer, + Self::PrReviewer, + Self::Researcher, + ]; + + /// The agent's name, as its agent file and the reply file name spell it. + #[must_use] + pub const fn name(self) -> &'static str { + match self { + Self::Orchestrator => "orchestrator", + Self::Implementer => "implementer", + Self::TaskReviewer => "task-reviewer", + Self::PrReviewer => "pr-reviewer", + Self::Researcher => "researcher", + } + } +} + +impl fmt::Display for Agent { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.name()) + } +} + +/// What a reply is about. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Subject { + /// A task of the issue's Implementation Plan, such as `t2`. + Task(u32), + /// A pull request, such as `pr2920`. + PullRequest(u32), +} + +impl FromStr for Subject { + type Err = NameError; + + fn from_str(text: &str) -> Result { + let invalid = || NameError::InvalidSubject(text.to_owned()); + if let Some(number) = text.strip_prefix("pr") { + return parse_positive(number).map(Self::PullRequest).ok_or_else(invalid); + } + if let Some(number) = text.strip_prefix('t') { + return parse_positive(number).map(Self::Task).ok_or_else(invalid); + } + Err(invalid()) + } +} + +impl fmt::Display for Subject { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Task(number) => write!(formatter, "t{number}"), + Self::PullRequest(number) => write!(formatter, "pr{number}"), + } + } +} + +/// The round of a reply: each call of an agent on a subject writes the next round. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Round(u8); + +impl Round { + /// The last round an agent gets on a subject before the orchestrator asks the contributor. + pub const MAX: u8 = 3; + + /// The round with this number, if it is between 1 and [`Round::MAX`]. + #[must_use] + pub const fn new(number: u8) -> Option { + if number >= 1 && number <= Self::MAX { + Some(Self(number)) + } else { + None + } + } + + /// The round's number. + #[must_use] + pub const fn number(self) -> u8 { + self.0 + } +} + +impl FromStr for Round { + type Err = NameError; + + fn from_str(text: &str) -> Result { + parse_positive(text) + .and_then(|number| u8::try_from(number).ok()) + .and_then(Self::new) + .ok_or_else(|| NameError::InvalidRound(text.to_owned())) + } +} + +impl fmt::Display for Round { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "r{}", self.0) + } +} + +/// A valid reply file name, split into its parts. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ReplyFileName { + pub agent: Agent, + pub subject: Subject, + pub round: Round, +} + +impl FromStr for ReplyFileName { + type Err = NameError; + + fn from_str(file_name: &str) -> Result { + let stem = file_name + .strip_suffix(EXTENSION) + .ok_or_else(|| NameError::NotJson(file_name.to_owned()))?; + let (agent, rest) = Agent::ALL + .into_iter() + .find_map(|agent| { + stem.strip_prefix(agent.name()) + .and_then(|rest| rest.strip_prefix('-')) + .map(|rest| (agent, rest)) + }) + .ok_or_else(|| NameError::UnknownAgent(file_name.to_owned()))?; + let (subject, round) = rest + .rsplit_once("-r") + .ok_or_else(|| NameError::MissingRound(file_name.to_owned()))?; + Ok(Self { + agent, + subject: subject.parse()?, + round: round.parse()?, + }) + } +} + +impl fmt::Display for ReplyFileName { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{}-{}-{}{EXTENSION}", self.agent, self.subject, self.round) + } +} + +/// Why a file name is not a valid reply file name. Each variant holds the text it rejects. +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] +pub enum NameError { + #[error("`{0}` does not end in `{EXTENSION}`")] + NotJson(String), + #[error("`{0}` does not start with the name of an agent that writes reply files, followed by `-`")] + UnknownAgent(String), + #[error("`{0}` has no round: the name must end in `-r{EXTENSION}`")] + MissingRound(String), + #[error("`{0}` is not a subject: expected `t` or `pr`, with no leading zero")] + InvalidSubject(String), + #[error("`{0}` is not a round: expected a number from 1 to {max}, with no leading zero", max = Round::MAX)] + InvalidRound(String), +} + +/// A positive decimal number with no sign and no leading zero. +fn parse_positive(text: &str) -> Option { + // `u32::from_str` accepts a leading `+`, so the digits are checked first. + let well_formed = !text.starts_with('0') && text.bytes().all(|byte| byte.is_ascii_digit()); + if well_formed { text.parse().ok() } else { None } +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + + use super::{Agent, NameError, ReplyFileName, Round, Subject}; + + fn name(agent: Agent, subject: Subject, round: u8) -> ReplyFileName { + ReplyFileName { + agent, + subject, + round: Round::new(round).expect("the round is in range"), + } + } + + #[rstest] + #[case::task_reviewer_on_a_task("task-reviewer-t2-r1.json", name(Agent::TaskReviewer, Subject::Task(2), 1))] + #[case::pr_reviewer_on_a_pull_request("pr-reviewer-pr2920-r3.json", name(Agent::PrReviewer, Subject::PullRequest(2920), 3))] + #[case::orchestrator("orchestrator-t12-r2.json", name(Agent::Orchestrator, Subject::Task(12), 2))] + #[case::implementer("implementer-t3-r1.json", name(Agent::Implementer, Subject::Task(3), 1))] + #[case::researcher("researcher-pr7-r1.json", name(Agent::Researcher, Subject::PullRequest(7), 1))] + fn it_should_split_the_name_into_agent_subject_and_round_when_it_follows_the_rule( + #[case] file_name: &str, + #[case] expected: ReplyFileName, + ) { + // Act + let parsed: ReplyFileName = file_name.parse().expect("the name is valid"); + + // Assert + assert_eq!(parsed, expected); + } + + #[rstest] + #[case::zero(0, false)] + #[case::first(1, true)] + #[case::last(Round::MAX, true)] + #[case::past_the_limit(Round::MAX + 1, false)] + fn it_should_accept_a_round_number_only_when_it_is_between_one_and_the_limit(#[case] number: u8, #[case] accepted: bool) { + // Act + let round = Round::new(number); + + // Assert + assert_eq!(round.map(Round::number), accepted.then_some(number)); + } + + #[rstest] + #[case::task("implementer-t12-r3.json")] + #[case::pull_request("task-reviewer-pr2920-r2.json")] + fn it_should_print_the_name_it_parsed_when_displayed(#[case] file_name: &str) { + // Arrange + let parsed: ReplyFileName = file_name.parse().expect("the name is valid"); + + // Act + let printed = parsed.to_string(); + + // Assert + assert_eq!(printed, file_name); + } + + #[rstest] + #[case::markdown("task-reviewer-t2-r1.md", NameError::NotJson("task-reviewer-t2-r1.md".to_owned()))] + #[case::no_extension("task-reviewer-t2-r1", NameError::NotJson("task-reviewer-t2-r1".to_owned()))] + #[case::not_ported_agent("planner-t2-r1.json", NameError::UnknownAgent("planner-t2-r1.json".to_owned()))] + #[case::handler_writes_no_reply("pr-review-handler-pr2920-r1.json", NameError::UnknownAgent("pr-review-handler-pr2920-r1.json".to_owned()))] + #[case::agent_with_wrong_separator("task-reviewer_t2-r1.json", NameError::UnknownAgent("task-reviewer_t2-r1.json".to_owned()))] + #[case::upper_case_agent("Task-reviewer-t2-r1.json", NameError::UnknownAgent("Task-reviewer-t2-r1.json".to_owned()))] + #[case::no_round("task-reviewer-t2.json", NameError::MissingRound("task-reviewer-t2.json".to_owned()))] + #[case::upper_case_task("task-reviewer-T2-r1.json", NameError::InvalidSubject("T2".to_owned()))] + #[case::task_zero("task-reviewer-t0-r1.json", NameError::InvalidSubject("t0".to_owned()))] + #[case::task_leading_zero("task-reviewer-t02-r1.json", NameError::InvalidSubject("t02".to_owned()))] + #[case::task_without_number("task-reviewer-t-r1.json", NameError::InvalidSubject("t".to_owned()))] + #[case::task_with_plus_sign("task-reviewer-t+2-r1.json", NameError::InvalidSubject("t+2".to_owned()))] + #[case::pull_request_zero("task-reviewer-pr0-r1.json", NameError::InvalidSubject("pr0".to_owned()))] + #[case::pull_request_leading_zero("task-reviewer-pr02-r1.json", NameError::InvalidSubject("pr02".to_owned()))] + #[case::pull_request_with_plus_sign("task-reviewer-pr+2-r1.json", NameError::InvalidSubject("pr+2".to_owned()))] + #[case::upper_case_pull_request("task-reviewer-PR2920-r1.json", NameError::InvalidSubject("PR2920".to_owned()))] + #[case::pull_request_with_hash("task-reviewer-pr#2920-r1.json", NameError::InvalidSubject("pr#2920".to_owned()))] + #[case::unknown_subject_kind("task-reviewer-issue2904-r1.json", NameError::InvalidSubject("issue2904".to_owned()))] + #[case::round_zero("task-reviewer-t2-r0.json", NameError::InvalidRound("0".to_owned()))] + #[case::round_past_the_limit("task-reviewer-t2-r4.json", NameError::InvalidRound("4".to_owned()))] + #[case::round_leading_zero("task-reviewer-t2-r01.json", NameError::InvalidRound("01".to_owned()))] + #[case::round_with_plus_sign("task-reviewer-t2-r+1.json", NameError::InvalidRound("+1".to_owned()))] + #[case::round_that_wraps_to_one_in_a_byte("task-reviewer-t2-r257.json", NameError::InvalidRound("257".to_owned()))] + fn it_should_reject_the_name_when_it_breaks_the_naming_rule(#[case] file_name: &str, #[case] expected: NameError) { + // Act + let error = file_name.parse::().expect_err("the name is invalid"); + + // Assert + assert_eq!(error, expected); + } +} diff --git a/contrib/dev-tools/checks/agent-reply-validator/src/reply.rs b/contrib/dev-tools/checks/agent-reply-validator/src/reply.rs new file mode 100644 index 0000000000..9c4355aed5 --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/src/reply.rs @@ -0,0 +1,534 @@ +//! The content of a reply file: one JSON object with the fields of the `agent-reply-v1` schema. +//! +//! Every field is required and no other field is accepted, so a reply either has the complete +//! shape or is rejected with the JSON path of the first problem. +//! +//! The fields are checked one by one; no rule joins two of them. For example a `QUESTION` +//! verdict with no questions is accepted. The orchestrator reads only the verdict, and any use of +//! the replies beyond that is out of the scope of issue #2904. + +use std::fmt; +use std::ops::Range; + +use schemars::JsonSchema; +use serde::de::{self, Deserializer, Unexpected, Visitor}; +use serde::{Deserialize, Serialize, Serializer}; + +use crate::name::{Agent, Round, Subject}; + +/// The version of the reply format this crate reads and writes. +pub const SCHEMA_VERSION: u8 = 1; + +/// One reply of an agent, as stored in its reply file. +#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)] +#[serde(deny_unknown_fields, rename_all = "kebab-case")] +#[schemars(title = "Torrust Agent Reply V1")] +pub struct Reply { + /// The version of the reply format: always 1. + pub schema_version: SchemaVersion, + /// The agent that wrote the reply. + pub agent: Agent, + /// The model the agent ran on, as the harness names it, such as `claude-opus-5-5`. + pub model: Text, + /// What the reply is about: a task (`t2`) or a pull request (`pr2920`). + pub subject: Subject, + /// The round of this agent on this subject. + pub round: Round, + /// When the reply was written, in UTC: `YYYY-MM-DD HH:MM`. + pub created_utc: UtcMinute, + /// The outcome, from which the orchestrator decides the next step. + #[serde(deserialize_with = "from_string")] + pub verdict: Verdict, + /// A short account of what the agent did or found. + pub summary: Text, + /// The problems found; empty when there are none. + pub findings: Vec, + /// The questions for the contributor; empty when there are none. + pub questions: Vec, + /// The commands run and what they printed, or other facts the reply rests on. + pub evidence: Vec, +} + +impl Reply { + /// Reads a reply from the text of a reply file. + /// + /// # Errors + /// + /// Returns a [`ReplyError`] with the JSON path of the first value that does not fit the + /// format, or the position of the first syntax error. + pub fn from_json(text: &str) -> Result { + let mut deserializer = serde_json::Deserializer::from_str(text); + let reply = serde_path_to_error::deserialize(&mut deserializer).map_err(|error| ReplyError { + path: error.path().to_string(), + message: error.inner().to_string(), + })?; + deserializer.end().map_err(|error| ReplyError { + path: ".".to_owned(), + message: error.to_string(), + })?; + first_non_object(text).map_or(Ok(reply), |path| { + Err(ReplyError { + path, + message: "expected a JSON object".to_owned(), + }) + }) + } +} + +/// The path of the reply or of the first finding written as a JSON array, if any. +/// +/// Serde also reads a struct from an array of its fields in order; the format allows only +/// objects, as the schema says. The text is known to be valid JSON when this runs; parsing it a +/// second time keeps the typed reading above, with its paths and duplicate-key check, unchanged. +fn first_non_object(text: &str) -> Option { + let value: serde_json::Value = serde_json::from_str(text).ok()?; + let Some(reply) = value.as_object() else { + return Some(".".to_owned()); + }; + let findings = reply.get("findings").and_then(serde_json::Value::as_array)?; + findings + .iter() + .position(|finding| !finding.is_object()) + .map(|index| format!("findings[{index}]")) +} + +/// Why a text is not a valid reply. +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] +#[error("{path}: {message}")] +pub struct ReplyError { + /// The JSON path of the value that does not fit, or `.` for the whole document. + pub path: String, + /// What is wrong with it. + pub message: String, +} + +/// The outcome of a reply. The list is closed: the orchestrator reads only this field. +#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum Verdict { + /// A review found nothing that blocks the work. + ReviewPassed, + /// A review found something that must change. + ReviewFailed, + /// The agent finished the work it was given. + Done, + /// The agent cannot go on without something it does not have. + Blocked, + /// The agent needs an answer from the contributor. + Question, +} + +/// One problem found by the agent. +#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Finding { + /// How much the problem matters. + #[serde(deserialize_with = "from_string")] + pub severity: Severity, + /// Where it is, such as `src/name.rs:42` or a section of a document. + pub location: Text, + /// What is wrong. + pub description: Text, +} + +/// The severity of a finding, with the same names as the pull-request review audits. +#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)] +pub enum Severity { + Blocker, + Major, + Minor, + Nit, + Suggestion, +} + +/// The schema version field: the number [`SCHEMA_VERSION`] and nothing else. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct SchemaVersion; + +impl Serialize for SchemaVersion { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_u8(SCHEMA_VERSION) + } +} + +impl<'de> Deserialize<'de> for SchemaVersion { + fn deserialize>(deserializer: D) -> Result { + let version = u64::deserialize(deserializer)?; + if version == u64::from(SCHEMA_VERSION) { + Ok(Self) + } else { + Err(de::Error::invalid_value( + Unexpected::Unsigned(version), + &"the schema version 1", + )) + } + } +} + +/// A text with at least one character that is not white space. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(transparent)] +pub struct Text(String); + +impl Text { + /// The text, if it has a character that is not white space. + #[must_use] + pub fn new(text: impl Into) -> Option { + let text = text.into(); + if is_blank(&text) { None } else { Some(Self(text)) } + } + + /// The text itself. + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl<'de> Deserialize<'de> for Text { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + if is_blank(&text) { + return Err(de::Error::invalid_value(Unexpected::Str(&text), &"a text that is not blank")); + } + Ok(Self(text)) + } +} + +/// Reads a unit-variant enum from a JSON string only. +/// +/// Serde's derived enum reader also takes the object form `{"DONE": null}`; the format, like the +/// schema, allows only the string `"DONE"`. +fn from_string<'de, D, T>(deserializer: D) -> Result +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + let text = String::deserialize(deserializer)?; + T::deserialize(de::value::StringDeserializer::::new(text)) +} + +/// Whether a text has no character other than white space. +fn is_blank(text: &str) -> bool { + text.trim().is_empty() +} + +/// A UTC time to the minute, written `YYYY-MM-DD HH:MM`, as in the issue specifications. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(transparent)] +pub struct UtcMinute(String); + +impl UtcMinute { + /// The time, if the text has the layout and names a real date and time. + #[must_use] + pub fn new(text: &str) -> Option { + let bytes = text.as_bytes(); + let layout = bytes.len() == 16 + && bytes.iter().enumerate().all(|(index, byte)| match index { + 4 | 7 => *byte == b'-', + 10 => *byte == b' ', + 13 => *byte == b':', + _ => byte.is_ascii_digit(), + }); + if !layout { + return None; + } + let number = |range: Range| text[range].parse::().ok(); + let (year, month, day, hour, minute) = (number(0..4)?, number(5..7)?, number(8..10)?, number(11..13)?, number(14..16)?); + let days_in_month = match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 if year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) => 29, + 2 => 28, + _ => return None, + }; + let valid = (1..=days_in_month).contains(&day) && hour < 24 && minute < 60; + valid.then(|| Self(text.to_owned())) + } +} + +impl<'de> Deserialize<'de> for UtcMinute { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + Self::new(&text).ok_or_else(|| de::Error::invalid_value(Unexpected::Str(&text), &"a UTC time written YYYY-MM-DD HH:MM")) + } +} + +impl Serialize for Agent { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.name()) + } +} + +impl<'de> Deserialize<'de> for Agent { + fn deserialize>(deserializer: D) -> Result { + let name = String::deserialize(deserializer)?; + Self::ALL + .into_iter() + .find(|agent| agent.name() == name) + .ok_or_else(|| de::Error::invalid_value(Unexpected::Str(&name), &"an agent that writes reply files")) + } +} + +impl Serialize for Subject { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } +} + +impl<'de> Deserialize<'de> for Subject { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + text.parse() + .map_err(|_| de::Error::invalid_value(Unexpected::Str(&text), &"a subject `t` or `pr`")) + } +} + +impl Serialize for Round { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_u8(self.number()) + } +} + +impl<'de> Deserialize<'de> for Round { + fn deserialize>(deserializer: D) -> Result { + struct RoundVisitor; + + impl Visitor<'_> for RoundVisitor { + type Value = Round; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "a round number from 1 to {}", Round::MAX) + } + + fn visit_u64(self, number: u64) -> Result { + u8::try_from(number) + .ok() + .and_then(Round::new) + .ok_or_else(|| E::invalid_value(Unexpected::Unsigned(number), &self)) + } + } + + deserializer.deserialize_u64(RoundVisitor) + } +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + use serde_json::{Value, json}; + + use super::{Finding, Reply, Severity, Text, UtcMinute, Verdict}; + use crate::name::{Agent, Round, Subject}; + + /// A complete reply of a task reviewer that failed a review with one finding. + fn valid_reply() -> Value { + json!({ + "schema-version": 1, + "agent": "task-reviewer", + "model": "claude-opus-5-5", + "subject": "t3", + "round": 2, + "created-utc": "2026-11-18 17:25", + "verdict": "REVIEW_FAILED", + "summary": "The digit check has no test.", + "findings": [ + { "severity": "Major", "location": "src/name.rs:212", "description": "A leading + is accepted." } + ], + "questions": [], + "evidence": ["cargo test -q -p agent-reply-validator: 23 passed"] + }) + } + + /// The valid reply with one top-level field replaced. + fn reply_with(field: &str, value: Value) -> String { + let mut reply = valid_reply(); + reply[field] = value; + reply.to_string() + } + + /// The valid reply without one top-level field. + fn reply_without(field: &str) -> String { + let mut reply = valid_reply(); + reply.as_object_mut().expect("the reply is an object").remove(field); + reply.to_string() + } + + fn text(value: &str) -> Text { + Text::new(value).expect("the text is not blank") + } + + #[test] + fn it_should_read_every_field_when_the_reply_is_complete() { + // Arrange + let json = valid_reply().to_string(); + + // Act + let reply = Reply::from_json(&json).expect("the reply is valid"); + + // Assert + assert_eq!(reply.agent, Agent::TaskReviewer); + assert_eq!(reply.model, text("claude-opus-5-5")); + assert_eq!(reply.subject, Subject::Task(3)); + assert_eq!(reply.round, Round::new(2).expect("the round is in range")); + assert_eq!( + reply.created_utc, + UtcMinute::new("2026-11-18 17:25").expect("the time is valid") + ); + assert_eq!(reply.verdict, Verdict::ReviewFailed); + assert_eq!(reply.summary, text("The digit check has no test.")); + assert_eq!( + reply.findings, + vec![Finding { + severity: Severity::Major, + location: text("src/name.rs:212"), + description: text("A leading + is accepted."), + }] + ); + assert_eq!(reply.questions, Vec::::new()); + assert_eq!( + reply.evidence, + vec![text("cargo test -q -p agent-reply-validator: 23 passed")] + ); + } + + #[test] + fn it_should_write_the_same_json_it_read_when_serialized() { + // Arrange + let reply = Reply::from_json(&valid_reply().to_string()).expect("the reply is valid"); + + // Act + let written = serde_json::to_value(&reply).expect("the reply serializes"); + + // Assert + assert_eq!(written, valid_reply()); + } + + #[rstest] + #[case::review_passed("REVIEW_PASSED", Verdict::ReviewPassed)] + #[case::review_failed("REVIEW_FAILED", Verdict::ReviewFailed)] + #[case::done("DONE", Verdict::Done)] + #[case::blocked("BLOCKED", Verdict::Blocked)] + #[case::question("QUESTION", Verdict::Question)] + fn it_should_read_the_verdict_when_it_is_in_the_closed_list(#[case] verdict: &str, #[case] expected: Verdict) { + // Arrange + let json = reply_with("verdict", json!(verdict)); + + // Act + let reply = Reply::from_json(&json).expect("the reply is valid"); + + // Assert + assert_eq!(reply.verdict, expected); + } + + #[rstest] + #[case::schema_version("schema-version")] + #[case::agent("agent")] + #[case::model("model")] + #[case::subject("subject")] + #[case::round("round")] + #[case::created_utc("created-utc")] + #[case::verdict("verdict")] + #[case::summary("summary")] + #[case::findings("findings")] + #[case::questions("questions")] + #[case::evidence("evidence")] + fn it_should_reject_the_reply_when_a_field_is_missing(#[case] field: &str) { + // Arrange + let json = reply_without(field); + + // Act + let error = Reply::from_json(&json).expect_err("the reply is incomplete"); + + // Assert + assert_eq!(error.path, "."); + assert!( + error.message.starts_with(&format!("missing field `{field}`")), + "unexpected message `{}`", + error.message + ); + } + + #[rstest] + #[case::unknown_field(reply_with("status", json!("done")), "status", "unknown field `status`")] + #[case::duplicate_field(valid_reply().to_string().replacen('{', "{\"agent\": \"implementer\", ", 1), ".", "duplicate field `agent`")] + #[case::schema_version_two(reply_with("schema-version", json!(2)), "schema-version", "the schema version 1")] + #[case::schema_version_as_text(reply_with("schema-version", json!("1")), "schema-version", "invalid type: string")] + #[case::handler_writes_no_reply(reply_with("agent", json!("pr-review-handler")), "agent", "an agent that writes reply files")] + #[case::not_ported_agent(reply_with("agent", json!("planner")), "agent", "an agent that writes reply files")] + #[case::blank_model(reply_with("model", json!(" ")), "model", "a text that is not blank")] + #[case::upper_case_subject(reply_with("subject", json!("T3")), "subject", "a subject")] + #[case::round_zero(reply_with("round", json!(0)), "round", "a round number from 1 to 3")] + #[case::round_past_the_limit(reply_with("round", json!(4)), "round", "a round number from 1 to 3")] + #[case::round_that_wraps_to_one_in_a_byte(reply_with("round", json!(257)), "round", "a round number from 1 to 3")] + #[case::round_as_text(reply_with("round", json!("2")), "round", "invalid type: string")] + #[case::time_with_seconds(reply_with("created-utc", json!("2026-11-18 17:25:00")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_in_iso_form(reply_with("created-utc", json!("2026-11-18T17:25")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_with_slashes(reply_with("created-utc", json!("2026/11/18 17:25")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_with_a_dot(reply_with("created-utc", json!("2026-11-18 17.25")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_with_an_extra_digit(reply_with("created-utc", json!("2026-11-18 17:255")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_with_a_plus_sign(reply_with("created-utc", json!("2026-+1-18 17:25")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_on_a_missing_leap_day(reply_with("created-utc", json!("2025-02-29 12:00")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_on_a_missing_leap_day_of_a_century(reply_with("created-utc", json!("2100-02-29 12:00")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_past_the_last_hour(reply_with("created-utc", json!("2026-11-18 24:00")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_past_the_last_minute(reply_with("created-utc", json!("2026-11-18 17:60")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_in_month_thirteen(reply_with("created-utc", json!("2026-13-18 17:25")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_on_day_thirty_one_of_april(reply_with("created-utc", json!("2026-04-31 17:25")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_on_day_thirty_one_of_june(reply_with("created-utc", json!("2026-06-31 17:25")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_on_day_thirty_one_of_september(reply_with("created-utc", json!("2026-09-31 17:25")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_on_day_thirty_one_of_november(reply_with("created-utc", json!("2026-11-31 17:25")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::time_on_day_zero(reply_with("created-utc", json!("2026-11-00 17:25")), "created-utc", "a UTC time written YYYY-MM-DD HH:MM")] + #[case::verdict_outside_the_list(reply_with("verdict", json!("PASSED")), "verdict", "unknown variant `PASSED`")] + #[case::verdict_as_an_object(reply_with("verdict", json!({ "REVIEW_PASSED": null })), "verdict", "invalid type: map, expected a string")] + #[case::verdict_in_lower_case(reply_with("verdict", json!("done")), "verdict", "unknown variant `done`")] + #[case::blank_summary(reply_with("summary", json!("")), "summary", "a text that is not blank")] + #[case::severity_outside_the_list(reply_with("findings", json!([{ "severity": "Critical", "location": "a", "description": "b" }])), "findings[0].severity", "unknown variant `Critical`")] + #[case::severity_as_an_object(reply_with("findings", json!([{ "severity": { "Major": null }, "location": "a", "description": "b" }])), "findings[0].severity", "invalid type: map, expected a string")] + #[case::blank_location(reply_with("findings", json!([{ "severity": "Nit", "location": "", "description": "b" }])), "findings[0].location", "a text that is not blank")] + #[case::finding_without_description(reply_with("findings", json!([{ "severity": "Nit", "location": "a" }])), "findings[0]", "missing field `description`")] + #[case::unknown_finding_field(reply_with("findings", json!([{ "severity": "Nit", "location": "a", "description": "b", "fix": "c" }])), "findings[0].fix", "unknown field `fix`")] + #[case::blank_question(reply_with("questions", json!(["Which branch?", " "])), "questions[1]", "a text that is not blank")] + #[case::blank_evidence(reply_with("evidence", json!([""])), "evidence[0]", "a text that is not blank")] + #[case::evidence_as_text(reply_with("evidence", json!("cargo test")), "evidence", "invalid type: string")] + #[case::reply_as_an_array( + r#"[1, "task-reviewer", "claude-opus-5-5", "t3", 2, "2026-11-18 17:25", "DONE", "s", [], [], []]"#.to_owned(), + ".", + "expected a JSON object" + )] + #[case::finding_as_an_array( + reply_with("findings", json!([{ "severity": "Nit", "location": "a", "description": "b" }, ["Nit", "a", "b"]])), + "findings[1]", + "expected a JSON object" + )] + #[case::truncated_json(r#"{"schema-version": 1, "agent": "#.to_owned(), "agent", "EOF while parsing")] + #[case::something_after_the_reply(format!("{} {{}}", valid_reply()), ".", "trailing characters")] + fn it_should_reject_the_reply_with_the_path_and_reason_of_the_value_that_breaks_the_format( + #[case] json: String, + #[case] path: &str, + #[case] reason: &str, + ) { + // Act + let error = Reply::from_json(&json).expect_err("the reply is invalid"); + + // Assert + assert_eq!(error.path, path, "unexpected path for the error `{}`", error.message); + assert!( + error.message.contains(reason), + "the error `{}` does not say `{reason}`", + error.message + ); + } + + #[rstest] + #[case::leap_day_of_a_leap_year("2024-02-29 12:00")] + #[case::leap_day_of_a_year_divisible_by_four_hundred("2000-02-29 12:00")] + #[case::last_day_of_a_thirty_one_day_month("2026-01-31 12:00")] + #[case::last_minute_of_the_year("2026-12-31 23:59")] + fn it_should_accept_the_time_when_it_names_a_real_minute(#[case] time: &str) { + // Act + let reply = Reply::from_json(&reply_with("created-utc", json!(time))); + + // Assert + assert!(reply.is_ok(), "`{time}` was rejected: {reply:?}"); + } +} diff --git a/contrib/dev-tools/checks/agent-reply-validator/src/schema.rs b/contrib/dev-tools/checks/agent-reply-validator/src/schema.rs new file mode 100644 index 0000000000..01e1d9773b --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/src/schema.rs @@ -0,0 +1,318 @@ +//! The `agent-reply-v1` JSON Schema, generated from the reply model. +//! +//! The model in [`crate::reply`] is the authority; the schema is its projection for other tools +//! and readers, tracked at [`ARTIFACT_PATH`]. The validator differs from a JSON Schema validator +//! in these places, which the schema cannot express: +//! +//! - `created-utc` must name a real date and time, not only have the layout; +//! - a number with a fraction, such as `1.0`, is not an integer, though JSON Schema counts it as +//! one; +//! - a key given twice is rejected; a JSON Schema validator sees only the parsed value; +//! - the white space of a blank text is Unicode white space, as Rust's `trim` defines it; the +//! pattern `\S` uses the ECMA-262 set, which differs for a few characters: a text of only +//! U+0085 passes the schema and fails the validator, and a text of only U+FEFF fails the schema +//! and passes the validator; +//! - the number of a subject must fit in 32 bits: the pattern accepts `t4294967296`, the +//! validator rejects it. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; + +use crate::name::{Agent, Round, Subject}; +use crate::reply::{Reply, SCHEMA_VERSION, SchemaVersion, Text, UtcMinute}; + +/// Where the generated schema is tracked, relative to the repository root. +pub const ARTIFACT_PATH: &str = "docs/schemas/agent-reply-v1.schema.json"; + +/// The pattern of a subject: `t` or `pr`, with no leading zero. +pub const SUBJECT_PATTERN: &str = "^(t|pr)[1-9][0-9]*$"; + +/// The layout of a UTC time to the minute. +pub const UTC_MINUTE_PATTERN: &str = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$"; + +/// A text with a character that is not white space. +pub const NOT_BLANK_PATTERN: &str = "\\S"; + +/// The schema of a reply. +#[must_use] +pub fn reply_schema() -> Schema { + schemars::schema_for!(Reply) +} + +/// The schema as the tracked artifact holds it: pretty JSON and a final newline. +/// +/// # Panics +/// +/// Never in practice: a generated schema is a JSON value, which always serializes. +#[must_use] +pub fn reply_schema_json() -> String { + let json = serde_json::to_string_pretty(&reply_schema()).expect("a schema serializes as JSON"); + format!("{json}\n") +} + +impl JsonSchema for SchemaVersion { + fn schema_name() -> Cow<'static, str> { + "SchemaVersion".into() + } + + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "The version of the reply format.", + "type": "integer", + "const": SCHEMA_VERSION + }) + } +} + +impl JsonSchema for Agent { + fn schema_name() -> Cow<'static, str> { + "Agent".into() + } + + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let names: Vec<&str> = Self::ALL.iter().map(|agent| agent.name()).collect(); + json_schema!({ + "description": "An agent that writes reply files.", + "type": "string", + "enum": names + }) + } +} + +impl JsonSchema for Subject { + fn schema_name() -> Cow<'static, str> { + "Subject".into() + } + + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A task of the Implementation Plan (`t2`) or a pull request (`pr2920`).", + "type": "string", + "pattern": SUBJECT_PATTERN + }) + } +} + +impl JsonSchema for Round { + fn schema_name() -> Cow<'static, str> { + "Round".into() + } + + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "The round of the agent on the subject.", + "type": "integer", + "minimum": 1, + "maximum": Self::MAX + }) + } +} + +impl JsonSchema for Text { + fn schema_name() -> Cow<'static, str> { + "Text".into() + } + + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A text that is not blank.", + "type": "string", + "pattern": NOT_BLANK_PATTERN + }) + } +} + +impl JsonSchema for UtcMinute { + fn schema_name() -> Cow<'static, str> { + "UtcMinute".into() + } + + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "A UTC time written `YYYY-MM-DD HH:MM`.", + "type": "string", + "pattern": UTC_MINUTE_PATTERN + }) + } +} + +#[cfg(test)] +mod tests { + // The pattern tests read each pattern with the Rust `regex` engine, an approximation of the + // ECMA-262 engine that JSON Schema names. They show that pattern and Rust check agree on the + // samples, not how every JSON Schema validator reads the pattern; the module doc names the + // known gap. + use regex::Regex; + use rstest::rstest; + use serde_json::{Value, json}; + + use super::{NOT_BLANK_PATTERN, SUBJECT_PATTERN, UTC_MINUTE_PATTERN, reply_schema}; + use crate::name::Subject; + use crate::reply::{Text, UtcMinute}; + + fn schema() -> Value { + serde_json::to_value(reply_schema()).expect("the schema is JSON") + } + + #[test] + fn it_should_require_every_field_of_the_reply_and_forbid_any_other() { + // Act + let reply = schema(); + + // Assert + let fields = json!([ + "schema-version", + "agent", + "model", + "subject", + "round", + "created-utc", + "verdict", + "summary", + "findings", + "questions", + "evidence" + ]); + assert_eq!( + (&reply["type"], &reply["required"], &reply["additionalProperties"]), + (&json!("object"), &fields, &json!(false)) + ); + } + + #[test] + fn it_should_require_every_field_of_a_finding_and_forbid_any_other() { + // Act + let finding = schema()["$defs"]["Finding"].clone(); + + // Assert + let fields = json!(["severity", "location", "description"]); + assert_eq!( + (&finding["type"], &finding["required"], &finding["additionalProperties"]), + (&json!("object"), &fields, &json!(false)) + ); + } + + #[test] + fn it_should_list_exactly_the_agents_that_write_reply_files() { + // Act + let agents = schema()["$defs"]["Agent"]["enum"].clone(); + + // Assert + assert_eq!( + agents, + json!(["orchestrator", "implementer", "task-reviewer", "pr-reviewer", "researcher"]) + ); + } + + #[test] + fn it_should_bound_the_round_from_one_to_three() { + // Act + let round = schema()["$defs"]["Round"].clone(); + + // Assert + assert_eq!( + (&round["type"], &round["minimum"], &round["maximum"]), + (&json!("integer"), &json!(1), &json!(3)) + ); + } + + #[test] + fn it_should_fix_the_schema_version_to_one() { + // Act + let version = schema()["$defs"]["SchemaVersion"].clone(); + + // Assert + assert_eq!((&version["type"], &version["const"]), (&json!("integer"), &json!(1))); + } + + #[test] + fn it_should_close_the_lists_of_verdicts_and_severities() { + // Act + let schema = schema(); + + // Assert + let verdicts: Vec<&Value> = schema["$defs"]["Verdict"]["oneOf"] + .as_array() + .expect("the verdicts are alternatives") + .iter() + .map(|verdict| &verdict["const"]) + .collect(); + assert_eq!(verdicts, ["REVIEW_PASSED", "REVIEW_FAILED", "DONE", "BLOCKED", "QUESTION"]); + assert_eq!( + schema["$defs"]["Severity"]["enum"], + json!(["Blocker", "Major", "Minor", "Nit", "Suggestion"]) + ); + } + + #[rstest] + #[case::task("t2")] + #[case::pull_request("pr2920")] + #[case::task_zero("t0")] + #[case::leading_zero("pr02")] + #[case::plus_sign("t+2")] + #[case::upper_case("T2")] + #[case::other_kind("issue2904")] + #[case::trailing_text("t2x")] + fn it_should_match_the_subject_pattern_when_the_parser_accepts_the_subject(#[case] subject: &str) { + // Act + let matched = Regex::new(SUBJECT_PATTERN).expect("the pattern compiles").is_match(subject); + + // Assert + assert_eq!( + matched, + subject.parse::().is_ok(), + "the pattern, read by the Rust `regex` engine, and the parser disagree on `{subject}`" + ); + } + + #[test] + fn it_should_match_a_subject_number_too_large_for_the_parser() { + // Arrange: the pattern has no length bound; the parser reads the number as a `u32`. + let subject = "t4294967296"; + + // Act + let matched = Regex::new(SUBJECT_PATTERN).expect("the pattern compiles").is_match(subject); + + // Assert: a known difference, named in the module doc. + assert!(matched); + assert!(subject.parse::().is_err()); + } + + #[rstest] + #[case::valid("2026-11-18 17:25")] + #[case::with_seconds("2026-11-18 17:25:00")] + #[case::iso_form("2026-11-18T17:25")] + #[case::slashes("2026/11/18 17:25")] + #[case::plus_sign("2026-+1-18 17:25")] + #[case::short_minute("2026-11-18 17:5")] + fn it_should_match_the_time_pattern_when_the_time_has_the_layout(#[case] time: &str) { + // Act: the pattern checks only the layout; the model also checks the calendar. + let matched = Regex::new(UTC_MINUTE_PATTERN).expect("the pattern compiles").is_match(time); + + // Assert + assert_eq!( + matched, + UtcMinute::new(time).is_some(), + "the pattern, read by the Rust `regex` engine, and the model disagree on `{time}`" + ); + } + + #[rstest] + #[case::word("claude-opus-5-5")] + #[case::padded(" a ")] + #[case::empty("")] + #[case::spaces(" ")] + #[case::tab_and_newline("\t\n")] + fn it_should_match_the_text_pattern_when_the_text_is_not_blank(#[case] text: &str) { + // Act + let matched = Regex::new(NOT_BLANK_PATTERN).expect("the pattern compiles").is_match(text); + + // Assert + assert_eq!( + matched, + Text::new(text).is_some(), + "the pattern, read by the Rust `regex` engine, and the model disagree on `{text:?}`" + ); + } +} diff --git a/contrib/dev-tools/checks/agent-reply-validator/tests/cli.rs b/contrib/dev-tools/checks/agent-reply-validator/tests/cli.rs new file mode 100644 index 0000000000..3c490c8f18 --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/tests/cli.rs @@ -0,0 +1,572 @@ +//! Command-boundary tests: the built binary runs in a disposable git repository. +//! +//! Every git invocation, including the binary's, clears inherited `GIT_*` variables and sets a +//! ceiling directory, so a test run from a git hook can never read or change the real repository. + +use std::fs; +use std::path::Path; +use std::process::Command; + +use serde_json::{Value, json}; +use tempfile::TempDir; + +/// The replies folder of an open specification, where a reply file belongs. +const FOLDER: &str = "docs/issues/open/2904-slug/agent-replies"; + +/// Inherited variables that would redirect git away from the disposable repository. +const GIT_ENVIRONMENT: &[&str] = &[ + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_INDEX_FILE", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_COMMON_DIR", + "GIT_PREFIX", + "GIT_CONFIG_PARAMETERS", + "GIT_CONFIG_COUNT", + "GIT_LITERAL_PATHSPECS", + "GIT_GLOB_PATHSPECS", + "GIT_NOGLOB_PATHSPECS", + "GIT_ICASE_PATHSPECS", +]; + +/// A valid reply whose round is the given one; the agent is `task-reviewer` and the subject `t3`. +fn reply(round: u8) -> String { + json!({ + "schema-version": 1, + "agent": "task-reviewer", + "model": "claude-opus-5-5", + "subject": "t3", + "round": round, + "created-utc": "2026-11-18 17:25", + "verdict": "REVIEW_PASSED", + "summary": "Nothing blocks the task.", + "findings": [], + "questions": [], + "evidence": ["cargo test -q -p agent-reply-validator passed"] + }) + .to_string() +} + +/// The exit code and the NDJSON records on stderr of one run. Stdout is checked to be empty. +struct Outcome { + exit_code: i32, + records: Vec, +} + +impl Outcome { + fn kinds(&self) -> Vec<&str> { + self.records.iter().map(|record| record["kind"].as_str().unwrap()).collect() + } + + fn last(&self) -> &Value { + self.records.last().expect("the run wrote a record") + } +} + +/// A disposable git repository; `TempDir` removes it on drop. +struct Repository { + directory: TempDir, +} + +impl Repository { + fn new() -> Self { + let repository = Self { + directory: TempDir::new().unwrap(), + }; + repository.git(&["init", "--quiet"]); + repository + } + + fn root(&self) -> &Path { + self.directory.path() + } + + fn write(&self, path: &str, content: &str) { + let file = self.root().join(path); + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(file, content).unwrap(); + } + + fn stage(&self, path: &str, content: &str) { + self.write(path, content); + self.git(&["add", "--", path]); + } + + /// Stages an empty file whose name is the given bytes, which need not be UTF-8. + #[cfg(unix)] + fn stage_raw_name(&self, path: &[u8]) { + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt; + let relative = OsStr::from_bytes(path); + let file = self.root().join(relative); + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(&file, "").unwrap(); + let status = isolated(Command::new("git"), self.root()) + .arg("add") + .arg("--") + .arg(relative) + .status() + .unwrap(); + assert!(status.success(), "git add failed"); + } + + fn git(&self, arguments: &[&str]) { + let status = isolated(Command::new("git"), self.root()).args(arguments).status().unwrap(); + assert!(status.success(), "git {arguments:?} failed"); + } + + fn run(&self, arguments: &[&str]) -> Outcome { + run_in(self.root(), arguments) + } +} + +fn run_in(directory: &Path, arguments: &[&str]) -> Outcome { + let output = isolated(Command::new(env!("CARGO_BIN_EXE_agent-reply-validator")), directory) + .args(arguments) + .output() + .unwrap(); + assert_eq!(String::from_utf8_lossy(&output.stdout), "", "stdout must stay empty"); + let records = std::str::from_utf8(&output.stderr) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap_or_else(|error| panic!("not NDJSON: {line}: {error}"))) + .collect(); + Outcome { + exit_code: output.status.code().unwrap(), + records, + } +} + +/// Every disposable repository lives below the temp directory, so git never searches above it. +fn isolated(mut command: Command, directory: &Path) -> Command { + for variable in GIT_ENVIRONMENT { + command.env_remove(variable); + } + command + .current_dir(directory) + .env("GIT_CEILING_DIRECTORIES", std::env::temp_dir()); + command +} + +#[test] +fn it_should_exit_zero_with_only_a_summary_when_every_staged_reply_is_valid() { + // Arrange + let repository = Repository::new(); + repository.stage(&format!("{FOLDER}/task-reviewer-t3-r2.json"), &reply(2)); + repository.stage("docs/schemas/other.json", "{}"); + + // Act + let outcome = repository.run(&["--all"]); + + // Assert + assert_eq!(outcome.exit_code, 0); + assert_eq!(outcome.records, vec![json!({ "kind": "summary", "files": 1, "problems": 0 })]); +} + +#[test] +fn it_should_exit_one_with_each_problem_when_a_staged_reply_is_invalid() { + // Arrange + let repository = Repository::new(); + let path = format!("{FOLDER}/task-reviewer-t3-r2.json"); + repository.stage(&path, &reply(1)); + + // Act + let outcome = repository.run(&["--all"]); + + // Assert + assert_eq!(outcome.exit_code, 1); + assert_eq!( + outcome.records, + vec![ + json!({ + "kind": "problem", + "path": path, + "check": "agreement", + "field_path": "round", + "message": "the file name says `2` but the field says `1`" + }), + json!({ "kind": "summary", "files": 1, "problems": 1 }), + ] + ); +} + +#[test] +fn it_should_check_the_staged_content_when_the_working_tree_differs() { + // Arrange + let repository = Repository::new(); + let path = format!("{FOLDER}/task-reviewer-t3-r2.json"); + repository.stage(&path, &reply(2)); + repository.write(&path, "not json"); + + // Act + let outcome = repository.run(&["--all"]); + + // Assert + assert_eq!(outcome.exit_code, 0); + assert_eq!(outcome.last(), &json!({ "kind": "summary", "files": 1, "problems": 0 })); +} + +#[test] +fn it_should_report_a_staged_reply_file_when_it_is_outside_a_replies_folder() { + // Arrange + let repository = Repository::new(); + repository.stage("docs/issues/open/2904-slug/task-reviewer-t3-r2.json", &reply(2)); + + // Act + let outcome = repository.run(&["--all"]); + + // Assert + assert_eq!(outcome.exit_code, 1); + assert_eq!( + outcome.records, + vec![ + json!({ + "kind": "problem", + "path": "docs/issues/open/2904-slug/task-reviewer-t3-r2.json", + "check": "location", + "field_path": null, + "message": "a reply file must be in `docs/issues///agent-replies/`" + }), + json!({ "kind": "summary", "files": 1, "problems": 1 }), + ] + ); +} + +#[test] +fn it_should_report_a_staged_file_when_it_is_in_a_replies_folder_without_a_reply_name() { + // Arrange + let repository = Repository::new(); + repository.stage(&format!("{FOLDER}/notes.md"), "# Notes\n"); + + // Act + let outcome = repository.run(&["--all"]); + + // Assert + assert_eq!(outcome.exit_code, 1); + assert_eq!(outcome.kinds(), vec!["problem", "problem", "summary"]); + assert_eq!( + outcome.records[0], + json!({ + "kind": "problem", + "path": format!("{FOLDER}/notes.md"), + "check": "name", + "field_path": null, + "message": "`notes.md` does not end in `.json`" + }) + ); + assert_eq!( + (&outcome.records[1]["check"], &outcome.records[1]["field_path"]), + (&json!("content"), &json!(".")) + ); +} + +#[test] +fn it_should_check_a_given_file_on_disk_when_it_is_not_staged() { + // Arrange + let repository = Repository::new(); + let path = format!("{FOLDER}/task-reviewer-t3-r2.json"); + repository.write(&path, &reply(4)); + + // Act + let outcome = repository.run(&[&path]); + + // Assert + assert_eq!(outcome.exit_code, 1); + assert_eq!(outcome.kinds(), vec!["problem", "summary"]); + assert_eq!(outcome.records[0]["path"], path); + assert_eq!(outcome.records[0]["field_path"], "round"); +} + +#[test] +fn it_should_name_a_given_file_from_the_repository_root_when_run_in_a_subfolder() { + // Arrange + let repository = Repository::new(); + let path = format!("{FOLDER}/task-reviewer-t3-r2.json"); + repository.write(&path, &reply(2)); + + // Act + let outcome = run_in( + &repository.root().join("docs/issues"), + &["./open/2904-slug/agent-replies/../agent-replies/task-reviewer-t3-r2.json"], + ); + + // Assert + assert_eq!(outcome.exit_code, 0); + assert_eq!(outcome.records, vec![json!({ "kind": "summary", "files": 1, "problems": 0 })]); +} + +#[test] +fn it_should_fail_with_a_runtime_error_when_a_given_file_does_not_exist() { + // Arrange + let repository = Repository::new(); + + // Act + let outcome = repository.run(&["missing.json"]); + + // Assert + assert_eq!(outcome.exit_code, 1); + assert_eq!(outcome.kinds(), vec!["runtime_error"]); + assert_eq!(outcome.records[0]["path"], "missing.json"); +} + +#[test] +fn it_should_fail_with_a_runtime_error_when_a_given_path_is_a_folder() { + // Arrange + let repository = Repository::new(); + repository.write(&format!("{FOLDER}/task-reviewer-t3-r2.json"), &reply(2)); + + // Act + let outcome = repository.run(&[FOLDER]); + + // Assert + assert_eq!(outcome.exit_code, 1); + assert_eq!(outcome.kinds(), vec!["runtime_error"]); + assert_eq!(outcome.records[0]["path"], FOLDER); +} + +#[test] +fn it_should_fail_with_a_runtime_error_when_a_given_file_is_outside_the_repository() { + // Arrange + let repository = Repository::new(); + let outside = TempDir::new().unwrap(); + let file = outside.path().join("task-reviewer-t3-r2.json"); + fs::write(&file, reply(2)).unwrap(); + + // Act + let outcome = repository.run(&[file.to_str().unwrap()]); + + // Assert + assert_eq!(outcome.exit_code, 1); + assert_eq!(outcome.kinds(), vec!["runtime_error"]); + assert_eq!(outcome.records[0]["message"], "the file is not inside the repository"); +} + +#[test] +fn it_should_fail_with_a_runtime_error_when_run_outside_a_repository() { + // Arrange + let directory = TempDir::new().unwrap(); + + // Act + let outcome = run_in(directory.path(), &["--all"]); + + // Assert + assert_eq!(outcome.exit_code, 1); + assert_eq!(outcome.kinds(), vec!["runtime_error"]); +} + +#[test] +fn it_should_exit_two_with_a_usage_error_when_no_mode_is_given() { + // Arrange + let repository = Repository::new(); + + // Act + let outcome = repository.run(&[]); + + // Assert + assert_eq!(outcome.exit_code, 2); + assert_eq!(outcome.kinds(), vec!["usage_error"]); +} + +#[test] +fn it_should_exit_two_with_a_usage_error_when_both_modes_are_given() { + // Arrange + let repository = Repository::new(); + + // Act + let outcome = repository.run(&["--all", "reply.json"]); + + // Assert + assert_eq!(outcome.exit_code, 2); + assert_eq!(outcome.kinds(), vec!["usage_error"]); +} + +#[test] +fn it_should_exit_zero_with_a_help_record_when_help_is_asked() { + // Arrange + let repository = Repository::new(); + + // Act + let outcome = repository.run(&["--help"]); + + // Assert + assert_eq!(outcome.exit_code, 0); + assert_eq!(outcome.kinds(), vec!["help"]); +} + +#[test] +fn it_should_check_a_given_file_whatever_its_name() { + // Arrange + let repository = Repository::new(); + repository.write("notes.md", "# Notes\n"); + + // Act + let outcome = repository.run(&["notes.md"]); + + // Assert: the file is not selected by its name, so all three checks report it. + assert_eq!(outcome.exit_code, 1); + assert_eq!(outcome.kinds(), vec!["problem", "problem", "problem", "summary"]); + let checks: Vec<_> = outcome.records.iter().filter_map(|record| record["check"].as_str()).collect(); + assert_eq!(checks, vec!["location", "name", "content"]); +} + +#[cfg(unix)] +#[test] +fn it_should_fail_with_a_runtime_error_when_a_given_file_is_a_symbolic_link() { + // Arrange: the link has a valid reply behind it, under a valid name in a replies folder. + let repository = Repository::new(); + repository.write("drafts/reply.txt", &reply(2)); + let link = format!("{FOLDER}/task-reviewer-t3-r2.json"); + fs::create_dir_all(repository.root().join(FOLDER)).unwrap(); + std::os::unix::fs::symlink(repository.root().join("drafts/reply.txt"), repository.root().join(&link)).unwrap(); + + // Act + let outcome = repository.run(&[&link]); + + // Assert + assert_eq!(outcome.exit_code, 1); + assert_eq!( + outcome.records, + vec![json!({ + "kind": "runtime_error", + "path": link, + "message": "the file is a symbolic link; a reply file must be a regular file", + "exit_code": 1 + })] + ); +} + +#[cfg(unix)] +#[test] +fn it_should_skip_a_staged_path_that_is_not_utf8_when_it_is_not_a_candidate() { + // Arrange + let repository = Repository::new(); + repository.stage_raw_name(b"docs/notes-\xff.md"); + + // Act + let outcome = repository.run(&["--all"]); + + // Assert + assert_eq!(outcome.exit_code, 0); + assert_eq!(outcome.records, vec![json!({ "kind": "summary", "files": 0, "problems": 0 })]); +} + +#[cfg(unix)] +#[test] +fn it_should_fail_with_a_runtime_error_when_a_staged_candidate_path_is_not_utf8() { + // Arrange + let repository = Repository::new(); + repository.stage_raw_name(&[FOLDER.as_bytes(), b"/notes-\xff.md"].concat()); + + // Act + let outcome = repository.run(&["--all"]); + + // Assert + assert_eq!(outcome.exit_code, 1); + assert_eq!(outcome.kinds(), vec!["runtime_error"]); + assert_eq!(outcome.records[0]["message"], "the path is not valid UTF-8"); +} + +#[test] +fn it_should_fail_with_a_runtime_error_when_a_given_file_is_not_utf8() { + // Arrange + let repository = Repository::new(); + let path = format!("{FOLDER}/task-reviewer-t3-r2.json"); + repository.write(&path, ""); + fs::write(repository.root().join(&path), b"\xff\xfe").unwrap(); + + // Act + let outcome = repository.run(&[&path]); + + // Assert: the keys are in the documented order. + assert_eq!(outcome.exit_code, 1); + assert_eq!( + outcome.records, + vec![json!({ "kind": "runtime_error", "path": path, "message": "the file is not valid UTF-8", "exit_code": 1 })] + ); + let keys: Vec<_> = outcome.records[0].as_object().unwrap().keys().cloned().collect(); + assert_eq!(keys, ["kind", "path", "message", "exit_code"]); +} + +#[test] +fn it_should_succeed_with_an_empty_summary_when_the_index_has_no_reply_file() { + // Arrange + let repository = Repository::new(); + + // Act + let outcome = repository.run(&["--all"]); + + // Assert + assert_eq!(outcome.exit_code, 0); + assert_eq!(outcome.records, vec![json!({ "kind": "summary", "files": 0, "problems": 0 })]); +} + +#[test] +fn it_should_read_the_index_that_git_index_file_names_when_it_is_set() { + // Arrange: the reply is staged only in a second index, as `git commit ` prepares one. + let repository = Repository::new(); + let path = format!("{FOLDER}/task-reviewer-t3-r2.json"); + repository.write(&path, &reply(1)); + let index = repository.root().join(".git/other-index"); + let status = isolated(Command::new("git"), repository.root()) + .env("GIT_INDEX_FILE", &index) + .args(["add", "--", &path]) + .status() + .unwrap(); + assert!(status.success()); + + // Act + let output = isolated(Command::new(env!("CARGO_BIN_EXE_agent-reply-validator")), repository.root()) + .env("GIT_INDEX_FILE", &index) + .arg("--all") + .output() + .unwrap(); + + // Assert: the reply in the second index disagrees with its name, so the run fails. + assert_eq!(output.status.code(), Some(1)); + let first: Value = serde_json::from_str(std::str::from_utf8(&output.stderr).unwrap().lines().next().unwrap()).unwrap(); + assert_eq!( + (&first["check"], &first["field_path"]), + (&json!("agreement"), &json!("round")) + ); +} + +#[test] +fn it_should_write_the_usage_error_keys_in_the_documented_order() { + // Arrange + let repository = Repository::new(); + + // Act + let outcome = repository.run(&["--version"]); + + // Assert + assert_eq!(outcome.exit_code, 2); + let keys: Vec<_> = outcome.records[0].as_object().unwrap().keys().cloned().collect(); + assert_eq!(keys, ["kind", "message", "exit_code"]); +} + +#[cfg(unix)] +#[test] +fn it_should_fail_with_a_runtime_error_when_a_staged_candidate_is_a_symbolic_link() { + // Arrange: the link's stored target is itself a valid reply text, under a valid name and place. + let repository = Repository::new(); + let link = format!("{FOLDER}/task-reviewer-t3-r2.json"); + fs::create_dir_all(repository.root().join(FOLDER)).unwrap(); + std::os::unix::fs::symlink(reply(2), repository.root().join(&link)).unwrap(); + repository.git(&["add", "--", &link]); + + // Act + let outcome = repository.run(&["--all"]); + + // Assert + assert_eq!(outcome.exit_code, 1); + assert_eq!( + outcome.records, + vec![json!({ + "kind": "runtime_error", + "path": link, + "message": "the file is a symbolic link; a reply file must be a regular file", + "exit_code": 1 + })] + ); +} diff --git a/contrib/dev-tools/checks/agent-reply-validator/tests/schema.rs b/contrib/dev-tools/checks/agent-reply-validator/tests/schema.rs new file mode 100644 index 0000000000..e4cfa31239 --- /dev/null +++ b/contrib/dev-tools/checks/agent-reply-validator/tests/schema.rs @@ -0,0 +1,45 @@ +//! The tracked schema artifact must be the one the model generates. + +use std::fs; +use std::path::Path; +use std::process::Command; + +use agent_reply_validator::schema::{ARTIFACT_PATH, reply_schema_json}; + +#[test] +fn it_should_track_the_schema_that_the_model_generates() { + // Arrange + let repository_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../.."); + let tracked = fs::read_to_string(repository_root.join(ARTIFACT_PATH)).expect("the schema artifact is tracked"); + + // Act + let generated = reply_schema_json(); + + // Assert + assert!( + tracked == generated, + "{ARTIFACT_PATH} differs from the model; regenerate it with \ + `cargo run --package agent-reply-validator --bin agent-reply-schema`" + ); +} + +#[test] +fn it_should_refuse_any_argument_and_write_nothing() { + // Arrange + let artifact = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../..").join(ARTIFACT_PATH); + let modified = |path: &Path| fs::metadata(path).and_then(|metadata| metadata.modified()).ok(); + let before = (fs::read_to_string(&artifact).ok(), modified(&artifact)); + + // Act + let output = Command::new(env!("CARGO_BIN_EXE_agent-reply-schema")) + .arg("check") + .output() + .expect("the binary runs"); + + // Assert + assert_eq!(output.status.code(), Some(2)); + assert_eq!(String::from_utf8_lossy(&output.stdout), ""); + let record: serde_json::Value = serde_json::from_slice(&output.stderr).expect("stderr holds one JSON record"); + assert_eq!(record["kind"], "usage_error"); + assert_eq!((fs::read_to_string(&artifact).ok(), modified(&artifact)), before); +} diff --git a/contrib/dev-tools/git/hooks/pre-commit.sh b/contrib/dev-tools/git/hooks/pre-commit.sh index 047565eebf..0bd44da285 100755 --- a/contrib/dev-tools/git/hooks/pre-commit.sh +++ b/contrib/dev-tools/git/hooks/pre-commit.sh @@ -54,6 +54,7 @@ declare -a STEPS=( "Checking staged Markdown frontmatter|cargo run --quiet --package frontmatter-validator --bin frontmatter-validator -- --staged" "Checking the agent skill layout|cargo run --quiet --package frontmatter-validator --bin frontmatter-validator -- --skill-layout" "Checking the agent skill descriptions|cargo run --quiet --package frontmatter-validator --bin frontmatter-validator -- --skill-descriptions" + "Checking agent reply files|cargo run --quiet --package agent-reply-validator --bin agent-reply-validator -- --all" "Checking for unused dependencies (cargo machete --with-metadata)|cargo machete --with-metadata" "Checking workspace layer boundary bans (cargo deny check bans)|cargo deny check bans" "Checking nightly Rust formatting|cargo +nightly fmt --all -- --check" diff --git a/docs/adrs/20260519000000_define_global_cli_output_contract.md b/docs/adrs/20260519000000_define_global_cli_output_contract.md index 257933fe14..fff1d53237 100644 --- a/docs/adrs/20260519000000_define_global_cli_output_contract.md +++ b/docs/adrs/20260519000000_define_global_cli_output_contract.md @@ -84,6 +84,8 @@ All diagnostics go to stderr via the tracing subscriber or direct JSON stderr wr | `clippy-allow-reasons` | `no-stdout-result` | Prospective repository check; pass/fail via exit code | | `frontmatter-validator` | `no-stdout-result` | Markdown frontmatter check; NDJSON diagnostics on stderr | | `frontmatter-schema` | `no-stdout-result` | Frontmatter schema check; currently non-compliant (plain-text diagnostics on stderr), migration issue #2763 | +| `agent-reply-validator` | `no-stdout-result` | Agent reply file check (issue #2904); NDJSON diagnostics on stderr | +| `agent-reply-schema` | `no-stdout-result` | Writes the agent reply schema (issue #2904); one NDJSON record on stderr | | `shipped-features-check` | `no-stdout-result` | Shipped-binary feature check; NDJSON diagnostics on stderr | | `agent-review-report-contract` | `no-stdout-result` | Review report check; currently non-compliant (plain-text success line on stdout, plain-text failures on stderr), migration issue #2763 | | `workspace-coupling` | `no-stdout-result` | Writes its Markdown report to a file (`OUTPUT_FILE`), nothing on stdout; NDJSON status events on stderr | diff --git a/docs/index.md b/docs/index.md index 56abc3e4d9..1fa10e4f0a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -53,7 +53,7 @@ Operational and development guides for working with the tracker. | [release_process.md](release_process.md) | Release index: versioning policy and which release process to use | | [release-process/tracker.md](release-process/tracker.md) | Tracker binary release: staging branches, tag, and deployment | | [release-process/workspace-packages.md](release-process/workspace-packages.md) | Workspace package and standalone crate release | -| [schemas/README.md](schemas/README.md) | Generated frontmatter JSON Schema: regeneration, drift check, Rust-only invariants | +| [schemas/README.md](schemas/README.md) | Generated JSON Schemas (frontmatter, agent replies): regeneration and drift checks | | [security/README.md](security/README.md) | Security processes, analysis catalogs, scanning, and disclosure routing | | [self-hosted-runner.md](self-hosted-runner.md) | Set up and operate the self-hosted CI runner for the container test jobs | | [self-hosted-runner-reports/README.md](self-hosted-runner-reports/README.md) | Periodic health reports for the self-hosted CI runner: CPU, disk space, and cleanup | diff --git a/docs/issues/open/2904-2003-migrate-custom-agents-to-claude-code/ISSUE.md b/docs/issues/open/2904-2003-migrate-custom-agents-to-claude-code/ISSUE.md index 18573fea88..f8dd9d84b8 100644 --- a/docs/issues/open/2904-2003-migrate-custom-agents-to-claude-code/ISSUE.md +++ b/docs/issues/open/2904-2003-migrate-custom-agents-to-claude-code/ISSUE.md @@ -7,9 +7,9 @@ priority: p1 epic: 2003 github-issue: 2904 spec-path: docs/issues/open/2904-2003-migrate-custom-agents-to-claude-code/ISSUE.md -branch: "2904-t2-pointer-claude-md" +branch: "2904-t3-reply-schema" related-pr: null -last-updated-utc: "2026-11-17 18:34" +last-updated-utc: "2026-11-18 17:59" semantic-links: skill-links: - create-issue @@ -518,7 +518,7 @@ on are merged. | --- | ------ | ---- | ----------------------- | | T1 | DONE | Specification pull request | This specification in `docs/issues/open/`, and a new row in the EPIC's Subissues table | | T2 | DONE | Pointer `CLAUDE.md` | A root `CLAUDE.md` whose only content is the import of `AGENTS.md` (D11); if scenario M4 shows that a scoped `AGENTS.md` is not loaded, an import-only `CLAUDE.md` beside each of the ten scoped `AGENTS.md` files; scenario M4 recorded | -| T3 | TODO | Reply schema and validator | `docs/schemas/agent-reply-v1.schema.json`; the validator with tests, developed in the progressive loop of the `write-unit-test` skill with a recorded design review per increment, and run by the repository checks; `docs/schemas/README.md` updated (D18) | +| T3 | DONE | Reply schema and validator | `docs/schemas/agent-reply-v1.schema.json`; the validator with tests, developed in the progressive loop of the `write-unit-test` skill with a recorded design review per increment, and run by the repository checks; `docs/schemas/README.md` updated (D18) | | T4 | TODO | `pr-review-handler` | `.claude/agents/pr-review-handler.md` with the pinned model; `wait-for-pr-review` and `process-pr-review` say which agent runs a round; the inventory `removed-profile-rules.md` created in this folder with the rules of `copilot-suggestions-handler` (AC6); scenarios M1 to M3 recorded | | T5 | TODO | `task-reviewer` | The agent file with the pinned model and the stop hook (D17), with tests of its limit of 3 refusals; the complexity item in `review-task` (D12); the reply rule in `review-task`, which also says that a reply file satisfies the earlier template's checkpoint (D18); scenario M7 recorded | | T6 | TODO | `implementer` | The agent file; the three committer rules in `commit-changes` (D14); the rules that only `planner` held moved into `create-issue` | @@ -602,6 +602,7 @@ a Conventional Commit message with the narrow affected scope, and sign every com - 2026-11-17 17:19 UTC - Claude Code (Claude Fable 5.2) - Independent review of T2 recorded in `agent-review-reports.md` (REVIEW PASSED, two minor findings and four nits). Addressed: the evidence states which probes have recorded tool calls and that the probed files were committed afterwards; `status` is `in-progress` and `branch` names the T2 branch; the T10 row names the ADR line that T2 made untrue; the branch is rebased on `develop`. - 2026-11-17 17:45 UTC - Claude Code (Claude Fable 5.2) - Addressed the reviews `5943570147` of `da2ce7` and `5943581377` of Copilot on pull request #2920: `.dockerignore` re-excludes the pointer files; the evidence states what probes 1, 2 and 4 show, names its commands as run, and stores every probe's answer in `evidence/m4-probe-answers.md`; T1 is `DONE` and the EPIC row is `IN_PROGRESS`. - 2026-11-17 18:34 UTC - Claude Code (Claude Fable 5.2) - Addressed the approving review `5944190011` of `da2ce7` on pull request #2920 (two nits): the evidence records the correction to the description of checkout P, and the stored answers say which angle-bracket names are the probes' own. +- 2026-11-18 17:59 UTC - Claude Code (Claude Opus 5.5) - Task T3: added the crate `agent-reply-validator` (an AI-harness workspace member, not a default member) in five test increments, each with an independent test-design review recorded in `agent-review-reports.md` and a mutation check of its rules: the reply file name, the strict content model, the checks of one file (place, name, content, agreement), the command (`--all` over the index for the hook and CI; paths on disk for the stop hook of T5), and the schema `docs/schemas/agent-reply-v1.schema.json` generated from the model with a drift test. The pre-commit hook and the Docs Lint workflow run `agent-reply-validator --all`; `docs/schemas/README.md`, the package catalog and the CLI output contract ADR describe it. Two choices the maintainer did not settle when asked, made with the recommended option: the schema is generated from a Rust model, and the per-increment design review is made by an independent subagent. The independent review of the whole task is recorded in `agent-review-reports.md` (REVIEW PASSED, two minor findings and a nit, all addressed); `docker build --target recipe --file Containerfile .` exited 0 with the new workspace member. ## Acceptance Criteria diff --git a/docs/issues/open/2904-2003-migrate-custom-agents-to-claude-code/agent-review-reports.md b/docs/issues/open/2904-2003-migrate-custom-agents-to-claude-code/agent-review-reports.md index bc3fbe721c..82f281b8ce 100644 --- a/docs/issues/open/2904-2003-migrate-custom-agents-to-claude-code/agent-review-reports.md +++ b/docs/issues/open/2904-2003-migrate-custom-agents-to-claude-code/agent-review-reports.md @@ -47,3 +47,234 @@ semantic-links: - Author, done before the pull request: reworded the two evidence passages; set `status: in-progress` and the T2 branch; added the ADR line to the T10 row; rebased on `develop`. The checkpoint nit is left as it is: the tick is true, and it is named here. + +### 2026-11-18 17:25 UTC - Test-design reviewer (Claude Code subagent, Claude Opus 5.5, `write-unit-test` skill) + +- Invocation scope: Read-only review of task T3, increment 1, on branch `2904-t3-reply-schema` + before its commit: the new crate `agent-reply-validator` (workspace member, `.dockerignore` + entry) and its file-name parser `src/name.rs` with the unit tests. Two rounds: a review, then + a re-review of the fixes. +- Inputs: D18 and P1 of the specification; `.claude/skills/write-unit-test/SKILL.md`; + `AGENTS.md`; the uncommitted crate. +- Evidence: `cargo test -q -p agent-reply-validator` passed with 23 tests in the first round + and 34 in the second. In the second round the reviewer checked, by reading the code, that + each of the author's seven mutations has a failing case: the digit check, the leading-zero + check, `u8::try_from` replaced by `as u8`, a plain `parse` on the `pr` branch, the + `number >= 1` and `number <= MAX` checks of `Round::new`, and the `-` after the agent. The + author ran the seven mutations; each made at least one test fail. +- Findings: + - Major (round 1): no test guarded the digit-only check, which alone rejects a leading `+` + (`t+2`, `r+1`); the `pr#2920` case did not guard it. + - Minor (round 1): no zero or leading-zero case on the `pr` branch. + - Minor (round 1): `r256` did not guard `u8::try_from`; `as u8` would turn it into 0, which + is still rejected. + - Minor (round 1): the round-trip test covered only a `pr` subject. + - Minor (round 1): no Arrange/Act/Assert comments and no `_when_` condition in the names. + - Nit (round 1): the error cases repeat the file name in the expected value. + - Nit (round 1): `rstest` without `default-features = false`, unlike some sibling crates. + - Suggestion (round 1): keep the file name in every `NameError` variant. + - Suggestion (round 1): the `!text.is_empty()` clause is redundant. + - Nit (round 2): the `Round::new` assertion could be plainer; the `pr#2920` case still + guards no clause of its own. +- Verdict: REVIEW FAILED in round 1; REVIEW PASSED in round 2. +- Follow-up actions: + - Author, done before the commit: added the cases `t+2`, `r+1`, `pr0`, `pr02`, `pr+2`, + `PR2920` and `r257`; made the round-trip test cover a task and a pull request; added the + comments and `_when_` names; removed the redundant clause. A mutation showed the + `number >= 1` clause unguarded, because `r0` is rejected first by the leading-zero rule, so + an rstest on `Round::new` was added. + - Not changed, with the reviewer's agreement in round 2: the repeated file name (the explicit + expected value is clearer than a helper), the file name in `NameError` (the validator + reports the path with every diagnostic), and `rstest` (as in `frontmatter-validator`). The + round 2 nits are left as they are. + - Author, after round 2: the spell checker rejected the case name that joins the agent and the + subject with no separator, so that case now uses `task-reviewer_t2-r1.json`, a wrong separator + instead. It guards the same clause: removing the `-` check makes it fail. + +### 2026-11-18 17:35 UTC - Test-design reviewer (Claude Code subagent, Claude Opus 5.5, `write-unit-test` skill) + +- Invocation scope: Read-only review of task T3, increment 2, on branch `2904-t3-reply-schema` + before its commit: `src/reply.rs`, the strict serde model of a reply file's JSON content, + with its unit tests and the new dependencies `serde`, `serde_json` and + `serde_path_to_error`. Two rounds: a review, then a re-review of the fixes. +- Inputs: D18 of the specification and the author's choices it leaves open (every field + required, no unknown field, `schema-version` the number 1, no blank text, `created-utc` as + `YYYY-MM-DD HH:MM` with calendar validity, the review-audit severities, no rule joining two + fields); `.claude/skills/write-unit-test/SKILL.md`; `AGENTS.md`. +- Evidence: `cargo test -p agent-reply-validator` passed with 89 tests in round 1 and 96 in + round 2; clippy printed nothing. The reviewer checked by reading, and once with `rustc` that + `u16::from_str` accepts a leading `+`. The author ran 28 mutations; each made at least one + test fail. +- Findings: + - Major (round 1): no test guarded the digit clause of the time layout, which alone rejects + `2026-+1-18 17:25`. + - Minor (round 1): only April stood for the 30-day months, and no 31-day month but December + was tested at day 31. + - Minor (round 1): the rejection table asserted only the path, not the reason. + - Minor (round 1): no test of malformed JSON. + - Suggestion (round 1): a lower bound for the year. + - Suggestion (round 1): record that no rule joins two fields; no test of a duplicate key. + - Nit (round 1): `std::ops::Range` written in full; a `clone` only for an error message; + the serde impls of the name types live in `reply.rs`, and the format mixes three casings. + - Nit (round 2): the time cases all assert the same reason, so they do not say which check + failed; each is shown to fail under its own mutation. +- Verdict: REVIEW FAILED in round 1; REVIEW PASSED in round 2. +- Follow-up actions: + - Author, done before the commit: added cases for a `+` in the time, day 31 of June, + September and November, an accepted 31 January, a duplicate key and a truncated object; + every rejection case asserts a reason; the module doc says no rule joins two fields; one + `is_blank` helper; `Range` imported. + - Not changed, with the reviewer's agreement in round 2: no year floor (any floor is + arbitrary, and the agent writes the time from `date -u`); the serde impls stay with the + reply format; the round 2 nit. + +### 2026-11-18 17:39 UTC - Test-design reviewer (Claude Code subagent, Claude Opus 5.5, `write-unit-test` skill) + +- Invocation scope: Read-only review of task T3, increment 3, on branch `2904-t3-reply-schema` + before its commit: `src/file.rs`, the checks of one reply file from its repository-relative + path and its text (location, name, content, and agreement of the name with the `agent`, + `subject` and `round` fields), with its unit tests. +- Inputs: D18 of the specification and the author's choices (the location read from the path + alone, every problem reported, agreement checked only when name and content are valid, one + problem per disagreeing field); `.claude/skills/write-unit-test/SKILL.md`; `AGENTS.md`. +- Evidence: `cargo test -p agent-reply-validator` passed with 116 tests. The reviewer checked by + reading that each of the author's 14 mutations has a failing case. +- Findings: + - Minor: the messages of the content and location problems, and the empty field path of the + location and name problems, were not asserted. + - Minor: `.` and `..` passed as the specification folder. + - Suggestion: paths starting with `./`, absolute paths and `\` separators fail with a + confusing name problem; the command must pass repository-relative paths with `/`. + - Suggestion: decide in the command increment which files it discovers, since the location + check only matters if misplaced files can reach it. + - Suggestion: a trailing slash and a file named `agent-replies` give acceptable outcomes. + - Nit: two test names say the agreement is skipped, which the types already enforce; the + fixture's evidence text named a stale test count. +- Verdict: REVIEW PASSED +- Follow-up actions: + - Author, done before the commit: the location, name and content tests assert the whole + problem (the content message only up to its position, which depends on the key order); + `.` and `..` are rejected as the specification folder, with a case each; the fixture's + evidence text no longer names a count. 118 tests pass, and four more mutations (each dot + folder, the content message, the content field path) each made a test fail. + - For the command increment: build the paths from the repository root with `/`, and choose + the discovery rule there. The nits are left as they are. + +### 2026-11-18 17:48 UTC - Test-design reviewer (Claude Code subagent, Claude Opus 5.5, `write-unit-test` skill) + +- Invocation scope: Read-only review of task T3, increment 4, on branch `2904-t3-reply-schema` + before its commit: the command `agent-reply-validator` (`src/bin/agent-reply-validator/`), + its command-boundary tests `tests/cli.rs`, and `is_reply_file_candidate` in `src/file.rs`. + Two rounds: a review, then a re-review of the fixes. +- Inputs: D18 of the specification; the CLI output contract ADR + `20260519000000_define_global_cli_output_contract.md`, sections 1 to 3; the + `frontmatter-validator` command as the pattern; `.claude/skills/write-unit-test/SKILL.md`; + `AGENTS.md`. +- Evidence: `cargo test -p agent-reply-validator` passed in both rounds (153 tests in round 2). + The reviewer checked the ADR contract (empty stdout, NDJSON records with `kind` on stderr, + exit codes 0, 1 and 2) and the git edge cases (a staged file deleted from disk, `git rm + --cached`, a relative `GIT_INDEX_FILE`) by reading. +- Findings: + - Major (round 1): no test showed that path mode checks a file whatever its name. + - Major (round 1): `fs::canonicalize` followed a symbolic link, so a link was checked under + its target's place and name. + - Minor (round 1): no unit tests for a failing stderr, `report` and `repository_relative`; no + test of the key order of the error records, of `--version`, of non-UTF-8 content, of + `GIT_INDEX_FILE` or of an empty index; one non-UTF-8 path anywhere in the index stopped + `--all`; a non-UTF-8 path was reported as outside the repository; a merge conflict stops + `--all`. + - Suggestion (round 1): `--all` checks every reply file, not only those of the pull request; + the stop hook must run inside the repository; `git.rs` copies the one of + `frontmatter-validator`. + - Nit (round 1): a path given twice is checked twice; two tests asserted on one record field + by index. + - Minor (round 2): no test put a non-UTF-8 path in the index; the author's report named a + mutation of the UTF-8 branch in words that read as the non-UTF-8 one. + - Minor (round 2): path mode read through a link, while `--all` reads the link's stored target + path, so the two modes disagreed on a link. + - Nit (round 2): one test kept only the `check` fields; one parsed stderr with `contains`. +- Verdict: REVIEW FAILED in round 1; REVIEW PASSED in round 2. +- Follow-up actions: + - Author, done before the commit: the tests and fixes above, with `serde_json` + `preserve_order` for the key order; the index is read as byte paths and only a candidate + path that is not UTF-8 stops the run, with a Unix test for each case; path mode rejects a + symbolic link, with a test; the two round 2 nits fixed. 155 tests pass. Mutations of the + candidate filter in path mode, of the link check, and of each non-UTF-8 branch each made a + test fail. A dedupe of conflicted paths was tried and removed as an equivalent mutant: a + conflicted candidate has no staged content, so the run stops with a runtime error either + way, as the doc comment says. + - Not changed: `--all` checks every reply file (CI runs it on the pull request's tree, and + `develop` only receives checked trees); the stop hook's working directory is for T5 to + confirm; a path given twice; the copy of `git.rs`, which a shared crate in the + harness-workspace work of EPIC #2003 can remove. + +### 2026-11-18 17:55 UTC - Test-design reviewer (Claude Code subagent, Claude Opus 5.5, `write-unit-test` skill) + +- Invocation scope: Read-only review of task T3, increment 5, on branch `2904-t3-reply-schema` + before its commit: the JSON Schema `docs/schemas/agent-reply-v1.schema.json` generated from the + reply model with `schemars` (`src/schema.rs`), its unit tests, the `agent-reply-schema` + binary that writes it, and the drift test `tests/schema.rs`. Two rounds: a review, then a + re-review of the fixes. +- Inputs: D18 of the specification; `docs/schemas/README.md` and the `frontmatter-schema` + binary as precedent; the CLI output contract ADR; `.claude/skills/add-rust-dependency/SKILL.md`; + `.claude/skills/write-unit-test/SKILL.md`. +- Evidence: `cargo test -p agent-reply-validator` passed in both rounds. In round 1 the + reviewer ran a probe crate against the model: a reply written as a JSON array was accepted, + `1.0` and a duplicate key were rejected, a text holding only a byte order mark (U+FEFF) was + accepted and one holding only a next-line character (U+0085) rejected. +- Findings: + - Major (round 1): serde reads a struct from an array of its fields, so a reply or a finding + written as a JSON array was accepted while the schema says `object`. The gap came from + increment 2. + - Minor (round 1): the module doc named one difference between the schema and the model; + there are four (the calendar, `1.0` as an integer, a duplicate key, and Unicode against + ECMA-262 white space for U+0085 and U+FEFF). + - Minor (round 1): the pattern tests use the Rust `regex` crate, not ECMA-262. + - Minor (round 1): the agent test built its expectation from `Agent::ALL`; the binary had no + test and wrote relative to the working directory; neither binary was in the CLI ADR table. + - Suggestion (round 1): validate sample replies against the schema with a JSON Schema crate. + - Nit (round 1): two tests checked two things each; `docs/schemas/README.md` lacked the + entry. + - Nit (round 2): bare `unwrap` in the new test. + - Suggestion (round 2): say that the second parse of the text is deliberate. +- Verdict: REVIEW FAILED in round 1; REVIEW PASSED in round 2. +- Follow-up actions: + - Author, done before the commit: `Reply::from_json` rejects a reply or finding written as an + array, with a case each and a mutation of each branch failing a test; the four differences + are in the module doc, the white-space gap documented rather than changed; literal agent + names; the binary writes to a path built from `CARGO_MANIFEST_DIR`, with a test of its + refusal of arguments; the tests split, and the reply and finding tests also check + `"type": "object"`; the round 2 nit and suggestion applied. + - Not changed: a JSON Schema validation crate (a heavy dev-dependency; the drift test and the + pattern tests cover the projection); a test of the binary's write failure (its path is fixed + at build time). The ADR table and `docs/schemas/README.md` entries are in the documentation + commit of T3. + +### 2026-11-18 18:01 UTC - Task reviewer (Claude Code subagent, Claude Opus 5.5, `review-task` skill) + +- Invocation scope: Read-only review of task T3 as a whole on branch `2904-t3-reply-schema`, + before its pull request: the seven commits of the branch (five reviewed test increments of the + crate `agent-reply-validator`, the wiring into the pre-commit hook, the Docs Lint workflow and + the `run-pre-commit-checks` skill, and the documentation) and the uncommitted specification + update (T3 `DONE`, the branch, a Progress Log line). The per-increment test-design reviews + above were not redone. +- Inputs: the T3 rows of the Implementation Plan and of Commit Points, D18, P1 and the + Verification Plan of the specification; `.claude/skills/review-task/SKILL.md`; + `.claude/skills/add-workspace-member/SKILL.md`. +- Evidence: `cargo test -p agent-reply-validator` passed; `cargo clippy -p agent-reply-validator + --all-targets -- -D warnings` exited 0; `agent-reply-validator --all` exited 0 with + `{"kind":"summary","files":0,"problems":0}`; `linter markdown` and `linter cspell` exited 0; + `git merge-tree --write-tree torrust/develop HEAD` merged with no conflict. The reviewer + checked by reading the commit order against Commit Points, the hook step order, the workspace + member and `.dockerignore` entry, the code against D18, and the claims of the documentation + (the drift test runs in the pre-push hook and in the `Testing` workflow). +- Findings: + - Minor: the `docs/index.md` row of `schemas/README.md` named only the frontmatter schema. + - Minor: no record of `docker build --target recipe --file Containerfile .`, which + `add-workspace-member` asks for after adding a member. + - Nit: the Progress Log line for T3 did not name this task-level review. +- Verdict: REVIEW PASSED +- Follow-up actions: + - Author, done before the pull request: the index row names both schemas; + `docker build --target recipe --file Containerfile .` exited 0 at 18:01:16Z (`date -u`); + this entry records the review, and the Progress Log line names it. diff --git a/docs/packages.md b/docs/packages.md index f37a3b07c6..d1565d4781 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -297,6 +297,7 @@ Under `contrib/dev-tools/`, all _(unpublished)_. | Tool | Crate Name | Description | | ------------------------------------- | ------------------------------ | ---------------------------------------------------------- | | `analysis/workspace-coupling` | `workspace-coupling` | Generates the workspace coupling report | +| `checks/agent-reply-validator` | `agent-reply-validator` | Validates agent reply files and generates their schema | | `checks/agent-review-report-contract` | `agent-review-report-contract` | Validates agent-review report documentation contracts | | `checks/ci-gate` | `ci-gate` | Decides which CI job groups a pull request needs | | `checks/clippy-allow-reasons` | `clippy-allow-reasons` | Validates documented Clippy allow attributes | diff --git a/docs/pr-reviews/pr-2952-review/PR-REVIEW.md b/docs/pr-reviews/pr-2952-review/PR-REVIEW.md new file mode 100644 index 0000000000..1e33d8fa0a --- /dev/null +++ b/docs/pr-reviews/pr-2952-review/PR-REVIEW.md @@ -0,0 +1,226 @@ +--- +pr-number: 2952 +pr-url: https://github.com/torrust/torrust-tracker/pull/2952 +last-updated-utc: "2026-11-19 07:49" +--- + + + +# PR #2952 Review Audit + +Source: pull-request reviews and inline review threads for https://github.com/torrust/torrust-tracker/pull/2952. + + + +## Ownership + +The PR author owns this tracked audit record. Reviewers, including repository review agents, +deliver findings through GitHub and have no repository-artifact obligation. + +- Post-merge workflow approval: N/A + + + +## Status Values + +- Relationship: `ORIGINAL`, `RE_RAISE_OF:` +- Disposition: `FIXED`, `NO_ACTION`, `SUPERSEDED`, `FOLLOW_UP` +- Thread state: `OPEN`, `RESOLVED`, `NON_RESOLVABLE`, `SUPERSEDED`. `OPEN` applies prospectively + to audits created or updated for approved follow-up work; historical audits remain valid without + bulk migration. +- Severity: `Blocker`, `Major`, `Minor`, `Nit`, `Suggestion`; append `(inferred)` when derived + from free prose. +- Author class: `Copilot`, `Human`, `Unknown` +- Category: `link-integrity`, `formatting`, `metadata`, `testing`, `correctness`, + `documentation`, `maintainability`, `security`, `other` +- An outdated thread whose concern was fixed is `FIXED`/`RESOLVED`, even when GitHub marks the + original thread outdated after the push. For in-PR feedback, use `NO_ACTION`/`SUPERSEDED` only + for a duplicate, superseded, or no-change concern. A post-merge `NO_ACTION` requires maintainer + approval to decline the follow-up work. +- When the current identity cannot resolve a thread (`viewerCanResolve` is `false`), keep the + disposition established from the current tree and record `Thread state=OPEN`. The reviewer or PR + author resolves it; permission says nothing about whether the concern was fixed. + +## Findings + +Round 1 is Copilot's review `5963279729` (COMMENTED, three comments without IDs, recorded as F1 to F3) on the first head. +Round 2 is Copilot's review `5964554730` (COMMENTED, two findings in its body with its own IDs F4 and F6, which collide +with no row) on the head that carried the round 1 audit. +Round 3 is Copilot's review `5970792387` (COMMENTED, one inline comment, recorded as F7) on the head that carried the round 2 +audit. +Round 4 is the approving review `5971081099` of `da2ce7` (APPROVED, four inline comments with its own IDs F1 to F4, which +collide with rows of round 1, so they are recorded as F8 to F11) on the head that carried the round 3 audit. + +| Finding ID | Review finding reference | Author class | Severity | Category | Relationship | Disposition | Thread state | +| ---------- | ------------------------ | ------------ | -------- | -------- | ------------ | ----------- | ------------ | +| F1 | `review-finding:pr-2952-f1` | Copilot | Minor (inferred) | documentation | ORIGINAL | FIXED | RESOLVED | +| F2 | `review-finding:pr-2952-f2` | Copilot | Suggestion (inferred) | maintainability | ORIGINAL | NO_ACTION | SUPERSEDED | +| F3 | `review-finding:pr-2952-f3` | Copilot | Minor (inferred) | testing | ORIGINAL | FIXED | RESOLVED | +| F4 | `review-finding:pr-2952-f4` | Copilot | Major | correctness | ORIGINAL | FIXED | NON_RESOLVABLE | +| F6 | `review-finding:pr-2952-f6` | Copilot | Minor | correctness | ORIGINAL | FIXED | NON_RESOLVABLE | +| F7 | `review-finding:pr-2952-f7` | Copilot | Major (inferred) | correctness | ORIGINAL | NO_ACTION | SUPERSEDED | +| F8 | `review-finding:pr-2952-f8` | Human | Minor | documentation | ORIGINAL | FIXED | RESOLVED | +| F9 | `review-finding:pr-2952-f9` | Human | Nit | documentation | ORIGINAL | FIXED | RESOLVED | +| F10 | `review-finding:pr-2952-f10` | Human | Nit | testing | ORIGINAL | FIXED | RESOLVED | +| F11 | `review-finding:pr-2952-f11` | Human | Nit | documentation | ORIGINAL | FIXED | RESOLVED | + +## Finding Details + +### F1 - `--version` is a usage error + +- PR number: 2952 +- Source review ID: 5963279729 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4619375545 +- Concern: clap's `DisplayVersion` would be treated as a usage error; either support `--version` or make its absence intentional and stable. +- Solution: The command has no version flag: clap adds one only with `#[command(version)]`, so `--version` is an unknown argument, a usage error with exit 2. The doc comment of the arguments now says so; the command test of the usage-error record already runs `--version` and expects exit 2. +- Current-tree verification: `cargo test -q -p agent-reply-validator --test cli` passed, including `it_should_write_the_usage_error_keys_in_the_documented_order`, which runs `--version`. +- Resolution reference: `docs(agent-reply-validator): [#2904] say that the command has no --version` +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4619474947 + +### F2 - `--all` stops at the first runtime error + +- PR number: 2952 +- Source review ID: 5963279729 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4619375594 +- Concern: a non-UTF-8 candidate path or file content stops `--all`, which can hide problems of other reply files in the same run; the suggestion is to report each runtime error and go on. +- Solution: No change. A runtime error is a failure of the environment (git, the index, the encoding of a file), not a finding about a reply, and the run exits 1 with the record that names the path, as `frontmatter-validator` does. Fixing it and running again shows the rest. +- Current-tree verification: `check_index` in `src/bin/agent-reply-validator/main.rs` returns at the first runtime error; the command tests `it_should_fail_with_a_runtime_error_when_a_staged_candidate_path_is_not_utf8` and the non-UTF-8 content test expect one `runtime_error` record and exit 1. +- Resolution reference: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4619475451 +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4619475451 + +### F3 - The pattern tests use the Rust `regex` engine, not ECMA-262 + +- PR number: 2952 +- Source review ID: 5963279729 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4619375673 +- Concern: JSON Schema patterns are ECMA-262; the tests read them with Rust's `regex`, so their messages can read as proof of equivalence. +- Solution: A comment on the tests and their assertion messages say the patterns are read by the Rust `regex` engine, an approximation, and that the tests show agreement on their samples only; the module doc already names the known gap (U+0085, U+FEFF). +- Current-tree verification: `cargo test -q -p agent-reply-validator --lib` passed (154 tests). +- Resolution reference: `test(agent-reply-validator): [#2904] say the pattern tests use the Rust regex engine` +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4619475894 + +### F4 - Verdicts and severities were read from the object form too + +- PR number: 2952 +- Source review ID: 5964554730 +- Reviewer finding ID: F4 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2952#pullrequestreview-5964554730 +- Concern: Serde's derived enum reader accepts `"verdict": {"REVIEW_PASSED": null}` and `"severity": {"Major": null}`, which the schema does not allow, and the shape check did not catch them. +- Solution: Both fields are read from a JSON string and then as the enum, so the object form is rejected with "invalid type: map, expected a string". The schema is unchanged. +- Current-tree verification: the rejection cases `verdict_as_an_object` and `severity_as_an_object` pass; removing the string-only reading of either field fails its case; `agent-reply-schema` regenerated the artifact with no change. +- Resolution reference: `fix(agent-reply-validator): [#2904] read verdicts and severities from strings only` +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2952#issuecomment-6990977404 + +### F6 - `--all` accepted a reply file staged as a symbolic link + +- PR number: 2952 +- Source review ID: 5964554730 +- Reviewer finding ID: F6 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2952#pullrequestreview-5964554730 +- Concern: `--all` discarded the index modes, so a symbolic link whose stored target text is a valid reply passed, while path mode rejects links. +- Solution: `--all` reads each entry with `git ls-files --stage -z` and rejects a candidate with mode `120000` before reading its content, with the same message as path mode. +- Current-tree verification: the command test `it_should_fail_with_a_runtime_error_when_a_staged_candidate_is_a_symbolic_link` passes; removing the check fails it. +- Resolution reference: `fix(agent-reply-validator): [#2904] reject a reply file staged as a symbolic link` +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2952#issuecomment-6990977404 + +### F7 - The verdict assertion compares JSON values with strings + +- PR number: 2952 +- Source review ID: 5970792387 +- Reviewer finding ID: N/A +- Source URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625468317 +- Concern: `assert_eq!(verdicts, [...])` compares a `Vec<&serde_json::Value>` with an array of `&str`, which the review says does not compile. +- Solution: No change. It compiles: `serde_json` implements `PartialEq` for `Value`, so `&Value == &str` holds through the standard implementation for references, and the assertion compares each verdict's `const` with the expected name. +- Current-tree verification: `cargo test -q -p agent-reply-validator --lib schema` passed (28 tests), including `it_should_close_the_lists_of_verdicts_and_severities`. +- Resolution reference: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625490224 +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625490224 + +### F8 - The README called the validator stricter on blank text + +- PR number: 2952 +- Source review ID: 5971081099 +- Reviewer finding ID: F1 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625703462 +- Concern: `docs/schemas/README.md` says the validator is stricter than the schema for blank text; for U+FEFF it is the other way, since ECMA-262 counts U+FEFF as white space and Rust's `trim` does not. +- Solution: The README now says the validator differs, and gives the direction per character: a text of only U+0085 passes the schema and fails the validator, a text of only U+FEFF fails the schema and passes the validator. The module documentation says the same. The body of the earlier commit that said "stricter" stays as it is, since history is not rewritten. +- Current-tree verification: `docs/schemas/README.md` and the module documentation of `src/schema.rs` give the same direction per character; `linter all` passed in the pre-commit gate. +- Resolution reference: `docs(schemas): [#2904] say in which direction the reply validator differs on blank text` +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625764634 + +### F9 - The subject pattern accepts numbers the parser rejects + +- PR number: 2952 +- Source review ID: 5971081099 +- Reviewer finding ID: F2 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625703469 +- Concern: `^(t|pr)[1-9][0-9]*$` has no length bound while the parser reads a `u32`, so `t4294967296` passes the schema and fails the validator; the difference is not listed. +- Solution: The module documentation and the README list the 32-bit limit as a difference, and the test `it_should_match_a_subject_number_too_large_for_the_parser` pins it: the pattern matches `t4294967296` and the parser rejects it. +- Current-tree verification: `cargo test -q -p agent-reply-validator` passed (157 unit, 6 helper, 23 command and 2 schema tests). +- Resolution reference: `test(agent-reply-validator): [#2904] name the 32-bit limit of a subject number as a schema difference` +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625764944 + +### F10 - The argument-refusal test could not observe a write + +- PR number: 2952 +- Source review ID: 5971081099 +- Reviewer finding ID: F3 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625703474 +- Concern: the test compared only the artifact's content, which a write of the same content leaves unchanged, so its name promised more than it checked. +- Solution: The test compares the artifact's modification time as well as its content, before and after the run. +- Current-tree verification: `cargo test -q -p agent-reply-validator --test schema` passed; with the binary changed to write the artifact before it refuses the argument, the test failed on the modification time, and passed again once the change was reverted. +- Resolution reference: `test(agent-reply-validator): [#2904] observe a write of the schema binary by its modification time` +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625765298 + +### F11 - The description's test counts predated the round 2 fixes + +- PR number: 2952 +- Source review ID: 5971081099 +- Reviewer finding ID: F4 +- Source URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625703481 +- Concern: the Validation list said 154 unit tests and 22 command-boundary tests; the head has more. +- Solution: The description now gives the counts at the head that carries the round 4 fixes: 157 unit tests, 6 helper tests, 23 command-boundary tests and 2 schema tests. +- Current-tree verification: `cargo test -q -p agent-reply-validator` printed those counts; the description was edited at 07:45:26Z (`date -u`). +- Resolution reference: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625765622 +- Follow-up PR URL: N/A +- Reply URL: https://github.com/torrust/torrust-tracker/pull/2952#discussion_r4625765622 + +## Processing Log + +- 2026-11-18 19:13 UTC - Started audit, before the replies of round 1. +- 2026-11-18 19:17 UTC - Round 1: Copilot's review `5963279729` (submitted 19:09:46Z, forge `submitted_at`) with three comments, recorded as F1 to F3. The fixes of F1 and F3 were committed at 19:11:51Z and 19:12:29Z (`git log --format=%cI`, in UTC) and pushed; `git ls-remote` showed the fork branch at the local head at 19:17:15Z (`date -u`). The three replies were posted between 19:17:27Z and 19:17:32Z (forge `created_at`), after the push. `validate-audit-record.py --pr-number 2952 --base torrust/develop`, with its `gh` calls made through `gh-bot`, exited 0 (3 rows, 0 failures) at 19:17:42Z; the three threads were then resolved by their thread IDs, and a GraphQL refresh showed 0 unresolved threads. No review of `da2ce7`, who was requested, arrived in the first 60 minutes. +- 2026-11-18 20:40 UTC - Round 2: Copilot's review `5964554730` (submitted 20:31:43Z, forge `submitted_at`) with two findings in its body, recorded as F4 and F6 under its IDs. They have no inline thread, so their rows are `NON_RESOLVABLE`. The fixes were committed at 20:34:01Z and 20:35:06Z (`git log --format=%cI`, in UTC) and pushed; `git ls-remote` showed the fork branch at the local head at 20:39:25Z (`date -u`). One conversation response, naming the review and both findings, was posted at 20:39:36Z (forge `created_at`), after the push, and edited at 20:39:44Z to correct its first line, which had named the round 1 review. +- 2026-11-19 07:16 UTC - Round 3: Copilot's review `5970792387` (submitted 07:13:39Z, forge `submitted_at`) with one inline comment, recorded as F7. Its body says the full review did not run before a timeout. The claim does not hold on the current tree, so there is no code change; the reply was posted at 07:16:25Z (forge `created_at`). `da2ce7`, who was requested, has still not reviewed, more than 12 hours after the request. +- 2026-11-19 07:49 UTC - Round 4: the approving review `5971081099` of `da2ce7` (submitted 07:41:52Z, forge `submitted_at`) with four inline comments, recorded as F8 to F11. The fixes of F8 to F10 were committed and pushed; `git ls-remote` showed the fork branch at the local head at 07:49:00Z (`date -u`). The description was edited for F11 at 07:45:26Z (`date -u`). The four replies were posted between 07:49:11Z and 07:49:18Z (forge `created_at`), after the push. + + + +## Completion Rules + +- Re-derive the reply claim against the current tree before replying or resolving a thread. +- Reply on every resolvable thread before resolving it. +- For an outdated thread whose concern was fixed, record `Disposition=FIXED` and + `Thread state=RESOLVED`, even if GitHub marks the thread outdated after the push. For a + duplicate, superseded, or no-change in-PR thread, reply exactly + `Superseded by : .`, record `Disposition=NO_ACTION` and + `Thread state=SUPERSEDED`, then resolve it. A post-merge `NO_ACTION` requires maintainer + approval to decline the follow-up work. When the current identity cannot resolve a thread + (`viewerCanResolve` is `false`), still reply, keep the disposition established from the current + tree, and record `Thread state=OPEN`; the reviewer or PR author resolves it. +- A consolidated PR conversation response may cover multiple review rounds only when it names + every review ID and every finding ID with its disposition and resolution reference. Record its + durable URL in each related row. +- Cite a fix by its unique Conventional Commit subject or durable reply URL, never by a branch SHA + that can change after a rebase. +- Refresh review threads using GraphQL and confirm that no unresolved actionable thread remains. diff --git a/docs/schemas/README.md b/docs/schemas/README.md index e81955427b..55d42f0c56 100644 --- a/docs/schemas/README.md +++ b/docs/schemas/README.md @@ -46,3 +46,38 @@ schema in one place the schema cannot express without a parallel model: `semantic-links.skill-links` and `semantic-links.related-artifacts` may be omitted but may not be an explicit `null`, while the schema types them as `array` or `null`. + +## Agent Reply V1 + +`agent-reply-v1.schema.json` is the JSON Schema Draft 2020-12 projection of the reply model in +`contrib/dev-tools/checks/agent-reply-validator/src/reply.rs`: the content of one reply file that +an AI agent writes in the `agent-replies/` folder of an issue specification (decision D18 of +issue #2904). Do not edit the generated JSON directly. + +Regenerate the artifact with: + +```sh +cargo run --package agent-reply-validator --bin agent-reply-schema +``` + +The test `contrib/dev-tools/checks/agent-reply-validator/tests/schema.rs` fails when the tracked +artifact differs from the model, so `cargo test`, the pre-push hook and CI catch a stale schema. + +Check reply files with: + +```sh +cargo run --package agent-reply-validator --bin agent-reply-validator -- --all +cargo run --package agent-reply-validator --bin agent-reply-validator -- ... +``` + +`--all` checks the staged content of every file in an `agent-replies/` folder or named like a +reply file; the pre-commit hook and the Docs Lint workflow run it. With paths, it checks those +files on disk. Besides the schema, the validator checks the file's place +(`docs/issues///agent-replies/`), its name +(`--r.json`), and that the name agrees with the `agent`, `subject` and +`round` fields. It also differs from the schema where the schema cannot follow it. It is +stricter on a real calendar date and time in `created-utc`, fractional numbers, repeated keys, +and a subject number beyond 32 bits. For blank text it uses Rust's Unicode white space, not the +ECMA-262 set of `\S`: a text of only U+0085 passes the schema and fails the validator, and a text +of only U+FEFF fails the schema and passes the validator. The module documentation of +`src/schema.rs` lists these. diff --git a/docs/schemas/agent-reply-v1.schema.json b/docs/schemas/agent-reply-v1.schema.json new file mode 100644 index 0000000000..e5d0e55ba5 --- /dev/null +++ b/docs/schemas/agent-reply-v1.schema.json @@ -0,0 +1,179 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Torrust Agent Reply V1", + "description": "One reply of an agent, as stored in its reply file.", + "type": "object", + "properties": { + "schema-version": { + "description": "The version of the reply format: always 1.", + "$ref": "#/$defs/SchemaVersion" + }, + "agent": { + "description": "The agent that wrote the reply.", + "$ref": "#/$defs/Agent" + }, + "model": { + "description": "The model the agent ran on, as the harness names it, such as `claude-opus-5-5`.", + "$ref": "#/$defs/Text" + }, + "subject": { + "description": "What the reply is about: a task (`t2`) or a pull request (`pr2920`).", + "$ref": "#/$defs/Subject" + }, + "round": { + "description": "The round of this agent on this subject.", + "$ref": "#/$defs/Round" + }, + "created-utc": { + "description": "When the reply was written, in UTC: `YYYY-MM-DD HH:MM`.", + "$ref": "#/$defs/UtcMinute" + }, + "verdict": { + "description": "The outcome, from which the orchestrator decides the next step.", + "$ref": "#/$defs/Verdict" + }, + "summary": { + "description": "A short account of what the agent did or found.", + "$ref": "#/$defs/Text" + }, + "findings": { + "description": "The problems found; empty when there are none.", + "type": "array", + "items": { + "$ref": "#/$defs/Finding" + } + }, + "questions": { + "description": "The questions for the contributor; empty when there are none.", + "type": "array", + "items": { + "$ref": "#/$defs/Text" + } + }, + "evidence": { + "description": "The commands run and what they printed, or other facts the reply rests on.", + "type": "array", + "items": { + "$ref": "#/$defs/Text" + } + } + }, + "additionalProperties": false, + "required": [ + "schema-version", + "agent", + "model", + "subject", + "round", + "created-utc", + "verdict", + "summary", + "findings", + "questions", + "evidence" + ], + "$defs": { + "SchemaVersion": { + "description": "The version of the reply format.", + "type": "integer", + "const": 1 + }, + "Agent": { + "description": "An agent that writes reply files.", + "type": "string", + "enum": [ + "orchestrator", + "implementer", + "task-reviewer", + "pr-reviewer", + "researcher" + ] + }, + "Text": { + "description": "A text that is not blank.", + "type": "string", + "pattern": "\\S" + }, + "Subject": { + "description": "A task of the Implementation Plan (`t2`) or a pull request (`pr2920`).", + "type": "string", + "pattern": "^(t|pr)[1-9][0-9]*$" + }, + "Round": { + "description": "The round of the agent on the subject.", + "type": "integer", + "minimum": 1, + "maximum": 3 + }, + "UtcMinute": { + "description": "A UTC time written `YYYY-MM-DD HH:MM`.", + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$" + }, + "Verdict": { + "description": "The outcome of a reply. The list is closed: the orchestrator reads only this field.", + "oneOf": [ + { + "description": "A review found nothing that blocks the work.", + "type": "string", + "const": "REVIEW_PASSED" + }, + { + "description": "A review found something that must change.", + "type": "string", + "const": "REVIEW_FAILED" + }, + { + "description": "The agent finished the work it was given.", + "type": "string", + "const": "DONE" + }, + { + "description": "The agent cannot go on without something it does not have.", + "type": "string", + "const": "BLOCKED" + }, + { + "description": "The agent needs an answer from the contributor.", + "type": "string", + "const": "QUESTION" + } + ] + }, + "Finding": { + "description": "One problem found by the agent.", + "type": "object", + "properties": { + "severity": { + "description": "How much the problem matters.", + "$ref": "#/$defs/Severity" + }, + "location": { + "description": "Where it is, such as `src/name.rs:42` or a section of a document.", + "$ref": "#/$defs/Text" + }, + "description": { + "description": "What is wrong.", + "$ref": "#/$defs/Text" + } + }, + "additionalProperties": false, + "required": [ + "severity", + "location", + "description" + ] + }, + "Severity": { + "description": "The severity of a finding, with the same names as the pull-request review audits.", + "type": "string", + "enum": [ + "Blocker", + "Major", + "Minor", + "Nit", + "Suggestion" + ] + } + } +} diff --git a/project-words.txt b/project-words.txt index 7d97687107..831c553e70 100644 --- a/project-words.txt +++ b/project-words.txt @@ -477,6 +477,7 @@ reflog relitigating reorganisation reorganising +replacen repoint repointed repoints