Files
plan2code/plan2code-app/src-tauri/src/review_loop.rs
T

4869 lines
173 KiB
Rust

//! The Review Loop's driver: rounds of review and fix, each in a fresh agent
//! session, the app judging what every round reports. The agent reviews and
//! fixes and reports (`roundOutcome`); only this module stages, commits and
//! records boundaries, so the agent never runs git (NFR-3). The run record
//! lives in memory alone: an app restart ends the run (NFR-5).
//!
//! The rules are in `round_logic` (judging, the next step, the commit subject)
//! and the boundaries in `round_boundary`; this module is the part with an
//! agent, git, files and a clock in it. A round runs in one session (`both`,
//! for an agent that can start a helper) or in two (a `reviewer` session, then
//! a `fixer` one that never saw the review: FR-17). A crashed, silent or failed
//! session gets one fresh retry one strength up; the second failure stops the
//! run with the rounds that finished kept (FR-3).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::agent_manager::{AgentManager, AgentState};
use crate::agents::Agent;
#[cfg(not(test))]
use crate::console_supervisor::find_console_dir;
use crate::loop_commit;
use crate::loop_driver::{
self, Hooks, Launch, Limits, LoopSlot, LoopStateEvent, RoundCount, StopCause, Strength,
};
use crate::loop_notify::NotifyKind;
use crate::loop_report::{EntryKind, EntryResult, LoopReport, ReportEntry, RoundEntry};
use crate::loop_shared::report_list;
use crate::loop_shared::retry::next_strength_word;
use crate::loop_shared::rounds::{
finding_line, page_is_this_round, proofs_for, report_text, reviewer_brief,
round_outcome_in as outcome_for_round,
};
use crate::loop_shared::session::{read_session_state, start_session, Ctx};
use crate::loop_shared::watch::{silence_expired, watch_loop, WatchStep};
use crate::loop_tools;
use crate::models::StrengthRow;
use crate::review_report::review_report_markdown;
use crate::round_boundary::{self, Boundary};
use crate::round_logic::{
self, Finding, Next, Role, RoundOutcome, RoundReview, RoundTests, RunView, StopReason, Verdict,
MAX_ROUNDS,
};
use crate::session_reader;
// ---------------------------------------------------------------- the setup
/// What the person asked a run to review.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ReviewScope {
Branch,
Uncommitted,
Spec,
}
impl ReviewScope {
pub fn word(self) -> &'static str {
match self {
ReviewScope::Branch => "branch",
ReviewScope::Uncommitted => "uncommitted",
ReviewScope::Spec => "spec",
}
}
}
/// Whether the run commits each round or only measures it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
Commit,
Snapshot,
}
/// How a round runs: one session with a helper reviewing, or two sessions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Shape {
OneSession,
TwoSession,
}
/// The Start screen's picks, plus the notification the Implementation Loop's
/// setup holds (read by the app, never taken from the page).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReviewSetup {
pub scope: ReviewScope,
/// The spec folder (`specs/<name>`) for the `spec` scope.
pub spec: Option<String>,
/// Rounds before the run stops at its cap, 1 to 6.
pub cap: u32,
/// Commit each round (off: snapshot mode).
pub commit: bool,
/// The person agreed to commit their uncommitted work first.
pub pre_run_commit_agreed: bool,
/// Fix the collected Suggestions in one batch after the run.
pub suggestions: bool,
/// The strength every round runs on; `None` runs on the launch choice.
pub strength: Option<Strength>,
pub silence_minutes: u32,
pub notify_rounds: bool,
pub notify_kind: NotifyKind,
pub notify_url: String,
pub notify_param: String,
}
impl Default for ReviewSetup {
fn default() -> Self {
ReviewSetup {
scope: ReviewScope::Branch,
spec: None,
cap: 3,
commit: true,
pre_run_commit_agreed: false,
suggestions: false,
strength: None,
silence_minutes: 20,
notify_rounds: false,
notify_kind: NotifyKind::default(),
notify_url: String::new(),
notify_param: String::new(),
}
}
}
// -------------------------------------------------------------- the record
/// What the banner says a round is doing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReviewStep {
Starting,
Reviewing,
Fixing,
Testing,
Committing,
}
impl ReviewStep {
pub fn label(self) -> &'static str {
match self {
ReviewStep::Starting => "Starting",
ReviewStep::Reviewing => "Reviewing",
ReviewStep::Fixing => "Fixing",
ReviewStep::Testing => "Testing",
ReviewStep::Committing => "Committing",
}
}
}
/// Which session of the run is going on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stage {
/// A one-session round.
Both,
/// A two-session round's reviewer.
Reviewer,
/// A two-session round's fixer.
Fixer,
/// The Suggestions batch: a fixer on the collected Suggestions.
Batch,
/// The final check: one fresh reviewer on the batch's diff.
Final,
}
impl Stage {
pub fn role(self) -> Role {
match self {
Stage::Both => Role::Both,
Stage::Reviewer | Stage::Final => Role::Reviewer,
Stage::Fixer | Stage::Batch => Role::Fixer,
}
}
fn word(self) -> &'static str {
match self {
Stage::Both => "both",
Stage::Reviewer => "reviewer",
Stage::Fixer => "fixer",
Stage::Batch => "batch",
Stage::Final => "final",
}
}
}
/// One finished round, for the report and the banner.
#[derive(Clone, Debug, Default)]
pub struct RoundRecord {
pub n: u32,
/// Where the round ended: the next round's diff starts here.
pub boundary: Option<Boundary>,
pub strength: Option<String>,
pub model: Option<String>,
pub effort: Option<String>,
pub started_at: String,
pub ended_at: String,
pub retried: bool,
/// The retry could not go a strength up (already Best, or not mapped).
pub could_not_step_up: bool,
pub verdict: Option<Verdict>,
pub critical: u32,
pub warning: u32,
pub suggestion: u32,
pub fixed: Vec<Finding>,
pub unfixed: Vec<Finding>,
pub suggestions: Vec<Finding>,
pub tests: Option<RoundTests>,
pub commit: Option<String>,
pub summary: String,
}
/// The Suggestions batch and its final check, kept apart from the rounds.
#[derive(Clone, Debug, Default)]
pub struct BatchRecord {
/// How many rounds had finished when the batch began: orders it among them.
pub after_rounds: usize,
/// The Suggestions the fixer was briefed with.
pub briefed: Vec<Finding>,
/// Where the run stood before the batch: the final check's diff starts here.
pub before: Option<Boundary>,
pub boundary: Option<Boundary>,
pub verdict: Option<Verdict>,
pub commit: Option<String>,
pub summary: String,
pub final_check: Option<Verdict>,
pub final_critical: u32,
pub final_warning: u32,
}
/// What Stop now left behind: the partial changes of the stopped round.
#[derive(Clone, Debug, Default)]
pub struct Partial {
/// The diff from the last finished boundary to a snapshot taken at the stop.
pub diff: PathBuf,
pub files: u32,
pub added: u32,
pub removed: u32,
/// Files that did not exist at the boundary: what Discard may delete.
pub new_files: Vec<String>,
/// Still to be kept or discarded.
pub pending: bool,
}
static NEXT_RUN: AtomicU64 = AtomicU64::new(1);
/// One Review Loop run, with the overview's run-record fields and the live
/// fields the watcher needs.
#[derive(Clone, Debug)]
pub struct ReviewRun {
/// Tells a watch thread whether the record is still its own run's.
pub run_id: u64,
pub id: String,
pub project: PathBuf,
pub setup: ReviewSetup,
pub scope: ReviewScope,
pub cap: u32,
pub mode: Mode,
pub shape: Shape,
pub launch: Launch,
/// Full id of the "Work before Review Loop" commit, when one was made.
pub pre_run_commit: Option<String>,
pub start: Boundary,
pub rounds: Vec<RoundRecord>,
pub suggestions_batch: Option<BatchRecord>,
/// Batches from before a Continue, kept for the report.
pub earlier_batches: Vec<BatchRecord>,
pub stop_reason: Option<StopReason>,
pub stop_evidence: Option<String>,
/// The round the run stopped in; `round` moves on with a sign-off's fix.
pub stop_round: u32,
// ---- live
/// The run's folder under the console home: scope files, diffs, reports.
pub run_dir: PathBuf,
/// False once the run has stopped (it is kept for Continue and the report).
pub running: bool,
pub round: u32,
pub stage: Stage,
pub step: ReviewStep,
pub sid: Option<String>,
pub last_sid: Option<String>,
pub generation: u64,
pub started_at: Instant,
pub started_at_ms: u64,
/// When the current session started, for the "console never opened" wait.
pub session_started_at: Instant,
pub last_activity: SystemTime,
pub activity_checked: Instant,
pub stop_after_round: bool,
pub stop_now: bool,
/// The current round's one retry is used.
pub retried: bool,
pub retries_used: u32,
/// The round in progress.
pub cur: RoundRecord,
pub strength_rows: BTreeMap<String, StrengthRow>,
pub cur_strength: Option<Strength>,
/// Suggestions collected across rounds (FR-19).
pub collected: Vec<Finding>,
pub reviewer_report: Option<String>,
/// The files the current round's reviewer was shown.
pub reviewed_files: Vec<String>,
/// The files the person's scope named when the run began.
pub scope_files: Vec<String>,
pub scope_base: Option<String>,
/// What the run was going to stop for when the Suggestions batch began.
pub pending_stop: Option<StopReason>,
pub batch_done: bool,
pub partial: Option<Partial>,
pub notify_failure: Option<String>,
/// A page announced for the session that holds no lock yet.
pub page_candidate: Option<String>,
/// What the person picked at sign-off, and how the squash went.
pub signoff: Option<SignOff>,
/// A sign-off's Suggestions fix is running: its end finishes the sign-off.
pub signing: bool,
pub signed_off: bool,
/// The report written into the spec folder, kept so sign-off rewrites it.
pub report_file: Option<PathBuf>,
}
/// How the sign-off's squash of the round commits went.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Squash {
/// Not asked for.
Off,
/// Done: the one commit that replaced this many commits of the run.
Done { commit: String, commits: usize },
/// Refused or failed, with the words the person reads.
Refused(String),
}
/// What the sign-off did, for the report and the finished screen.
#[derive(Clone, Debug)]
pub struct SignOff {
/// The Suggestions the person ticked.
pub picked: Vec<Finding>,
/// The Suggestions they left.
pub left: Vec<Finding>,
pub squash_asked: bool,
pub squash: Squash,
/// Why the picked Suggestions were not all fixed, when they were not.
pub problem: Option<String>,
}
pub type ReviewSlot = Arc<Mutex<Option<ReviewRun>>>;
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn epoch_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| u64::try_from(d.as_millis()).unwrap_or(0))
.unwrap_or(0)
}
fn clock() -> String {
chrono::Local::now().format("%Y-%m-%d %H:%M").to_string()
}
fn one_line(text: &str) -> String {
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Whether the loop's agent can start a helper from inside a session.
pub(crate) fn agent_helpers(agent: &Agent) -> bool {
matches!(agent, Agent::Builtin(entry) if entry.helpers)
}
/// A session that never opened its console counts as crashed after this long.
const NOTICE_WAIT: Duration = Duration::from_secs(180);
impl ReviewRun {
#[allow(clippy::too_many_arguments)]
pub fn new(
project: PathBuf,
setup: ReviewSetup,
launch: Launch,
mode: Mode,
shape: Shape,
start: Boundary,
run_dir: PathBuf,
strength_rows: BTreeMap<String, StrengthRow>,
) -> ReviewRun {
let now = Instant::now();
let run_id = NEXT_RUN.fetch_add(1, Ordering::SeqCst);
ReviewRun {
run_id,
id: format!("review-{}-{run_id}", epoch_ms()),
project,
scope: setup.scope,
cap: setup.cap.clamp(1, MAX_ROUNDS),
cur_strength: setup.strength,
setup,
mode,
shape,
launch,
pre_run_commit: None,
start,
rounds: Vec::new(),
suggestions_batch: None,
earlier_batches: Vec::new(),
stop_reason: None,
stop_evidence: None,
stop_round: 0,
run_dir,
running: true,
round: 1,
stage: Stage::Both,
step: ReviewStep::Starting,
sid: None,
last_sid: None,
generation: 0,
started_at: now,
started_at_ms: epoch_ms(),
session_started_at: now,
last_activity: SystemTime::now(),
activity_checked: now,
stop_after_round: false,
stop_now: false,
retried: false,
retries_used: 0,
cur: RoundRecord::default(),
strength_rows,
collected: Vec::new(),
reviewer_report: None,
reviewed_files: Vec::new(),
scope_files: Vec::new(),
scope_base: None,
pending_stop: None,
batch_done: false,
partial: None,
notify_failure: None,
page_candidate: None,
signoff: None,
signing: false,
signed_off: false,
report_file: None,
}
}
/// The boundary before round `n` began: the run's start, or where the
/// round before it ended.
fn boundary_before(&self, n: u32) -> Boundary {
n.checked_sub(2)
.and_then(|at| self.rounds.get(at as usize))
.and_then(|round| round.boundary.clone())
.unwrap_or_else(|| self.start.clone())
}
/// The Critical and Warning findings still open: every round's unfixed
/// ones that no later round fixed. A later round reviews only the fix
/// diff, so a clean one never clears what an earlier round left.
pub fn open_findings(&self) -> Vec<Finding> {
let same = |a: &Finding, b: &Finding| a.title == b.title && a.file == b.file;
let mut open: Vec<Finding> = Vec::new();
for round in &self.rounds {
open.retain(|left| !round.fixed.iter().any(|fixed| same(left, fixed)));
for finding in &round.unfixed {
if !open.iter().any(|left| same(left, finding)) {
open.push(finding.clone());
}
}
}
open
}
/// Where the last finished round ended (or the start).
pub fn last_boundary(&self) -> Boundary {
// The newest committed work: a Suggestions batch counts after the
// rounds that had finished when it ran, and before any later round
// (a Continue starts a round after a finished batch).
let round = self
.rounds
.iter()
.enumerate()
.rev()
.find_map(|(i, round)| round.boundary.clone().map(|b| (i, b)));
let batch = self
.suggestions_batch
.iter()
.chain(self.earlier_batches.iter().rev())
.find_map(|batch| batch.boundary.clone().map(|b| (batch.after_rounds, b)));
match (round, batch) {
(Some((i, round)), Some((after, batch))) => {
if after > i {
batch
} else {
round
}
}
(Some((_, round)), None) => round,
(None, Some((_, batch))) => batch,
(None, None) => self.start.clone(),
}
}
fn view(&self, round: u32) -> RunView {
RunView {
round,
cap: self.cap,
rounds_run: u32::try_from(self.rounds.len()).unwrap_or(u32::MAX),
suggestions_on: self.setup.suggestions,
suggestions_pending: !self.collected.is_empty(),
batch_done: self.batch_done,
retried_this_round: self.retried,
stop_after_round: self.stop_after_round,
stop_now: self.stop_now,
}
}
}
// ----------------------------------------------------------------- events
/// The banner's state for a Review Loop (`kind: "rounds"`).
pub fn review_state_event(run: &ReviewRun) -> LoopStateEvent {
let (critical, warning) = run
.rounds
.last()
.map_or((0, 0), |round| (round.critical, round.warning));
let strength = run.cur_strength.map(|word| word.word().to_string());
let row = run
.cur_strength
.and_then(|word| run.strength_rows.get(word.word()));
// The Suggestions batch and the final check come after the rounds: they
// are named for what they are, and never read as a round past the cap.
let after_rounds = match run.stage {
Stage::Batch => "Suggestions batch",
Stage::Final => "Final check",
_ => "",
};
let (shown, detail) = if after_rounds.is_empty() {
(
run.round,
round_logic::round_detail(run.round, run.cap, run.step.label(), critical, warning),
)
} else {
(
run.round.min(run.cap),
format!("{after_rounds}: {}", run.step.label()),
)
};
LoopStateEvent {
running: run.running,
spec_name: run
.setup
.spec
.as_deref()
.map_or_else(|| run.scope.word().to_string(), |spec| spec.to_string()),
phase: shown,
phases: run.cap,
phase_name: detail,
previous_phase: None,
previous_committed: false,
phase_retried: run.retried,
step: run.step.label().to_string(),
started_at_ms: run.started_at_ms,
retries_used: run.retries_used,
stop_after_phase: run.stop_after_round,
stopping: run.stop_now,
can_stop_after: run.running && run.round < run.cap,
strength,
model: row.map(|r| r.model.clone()),
effort: row.and_then(|r| r.effort.clone()),
kind: "rounds",
round: shown,
rounds: run.cap,
round_counts: run
.rounds
.iter()
.map(|round| RoundCount {
critical: round.critical,
warning: round.warning,
})
.collect(),
stop_after_round: run.stop_after_round,
after_rounds,
}
}
/// The running Review Loop's banner state, or `None` when none runs.
pub fn current_event(slot: &ReviewSlot) -> Option<LoopStateEvent> {
lock(slot)
.as_ref()
.filter(|run| run.running)
.map(review_state_event)
}
/// Whether a Review Loop is running (a stopped run waiting for Continue or
/// the report is not).
pub fn is_running(slot: &ReviewSlot) -> bool {
lock(slot).as_ref().is_some_and(|run| run.running)
}
/// Forget the run without a word to the page: the app is quitting.
pub fn abandon(slot: &ReviewSlot) {
*lock(slot) = None;
}
// ------------------------------------------------------------- the context
/// What the watch thread needs: the run's slot and the shared session context.
#[derive(Clone)]
pub struct RoundCtx {
pub slot: ReviewSlot,
pub ctx: Ctx,
}
fn with_run<R>(rc: &RoundCtx, f: impl FnOnce(&mut ReviewRun) -> R) -> Option<R> {
let mut guard = lock(&rc.slot);
guard
.as_mut()
.filter(|run| run.run_id == rc.ctx.run_id)
.map(f)
}
fn emit(rc: &RoundCtx) {
let event = with_run(rc, |run| review_state_event(run));
if let Some(event) = event {
(rc.ctx.hooks.emit)(event);
}
}
/// The console the end screen is posted to. A test never reaches the real
/// one (it would post to, and resume sessions in, the person's console).
fn console_dir() -> PathBuf {
#[cfg(test)]
{
PathBuf::from(".")
}
#[cfg(not(test))]
{
find_console_dir().unwrap_or_else(|_| PathBuf::from("."))
}
}
fn new_ctx(
run: &ReviewRun,
agent: Arc<AgentManager>,
home: PathBuf,
hooks: Hooks,
limits: Limits,
) -> Ctx {
Ctx {
// The Review Loop keeps its own slot; this one only fills the field
// the shared session code carries for the Implementation Loop.
slot: Arc::new(Mutex::new(None)),
agent,
console_dir: console_dir(),
home,
launch: run.launch.clone(),
run_id: run.run_id,
hooks: Arc::new(hooks),
limits,
}
}
// ------------------------------------------------------------ git helpers
fn git_cmd(project: &Path, args: &[&str]) -> Command {
let mut cmd = Command::new("git");
cmd.args(args).current_dir(project);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
}
cmd
}
/// What `git <args>` printed, or the first line of why it failed.
fn git_text(project: &Path, args: &[&str]) -> Result<String, String> {
let out = git_cmd(project, args)
.output()
.map_err(|err| format!("git could not run: {err}"))?;
if !out.status.success() {
let why = String::from_utf8_lossy(&out.stderr)
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.unwrap_or("no reason given")
.to_string();
return Err(format!("git {} failed: {why}", args.first().unwrap_or(&"")));
}
Ok(String::from_utf8_lossy(&out.stdout).to_string())
}
fn lines_of(text: &str) -> Vec<String> {
text.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.map(str::to_string)
.collect()
}
/// Names from `git ... -z` output: NUL-separated, never quoted.
fn nul_lines(text: &str) -> Vec<String> {
text.split('\0')
.filter(|name| !name.is_empty())
.map(str::to_string)
.collect()
}
/// The branch the work is measured against: the first of `main`,
/// `origin/main`, `master`, `origin/master` that exists.
fn base_branch(project: &Path) -> Option<String> {
["main", "origin/main", "master", "origin/master"]
.into_iter()
.find(|name| {
git_text(
project,
&["rev-parse", "--verify", "-q", &format!("{name}^{{commit}}")],
)
.is_ok()
})
.map(str::to_string)
}
/// The files a scope names, and the base branch it measured against: for
/// `branch`, the diff against the base plus staged, unstaged and untracked
/// files; for `uncommitted`, those changed files; for `spec`, the spec folder's
/// files plus the branch diff.
pub fn scope_files(
project: &Path,
scope: ReviewScope,
spec: Option<&str>,
) -> Result<(Option<String>, Vec<String>), String> {
let mut files: Vec<String> = Vec::new();
let mut base = None;
let uncommitted = |files: &mut Vec<String>| -> Result<(), String> {
files.extend(loop_tools::git_status_porcelain(project)?);
Ok(())
};
let against_base = |files: &mut Vec<String>, base: &mut Option<String>| -> Result<(), String> {
// Counting only untracked files would hide every commit on the
// branch, so no trunk is an error, as `review-scope.mjs` says. A
// repository with no commits yet has nothing committed to miss.
let has_head = git_text(project, &["rev-parse", "--verify", "-q", "HEAD"]).is_ok();
match base_branch(project) {
Some(name) => {
let found = git_text(project, &["merge-base", "HEAD", &name])
.map_err(|e| format!("The branch could not be compared with {name}: {e}"))?;
let point = found.trim().to_string();
if !point.is_empty() {
files.extend(nul_lines(&git_text(
project,
&["diff", "--name-only", "-z", "--no-renames", &point],
)?));
*base = Some(name);
}
}
None if has_head => {
return Err(
"There is no main or master branch (local or origin) to compare this branch with."
.to_string(),
);
}
None => {}
}
files.extend(lines_of(&git_text(
project,
&["ls-files", "--others", "--exclude-standard"],
)?));
Ok(())
};
match scope {
ReviewScope::Uncommitted => uncommitted(&mut files)?,
ReviewScope::Branch => against_base(&mut files, &mut base)?,
ReviewScope::Spec => {
let spec = spec.ok_or("A spec scope needs a spec folder.")?;
let folder = project.join(spec);
if !folder.is_dir() {
return Err(format!("{spec} is not a folder in this project."));
}
against_base(&mut files, &mut base)?;
if let Ok(entries) = std::fs::read_dir(&folder) {
for entry in entries.flatten() {
if entry.path().is_file() {
files.push(format!(
"{}/{}",
spec.trim_end_matches('/'),
entry.file_name().to_string_lossy()
));
}
}
}
}
}
files.sort();
files.dedup();
Ok((base, files))
}
// ------------------------------------------------------- the scope and prompt
/// Everything a round's scope file says.
struct ScopeInput<'a> {
round: u32,
stage: Stage,
scope: ReviewScope,
spec: Option<&'a str>,
base: Option<&'a str>,
files: &'a [String],
diff: Option<&'a Path>,
report: Option<&'a Path>,
brief: &'a [Finding],
}
/// The text of a round's scope file.
fn scope_text(input: &ScopeInput) -> String {
let mut text = format!(
"# Review Loop round {} scope\n\nRole: {}\n",
input.round,
input.stage.role_word()
);
if let Some(diff) = input.diff {
text.push_str(&format!(
"\nReview exactly this diff, the previous round's changes, and nothing else:\n\n- {}\n",
diff.display()
));
} else if input.stage == Stage::Batch {
text.push_str("\nFix these Suggestions and nothing else:\n\n");
for finding in input.brief {
text.push_str(&finding_line(finding));
text.push('\n');
}
} else {
text.push_str(&format!("\nScope: {}\n", input.scope.word()));
if let Some(spec) = input.spec {
text.push_str(&format!("Spec folder: {spec}\n"));
}
if let Some(base) = input.base {
text.push_str(&format!("Base branch: {base}\n"));
}
text.push_str("\nFiles:\n\n");
for file in input.files {
text.push_str(&format!("- {file}\n"));
}
}
if let Some(report) = input.report {
text.push_str(&format!(
"\nThe reviewer's report (fix its Critical and Warning findings):\n\n- {}\n",
report.display()
));
}
text
}
impl Stage {
fn role_word(self) -> &'static str {
match self.role() {
Role::Both => "both",
Role::Reviewer => "reviewer",
Role::Fixer => "fixer",
}
}
}
/// A path as the agent's prompt carries it: quoted when it holds a space.
fn quoted(path: &Path) -> String {
let text = path.display().to_string();
if text.contains(char::is_whitespace) {
format!("\"{text}\"")
} else {
text
}
}
/// The prompt a round's session starts on.
pub fn round_prompt(round: u32, role: Role, scope_file: &Path) -> String {
let role = match role {
Role::Both => "both",
Role::Reviewer => "reviewer",
Role::Fixer => "fixer",
};
format!(
"/plan2code-review --web --loop --round {round} --role {role} --scope-file {}",
quoted(scope_file)
)
}
/// Suggestions kept across rounds (FR-19): the new round's are added, a repeat
/// (same file and title) is dropped, one whose file and line a round fixed is
/// dropped, and an earlier one about a file the latest reviewer was shown but
/// did not report again is dropped.
pub fn merge_suggestions(
collected: &[Finding],
new: &[Finding],
fixed: &[Finding],
reviewed_files: &[String],
) -> Vec<Finding> {
let was_fixed = |finding: &Finding| {
fixed
.iter()
.any(|f| f.file == finding.file && f.line.is_some() && f.line == finding.line)
};
let same = |a: &Finding, b: &Finding| a.file == b.file && a.title == b.title;
let mut kept: Vec<Finding> = collected
.iter()
.filter(|old| {
!was_fixed(old)
&& (new.iter().any(|n| same(n, old))
|| !reviewed_files.iter().any(|file| file == &old.file))
})
.cloned()
.collect();
for finding in new {
if !was_fixed(finding) && !kept.iter().any(|k| same(k, finding)) {
kept.push(finding.clone());
}
}
kept
}
/// The files a unified diff touches, from its `+++ b/<file>` lines.
fn diff_files(diff: &Path) -> Vec<String> {
let Ok(text) = std::fs::read_to_string(diff) else {
return Vec::new();
};
let mut files: Vec<String> = text
.lines()
.filter_map(|line| line.strip_prefix("+++ b/"))
.map(str::to_string)
.collect();
files.sort();
files.dedup();
files
}
// ------------------------------------------------------------ starting a run
fn is_dirty(project: &Path) -> Result<bool, String> {
Ok(!loop_tools::git_status_porcelain(project)?.is_empty())
}
/// Stage by name and commit what changed since `before` (everything, with an
/// empty list), through the same checks a phase's commit takes. `Ok(None)`
/// when nothing changed; otherwise the new commit's full id.
fn commit_all(
project: &Path,
subject: &str,
limit: Duration,
) -> Result<Option<String>, (String, String)> {
match loop_commit::stage_and_check(project, Some(&[])) {
Ok(()) => {}
Err(loop_commit::StageError::Add(failure)) => {
return Err((failure.first_line, failure.output));
}
Err(loop_commit::StageError::Problem(problem)) => {
let files = problem.files.join(", ");
let line = format!("{} {}", files, problem.why);
return Err((line.clone(), line));
}
}
let staged = loop_tools::git_staged(project).map_err(|e| (e.clone(), e))?;
if staged.is_empty() {
return Ok(None);
}
let message = match loop_tools::commit_message(project, subject) {
Ok(message) => message,
Err(e) => {
// Nothing is committed: the files this run staged come out again.
loop_commit::unstage(project);
return Err((e.clone(), e));
}
};
let done = loop_tools::git_commit_with(project, &message, limit);
if !done.ok {
loop_commit::unstage(project);
return Err((loop_commit::first_line(&done.output), done.output));
}
loop_tools::git_head_full(project)
.map(Some)
.map_err(|e| (e.clone(), e))
}
/// Check the setup, make the pre-run commit when agreed, and take the start
/// boundary: everything a run needs before round 1.
pub fn prepare_run(
project: &Path,
launch: &Launch,
setup: ReviewSetup,
home: &Path,
) -> Result<ReviewRun, String> {
if !(1..=MAX_ROUNDS).contains(&setup.cap) {
return Err(format!("The round cap is 1 to {MAX_ROUNDS}."));
}
if setup.scope == ReviewScope::Spec {
let spec = setup
.spec
.as_deref()
.ok_or("A spec scope needs a spec folder.")?;
loop_driver::validate_spec(project, spec)?;
}
let (base, files) = scope_files(project, setup.scope, setup.spec.as_deref())?;
let mode = if setup.commit {
Mode::Commit
} else {
Mode::Snapshot
};
let shape = if agent_helpers(&launch.0) {
Shape::OneSession
} else {
Shape::TwoSession
};
let mut pre_run_commit = None;
if mode == Mode::Commit && is_dirty(project)? {
if !setup.pre_run_commit_agreed {
return Err(
"Your project has uncommitted changes. Agree to commit them first, or turn commits off."
.to_string(),
);
}
match commit_all(
project,
"Work before Review Loop",
Duration::from_secs(10 * 60),
) {
Ok(id) => pre_run_commit = id,
Err((line, _)) => {
return Err(format!("The work before the run was not committed: {line}"))
}
}
}
let start = match mode {
Mode::Commit => round_boundary::head(project)?,
Mode::Snapshot => round_boundary::snapshot(project)?,
};
let rows = if setup.strength.is_some() {
loop_driver::strength_rows_for(&launch.0)
} else {
BTreeMap::new()
};
let mut run = ReviewRun::new(
project.to_path_buf(),
setup,
launch.clone(),
mode,
shape,
start,
PathBuf::new(),
rows,
);
run.run_dir = home.join("review-loop").join(&run.id);
run.pre_run_commit = pre_run_commit;
run.scope_files = files;
run.scope_base = base;
Ok(run)
}
/// Start a Review Loop: refuse while any loop runs, prepare the run, store it
/// and start round 1; a watch thread follows it.
pub fn start_review_loop(
slot: &ReviewSlot,
phases: &LoopSlot,
agent: Arc<AgentManager>,
launch: Launch,
project: PathBuf,
setup: ReviewSetup,
hooks: Hooks,
) -> Result<(), String> {
let home = session_reader::console_home().ok_or("no home folder found")?;
start_review_loop_with(
slot,
phases,
agent,
launch,
project,
setup,
hooks,
Limits::default(),
home,
true,
)
}
/// `start_review_loop` with the console home and the watcher's timing given,
/// and the watch thread optional: a test starts a run and plays the watcher
/// itself.
#[allow(clippy::too_many_arguments)]
pub fn start_review_loop_with(
slot: &ReviewSlot,
phases: &LoopSlot,
agent: Arc<AgentManager>,
launch: Launch,
project: PathBuf,
setup: ReviewSetup,
hooks: Hooks,
limits: Limits,
home: PathBuf,
watch: bool,
) -> Result<(), String> {
if loop_driver::is_running(phases) || is_running(slot) {
return Err("A loop is already running in this window.".to_string());
}
let run = prepare_run(&project, &launch, setup, &home)?;
if run.scope_files.is_empty() {
return Err("There is nothing to review in that scope.".to_string());
}
let rc = RoundCtx {
slot: Arc::clone(slot),
ctx: new_ctx(&run, agent, home, hooks, limits),
};
{
let mut guard = lock(slot);
if guard.as_ref().is_some_and(|held| held.running) {
return Err("A loop is already running in this window.".to_string());
}
*guard = Some(run);
}
let first = with_run(&rc, |run| first_stage(run.shape)).unwrap_or(Stage::Both);
if let Err(e) = start_stage(&rc, first, 1) {
*lock(slot) = None;
(rc.ctx.hooks.emit)(LoopStateEvent::ended());
return Err(e);
}
if watch {
thread::spawn(move || watcher(rc));
}
Ok(())
}
fn first_stage(shape: Shape) -> Stage {
match shape {
Shape::OneSession => Stage::Both,
Shape::TwoSession => Stage::Reviewer,
}
}
// ------------------------------------------------------ starting a session
/// What a session's scope file needs, copied out so git runs outside the lock.
struct Plan {
project: PathBuf,
scope: ReviewScope,
spec: Option<String>,
base: Option<String>,
files: Vec<String>,
diff: Option<(Boundary, Boundary)>,
reviewer_report: Option<String>,
brief: Vec<Finding>,
dir: PathBuf,
prompt_round: u32,
strength: Option<(Strength, StrengthRow)>,
}
fn plan_for(run: &ReviewRun, stage: Stage, round: u32) -> Plan {
let diff = match stage {
Stage::Both | Stage::Reviewer | Stage::Fixer if round >= 2 => {
// The round being started ends where the last finished work did, so
// a Suggestions batch committed before a Continue is in its diff.
let to = if usize::try_from(round).ok() == Some(run.rounds.len() + 1) {
run.last_boundary()
} else {
run.boundary_before(round)
};
Some((run.boundary_before(round - 1), to))
}
Stage::Final => run
.suggestions_batch
.as_ref()
.and_then(|batch| Some((batch.before.clone()?, batch.boundary.clone()?))),
_ => None,
};
let brief = if stage == Stage::Batch {
run.collected.clone()
} else {
Vec::new()
};
let name = format!("round-{round}-{}-t{}", stage.word(), run.retries_used);
Plan {
project: run.project.clone(),
scope: run.scope,
spec: run.setup.spec.clone(),
base: run.scope_base.clone(),
files: run.scope_files.clone(),
diff,
reviewer_report: (stage == Stage::Fixer)
.then(|| run.reviewer_report.clone())
.flatten(),
brief,
dir: run.run_dir.join(name),
prompt_round: round,
strength: run.cur_strength.and_then(|word| {
run.strength_rows
.get(word.word())
.map(|row| (word, row.clone()))
}),
}
}
/// Write the scope file (and the diff and reviewer report it names) and start
/// the stage's session. The prompt names the round, the role and the file.
fn start_stage(rc: &RoundCtx, stage: Stage, round: u32) -> Result<(), String> {
let plan =
with_run(rc, |run| plan_for(run, stage, round)).ok_or("The Review Loop has ended.")?;
std::fs::create_dir_all(&plan.dir)
.map_err(|err| format!("could not make {}: {err}", plan.dir.display()))?;
let mut diff_path = None;
let mut touched = Vec::new();
if let Some((from, to)) = &plan.diff {
let name = if stage == Stage::Final {
"batch.diff".to_string()
} else {
format!("round-{}.diff", round - 1)
};
let path = plan.dir.join(name);
round_boundary::diff(&plan.project, from, to, &path)?;
touched = diff_files(&path);
diff_path = Some(path);
}
let report_path = match &plan.reviewer_report {
Some(text) => {
let path = plan.dir.join("reviewer-report.md");
std::fs::write(&path, text)
.map_err(|err| format!("could not write {}: {err}", path.display()))?;
Some(path)
}
None => None,
};
let text = scope_text(&ScopeInput {
round,
stage,
scope: plan.scope,
spec: plan.spec.as_deref(),
base: plan.base.as_deref(),
files: &plan.files,
diff: diff_path.as_deref(),
report: report_path.as_deref(),
brief: &plan.brief,
});
let scope_file = plan.dir.join("scope.md");
std::fs::write(&scope_file, text)
.map_err(|err| format!("could not write {}: {err}", scope_file.display()))?;
let prompt = round_prompt(plan.prompt_round, stage.role(), &scope_file);
// A running session (a silent one being retried) is ended first.
rc.ctx.agent.stop();
let started = start_session(
&rc.ctx,
&prompt,
plan.strength.as_ref().map(|(word, row)| (*word, row)),
)?;
let worked = with_run(rc, |run| {
run.round = round;
run.stage = stage;
run.sid = None;
run.page_candidate = None;
run.generation = started.generation;
run.session_started_at = Instant::now();
run.last_activity = SystemTime::now();
run.activity_checked = Instant::now();
run.step = match stage.role() {
Role::Fixer => ReviewStep::Fixing,
_ => ReviewStep::Reviewing,
};
if !run.retried && matches!(stage, Stage::Both | Stage::Reviewer) {
run.cur = RoundRecord {
n: round,
started_at: clock(),
..RoundRecord::default()
};
run.reviewed_files = if touched.is_empty() && round == 1 {
run.scope_files.clone()
} else {
touched.clone()
};
}
run.cur.strength = run.cur_strength.map(|word| word.word().to_string());
run.cur.model = started.model.clone();
run.cur.effort = started.effort.clone();
run.cur.retried = run.retried;
});
if worked.is_none() {
rc.ctx.agent.stop();
return Err("The Review Loop has ended.".to_string());
}
emit(rc);
Ok(())
}
// -------------------------------------------------------------- the watcher
fn watcher(rc: RoundCtx) {
let panicked = watch_loop(rc.ctx.limits.watch_every, || {
if tick(&rc) {
WatchStep::Continue
} else {
WatchStep::Stop
}
});
if let Some(text) = panicked {
let text: String = one_line(&text).chars().take(200).collect();
finish_run(
&rc,
StopReason::Failed(format!("the Review Loop's watcher failed: {text}")),
None,
);
}
}
/// What one look needs, copied out so no lock is held while a tool runs.
struct Look {
project: PathBuf,
round: u32,
stage: Stage,
sid: Option<String>,
generation: u64,
stop_now: bool,
running: bool,
last_activity: SystemTime,
activity_due: bool,
waited: Duration,
silence_minutes: u32,
candidate: Option<String>,
}
fn take_look(rc: &RoundCtx) -> Option<Look> {
with_run(rc, |run| Look {
project: run.project.clone(),
round: run.round,
stage: run.stage,
sid: run.sid.clone(),
generation: run.generation,
stop_now: run.stop_now,
running: run.running,
last_activity: run.last_activity,
activity_due: run.activity_checked.elapsed() >= rc.ctx.limits.activity_every,
waited: run.session_started_at.elapsed(),
silence_minutes: run.setup.silence_minutes,
candidate: run.page_candidate.clone(),
})
}
/// A page the app took: while a run waits for its round's session, a Review
/// page locked for that round and role is the session. One without the lock
/// yet is kept as a candidate the watch adopts once it shows.
pub fn note_page(slot: &ReviewSlot, workflow: &str, sid: &str, state: &Value) {
if workflow != "review" {
return;
}
if let Some(run) = lock(slot).as_mut().filter(|run| run.running) {
if run.sid.is_some() {
return;
}
if page_is_this_round(state, run.round, run.stage.role()) {
run.sid = Some(sid.to_string());
run.last_sid = Some(sid.to_string());
run.last_activity = SystemTime::now();
run.page_candidate = None;
} else if state.is_object() && state.get("roundOutcome").is_none_or(Value::is_null) {
run.page_candidate = Some(sid.to_string());
}
}
}
fn adopt_candidate(rc: &RoundCtx, look: &Look) -> Option<String> {
let candidate = look.candidate.as_deref()?;
let state = read_session_state(&rc.ctx, candidate)?;
if !page_is_this_round(&state, look.round, look.stage.role()) {
return None;
}
with_run(rc, |run| {
if run.sid.is_none() && run.page_candidate.as_deref() == Some(candidate) {
run.sid = Some(candidate.to_string());
run.last_sid = Some(candidate.to_string());
run.page_candidate = None;
}
run.sid.clone()
})
.flatten()
}
/// The reason the current session's agent ended by itself, if it did.
fn crashed(rc: &RoundCtx, look: &Look) -> Option<String> {
let seen = rc.ctx.agent.snapshot();
match seen.state {
AgentState::Ended { reason } if seen.generation == look.generation => Some(reason),
_ => None,
}
}
/// The silence rule's setup: the shared check wants a `LoopSetup`.
fn silence_setup(minutes: u32) -> loop_driver::LoopSetup {
loop_driver::LoopSetup {
silence_minutes: minutes,
..loop_driver::LoopSetup::default()
}
}
/// The round's outcome in `state`, when it is this look's round and role.
fn round_outcome_in(state: &Value, look: &Look) -> Option<Result<RoundOutcome, String>> {
outcome_for_round(state, look.round, look.stage.role())
}
/// One look at the running round. Returns false when the run is over.
pub fn tick(rc: &RoundCtx) -> bool {
let Some(look) = take_look(rc) else {
return false;
};
if !look.running {
return false;
}
if look.stop_now {
stop_now_finish(rc);
return false;
}
let Some(sid) = look.sid.clone().or_else(|| adopt_candidate(rc, &look)) else {
if let Some(reason) = crashed(rc, &look) {
return fail(rc, &look, &StopCause::Crash, &reason);
}
if look.waited > NOTICE_WAIT.max(rc.ctx.limits.notice_wait) {
return fail(rc, &look, &StopCause::NoSession, "");
}
return true;
};
let session = match session_reader::load(&rc.ctx.home, &sid) {
Ok(session) => session,
Err(_) => {
if let Some(go) = crash_or_outcome(rc, &look, &sid) {
return go;
}
return silence_check(rc, &look, look.last_activity, None, false);
}
};
if let Some(found) = round_outcome_in(&session.state, &look) {
return take_outcome(rc, &look, &session.state, found);
}
if let Some(go) = crash_or_outcome(rc, &look, &sid) {
return go;
}
// A round that asks the person a question cannot be answered: it fails.
if let Some(question) = loop_driver::first_open_question(&session.state) {
let reason = format!("the agent asked a question: {}", one_line(&question));
return settle_failure(rc, &look, reason);
}
observe(rc, session.state["headline"]["stage"].as_str());
let quiet = session.state["agent"]["quietMinutes"]
.as_u64()
.and_then(|m| u32::try_from(m).ok());
let mut last = look.last_activity;
if look.activity_due {
last = refresh_activity(rc, &look, &session.dir);
}
silence_check(rc, &look, last, quiet, false)
}
fn silence_check(
rc: &RoundCtx,
look: &Look,
last: SystemTime,
quiet: Option<u32>,
waiting: bool,
) -> bool {
let setup = silence_setup(look.silence_minutes);
if silence_expired(SystemTime::now(), last, &setup, quiet, waiting) {
let minutes = look.silence_minutes.max(quiet.unwrap_or(0)).min(60);
return fail(rc, look, &StopCause::Silence, &minutes.to_string());
}
true
}
/// The agent ended by itself: read the session once more before calling it a
/// crash, since an agent that writes its report and exits between two looks
/// must be judged, not retried.
fn crash_or_outcome(rc: &RoundCtx, look: &Look, sid: &str) -> Option<bool> {
let reason = crashed(rc, look)?;
if let Ok(session) = session_reader::load(&rc.ctx.home, sid) {
if let Some(found) = round_outcome_in(&session.state, look) {
return Some(take_outcome(rc, look, &session.state, found));
}
}
Some(fail(rc, look, &StopCause::Crash, &reason))
}
fn refresh_activity(rc: &RoundCtx, look: &Look, session_dir: &Path) -> SystemTime {
let newest = loop_driver::newest_work(session_dir, &look.project);
with_run(rc, |run| {
run.activity_checked = Instant::now();
if let Some(time) = newest.map(loop_driver::clamp_to_now) {
if time > run.last_activity {
run.last_activity = time;
}
}
run.last_activity
})
.unwrap_or(look.last_activity)
}
/// Take the banner's step from the page's headline stage.
fn observe(rc: &RoundCtx, stage: Option<&str>) {
let changed = with_run(rc, |run| {
let before = run.step;
if let Some(stage) = stage {
let lower = stage.to_lowercase();
if lower.contains("test") {
run.step = ReviewStep::Testing;
} else if lower.contains("fix") {
run.step = ReviewStep::Fixing;
} else if lower.contains("review") {
run.step = ReviewStep::Reviewing;
}
}
run.step != before
});
if changed == Some(true) {
emit(rc);
}
}
fn cause_text(cause: &StopCause, detail: &str) -> String {
match cause {
StopCause::Crash => format!("the agent crashed ({detail})"),
StopCause::Silence => format!("the agent went silent for {detail} minutes"),
StopCause::NoSession => "the round's console never opened".to_string(),
_ => "the round failed".to_string(),
}
}
/// A crash, silence or a console that never opened.
fn fail(rc: &RoundCtx, look: &Look, cause: &StopCause, detail: &str) -> bool {
settle_failure(rc, look, cause_text(cause, detail))
}
/// A failed round try: one fresh retry a strength up, else the run stops.
fn settle_failure(rc: &RoundCtx, look: &Look, reason: String) -> bool {
// Stop now was pressed since this look began: the ended agent is not a
// crash and nothing is retried.
if with_run(rc, |run| run.stop_now) == Some(true) {
stop_now_finish(rc);
return false;
}
// The final check that fails twice never changes why the run ended: its
// own result is kept apart, and the run stops for the reason it already
// had (FR-19).
if look.stage == Stage::Final {
let original = with_run(rc, |run| {
if !run.retried {
return None;
}
if let Some(batch) = run.suggestions_batch.as_mut() {
batch.final_check = Some(Verdict::Failed(reason.clone()));
}
Some(run.pending_stop.clone().unwrap_or(StopReason::Clean))
})
.flatten();
if let Some(original) = original {
let note = format!("the final check did not finish ({reason})");
return act(
rc,
Stage::Final,
round_logic::after_final_check(original),
Some(&note),
);
}
}
let next = with_run(rc, |run| {
round_logic::next_step(&run.view(look.round), &Verdict::Failed(reason.clone()))
});
match next {
Some(next) => act(rc, look.stage, next, Some(&reason)),
None => false,
}
}
// ------------------------------------------------------ handling an outcome
fn take_outcome(
rc: &RoundCtx,
look: &Look,
state: &Value,
found: Result<RoundOutcome, String>,
) -> bool {
// Stop now came since this look began: nothing is judged or committed.
if with_run(rc, |run| run.stop_now) == Some(true) {
stop_now_finish(rc);
return false;
}
let mut outcome = match found {
Ok(outcome) => outcome,
Err(reason) => {
rc.ctx.agent.stop();
return settle_failure(rc, look, reason);
}
};
if look.stage == Stage::Fixer {
let (critical, warning) =
with_run(rc, |run| (run.cur.critical, run.cur.warning)).unwrap_or((0, 0));
round_logic::hold_reviewer_counts(&mut outcome.review, critical, warning);
}
let role = look.stage.role();
let proofs = proofs_for(state, &outcome, role);
let verdict = round_logic::judge_round(&outcome, &proofs);
let report = outcome
.report
.as_deref()
.and_then(|id| report_text(state, id))
.unwrap_or_default();
// This session's work is read: its agent ends before anything else starts.
rc.ctx.agent.stop();
match look.stage {
Stage::Both | Stage::Fixer => finish_round(rc, look, &outcome, verdict),
Stage::Reviewer => match verdict {
Verdict::Failed(reason) => settle_failure(rc, look, reason),
Verdict::Clean => finish_round(rc, look, &outcome, verdict),
Verdict::Findings { .. } => {
let brief = reviewer_brief(&report, &outcome);
with_run(rc, |run| {
run.reviewer_report = Some(brief);
// The round has one retry in all: the fixer gets none when
// the reviewer's session used it.
run.cur.critical = outcome.review.critical;
run.cur.warning = outcome.review.warning;
});
match start_stage(rc, Stage::Fixer, look.round) {
Ok(()) => true,
Err(e) => {
finish_run(
rc,
StopReason::Failed(format!(
"the fixer could not start ({})",
one_line(&e)
)),
Some(e),
);
false
}
}
}
},
Stage::Batch => finish_batch(rc, look, &outcome, verdict),
Stage::Final => finish_final(rc, look, &outcome, verdict),
}
}
/// Commit what a round changed (commit mode) or take a snapshot (snapshot
/// mode), and say where the round ended. A refused or failed commit stops the
/// run as `Failed` with what git or the staged-file check said.
fn close_round(
rc: &RoundCtx,
project: &Path,
mode: Mode,
subject: &str,
) -> Result<(Option<String>, Boundary), (String, String)> {
with_run(rc, |run| run.step = ReviewStep::Committing);
emit(rc);
match mode {
Mode::Snapshot => round_boundary::snapshot(project)
.map(|boundary| (None, boundary))
.map_err(|e| (e.clone(), e)),
Mode::Commit => {
let commit = commit_all(project, subject, rc.ctx.limits.commit_limit)?;
let boundary = round_boundary::head(project).map_err(|e| (e.clone(), e))?;
Ok((commit, boundary))
}
}
}
/// A title as a commit subject takes it: `commit-msg.mjs` refuses a double
/// quote (straight or curly), a backtick, `$`, `!` and a backslash, since shells
/// read them differently inside double quotes, and review titles carry them
/// often (a backticked name). Quotes become `'`, the rest are dropped.
fn safe_title(title: &str) -> String {
title
.chars()
.filter(|c| !matches!(c, '`' | '$' | '!' | '\\'))
.map(|c| {
if c == '"' || ('\u{201C}'..='\u{201F}').contains(&c) {
'\''
} else {
c
}
})
.collect::<String>()
.trim()
.to_string()
}
fn fix_titles(review: &RoundReview, subject: Option<&str>) -> Vec<String> {
let mut titles: Vec<String> = review.fixed.iter().map(|f| safe_title(&f.title)).collect();
if titles.is_empty() {
titles.extend(subject.map(safe_title));
}
titles
}
/// The Suggestions batch's commit subject, fitted to 72 characters with its
/// own prefix (a longer one than a round's).
fn batch_subject(titles: &[String]) -> String {
let subject =
round_logic::round_commit_message(0, titles).replacen("round 0", "Suggestions batch", 1);
if subject.chars().count() <= 72 {
return subject;
}
let cut: String = subject.chars().take(69).collect();
format!("{}...", cut.trim_end())
}
/// A judged round: record it, commit or snapshot it, then take the next step.
fn finish_round(rc: &RoundCtx, look: &Look, outcome: &RoundOutcome, verdict: Verdict) -> bool {
if let Verdict::Failed(reason) = &verdict {
return settle_failure(rc, look, reason.clone());
}
if with_run(rc, |run| run.stop_now) == Some(true) {
stop_now_finish(rc);
return false;
}
let (mode, round) = with_run(rc, |run| (run.mode, run.round)).unwrap_or((Mode::Snapshot, 0));
let subject = round_logic::round_commit_message(
round,
&fix_titles(&outcome.review, outcome.subject.as_deref()),
);
let (commit, boundary) = match close_round(rc, &look.project, mode, &subject) {
Ok(saved) => saved,
Err((line, evidence)) => {
finish_run(
rc,
StopReason::Failed(format!("the round could not be saved ({line})")),
Some(evidence),
);
return false;
}
};
let next = with_run(rc, |run| {
let mut done = std::mem::take(&mut run.cur);
done.n = look.round;
done.boundary = Some(boundary);
done.verdict = Some(verdict.clone());
done.ended_at = clock();
done.critical = outcome.review.critical;
done.warning = outcome.review.warning;
done.suggestion = outcome.review.suggestion;
done.fixed = outcome.review.fixed.clone();
done.unfixed = outcome.review.unfixed.clone();
done.suggestions = outcome.review.suggestions.clone();
done.tests = outcome.tests.clone();
done.commit = commit;
done.retried = run.retried;
done.summary = outcome.summary.clone();
run.collected = merge_suggestions(
&run.collected,
&outcome.review.suggestions,
&outcome.review.fixed,
&run.reviewed_files,
);
run.rounds.push(done);
run.step = ReviewStep::Starting;
let next = round_logic::next_step(&run.view(look.round), &verdict);
if next == Next::SuggestionsBatch {
run.pending_stop = Some(if verdict == Verdict::Clean {
StopReason::Clean
} else {
StopReason::Cap
});
}
next
});
let Some(next) = next else { return false };
notify_round(rc, look.round, outcome, &verdict);
emit(rc);
act(rc, look.stage, next, None)
}
/// Act on the step `next_step` chose. Returns whether the run goes on.
fn act(rc: &RoundCtx, stage: Stage, next: Next, why: Option<&str>) -> bool {
match next {
Next::StartRound(n) => {
with_run(rc, |run| {
run.retried = false;
run.reviewer_report = None;
// A retry's step up applies to that round only.
run.cur_strength = run.setup.strength;
});
let first = with_run(rc, |run| first_stage(run.shape)).unwrap_or(Stage::Both);
go(rc, start_stage(rc, first, n))
}
Next::Retry => {
let round = with_run(rc, |run| run.round).unwrap_or(1);
with_run(rc, |run| {
run.retried = true;
run.retries_used += 1;
let stepped = run
.cur_strength
.and_then(|word| next_strength_word(&run.strength_rows, word.word()))
.and_then(|word| Strength::from_word(&word));
match stepped {
Some(word) => run.cur_strength = Some(word),
None => run.cur.could_not_step_up = true,
}
run.cur.retried = true;
});
emit(rc);
go(rc, start_stage(rc, stage, round))
}
Next::SuggestionsBatch => {
let round = with_run(rc, |run| {
let n = u32::try_from(run.rounds.len()).unwrap_or(0) + 1;
run.retried = false;
// A retried round's step up was for that round only.
run.cur_strength = run.setup.strength;
run.suggestions_batch = Some(BatchRecord {
briefed: run.collected.clone(),
before: Some(run.last_boundary()),
after_rounds: run.rounds.len(),
..BatchRecord::default()
});
n
})
.unwrap_or(1);
go(rc, start_stage(rc, Stage::Batch, round))
}
Next::FinalCheck => {
let round = with_run(rc, |run| {
run.retried = false;
run.cur_strength = run.setup.strength;
u32::try_from(run.rounds.len()).unwrap_or(0) + 2
})
.unwrap_or(2);
go(rc, start_stage(rc, Stage::Final, round))
}
Next::Stop(reason) => {
let evidence = why.map(str::to_string);
finish_run(rc, reason, evidence);
false
}
}
}
/// A session start that failed stops the run as `Failed`.
fn go(rc: &RoundCtx, started: Result<(), String>) -> bool {
match started {
Ok(()) => true,
Err(e) => {
finish_run(
rc,
StopReason::Failed(format!("a session could not start ({})", one_line(&e))),
Some(e),
);
false
}
}
}
/// The Suggestions batch's fixer reported: commit it on its own, then check it.
fn finish_batch(rc: &RoundCtx, look: &Look, outcome: &RoundOutcome, verdict: Verdict) -> bool {
if let Verdict::Failed(reason) = &verdict {
return settle_failure(rc, look, reason.clone());
}
if with_run(rc, |run| run.stop_now) == Some(true) {
stop_now_finish(rc);
return false;
}
let mode = with_run(rc, |run| run.mode).unwrap_or(Mode::Snapshot);
let subject = batch_subject(&fix_titles(&outcome.review, outcome.subject.as_deref()));
let (commit, boundary) = match close_round(rc, &look.project, mode, &subject) {
Ok(saved) => saved,
Err((line, evidence)) => {
finish_run(
rc,
StopReason::Failed(format!("the Suggestions batch could not be saved ({line})")),
Some(evidence),
);
return false;
}
};
let next = with_run(rc, |run| {
if let Some(batch) = run.suggestions_batch.as_mut() {
batch.boundary = Some(boundary);
batch.commit = commit;
batch.verdict = Some(verdict.clone());
batch.summary = outcome.summary.clone();
}
// Fixed and committed: a later round never briefs them again.
run.collected.clear();
run.batch_done = true;
run.step = ReviewStep::Starting;
round_logic::next_step(&run.view(look.round), &verdict)
});
let Some(next) = next else { return false };
emit(rc);
act(rc, look.stage, next, None)
}
/// The final check reported: its verdict is kept apart, and the run ends for
/// the reason it was already ending for (FR-19).
fn finish_final(rc: &RoundCtx, look: &Look, outcome: &RoundOutcome, verdict: Verdict) -> bool {
if let Verdict::Failed(reason) = &verdict {
let retried = with_run(rc, |run| run.retried).unwrap_or(true);
if !retried {
return settle_failure(rc, look, reason.clone());
}
}
if with_run(rc, |run| run.stop_now) == Some(true) {
stop_now_finish(rc);
return false;
}
let original = with_run(rc, |run| {
if let Some(batch) = run.suggestions_batch.as_mut() {
batch.final_check = Some(verdict.clone());
batch.final_critical = outcome.review.critical;
batch.final_warning = outcome.review.warning;
}
run.pending_stop.clone().unwrap_or(StopReason::Clean)
});
let Some(original) = original else {
return false;
};
let next = round_logic::after_final_check(original);
let note = match &verdict {
Verdict::Failed(reason) => Some(format!("the final check did not finish ({reason})")),
_ => None,
};
act(rc, look.stage, next, note.as_deref())
}
// -------------------------------------------------------- ending a run
/// End the run: record why, end the agent, tell the banner, then show the end
/// screen. The run is kept for Continue and sign-off. A sign-off's own
/// Suggestions fix ends here too: it keeps the reason the run already ended
/// for and finishes the sign-off.
pub fn finish_run(rc: &RoundCtx, reason: StopReason, evidence: Option<String>) {
rc.ctx.agent.stop();
let notice = with_run(rc, |run| {
let signing = run.signing;
if signing {
match &reason {
StopReason::Person => {
// Stop now during sign-off: not signed off, the person
// settles the partial changes and signs off again.
run.signing = false;
if let Some(signoff) = run.signoff.as_mut() {
signoff.problem =
Some("Stop now was pressed while the Suggestions were fixed".into());
}
}
StopReason::Failed(why) => {
if let Some(signoff) = run.signoff.as_mut() {
signoff.problem = Some(one_line(why));
}
}
_ => {}
}
} else {
run.stop_reason = Some(reason.clone());
run.stop_evidence = evidence;
run.stop_round = run.round;
}
run.running = false;
run.step = ReviewStep::Starting;
(
signing,
run.setup.notify_kind,
run.setup.notify_url.clone(),
run.setup.notify_param.clone(),
run.round,
run.open_findings().len(),
)
});
(rc.ctx.hooks.emit)(LoopStateEvent::ended());
let Some((signing, kind, url, param, round, open)) = notice else {
return;
};
if with_run(rc, |run| run.signing) == Some(true) {
complete_sign_off(rc);
}
show_end(rc);
if !signing {
if let Some(words) = stop_words(&reason, round, open).filter(|_| !url.trim().is_empty()) {
send_notice(rc, kind, url, param, format!("Review Loop {words}"));
}
}
}
// ----------------------------------------------------- the end screen
/// The doc ids the end post uses.
const REPORT_DOC: &str = "review-report";
const PARTIAL_DOC: &str = "review-partial";
/// The most Suggestions and open findings the end screen lists.
const LIST_LIMIT: usize = 50;
fn text_line(text: &str, max: usize) -> String {
one_line(text).chars().take(max).collect()
}
fn count_words(n: usize, one: &str, many: &str) -> String {
if n == 1 {
format!("1 {one}")
} else {
format!("{n} {many}")
}
}
fn reason_key(reason: Option<&StopReason>) -> &'static str {
match reason {
Some(StopReason::Clean) => "clean",
Some(StopReason::Cap) => "cap",
Some(StopReason::Person) => "person",
Some(StopReason::Failed(_)) | None => "failed",
}
}
/// The one line the end screen leads with, never over 200 characters.
pub fn end_line(run: &ReviewRun) -> String {
let rounds = run.rounds.len();
let ran = count_words(rounds, "round", "rounds");
let open = run.open_findings().len();
let line = match &run.stop_reason {
Some(StopReason::Clean) if open > 0 => format!(
"Clean after {ran}, but {} still open.",
count_words(
open,
"finding an earlier round left unfixed is",
"findings earlier rounds left unfixed are"
)
),
Some(StopReason::Clean) => {
format!("Clean after {ran}: no Critical or Warning findings are left.")
}
Some(StopReason::Cap) => format!(
"Stopped at the round cap after {ran}: {} still open.",
count_words(open, "finding is", "findings are")
),
Some(StopReason::Person) if rounds == 0 => {
"Stopped by you before a round finished.".to_string()
}
Some(StopReason::Person) => format!("Stopped by you after {ran} finished."),
Some(StopReason::Failed(why)) => {
let round = if run.stop_round > 0 {
run.stop_round
} else {
run.round
};
format!("Failed in round {round}: {why}.")
}
None => "The Review Loop has not finished.".to_string(),
};
text_line(&line, 200)
}
/// Whether the end screen offers Continue: not after a clean run or a
/// sign-off, not while partial changes wait, and never past six rounds.
pub fn can_continue(run: &ReviewRun) -> bool {
if run.running || run.signing || run.signed_off {
return false;
}
if run.partial.as_ref().is_some_and(|partial| partial.pending) {
return false;
}
let rounds = u32::try_from(run.rounds.len()).unwrap_or(u32::MAX);
match run.stop_reason {
Some(StopReason::Cap) => round_logic::continue_cap(run.cap, rounds).is_some(),
Some(StopReason::Person) | Some(StopReason::Failed(_)) => rounds < MAX_ROUNDS,
Some(StopReason::Clean) | None => false,
}
}
/// The squash switch shows only in commit mode with two round commits.
pub fn can_squash(run: &ReviewRun) -> bool {
run.mode == Mode::Commit
&& !run.signed_off
&& run
.rounds
.iter()
.filter(|round| round.commit.is_some())
.count()
>= 2
}
fn finding_json(finding: &Finding) -> Value {
let mut value = serde_json::json!({
"title": text_line(&finding.title, 200),
"file": finding.file.trim(),
});
if let Some(line) = finding.line.filter(|line| *line > 0) {
value["line"] = serde_json::json!(line);
}
value
}
/// What sign-off did, in one line for the finished screen.
fn sign_off_note(run: &ReviewRun) -> Option<String> {
let signoff = run.signoff.as_ref().filter(|_| run.signed_off)?;
let mut parts: Vec<String> = Vec::new();
match &signoff.squash {
Squash::Done { commits, .. } => parts.push(format!(
"Squashed {} into one.",
count_words(*commits, "commit", "commits")
)),
Squash::Refused(why) => parts.push(why.clone()),
Squash::Off => {}
}
if !signoff.picked.is_empty() && signoff.problem.is_none() {
parts.push(format!(
"Fixed {}.",
count_words(signoff.picked.len(), "Suggestion", "Suggestions")
));
}
if let Some(problem) = &signoff.problem {
parts.push(format!("The Suggestions were not all fixed: {problem}."));
}
(!parts.is_empty()).then(|| text_line(&parts.join(" "), 200))
}
/// The page's `loopEnd` for the run as it stands. `partial_doc` says the
/// partial diff was put on the page.
pub fn end_patch_for(run: &ReviewRun, partial_doc: bool, report_md: &str) -> Value {
use serde_json::json;
let mut docs = vec![json!({
"id": REPORT_DOC,
"title": "Review Loop report",
"blocks": [{ "id": "body", "state": "settled", "md": report_md }],
})];
let mut end = json!({
"kind": "review",
"line": end_line(run),
"reason": reason_key(run.stop_reason.as_ref()),
"report": REPORT_DOC,
"canContinue": can_continue(run),
"canSquash": can_squash(run),
"can": [],
});
if let Some(partial) = run.partial.as_ref().filter(|p| p.pending && partial_doc) {
docs.push(json!({
"id": PARTIAL_DOC,
"title": "Partial changes",
"blocks": [{ "id": "diff", "diff": "partial.diff" }],
}));
end["partial"] = json!({
"files": partial.files,
"added": partial.added,
"removed": partial.removed,
"diff": PARTIAL_DOC,
});
}
if !run.signed_off && !run.collected.is_empty() {
let list: Vec<Value> = run
.collected
.iter()
.take(LIST_LIMIT)
.enumerate()
.map(|(i, finding)| {
let mut value = finding_json(finding);
value["id"] = json!(format!("s{}", i + 1));
value
})
.collect();
end["suggestions"] = json!(list);
}
let open: Vec<Value> = run
.open_findings()
.iter()
.take(LIST_LIMIT)
.map(finding_json)
.collect();
if !open.is_empty() {
end["open"] = json!(open);
}
if run.signed_off {
end["signedOff"] = json!(true);
if let Some(note) = sign_off_note(run) {
end["note"] = json!(note);
}
}
json!({ "docs": docs, "loopEnd": end })
}
/// Put the partial diff in the session's own folder, where a diff block must
/// live. False when the file could not be copied.
fn publish_partial(home: &Path, sid: &str, partial: &Partial) -> bool {
let folder = crate::session_reader::session_dir(home, sid);
std::fs::create_dir_all(&folder).is_ok()
&& std::fs::copy(&partial.diff, folder.join("partial.diff")).is_ok()
}
/// Tell the page how the run ended. A session the console no longer holds is
/// opened again once; a post it refuses is repeated without the partial diff.
fn post_review_end(console_dir: &Path, run: &ReviewRun, patch: &Value) {
let Some(sid) = run.sid.clone().or_else(|| run.last_sid.clone()) else {
return;
};
// No console to post to (a test, or the console not found): nothing to do.
if !console_dir.join("console.mjs").is_file() {
return;
}
if loop_tools::console_post(console_dir, &sid, patch).ok {
return;
}
if loop_tools::console_resume(console_dir, &sid, "review").ok
&& loop_tools::console_post(console_dir, &sid, patch).ok
{
return;
}
let mut plain = patch.clone();
if let Some(docs) = plain.get_mut("docs").and_then(Value::as_array_mut) {
docs.retain(|doc| doc["id"].as_str() != Some(PARTIAL_DOC));
}
if let Some(end) = plain.get_mut("loopEnd").and_then(Value::as_object_mut) {
end.remove("partial");
}
let _ = loop_tools::console_post(console_dir, &sid, &plain);
}
/// `REVIEW-LOOP-<date>.md`, or `-2`, `-3` and so on when that name is taken.
pub fn unused_report_name(date: &str, taken: impl Fn(&str) -> bool) -> String {
let first = format!("REVIEW-LOOP-{date}.md");
if !taken(&first) {
return first;
}
(2..)
.map(|n| format!("REVIEW-LOOP-{date}-{n}.md"))
.find(|name| !taken(name))
.unwrap_or(first)
}
/// Take the report file out of the spec folder before more work that commits
/// starts (a Suggestions fix, a Continue): the commit would otherwise sweep a
/// stale report into it. The next end writes a fresh one.
fn drop_spec_report(run: &mut ReviewRun) {
if let Some(file) = run.report_file.take() {
let _ = std::fs::remove_file(file);
}
}
/// Write the report into the spec folder, for a run launched on a spec and
/// only then. A later write (the sign-off's) replaces the first one.
pub fn write_spec_report(run: &ReviewRun, md: &str) -> Option<PathBuf> {
if run.scope != ReviewScope::Spec {
return None;
}
let spec = run.setup.spec.as_deref()?;
loop_driver::validate_spec(&run.project, spec).ok()?;
let folder = run.project.join(spec);
let file = match &run.report_file {
Some(file) => file.clone(),
None => {
let date = chrono::Local::now().format("%Y-%m-%d").to_string();
folder.join(unused_report_name(&date, |name| folder.join(name).exists()))
}
};
loop_driver::write_atomic(&file, md).ok().map(|()| file)
}
/// This run's entry for the report list: its rounds and how it ended.
pub fn review_entry(run: &ReviewRun) -> ReportEntry {
let rounds = run
.rounds
.iter()
.map(|round| RoundEntry {
n: round.n,
critical: round.critical,
warning: round.warning,
suggestion: round.suggestion,
fixed: round
.fixed
.iter()
.map(|f| text_line(&f.title, 200))
.collect(),
left_open: round
.unfixed
.iter()
.map(|f| text_line(&f.title, 200))
.collect(),
commit: round.commit.clone(),
tests: match &round.tests {
None => "not reported".to_string(),
Some(t) if !t.summary.is_empty() => text_line(&t.summary, 200),
Some(t) if t.passed => "passed".to_string(),
Some(_) => "failed".to_string(),
},
started: round.started_at.clone(),
ended: round.ended_at.clone(),
strength: round.strength.clone().unwrap_or_default(),
retried: round.retried,
})
.collect();
ReportEntry {
kind: EntryKind::Review,
rounds,
at: clock(),
name: run
.setup
.spec
.clone()
.unwrap_or_else(|| run.scope.word().to_string()),
result: if run.stop_reason == Some(StopReason::Clean) {
EntryResult::Passed
} else {
EntryResult::Stopped
},
line: end_line(run),
summary: end_line(run),
reported: true,
..ReportEntry::default()
}
}
/// Save the run's entry in the report list. It has a key of its own, so it
/// never meets an Implementation Loop report for the same spec.
fn save_review_entry(home: &Path, run: &ReviewRun) -> Result<(), String> {
let mut report = LoopReport::new(&format!("review-loop:{}", run.id), &clock());
report.entries.push(review_entry(run));
report_list::save_report(home, &run.project, &report)
}
/// Write the report where it goes (the report list, and the spec folder for a
/// spec launch) and post the end to the page. Returns the spec file written.
fn publish_end(console_dir: &Path, home: &Path, run: &ReviewRun) -> Option<PathBuf> {
let md = review_report_markdown(run);
let file = write_spec_report(run, &md);
let _ = save_review_entry(home, run);
let sid = run.sid.clone().or_else(|| run.last_sid.clone());
let partial_doc = match (&sid, run.partial.as_ref().filter(|p| p.pending)) {
(Some(sid), Some(partial)) => publish_partial(home, sid, partial),
_ => false,
};
post_review_end(console_dir, run, &end_patch_for(run, partial_doc, &md));
file
}
/// Show the end screen for the run as it stands.
fn show_end(rc: &RoundCtx) {
let Some(run) = with_run(rc, |run| run.clone()) else {
return;
};
if let Some(file) = publish_end(&rc.ctx.console_dir, &rc.ctx.home, &run) {
with_run(rc, |run| run.report_file = Some(file));
}
}
// ------------------------------------------------------------- sign-off
/// The Suggestion a pick id (`s1`, `s2`...) names, as an index.
fn pick_index(id: &str, count: usize) -> Option<usize> {
let n: usize = id.strip_prefix('s')?.parse().ok()?;
(1..=count.min(LIST_LIMIT)).contains(&n).then(|| n - 1)
}
const FOREIGN_COMMIT: &str =
"Something else was committed during the run, so the rounds were not squashed.";
/// The squash commit's subject: the rounds it covers and what they fixed.
fn squash_subject(first: u32, last: u32, titles: &[String]) -> String {
let subject = round_logic::round_commit_message(0, titles).replacen(
"round 0",
&format!("rounds {first} to {last}"),
1,
);
if subject.chars().count() <= 72 {
return subject;
}
let cut: String = subject.chars().take(69).collect();
format!("{}...", cut.trim_end())
}
/// Squash the run's commits (the round commits and the Suggestions commit)
/// into one on top of the start boundary, which holds the pre-run commit and
/// everything before it. Refuses, and changes nothing, when any commit
/// between the start and HEAD was not made by this run or something is
/// staged.
fn squash_rounds(project: &Path, start: &Boundary, mine: &[String], subject: &str) -> Squash {
let Boundary::Commit(start_id) = start else {
return Squash::Refused("There are no round commits to squash.".to_string());
};
let Ok(list) = git_text(
project,
&["rev-list", "--reverse", &format!("{start_id}..HEAD")],
) else {
return Squash::Refused(FOREIGN_COMMIT.to_string());
};
let ids = lines_of(&list);
if ids.len() < 2 {
return Squash::Refused("There are not two commits of the run to squash.".to_string());
}
if ids.len() != mine.len() || ids.iter().any(|id| !mine.contains(id)) {
return Squash::Refused(FOREIGN_COMMIT.to_string());
}
if git_text(project, &["diff", "--cached", "--quiet"]).is_err() {
return Squash::Refused("Something is staged, so the rounds were not squashed.".into());
}
let Ok(head) = loop_tools::git_head_full(project) else {
return Squash::Refused("git could not read the current commit.".to_string());
};
let message = match loop_tools::commit_message(project, subject) {
Ok(message) => message,
Err(why) => return Squash::Refused(format!("The squash commit was refused: {why}")),
};
if let Err(why) = git_text(project, &["reset", "--soft", start_id]) {
return Squash::Refused(format!("The rounds were not squashed: {why}"));
}
let done = loop_tools::git_commit(project, &message);
if !done.ok {
// Put every round commit back where it was.
let _ = git_text(project, &["reset", "--soft", &head]);
return Squash::Refused(format!(
"The squash commit failed, so the round commits are as they were ({}).",
loop_commit::first_line(&done.output)
));
}
match loop_tools::git_head_full(project) {
Ok(commit) => Squash::Done {
commit,
commits: ids.len(),
},
Err(why) => Squash::Refused(format!("The squash ran, but {why}.")),
}
}
/// The commits this run made, from its records.
fn run_commits(run: &ReviewRun) -> Vec<String> {
run.rounds
.iter()
.filter_map(|round| round.commit.clone())
.chain(
run.earlier_batches
.iter()
.chain(run.suggestions_batch.iter())
.filter_map(|batch| batch.commit.clone()),
)
.collect()
}
/// Run the squash the person asked for (if they did) and mark the run signed
/// off. Called once the Suggestions fix, if there was one, has ended.
fn complete_sign_off(rc: &RoundCtx) {
let plan = with_run(rc, |run| {
let asked = run.signoff.as_ref().is_some_and(|s| s.squash_asked);
let first = run.rounds.first().map_or(1, |r| r.n);
let last = run.rounds.last().map_or(1, |r| r.n);
let titles: Vec<String> = run
.rounds
.iter()
.flat_map(|r| r.fixed.iter().map(|f| safe_title(&f.title)))
.collect();
(
asked,
run.mode,
run.project.clone(),
run.start.clone(),
run_commits(run),
squash_subject(first, last, &titles),
)
});
let Some((asked, mode, project, start, mine, subject)) = plan else {
return;
};
let squash = match (asked, mode) {
(false, _) => Squash::Off,
(true, Mode::Commit) => squash_rounds(&project, &start, &mine, &subject),
(true, Mode::Snapshot) => Squash::Refused("A squash needs commit mode.".to_string()),
};
with_run(rc, |run| {
if let Some(signoff) = run.signoff.as_mut() {
signoff.squash = squash;
}
run.signing = false;
run.signed_off = true;
});
}
/// Sign off a finished run: fix the Suggestions the person ticked (one fixer
/// session, its fresh check and its own commit, the same path as the auto
/// batch), then squash the round commits when asked, then show the finished
/// screen. With no Suggestions ticked nothing runs but the squash.
#[allow(clippy::too_many_arguments)]
pub fn sign_off(
slot: &ReviewSlot,
phases: &LoopSlot,
agent: Arc<AgentManager>,
hooks: Hooks,
limits: Limits,
home: PathBuf,
picks: &[String],
squash: bool,
watch: bool,
) -> Result<(), String> {
if loop_driver::is_running(phases) || is_running(slot) {
return Err("A loop is already running in this window.".to_string());
}
let (rc, any_picked) = {
let mut guard = lock(slot);
let run = guard
.as_mut()
.ok_or("There is no Review Loop to sign off.")?;
if run.running || run.signing {
return Err("A loop is already running in this window.".to_string());
}
if run.signed_off {
return Err("This Review Loop was already signed off.".to_string());
}
if run.stop_reason.is_none() {
return Err("The Review Loop has not finished.".to_string());
}
if run.partial.as_ref().is_some_and(|partial| partial.pending) {
return Err("Keep or discard the partial changes first.".to_string());
}
let mut chosen: Vec<usize> = Vec::new();
for id in picks {
let at =
pick_index(id, run.collected.len()).ok_or("That Suggestion is not on the list.")?;
if chosen.contains(&at) {
return Err("A Suggestion was picked twice.".to_string());
}
chosen.push(at);
}
chosen.sort_unstable();
let picked: Vec<Finding> = chosen.iter().map(|at| run.collected[*at].clone()).collect();
let left: Vec<Finding> = run
.collected
.iter()
.enumerate()
.filter(|(at, _)| !chosen.contains(at))
.map(|(_, finding)| finding.clone())
.collect();
run.signoff = Some(SignOff {
picked: picked.clone(),
left,
squash_asked: squash,
squash: Squash::Off,
problem: None,
});
if !picked.is_empty() {
run.signing = true;
run.running = true;
// A neutral sentinel: the check then ends the fix with Clean, so a
// Person or Failed reason can only come from this fix itself.
run.pending_stop = Some(StopReason::Clean);
run.collected = picked;
run.batch_done = false;
run.retried = false;
run.stop_now = false;
run.stop_after_round = false;
run.cur_strength = run.setup.strength;
drop_spec_report(run);
if let Some(batch) = run.suggestions_batch.take() {
run.earlier_batches.push(batch);
}
}
let any = run.signing;
let rc = RoundCtx {
slot: Arc::clone(slot),
ctx: new_ctx(run, agent, home, hooks, limits),
};
(rc, any)
};
if !any_picked {
complete_sign_off(&rc);
show_end(&rc);
return Ok(());
}
emit(&rc);
// A start that fails ends the sign-off through `finish_run`, which says so.
let started = act(&rc, Stage::Batch, Next::SuggestionsBatch, None);
if started && watch {
thread::spawn(move || watcher(rc));
}
Ok(())
}
/// The prompt behind a finished screen's button: PR Prep, or a Quick task on
/// what the run left open.
pub fn next_prompt(slot: &ReviewSlot, which: &str) -> Result<String, String> {
let guard = lock(slot);
let run = guard.as_ref().ok_or("There is no Review Loop run.")?;
if run.running {
return Err("The Review Loop is still running.".to_string());
}
match which {
"pr-prep" => Ok("/plan2code-pr-prep --web".to_string()),
"quick-task" => {
let open: Vec<String> = run
.open_findings()
.iter()
.enumerate()
.map(|(i, finding)| {
let at = match (finding.file.is_empty(), finding.line) {
(true, _) => String::new(),
(false, None) => format!(" ({})", finding.file),
(false, Some(line)) => format!(" ({}:{line})", finding.file),
};
format!("{}. {}{at}", i + 1, text_line(&finding.title, 200))
})
.collect();
if open.is_empty() {
return Err("Nothing is left open.".to_string());
}
Ok(format!(
"/plan2code-quick-task --web Fix by hand what the Review Loop left open: {}",
open.join("; ")
))
}
_ => Err("That is not a next step.".to_string()),
}
}
/// Keep or discard what Stop now left, then show the end screen again
/// without it (Continue is offered once the partial changes are settled).
pub fn settle_partial(slot: &ReviewSlot, keep: bool, home: &Path) -> Result<(), String> {
partial(slot, keep)?;
let run = lock(slot).clone();
if let Some(run) = run {
if let Some(file) = publish_end(&console_dir(), home, &run) {
if let Some(held) = lock(slot).as_mut().filter(|r| r.run_id == run.run_id) {
held.report_file = Some(file);
}
}
}
Ok(())
}
/// What the ending notice says, always naming the round it ended in, or none
/// when the person stopped the run themselves (as the Implementation Loop does).
fn stop_words(reason: &StopReason, round: u32, open: usize) -> Option<String> {
match reason {
StopReason::Clean if open > 0 => Some(format!(
"finished after round {round}, but {} still open.",
count_words(
open,
"finding an earlier round left unfixed is",
"findings earlier rounds left unfixed are"
)
)),
StopReason::Clean => Some(format!(
"finished after round {round}: no Critical or Warning findings are left."
)),
StopReason::Cap => Some(format!("stopped at the round cap after round {round}.")),
StopReason::Person => None,
StopReason::Failed(why) => Some(format!("failed in round {round}: {why}.")),
}
}
/// Tell the address on its own thread: a slow one must not delay the watch.
fn send_notice(rc: &RoundCtx, kind: NotifyKind, url: String, param: String, message: String) {
let (slot, run_id) = (Arc::clone(&rc.slot), rc.ctx.run_id);
thread::spawn(move || {
if let Err(reason) = crate::loop_shared::notify(kind, &url, &param, &message) {
if let Some(run) = lock(&slot).as_mut().filter(|run| run.run_id == run_id) {
run.notify_failure = Some(reason);
}
}
});
}
fn notify_round(rc: &RoundCtx, round: u32, outcome: &RoundOutcome, verdict: &Verdict) {
let target = with_run(rc, |run| {
(run.setup.notify_rounds && !run.setup.notify_url.trim().is_empty()).then(|| {
(
run.setup.notify_kind,
run.setup.notify_url.clone(),
run.setup.notify_param.clone(),
)
})
})
.flatten();
if let Some((kind, url, param)) = target {
let how = match verdict {
Verdict::Clean => "clean".to_string(),
Verdict::Findings { critical, warning } => {
format!("{critical} Critical, {warning} Warning")
}
Verdict::Failed(reason) => format!("failed ({reason})"),
};
let message = format!("Review Loop round {round}: {how}. {}", outcome.summary);
send_notice(rc, kind, url, param, message);
}
}
// ------------------------------------------------------- the stop buttons
/// Stop after this round: it finishes, is judged and committed, then the run
/// stops instead of starting the next. Returns the banner's new state.
pub fn request_stop_after(slot: &ReviewSlot, on: bool) -> Result<LoopStateEvent, String> {
let mut guard = lock(slot);
let run = guard
.as_mut()
.filter(|run| run.running)
.ok_or("No Review Loop is running")?;
run.stop_after_round = on;
Ok(review_state_event(run))
}
/// Stop now: the flag is set first, so the ended agent is never taken for a
/// crash and nothing more is committed, then the agent ends. The banner's new
/// state goes to `emit` while the slot is held.
pub fn request_stop_now(
slot: &ReviewSlot,
agent: Option<&AgentManager>,
emit: impl FnOnce(&LoopStateEvent),
) -> Result<LoopStateEvent, String> {
let event = {
let mut guard = lock(slot);
let run = guard
.as_mut()
.filter(|run| run.running)
.ok_or("No Review Loop is running")?;
run.stop_now = true;
let event = review_state_event(run);
emit(&event);
event
};
if let Some(agent) = agent {
agent.stop();
}
Ok(event)
}
/// Stop now was pressed: end the run as stopped by the person, commit
/// nothing, and leave the partial changes (a diff from the last finished
/// boundary to a fresh snapshot) for the stop screen.
fn stop_now_finish(rc: &RoundCtx) {
rc.ctx.agent.stop();
let plan = with_run(rc, |run| {
(
run.project.clone(),
run.last_boundary(),
run.run_dir.join("partial.diff"),
)
});
let Some((project, from, out)) = plan else {
return;
};
let mut partial = Partial {
diff: out.clone(),
pending: true,
..Partial::default()
};
let _ = std::fs::create_dir_all(out.parent().unwrap_or(Path::new(".")));
let mut evidence = None;
match round_boundary::snapshot(&project) {
Ok(now) => match round_boundary::diff(&project, &from, &now, &out) {
Ok(stats) => {
partial.files = stats.files;
partial.added = stats.added;
partial.removed = stats.removed;
partial.new_files = git_text(
&project,
&[
"diff",
"--name-only",
"-z",
"--no-renames",
"--diff-filter=A",
from.id(),
now.id(),
],
)
.map(|text| nul_lines(&text))
.unwrap_or_default();
}
Err(e) => evidence = Some(format!("the partial changes could not be listed ({e})")),
},
Err(e) => evidence = Some(format!("the partial changes could not be listed ({e})")),
}
with_run(rc, |run| run.partial = Some(partial));
finish_run(rc, StopReason::Person, evidence);
}
/// Keep or discard what Stop now left. Keep leaves the partial changes
/// uncommitted. Discard puts tracked files back to the last finished
/// boundary and removes only the untracked files that appeared during the
/// stopped round, never others.
pub fn partial(slot: &ReviewSlot, keep: bool) -> Result<(), String> {
let (project, boundary, new_files) = {
let guard = lock(slot);
let run = guard.as_ref().ok_or("No Review Loop to settle")?;
if run.running {
return Err("The Review Loop is still running.".to_string());
}
let partial = run
.partial
.as_ref()
.filter(|partial| partial.pending)
.ok_or("There are no partial changes waiting.")?;
(
run.project.clone(),
run.last_boundary(),
partial.new_files.clone(),
)
};
if !keep {
// Git names files from the repository's top folder, and the project
// may be a folder inside it: put back and remove from the top.
let top = loop_tools::git_toplevel(&project).unwrap_or_else(|| project.clone());
match &boundary {
Boundary::Commit(id) => {
git_text(&top, &["checkout", id, "--", "."])?;
}
Boundary::Tree(id) => restore_tree(&top, id)?,
}
for file in &new_files {
let path = top.join(file);
if path.is_file() {
let _ = std::fs::remove_file(&path);
}
}
}
if let Some(run) = lock(slot).as_mut() {
if let Some(partial) = run.partial.as_mut() {
partial.pending = false;
}
}
Ok(())
}
/// Put the working tree's files back to a tree id, through a temp index so the
/// real one is never touched.
fn restore_tree(project: &Path, tree: &str) -> Result<(), String> {
let temp = std::env::temp_dir().join(format!(
"plan2code-round-restore-{}-{}",
std::process::id(),
NEXT_RUN.fetch_add(1, Ordering::SeqCst)
));
let run = |args: &[&str]| -> Result<(), String> {
let out = git_cmd(project, args)
.env("GIT_INDEX_FILE", &temp)
.output()
.map_err(|err| format!("git could not run: {err}"))?;
if out.status.success() {
Ok(())
} else {
Err(format!(
"git {} failed: {}",
args.first().unwrap_or(&""),
String::from_utf8_lossy(&out.stderr)
.lines()
.next()
.unwrap_or("")
))
}
};
let result = run(&["read-tree", tree]).and_then(|()| run(&["checkout-index", "-a", "-f"]));
let _ = std::fs::remove_file(&temp);
result
}
// ----------------------------------------------------------------- Continue
/// Continue after a stop by the person, a failure or the cap: start the next
/// round from the run's last boundary. At the cap the cap goes up by one, and
/// never above six rounds in all.
pub fn continue_run(
slot: &ReviewSlot,
phases: &LoopSlot,
agent: Arc<AgentManager>,
hooks: Hooks,
limits: Limits,
home: PathBuf,
watch: bool,
) -> Result<(), String> {
if loop_driver::is_running(phases) || is_running(slot) {
return Err("A loop is already running in this window.".to_string());
}
let (round, rc) = {
let mut guard = lock(slot);
let run = guard
.as_mut()
.ok_or("There is no Review Loop to continue.")?;
if run.running || run.signing {
return Err("A loop is already running in this window.".to_string());
}
if run.signed_off {
return Err("This Review Loop was signed off.".to_string());
}
if run.partial.as_ref().is_some_and(|partial| partial.pending) {
return Err("Keep or discard the partial changes first.".to_string());
}
let rounds_run = u32::try_from(run.rounds.len()).unwrap_or(u32::MAX);
match run.stop_reason {
Some(StopReason::Clean) | None => {
return Err(
"This Review Loop finished clean: there is nothing to continue.".into(),
);
}
Some(StopReason::Cap) => {
let cap = round_logic::continue_cap(run.cap, rounds_run)
.ok_or("A Review Loop runs at most 6 rounds.")?;
run.cap = cap;
}
Some(StopReason::Person) | Some(StopReason::Failed(_)) => {
if rounds_run >= MAX_ROUNDS {
return Err("A Review Loop runs at most 6 rounds.".to_string());
}
if rounds_run >= run.cap {
run.cap = rounds_run + 1;
}
}
}
run.running = true;
run.stop_reason = None;
run.stop_evidence = None;
run.stop_now = false;
run.stop_after_round = false;
run.retried = false;
run.reviewer_report = None;
run.cur_strength = run.setup.strength;
run.pending_stop = None;
run.partial = None;
run.batch_done = false;
drop_spec_report(run);
// A finished batch stays in the record; the next one is a new batch.
if let Some(batch) = run.suggestions_batch.take() {
run.earlier_batches.push(batch);
}
let rc = RoundCtx {
slot: Arc::clone(slot),
ctx: new_ctx(run, agent, home, hooks, limits),
};
(rounds_run + 1, rc)
};
let first = with_run(&rc, |run| first_stage(run.shape)).unwrap_or(Stage::Both);
if let Err(e) = start_stage(&rc, first, round) {
with_run(&rc, |run| {
run.running = false;
run.stop_round = round;
run.stop_reason = Some(StopReason::Failed(format!(
"a session could not start ({})",
one_line(&e)
)));
});
// The report was dropped above: write it again and re-post the end.
show_end(&rc);
(rc.ctx.hooks.emit)(LoopStateEvent::ended());
return Err(e);
}
if watch {
thread::spawn(move || watcher(rc));
}
Ok(())
}
// ------------------------------------------------------------- the facts
/// What the setup screen shows about the agent a Review Loop would use.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReviewFacts {
pub agent: Option<String>,
pub agent_label: Option<String>,
pub helpers: bool,
pub strengths_mapped: bool,
pub running: bool,
pub prompt_support: bool,
pub notify_kind: NotifyKind,
pub notify_url: String,
pub notify_param: String,
}
/// The facts for `agent` (or none), a loop running, and the Implementation
/// Loop's notification settings (`loop_setup`).
pub fn facts(
agent: Option<&Agent>,
running: bool,
loop_setup: &loop_driver::LoopSetup,
) -> ReviewFacts {
ReviewFacts {
agent: agent.map(|a| a.id().to_string()),
agent_label: agent.map(|a| a.label().to_string()),
helpers: agent.is_some_and(agent_helpers),
strengths_mapped: agent.is_some_and(|a| !loop_driver::strength_rows_for(a).is_empty()),
running,
prompt_support: agent.is_none_or(loop_driver::prompt_support),
notify_kind: loop_setup.notify_kind,
notify_url: loop_setup.notify_url.clone(),
notify_param: loop_setup.notify_param.clone(),
}
}
/// The Start screen's request, as the page sends it. The notification comes
/// from the Implementation Loop's setup, never from this message.
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReviewRequest {
pub scope: ReviewScope,
#[serde(default)]
pub spec: Option<String>,
#[serde(default = "default_cap")]
pub cap: u32,
#[serde(default = "default_true")]
pub commit: bool,
#[serde(default)]
pub pre_run_commit_agreed: bool,
#[serde(default)]
pub suggestions: bool,
#[serde(default)]
pub strength: String,
#[serde(default = "default_silence")]
pub silence_minutes: u32,
#[serde(default)]
pub notify_rounds: bool,
}
fn default_cap() -> u32 {
3
}
fn default_true() -> bool {
true
}
fn default_silence() -> u32 {
20
}
impl ReviewRequest {
pub fn into_setup(self, loop_setup: &loop_driver::LoopSetup) -> ReviewSetup {
ReviewSetup {
scope: self.scope,
spec: self.spec.filter(|spec| !spec.trim().is_empty()),
cap: self.cap,
commit: self.commit,
pre_run_commit_agreed: self.pre_run_commit_agreed,
suggestions: self.suggestions,
strength: Strength::from_word(&self.strength),
silence_minutes: self.silence_minutes.clamp(1, 60),
notify_rounds: self.notify_rounds,
notify_kind: loop_setup.notify_kind,
notify_url: loop_setup.notify_url.clone(),
notify_param: loop_setup.notify_param.clone(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::loop_driver::tests::{
fake_agent_launch, fake_agent_manager, git_in, harness_ready, wait_until,
};
use serde_json::json;
#[test]
fn every_ending_notice_names_the_round_and_a_stop_by_the_person_sends_none() {
assert_eq!(
stop_words(&StopReason::Cap, 3, 0).as_deref(),
Some("stopped at the round cap after round 3.")
);
assert!(stop_words(&StopReason::Clean, 2, 0)
.unwrap()
.contains("after round 2"));
assert!(stop_words(&StopReason::Clean, 2, 1)
.unwrap()
.ends_with("1 finding an earlier round left unfixed is still open."));
assert!(stop_words(&StopReason::Failed("tests failed".into()), 2, 0)
.unwrap()
.starts_with("failed in round 2: tests failed"));
assert_eq!(stop_words(&StopReason::Person, 1, 0), None);
}
/// A new repository on `main` in a unique temp folder, with a committed
/// `a.txt` and a `.gitignore` for `ignored.log`, its config scrubbed of
/// anything global.
fn scratch_repo(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!(
"plan2code-review-loop-{name}-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&base);
let repo = base.join("repo");
std::fs::create_dir_all(&repo).unwrap();
git_in(&repo, &["init", "-q"]);
git_in(&repo, &["symbolic-ref", "HEAD", "refs/heads/main"]);
for (key, value) in [
("user.name", "Review Test"),
("user.email", "review@example.com"),
("commit.gpgsign", "false"),
("core.autocrlf", "false"),
("core.hooksPath", ".git/hooks"),
] {
git_in(&repo, &["config", key, value]);
}
std::fs::write(repo.join("a.txt"), "one\ntwo\n").unwrap();
std::fs::write(repo.join(".gitignore"), "ignored.log\n").unwrap();
git_in(&repo, &["add", "-A"]);
git_in(&repo, &["commit", "-q", "-m", "first"]);
repo
}
struct Rig {
rc: RoundCtx,
repo: PathBuf,
home: PathBuf,
phases: LoopSlot,
events: Arc<Mutex<Vec<LoopStateEvent>>>,
}
fn hooks_into(events: &Arc<Mutex<Vec<LoopStateEvent>>>) -> Hooks {
let sink = Arc::clone(events);
Hooks {
emit: Box::new(move |event| lock(&sink).push(event)),
attention: Box::new(|| {}),
}
}
/// A run on a scratch repo with the fake agent, round 1 started, and no
/// watch thread: a test plays the watcher by calling `tick`.
fn rig(name: &str, setup: ReviewSetup, shape: Shape) -> Rig {
rig_on(scratch_repo(name), setup, shape)
}
fn rig_on(repo: PathBuf, setup: ReviewSetup, shape: Shape) -> Rig {
let home = repo.parent().unwrap().join("console-home");
std::fs::create_dir_all(home.join("sessions")).unwrap();
let launch = fake_agent_launch();
let mut run = prepare_run(&repo, &launch, setup, &home).expect("the run prepares");
run.shape = shape;
let (agent, _seen) = fake_agent_manager(&repo);
let events = Arc::new(Mutex::new(Vec::new()));
let ctx = new_ctx(
&run,
agent,
home.clone(),
hooks_into(&events),
Limits::default(),
);
let rc = RoundCtx {
slot: Arc::new(Mutex::new(Some(run))),
ctx,
};
start_stage(&rc, first_stage(shape), 1).expect("round 1 starts");
Rig {
rc,
repo,
home,
phases: Arc::new(Mutex::new(None)),
events,
}
}
fn snap(rig: &Rig) -> ReviewRun {
lock(&rig.rc.slot).clone().expect("a run")
}
fn done(rig: &Rig) {
rig.rc.ctx.agent.stop();
let _ = std::fs::remove_dir_all(rig.repo.parent().unwrap());
}
fn subjects(repo: &Path) -> Vec<String> {
git_in(repo, &["log", "--format=%s"])
.lines()
.map(str::to_string)
.collect()
}
/// A `roundOutcome` the way a round agent posts it.
fn outcome(round: u32, role: &str, critical: u32, warning: u32, fixed: &[&str]) -> Value {
let list: Vec<Value> = fixed
.iter()
.map(|title| json!({ "title": title, "file": "a.txt" }))
.collect();
let mut value = json!({
"round": round, "role": role, "result": "passed", "reason": null,
"summary": "Round done",
"review": { "critical": critical, "warning": warning, "suggestion": 0,
"fixed": list, "unfixed": [], "suggestions": [] },
"tests": { "ran": true, "passed": true, "summary": "ok" },
});
if role != "fixer" {
value["report"] = json!("report");
}
if role == "reviewer" {
value.as_object_mut().unwrap().remove("tests");
value["review"]["unfixed"] = json!(fixed
.iter()
.map(|title| json!({ "title": title, "file": "a.txt" }))
.collect::<Vec<_>>());
value["review"]["fixed"] = json!([]);
}
value
}
/// Put `outcome` in session `sid` (with the report doc it names, as the
/// console holds it), make `sid` the round's session, and take one look.
fn answer(rig: &Rig, sid: &str, outcome: Value) -> bool {
let mut state = json!({ "schema": session_reader::SCHEMA, "roundOutcome": outcome });
if let Some(id) = state["roundOutcome"]["report"].as_str() {
state["docs"] = json!([{ "id": id, "kind": "report", "title": "Review round",
"blocks": [{ "id": "r", "md": "Found things to fix." }] }]);
}
let dir = rig.home.join("sessions").join(sid);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("state.json"), state.to_string()).unwrap();
with_run(&rig.rc, |run| run.sid = Some(sid.to_string()));
tick(&rig.rc)
}
fn edit(rig: &Rig, file: &str, text: &str) {
std::fs::write(rig.repo.join(file), text).unwrap();
}
fn one_session(name: &str, setup: ReviewSetup) -> Option<Rig> {
harness_ready(name).then(|| rig(name, setup, Shape::OneSession))
}
fn go_on(rig: &Rig) -> Result<(), String> {
continue_run(
&rig.rc.slot,
&rig.phases,
Arc::clone(&rig.rc.ctx.agent),
hooks_into(&rig.events),
Limits::default(),
rig.home.clone(),
false,
)
}
fn rows() -> BTreeMap<String, StrengthRow> {
["thrifty", "balanced", "best"]
.into_iter()
.map(|word| {
(
word.to_string(),
StrengthRow {
model: format!("{word}-model"),
effort: None,
},
)
})
.collect()
}
// ------------------------------------------------------------ pure parts
fn finding(title: &str, file: &str, line: Option<u32>) -> Finding {
Finding {
title: title.into(),
file: file.into(),
line,
}
}
#[test]
fn suggestions_drop_repeats_fixed_ones_and_ones_the_latest_reviewer_dropped() {
let timer = finding("Name the timer", "x.js", Some(4));
let handle = finding("Close the handle", "z.js", Some(9));
let first = merge_suggestions(&[], std::slice::from_ref(&timer), &[], &["x.js".into()]);
assert_eq!(first, vec![timer.clone()]);
let again = merge_suggestions(&first, std::slice::from_ref(&timer), &[], &["x.js".into()]);
assert_eq!(again.len(), 1, "a repeat is kept once");
let fixed = merge_suggestions(&first, &[], std::slice::from_ref(&timer), &["x.js".into()]);
assert!(fixed.is_empty(), "a later round fixed that file and line");
let seen = ["x.js".to_string(), "z.js".to_string()];
let dropped = merge_suggestions(&first, std::slice::from_ref(&handle), &[], &seen);
assert_eq!(
dropped,
vec![handle.clone()],
"the latest reviewer saw x.js and left it out"
);
let kept = merge_suggestions(
&first,
std::slice::from_ref(&handle),
&[],
&["z.js".to_string()],
);
assert_eq!(
kept,
vec![timer, handle],
"a file the reviewer never saw stays"
);
}
#[test]
fn the_round_prompt_names_the_round_the_role_and_the_scope_file() {
let prompt = round_prompt(2, Role::Fixer, Path::new("C:/runs/scope.md"));
assert_eq!(
prompt,
"/plan2code-review --web --loop --round 2 --role fixer --scope-file C:/runs/scope.md"
);
let spaced = round_prompt(1, Role::Both, Path::new("C:/Jane Doe/scope.md"));
assert!(
spaced.ends_with("--scope-file \"C:/Jane Doe/scope.md\""),
"{spaced}"
);
}
#[test]
fn the_banner_event_is_a_rounds_event_and_the_phases_one_is_unchanged() {
let run = ReviewRun::new(
PathBuf::from("."),
ReviewSetup::default(),
fake_agent_launch(),
Mode::Commit,
Shape::OneSession,
Boundary::Commit("a".repeat(40)),
PathBuf::from("runs"),
BTreeMap::new(),
);
let event = review_state_event(&run);
assert_eq!((event.kind, event.round, event.rounds), ("rounds", 1, 3));
assert!(event.running && event.round_counts.is_empty());
assert_eq!(event.phase_name, "Round 1 of 3: Starting");
let ended = LoopStateEvent::ended();
assert_eq!((ended.kind, ended.round, ended.rounds), ("phases", 0, 0));
assert!(ended.round_counts.is_empty() && !ended.stop_after_round);
}
#[test]
fn a_request_takes_its_notification_from_the_loop_setup_only() {
let request: ReviewRequest = serde_json::from_value(json!({
"scope": "spec", "spec": "specs/x", "cap": 4, "suggestions": true,
"strength": "best", "silenceMinutes": 99, "notifyRounds": true,
"notifyUrl": "http://evil.example/", "notifyParam": "x"
}))
.unwrap();
let loop_setup = loop_driver::LoopSetup {
notify_url: "http://mine.example/".into(),
notify_param: "msg".into(),
..loop_driver::LoopSetup::default()
};
let setup = request.into_setup(&loop_setup);
assert_eq!(setup.notify_url, "http://mine.example/");
assert_eq!(setup.notify_param, "msg");
assert_eq!(setup.silence_minutes, 60, "clamped to an hour");
assert_eq!(setup.strength, Some(Strength::Best));
assert!(
setup.commit,
"commits are on unless the page turns them off"
);
}
// ---------------------------------------------------- the four stop reasons
#[test]
fn a_clean_first_round_stops_clean_with_nothing_to_commit() {
let Some(rig) = one_session("clean", ReviewSetup::default()) else {
return;
};
let head = git_in(&rig.repo, &["rev-parse", "HEAD"]);
assert!(
!answer(&rig, "s1", outcome(1, "both", 0, 0, &[])),
"the run is over"
);
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Clean));
assert!(!run.running);
assert_eq!(run.rounds.len(), 1);
assert_eq!(run.rounds[0].verdict, Some(Verdict::Clean));
assert_eq!(run.rounds[0].commit, None);
assert_eq!(git_in(&rig.repo, &["rev-parse", "HEAD"]), head);
assert!(!is_running(&rig.rc.slot));
assert!(lock(&rig.events).last().is_some_and(|e| !e.running));
done(&rig);
}
#[test]
fn findings_then_clean_commits_each_round_by_number_and_scopes_round_two_to_round_ones_diff() {
let Some(rig) = one_session("two-rounds", ReviewSetup::default()) else {
return;
};
edit(&rig, "b.txt", "fixed b\n");
assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"])));
let run = snap(&rig);
assert_eq!(
(run.round, run.stage, run.rounds.len()),
(2, Stage::Both, 1)
);
// The agent never ran git: the app committed the round.
assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix b");
// Round 2 reviews exactly round 1's diff.
let dir = run.run_dir.join("round-2-both-t0");
let diff = std::fs::read_to_string(dir.join("round-1.diff")).unwrap();
assert!(
diff.contains("+++ b/b.txt") && !diff.contains("a.txt"),
"{diff}"
);
let scope = std::fs::read_to_string(dir.join("scope.md")).unwrap();
assert!(scope.contains("round-1.diff"), "{scope}");
edit(&rig, "c.txt", "tidy c\n");
assert!(!answer(&rig, "s2", outcome(2, "both", 0, 0, &["Tidy c"])));
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Clean));
let log = subjects(&rig.repo);
assert_eq!(log[0], "Review Loop round 2: Tidy c");
assert_eq!(log[1], "Review Loop round 1: Fix b");
assert_eq!(run.rounds.len(), 2);
assert_eq!(run.rounds[1].commit.as_deref().map(str::len), Some(40));
done(&rig);
}
#[test]
fn findings_every_round_stop_at_the_cap_after_three_commits() {
let Some(rig) = one_session("cap", ReviewSetup::default()) else {
return;
};
for n in 1..=3 {
edit(&rig, &format!("f{n}.txt"), "x\n");
let more = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"]));
assert_eq!(more, n < 3, "round {n}");
}
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Cap));
assert_eq!(run.rounds.len(), 3);
assert_eq!(
subjects(&rig.repo).len(),
4,
"three rounds and the first commit"
);
done(&rig);
}
#[test]
fn stop_after_this_round_commits_the_round_then_stops() {
let Some(rig) = one_session("stop-after", ReviewSetup::default()) else {
return;
};
let event = request_stop_after(&rig.rc.slot, true).unwrap();
assert!(event.stop_after_round);
edit(&rig, "b.txt", "x\n");
assert!(!answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"])));
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Person));
assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix b");
assert_eq!(run.rounds.len(), 1);
done(&rig);
}
#[test]
fn stop_now_commits_nothing_and_keep_leaves_the_partial_changes() {
let Some(rig) = one_session("stop-now-keep", ReviewSetup::default()) else {
return;
};
let before = git_in(&rig.repo, &["rev-parse", "HEAD"]);
edit(&rig, "a.txt", "changed\n");
edit(&rig, "p.txt", "new\n");
request_stop_now(&rig.rc.slot, Some(&rig.rc.ctx.agent), |_| {}).unwrap();
assert!(!tick(&rig.rc), "the next look ends the run");
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Person));
assert_eq!(
git_in(&rig.repo, &["rev-parse", "HEAD"]),
before,
"nothing committed"
);
let info = run.partial.clone().expect("partial data");
assert!(info.pending && info.files == 2, "{info:?}");
let diff = std::fs::read_to_string(&info.diff).unwrap();
assert!(diff.contains("+++ b/p.txt") && diff.contains("+++ b/a.txt"));
// Continue is held until the partial changes are settled.
assert!(go_on(&rig).unwrap_err().contains("partial changes"));
partial(&rig.rc.slot, true).unwrap();
assert_eq!(
std::fs::read_to_string(rig.repo.join("a.txt")).unwrap(),
"changed\n"
);
assert!(rig.repo.join("p.txt").exists());
assert!(snap(&rig).partial.is_some_and(|p| !p.pending));
done(&rig);
}
#[test]
fn stop_now_then_discard_puts_back_tracked_files_and_removes_only_the_rounds_new_ones() {
for (commit, name) in [(true, "discard-commit"), (false, "discard-snapshot")] {
let setup = ReviewSetup {
commit,
..ReviewSetup::default()
};
let Some(rig) = one_session(name, setup) else {
return;
};
// An ignored file that was there before the round: never touched.
std::fs::write(rig.repo.join("ignored.log"), "mine\n").unwrap();
edit(&rig, "a.txt", "changed\n");
edit(&rig, "p.txt", "new\n");
request_stop_now(&rig.rc.slot, Some(&rig.rc.ctx.agent), |_| {}).unwrap();
assert!(!tick(&rig.rc));
partial(&rig.rc.slot, false).unwrap();
assert_eq!(
std::fs::read_to_string(rig.repo.join("a.txt")).unwrap(),
"one\ntwo\n",
"{name}: the tracked file is back"
);
assert!(
!rig.repo.join("p.txt").exists(),
"{name}: the round's new file is gone"
);
assert!(
rig.repo.join("ignored.log").exists(),
"{name}: ignored files are never touched"
);
assert!(snap(&rig).partial.is_some_and(|p| !p.pending));
// Settled once: a second answer has nothing to act on.
assert!(partial(&rig.rc.slot, false).is_err());
done(&rig);
}
}
#[test]
fn continue_past_the_cap_runs_one_round_at_a_time_and_refuses_a_seventh() {
let Some(rig) = one_session("continue", ReviewSetup::default()) else {
return;
};
for n in 1..=3 {
edit(&rig, &format!("f{n}.txt"), "x\n");
answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"]));
}
assert_eq!(snap(&rig).stop_reason, Some(StopReason::Cap));
// Each Continue past the cap adds exactly one round.
for n in 4..=6 {
go_on(&rig).unwrap_or_else(|e| panic!("continue for round {n}: {e}"));
let run = snap(&rig);
assert_eq!((run.round, run.cap, run.running), (n, n, true));
edit(&rig, &format!("f{n}.txt"), "x\n");
assert!(!answer(
&rig,
&format!("s{n}"),
outcome(n, "both", 0, 1, &["Fix"])
));
assert_eq!(snap(&rig).stop_reason, Some(StopReason::Cap));
}
assert_eq!(
go_on(&rig).unwrap_err(),
"A Review Loop runs at most 6 rounds."
);
assert_eq!(snap(&rig).rounds.len(), 6);
// A run that finished clean has nothing to continue.
with_run(&rig.rc, |run| run.stop_reason = Some(StopReason::Clean));
assert!(go_on(&rig).unwrap_err().contains("nothing to continue"));
done(&rig);
}
// ----------------------------------------- shapes, proofs, retries, modes
#[test]
fn the_two_session_shape_runs_a_reviewer_then_a_fixer_that_gets_the_reviewers_report() {
if !harness_ready("two-session") {
return;
}
let rig = rig("two-session", ReviewSetup::default(), Shape::TwoSession);
assert_eq!(snap(&rig).stage, Stage::Reviewer);
let reviewer_generation = snap(&rig).generation;
assert!(answer(&rig, "r1", outcome(1, "reviewer", 0, 1, &["Fix x"])));
let run = snap(&rig);
assert_eq!(
run.stage,
Stage::Fixer,
"the fixer starts in its own session"
);
assert_ne!(
run.generation, reviewer_generation,
"a fresh agent, not the reviewer's"
);
let fixer = run.run_dir.join("round-1-fixer-t0");
let report = std::fs::read_to_string(fixer.join("reviewer-report.md")).unwrap();
assert!(
report.contains("Found things to fix.") && report.contains("Fix x"),
"{report}"
);
let scope = std::fs::read_to_string(fixer.join("scope.md")).unwrap();
assert!(scope.contains("reviewer-report.md"), "{scope}");
assert_eq!(
subjects(&rig.repo).len(),
1,
"a report alone commits nothing"
);
edit(&rig, "x.txt", "fixed\n");
assert!(answer(&rig, "f1", outcome(1, "fixer", 0, 1, &["Fix x"])));
assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix x");
let run = snap(&rig);
assert_eq!((run.round, run.stage), (2, Stage::Reviewer));
assert!(!answer(&rig, "r2", outcome(2, "reviewer", 0, 0, &[])));
assert_eq!(snap(&rig).stop_reason, Some(StopReason::Clean));
done(&rig);
}
#[test]
fn a_fixer_that_reports_zero_counts_cannot_end_the_run_clean() {
if !harness_ready("fixer-zero") {
return;
}
let rig = rig("fixer-zero", ReviewSetup::default(), Shape::TwoSession);
assert!(answer(&rig, "r1", outcome(1, "reviewer", 0, 1, &["Fix x"])));
edit(&rig, "x.txt", "fixed\n");
assert!(
answer(&rig, "f1", outcome(1, "fixer", 0, 0, &["Fix x"])),
"the run goes on: the reviewer found a Warning"
);
let run = snap(&rig);
assert_eq!((run.round, run.stage), (2, Stage::Reviewer));
assert_eq!(run.stop_reason, None);
assert_eq!(
run.rounds[0].warning, 1,
"recorded with the reviewer's count"
);
assert!(!answer(&rig, "r2", outcome(2, "reviewer", 0, 0, &[])));
assert_eq!(snap(&rig).stop_reason, Some(StopReason::Clean));
done(&rig);
}
#[test]
fn a_finding_a_round_left_unfixed_stays_open_after_a_clean_fix_diff_round() {
if !harness_ready("carry-open") {
return;
}
let rig = rig("carry-open", ReviewSetup::default(), Shape::OneSession);
let mut first = outcome(1, "both", 0, 2, &["Fix a"]);
first["review"]["unfixed"] = json!([{ "title": "Hard one", "file": "b.txt" }]);
edit(&rig, "a.txt", "fixed\n");
assert!(answer(&rig, "s1", first));
assert!(!answer(&rig, "s2", outcome(2, "both", 0, 0, &[])));
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Clean));
let open = run.open_findings();
assert_eq!(open.len(), 1);
assert_eq!(open[0].title, "Hard one");
let line = end_line(&run);
assert!(
line.contains("1 finding an earlier round left unfixed is still open"),
"{line}"
);
done(&rig);
}
#[test]
fn a_report_that_ran_no_tests_fails_the_round_and_the_retry_runs_one_strength_up() {
if !harness_ready("no-tests") {
return;
}
let setup = ReviewSetup {
strength: Some(Strength::Thrifty),
..ReviewSetup::default()
};
let rig = rig("no-tests", setup, Shape::OneSession);
with_run(&rig.rc, |run| run.strength_rows = rows());
let mut bad = outcome(1, "both", 0, 0, &[]);
bad["tests"] = json!({ "ran": false, "passed": false, "summary": "" });
assert!(
answer(&rig, "s1", bad.clone()),
"a first failure is retried"
);
let run = snap(&rig);
assert!(run.retried && run.running);
assert_eq!(run.cur_strength, Some(Strength::Balanced));
assert!(run.cur.retried && !run.cur.could_not_step_up);
assert!(!answer(&rig, "s2", bad), "the second failure stops the run");
let run = snap(&rig);
assert_eq!(
run.stop_reason,
Some(StopReason::Failed("targeted tests did not run".into()))
);
assert!(run.rounds.is_empty());
done(&rig);
}
#[test]
fn a_second_failure_keeps_the_rounds_that_finished_and_best_cannot_step_up() {
if !harness_ready("keep-finished") {
return;
}
let setup = ReviewSetup {
strength: Some(Strength::Best),
..ReviewSetup::default()
};
let rig = rig("keep-finished", setup, Shape::OneSession);
with_run(&rig.rc, |run| run.strength_rows = rows());
edit(&rig, "b.txt", "x\n");
assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"])));
let mut failed = outcome(2, "both", 0, 0, &[]);
failed["result"] = json!("failed");
failed["reason"] = json!("tests");
assert!(answer(&rig, "s2", failed.clone()));
let run = snap(&rig);
assert_eq!(run.cur_strength, Some(Strength::Best));
assert!(
run.cur.could_not_step_up,
"Best stays Best, and the report says so"
);
assert!(!answer(&rig, "s3", failed));
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Failed("tests".into())));
assert_eq!(run.rounds.len(), 1, "round 1 is kept");
assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix b");
done(&rig);
}
#[test]
fn a_crashed_agent_gets_one_retry_then_stops_the_run() {
let Some(rig) = one_session("crash", ReviewSetup::default()) else {
return;
};
let dir = rig.home.join("sessions/s1");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("state.json"), json!({ "schema": 1 }).to_string()).unwrap();
for attempt in ["first", "second"] {
with_run(&rig.rc, |run| run.sid = Some("s1".into()));
wait_until("the fake agent to be up", || {
rig.rc.ctx.agent.snapshot().state == AgentState::Running
});
rig.rc.ctx.agent.input(b"EXIT 3\r").unwrap();
wait_until("the agent to end", || {
matches!(rig.rc.ctx.agent.snapshot().state, AgentState::Ended { .. })
});
let goes_on = tick(&rig.rc);
assert_eq!(goes_on, attempt == "first", "{attempt} crash");
}
let run = snap(&rig);
assert!(
matches!(run.stop_reason, Some(StopReason::Failed(ref why)) if why.contains("crashed")),
"{:?}",
run.stop_reason
);
done(&rig);
}
#[test]
fn snapshot_mode_diffs_between_snapshots_and_makes_no_commit() {
let setup = ReviewSetup {
commit: false,
..ReviewSetup::default()
};
let Some(rig) = one_session("snapshot", setup) else {
return;
};
assert!(matches!(snap(&rig).start, Boundary::Tree(_)));
edit(&rig, "b.txt", "fixed b\n");
assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"])));
assert_eq!(
subjects(&rig.repo),
vec!["first"],
"no commit in snapshot mode"
);
let run = snap(&rig);
assert!(matches!(run.rounds[0].boundary, Some(Boundary::Tree(_))));
assert_eq!(run.rounds[0].commit, None);
let diff =
std::fs::read_to_string(run.run_dir.join("round-2-both-t0/round-1.diff")).unwrap();
assert!(diff.contains("+++ b/b.txt"), "{diff}");
assert_eq!(
git_in(&rig.repo, &["status", "--porcelain"]).trim(),
"?? b.txt",
"the work stays in the tree, uncommitted"
);
done(&rig);
}
#[test]
fn the_pre_run_commit_is_made_only_when_agreed() {
if !harness_ready("pre-run") {
return;
}
let repo = scratch_repo("pre-run");
let home = repo.parent().unwrap().join("console-home");
std::fs::write(repo.join("d.txt"), "mine\n").unwrap();
let launch = fake_agent_launch();
let refused = prepare_run(&repo, &launch, ReviewSetup::default(), &home).unwrap_err();
assert!(refused.contains("uncommitted changes"), "{refused}");
assert_eq!(subjects(&repo), vec!["first"], "nothing was committed");
let setup = ReviewSetup {
pre_run_commit_agreed: true,
..ReviewSetup::default()
};
let run = prepare_run(&repo, &launch, setup, &home).expect("agreed");
assert_eq!(subjects(&repo)[0], "Work before Review Loop");
let head = git_in(&repo, &["rev-parse", "HEAD"]);
assert_eq!(run.pre_run_commit.as_deref(), Some(head.as_str()));
assert_eq!(run.start, Boundary::Commit(head));
assert!(git_in(&repo, &["status", "--porcelain"]).trim().is_empty());
// Commits off needs no agreement: the tree is only measured.
std::fs::write(repo.join("e.txt"), "more\n").unwrap();
let snapshot_only = ReviewSetup {
commit: false,
..ReviewSetup::default()
};
let run = prepare_run(&repo, &launch, snapshot_only, &home).expect("snapshot mode");
assert!(run.pre_run_commit.is_none() && matches!(run.start, Boundary::Tree(_)));
let _ = std::fs::remove_dir_all(repo.parent().unwrap());
}
#[test]
fn a_loop_already_running_refuses_a_second_start_and_a_bad_cap() {
if !harness_ready("refuse") {
return;
}
let rig = rig("refuse", ReviewSetup::default(), Shape::OneSession);
let start = |rig: &Rig| {
let (agent, _) = fake_agent_manager(&rig.repo);
start_review_loop_with(
&rig.rc.slot,
&rig.phases,
agent,
fake_agent_launch(),
rig.repo.clone(),
ReviewSetup::default(),
hooks_into(&rig.events),
Limits::default(),
rig.home.clone(),
false,
)
};
assert_eq!(
start(&rig).unwrap_err(),
"A loop is already running in this window."
);
let high = ReviewSetup {
cap: 7,
..ReviewSetup::default()
};
let launch = fake_agent_launch();
assert!(prepare_run(&rig.repo, &launch, high, &rig.home)
.unwrap_err()
.contains("1 to 6"));
// An Implementation Loop running blocks it too.
abandon(&rig.rc.slot);
*lock(&rig.phases) = Some(loop_driver::RunningRecord::new(
rig.repo.clone(),
"specs/x".into(),
loop_driver::LoopSetup::default(),
vec![],
));
assert_eq!(
start(&rig).unwrap_err(),
"A loop is already running in this window."
);
done(&rig);
}
// ---------------------------------------------- the Suggestions batch
fn with_suggestions(round: u32, role: &str) -> Value {
let mut value = outcome(round, role, 0, 0, &[]);
value["review"]["suggestion"] = json!(1);
value["review"]["suggestions"] = json!([{ "title": "Name the timer", "file": "a.txt" }]);
value
}
#[test]
fn with_the_switch_on_a_clean_stop_runs_the_batch_and_the_final_check_outside_the_cap() {
let setup = ReviewSetup {
suggestions: true,
..ReviewSetup::default()
};
let Some(rig) = one_session("batch-on", setup) else {
return;
};
assert!(answer(&rig, "s1", with_suggestions(1, "both")));
let run = snap(&rig);
assert_eq!((run.stage, run.round), (Stage::Batch, 2));
assert_eq!(run.pending_stop, Some(StopReason::Clean));
assert_eq!(run.suggestions_batch.as_ref().unwrap().briefed.len(), 1);
let scope = std::fs::read_to_string(run.run_dir.join("round-2-batch-t0/scope.md")).unwrap();
assert!(scope.contains("Name the timer"), "{scope}");
edit(&rig, "t.txt", "named\n");
assert!(answer(
&rig,
"b1",
outcome(2, "fixer", 0, 0, &["Name the timer"])
));
assert_eq!(
subjects(&rig.repo)[0],
"Review Loop Suggestions batch: Name the timer",
"the batch is committed on its own"
);
let run = snap(&rig);
assert_eq!((run.stage, run.round), (Stage::Final, 3));
let diff =
std::fs::read_to_string(run.run_dir.join("round-3-final-t0/batch.diff")).unwrap();
assert!(diff.contains("+++ b/t.txt"), "{diff}");
assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[])));
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Clean));
assert_eq!(
run.rounds.len(),
1,
"the batch and the check are outside the rounds"
);
let batch = run.suggestions_batch.unwrap();
assert_eq!(batch.final_check, Some(Verdict::Clean));
assert!(batch.commit.is_some());
done(&rig);
}
#[test]
fn with_the_switch_off_no_batch_runs() {
let Some(rig) = one_session("batch-off", ReviewSetup::default()) else {
return;
};
assert!(!answer(&rig, "s1", with_suggestions(1, "both")));
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Clean));
assert!(run.suggestions_batch.is_none());
assert_eq!(
run.collected.len(),
1,
"collected for the report, not fixed"
);
done(&rig);
}
#[test]
fn after_a_person_stop_or_a_failure_no_batch_runs_even_when_on() {
let setup = ReviewSetup {
suggestions: true,
..ReviewSetup::default()
};
let Some(rig) = one_session("batch-person", setup.clone()) else {
return;
};
request_stop_after(&rig.rc.slot, true).unwrap();
edit(&rig, "b.txt", "x\n");
let mut found = with_suggestions(1, "both");
found["review"]["warning"] = json!(1);
found["review"]["fixed"] = json!([{ "title": "Fix b", "file": "b.txt" }]);
assert!(!answer(&rig, "s1", found));
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Person));
assert!(run.suggestions_batch.is_none());
done(&rig);
let Some(rig) = one_session("batch-failed", setup) else {
return;
};
let mut failed = with_suggestions(1, "both");
failed["result"] = json!("failed");
failed["reason"] = json!("other");
assert!(answer(&rig, "s1", failed.clone()));
assert!(!answer(&rig, "s2", failed));
let run = snap(&rig);
assert!(matches!(run.stop_reason, Some(StopReason::Failed(_))));
assert!(run.suggestions_batch.is_none());
done(&rig);
}
#[test]
fn a_batch_at_the_cap_keeps_the_cap_as_the_stop_reason() {
let setup = ReviewSetup {
suggestions: true,
cap: 1,
..ReviewSetup::default()
};
let Some(rig) = one_session("batch-cap", setup) else {
return;
};
edit(&rig, "b.txt", "x\n");
let mut found = with_suggestions(1, "both");
found["review"]["warning"] = json!(1);
found["review"]["fixed"] = json!([{ "title": "Fix b", "file": "b.txt" }]);
assert!(answer(&rig, "s1", found));
assert_eq!(snap(&rig).pending_stop, Some(StopReason::Cap));
edit(&rig, "t.txt", "x\n");
assert!(answer(
&rig,
"b1",
outcome(2, "fixer", 0, 0, &["Name the timer"])
));
assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 1, &["Late"])));
assert_eq!(
snap(&rig).stop_reason,
Some(StopReason::Cap),
"the final check's own verdict never changes why the run ended"
);
done(&rig);
}
#[test]
fn a_page_announced_for_this_round_and_role_becomes_its_session() {
let Some(rig) = one_session("note-page", ReviewSetup::default()) else {
return;
};
let unlocked = json!({ "schema": 1 });
note_page(&rig.rc.slot, "review", "other", &unlocked);
assert_eq!(snap(&rig).sid, None);
assert_eq!(snap(&rig).page_candidate.as_deref(), Some("other"));
let wrong_round = json!({ "loop": { "driving": true, "round": 2, "role": "both" } });
note_page(&rig.rc.slot, "review", "later", &wrong_round);
assert_eq!(snap(&rig).sid, None);
let right = json!({ "loop": { "driving": true, "round": 1, "role": "both" } });
note_page(&rig.rc.slot, "implement", "x", &right);
assert_eq!(snap(&rig).sid, None, "only a Review page counts");
note_page(&rig.rc.slot, "review", "mine", &right);
assert_eq!(snap(&rig).sid.as_deref(), Some("mine"));
done(&rig);
}
// ------------------------------------------------- the review's fixes
#[test]
fn a_title_with_shell_characters_is_cleaned_and_the_round_still_commits() {
assert_eq!(
safe_title("Guard `None` in \u{201C}parse\u{201D} $x! \\n"),
"Guard None in 'parse' x n"
);
let Some(rig) = one_session("shell-title", ReviewSetup::default()) else {
return;
};
edit(&rig, "b.txt", "x\n");
let title = "Guard `None` in \"parse\" $x!";
assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &[title])));
assert_eq!(
subjects(&rig.repo)[0],
"Review Loop round 1: Guard None in 'parse' x"
);
assert!(git_in(&rig.repo, &["status", "--porcelain"])
.trim()
.is_empty());
done(&rig);
}
#[test]
fn a_refused_subject_takes_the_staged_files_out_again() {
if !harness_ready("refused-subject") {
return;
}
let repo = scratch_repo("refused-subject");
std::fs::write(repo.join("b.txt"), "x\n").unwrap();
let long = "x".repeat(150);
let refused = commit_all(&repo, &long, Duration::from_secs(60));
assert!(refused.is_err(), "a 150 character subject is refused");
assert!(
git_in(&repo, &["diff", "--cached", "--name-only"])
.trim()
.is_empty(),
"nothing is left staged"
);
let _ = std::fs::remove_dir_all(repo.parent().unwrap());
}
#[test]
fn the_batch_subject_fits_72_characters_with_its_own_prefix() {
let titles: Vec<String> = [
"Name the timer correctly everywhere",
"Close the file handle",
]
.iter()
.map(|t| t.to_string())
.collect();
let subject = batch_subject(&titles);
assert!(
subject.starts_with("Review Loop Suggestions batch"),
"{subject}"
);
assert!(subject.chars().count() <= 72, "{subject}");
let long = vec!["y".repeat(120)];
let cut = batch_subject(&long);
assert!(cut.chars().count() <= 72 && cut.ends_with("..."), "{cut}");
assert_eq!(batch_subject(&[]), "Review Loop Suggestions batch");
}
#[test]
fn stop_now_in_the_final_check_then_discard_keeps_the_committed_batch() {
let setup = ReviewSetup {
suggestions: true,
..ReviewSetup::default()
};
let Some(rig) = one_session("final-discard", setup) else {
return;
};
assert!(answer(&rig, "s1", with_suggestions(1, "both")));
edit(&rig, "t.txt", "named\n");
assert!(answer(
&rig,
"b1",
outcome(2, "fixer", 0, 0, &["Name the timer"])
));
assert_eq!(snap(&rig).stage, Stage::Final);
// The final check is running; the person stops it and a stray file lands.
edit(&rig, "q.txt", "partial\n");
request_stop_now(&rig.rc.slot, Some(&rig.rc.ctx.agent), |_| {}).unwrap();
assert!(!tick(&rig.rc));
let info = snap(&rig).partial.expect("partial data");
assert_eq!(
info.new_files,
vec!["q.txt".to_string()],
"only the stray file"
);
partial(&rig.rc.slot, false).unwrap();
assert!(rig.repo.join("t.txt").exists(), "the committed batch stays");
assert!(!rig.repo.join("q.txt").exists());
done(&rig);
}
#[test]
fn the_branch_scope_needs_a_trunk_and_says_so() {
if !harness_ready("no-trunk") {
return;
}
let repo = scratch_repo("no-trunk");
git_in(&repo, &["branch", "-m", "main", "feature"]);
let err = scope_files(&repo, ReviewScope::Branch, None).unwrap_err();
assert!(err.contains("no main or master branch"), "{err}");
let spec_err = scope_files(&repo, ReviewScope::Spec, Some(".")).unwrap_err();
assert!(spec_err.contains("no main or master branch"), "{spec_err}");
assert!(scope_files(&repo, ReviewScope::Uncommitted, None).is_ok());
let _ = std::fs::remove_dir_all(repo.parent().unwrap());
}
#[test]
fn a_final_check_that_fails_twice_keeps_the_reason_the_run_was_ending_for() {
let setup = ReviewSetup {
suggestions: true,
..ReviewSetup::default()
};
let Some(rig) = one_session("final-fails", setup) else {
return;
};
assert!(answer(&rig, "s1", with_suggestions(1, "both")));
edit(&rig, "t.txt", "named\n");
assert!(answer(
&rig,
"b1",
outcome(2, "fixer", 0, 0, &["Name the timer"])
));
let mut failed = outcome(3, "reviewer", 0, 0, &[]);
failed["result"] = json!("failed");
failed["reason"] = json!("other");
assert!(
answer(&rig, "c1", failed.clone()),
"the first failure is retried"
);
assert!(!answer(&rig, "c2", failed));
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Clean), "not Failed");
assert!(matches!(
run.suggestions_batch
.as_ref()
.and_then(|b| b.final_check.clone()),
Some(Verdict::Failed(_))
));
assert!(run.stop_evidence.is_some_and(|e| e.contains("final check")));
done(&rig);
}
#[test]
fn last_boundary_orders_a_kept_batch_among_the_rounds() {
let Some(rig) = one_session("last-boundary", ReviewSetup::default()) else {
return;
};
let mut run = snap(&rig);
let c = |id: &str| Boundary::Commit(id.to_string());
let round = |n: u32, id: &str| RoundRecord {
n,
boundary: Some(c(id)),
..RoundRecord::default()
};
let batch = |after: usize, id: &str| BatchRecord {
after_rounds: after,
boundary: Some(c(id)),
..BatchRecord::default()
};
run.rounds = vec![round(1, "r1"), round(2, "r2")];
run.earlier_batches = vec![batch(2, "b1")];
assert_eq!(run.last_boundary(), c("b1"), "the batch came after round 2");
run.rounds.push(round(3, "r3"));
assert_eq!(run.last_boundary(), c("r3"), "a round after the batch wins");
run.suggestions_batch = Some(batch(3, "b2"));
assert_eq!(run.last_boundary(), c("b2"), "the current batch is newest");
done(&rig);
}
#[test]
fn the_round_after_a_continue_is_scoped_from_the_batch_committed_before_it() {
let Some(rig) = one_session("diff-after-batch", ReviewSetup::default()) else {
return;
};
let mut run = snap(&rig);
let c = |id: &str| Boundary::Commit(id.to_string());
let round = |n: u32, id: &str| RoundRecord {
n,
boundary: Some(c(id)),
..RoundRecord::default()
};
run.rounds = vec![round(1, "r1"), round(2, "r2")];
run.earlier_batches = vec![BatchRecord {
after_rounds: 2,
boundary: Some(c("b1")),
..BatchRecord::default()
}];
let (from, to) = plan_for(&run, Stage::Both, 3)
.diff
.expect("round 3 has a diff");
assert_eq!((from, to), (c("r1"), c("b1")), "round 3 sees the batch");
let (from, to) = plan_for(&run, Stage::Both, 2)
.diff
.expect("round 2 has a diff");
assert_eq!(
(from, to),
(run.start.clone(), c("r1")),
"an earlier round is unchanged"
);
done(&rig);
}
#[test]
fn nul_separated_names_are_never_quoted_or_split_on_spaces() {
assert_eq!(
nul_lines("a b.txt\0caf\u{e9}.txt\0"),
vec!["a b.txt".to_string(), "caf\u{e9}.txt".to_string()]
);
}
#[test]
fn continue_after_a_capped_batch_keeps_the_batch_and_never_briefs_it_again() {
let setup = ReviewSetup {
suggestions: true,
cap: 1,
..ReviewSetup::default()
};
let Some(rig) = one_session("continue-batch", setup) else {
return;
};
edit(&rig, "b.txt", "x\n");
let mut found = with_suggestions(1, "both");
found["review"]["warning"] = json!(1);
found["review"]["fixed"] = json!([{ "title": "Fix b", "file": "b.txt" }]);
assert!(answer(&rig, "s1", found));
edit(&rig, "t.txt", "x\n");
assert!(answer(
&rig,
"b1",
outcome(2, "fixer", 0, 0, &["Name the timer"])
));
assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[])));
assert_eq!(snap(&rig).stop_reason, Some(StopReason::Cap));
assert!(snap(&rig).collected.is_empty(), "the batch fixed them");
go_on(&rig).unwrap();
let run = snap(&rig);
assert_eq!((run.round, run.cap), (2, 2));
assert_eq!(run.earlier_batches.len(), 1, "the first batch is kept");
assert!(run.earlier_batches[0].commit.is_some());
assert!(!answer(&rig, "s2", outcome(2, "both", 0, 0, &[])));
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Clean));
assert!(run.suggestions_batch.is_none(), "no second batch");
done(&rig);
}
#[test]
fn discard_works_from_the_repositorys_top_when_the_project_is_a_folder_inside_it() {
if !harness_ready("subfolder") {
return;
}
let repo = scratch_repo("subfolder");
std::fs::create_dir_all(repo.join("sub")).unwrap();
std::fs::write(repo.join("sub/y.txt"), "y\n").unwrap();
git_in(&repo, &["add", "-A"]);
git_in(&repo, &["commit", "-q", "-m", "add sub"]);
let head = git_in(&repo, &["rev-parse", "HEAD"]);
let mut run = ReviewRun::new(
repo.join("sub"),
ReviewSetup::default(),
fake_agent_launch(),
Mode::Commit,
Shape::OneSession,
Boundary::Commit(head),
repo.parent().unwrap().join("runs"),
BTreeMap::new(),
);
run.running = false;
run.stop_reason = Some(StopReason::Person);
run.partial = Some(Partial {
pending: true,
new_files: vec!["sub/new.txt".to_string()],
..Partial::default()
});
let slot: ReviewSlot = Arc::new(Mutex::new(Some(run)));
std::fs::write(repo.join("sub/y.txt"), "changed\n").unwrap();
std::fs::write(repo.join("a.txt"), "changed\n").unwrap();
std::fs::write(repo.join("sub/new.txt"), "new\n").unwrap();
partial(&slot, false).unwrap();
assert_eq!(
std::fs::read_to_string(repo.join("sub/y.txt")).unwrap(),
"y\n"
);
assert_eq!(
std::fs::read_to_string(repo.join("a.txt")).unwrap(),
"one\ntwo\n",
"a tracked file outside the project folder is put back too"
);
assert!(!repo.join("sub/new.txt").exists());
let _ = std::fs::remove_dir_all(repo.parent().unwrap());
}
// ------------------------------------------------------ Phase 6: the end
/// A run's finished state with `rounds` committed rounds on a scratch repo,
/// stopped at the cap: the state sign-off starts from.
fn capped(name: &str, setup: ReviewSetup, rounds: u32) -> Option<Rig> {
let rig = one_session(name, setup)?;
for n in 1..=rounds {
edit(&rig, &format!("f{n}.txt"), "x\n");
let _ = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"]));
}
Some(rig)
}
fn sign(rig: &Rig, picks: &[&str], squash: bool) -> Result<(), String> {
let picks: Vec<String> = picks.iter().map(|p| p.to_string()).collect();
sign_off(
&rig.rc.slot,
&rig.phases,
Arc::clone(&rig.rc.ctx.agent),
hooks_into(&rig.events),
Limits::default(),
rig.home.clone(),
&picks,
squash,
false,
)
}
#[test]
fn squashing_three_round_commits_makes_one_commit_and_keeps_the_commit_before_the_run() {
let Some(rig) = capped("squash-three", ReviewSetup::default(), 3) else {
return;
};
let before = subjects(&rig.repo);
assert_eq!(before.len(), 4, "three rounds and the first commit");
assert!(can_squash(&snap(&rig)));
sign(&rig, &[], true).expect("sign-off with no picks runs no agent");
let run = snap(&rig);
assert!(run.signed_off);
match &run.signoff.as_ref().unwrap().squash {
Squash::Done { commits, commit } => {
assert_eq!(*commits, 3);
assert_eq!(commit.as_str(), git_in(&rig.repo, &["rev-parse", "HEAD"]));
}
other => panic!("expected a squash, got {other:?}"),
}
let after = subjects(&rig.repo);
assert_eq!(
after.len(),
2,
"one squash commit on top of the first: {after:?}"
);
assert!(
after[0].starts_with("Review Loop rounds 1 to 3"),
"{after:?}"
);
assert_eq!(after[1], "first", "the commit before the run is untouched");
for n in 1..=3 {
assert!(rig.repo.join(format!("f{n}.txt")).exists(), "f{n}.txt");
}
assert_eq!(
git_in(&rig.repo, &["status", "--porcelain"]),
"",
"the tree is clean after the squash"
);
done(&rig);
}
#[test]
fn the_squash_never_includes_the_pre_run_commit() {
if !harness_ready("squash-pre") {
return;
}
let repo = scratch_repo("squash-pre");
std::fs::write(repo.join("mine.txt"), "mine\n").unwrap();
let setup = ReviewSetup {
pre_run_commit_agreed: true,
cap: 2,
..ReviewSetup::default()
};
let rig = rig_on(repo, setup, Shape::OneSession);
for n in 1..=2 {
edit(&rig, &format!("f{n}.txt"), "x\n");
let _ = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"]));
}
assert_eq!(subjects(&rig.repo)[2], "Work before Review Loop");
sign(&rig, &[], true).unwrap();
let after = subjects(&rig.repo);
assert_eq!(after.len(), 3, "{after:?}");
assert!(
after[0].starts_with("Review Loop rounds 1 to 2"),
"{after:?}"
);
assert_eq!(after[1], "Work before Review Loop");
done(&rig);
}
#[test]
fn the_squash_refuses_when_a_commit_that_is_not_the_runs_sits_on_top() {
let Some(rig) = capped("squash-foreign", ReviewSetup::default(), 3) else {
return;
};
std::fs::write(rig.repo.join("other.txt"), "other\n").unwrap();
git_in(&rig.repo, &["add", "-A"]);
git_in(&rig.repo, &["commit", "-q", "-m", "somebody else"]);
let before = subjects(&rig.repo);
sign(&rig, &[], true).unwrap();
let run = snap(&rig);
assert!(run.signed_off, "the sign-off still finishes");
assert_eq!(
run.signoff.unwrap().squash,
Squash::Refused(FOREIGN_COMMIT.to_string())
);
assert_eq!(subjects(&rig.repo), before, "nothing was rewritten");
done(&rig);
}
#[test]
fn the_squash_switch_needs_commit_mode_and_two_round_commits() {
let Some(rig) = capped("squash-switch", ReviewSetup::default(), 1) else {
return;
};
assert!(!can_squash(&snap(&rig)), "one round commit");
done(&rig);
let snapshots = ReviewSetup {
commit: false,
..ReviewSetup::default()
};
let Some(rig) = capped("squash-snap", snapshots, 2) else {
return;
};
assert!(!can_squash(&snap(&rig)), "snapshot mode makes no commits");
done(&rig);
}
#[test]
fn picked_suggestions_run_as_one_fixer_session_with_its_own_commit_and_a_fresh_check() {
let Some(rig) = one_session("sign-picks", ReviewSetup::default()) else {
return;
};
assert!(!answer(&rig, "s1", with_suggestions(1, "both")));
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Clean));
assert_eq!(run.collected.len(), 1);
let patch = end_patch_for(&run, false, "report");
assert_eq!(patch["loopEnd"]["suggestions"][0]["id"], "s1");
assert_eq!(
patch["loopEnd"]["suggestions"][0]["title"],
"Name the timer"
);
assert!(
sign(&rig, &["s9"], false).is_err(),
"an unknown pick is refused"
);
sign(&rig, &["s1"], false).expect("sign-off starts the fix");
let run = snap(&rig);
assert!(run.signing && run.running);
assert_eq!((run.stage, run.round), (Stage::Batch, 2));
assert_eq!(run.suggestions_batch.as_ref().unwrap().briefed.len(), 1);
edit(&rig, "t.txt", "named\n");
assert!(answer(
&rig,
"b1",
outcome(2, "fixer", 0, 0, &["Name the timer"])
));
assert_eq!(
subjects(&rig.repo)[0],
"Review Loop Suggestions batch: Name the timer"
);
assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[])));
let run = snap(&rig);
assert!(run.signed_off && !run.signing && !run.running);
assert_eq!(
run.stop_reason,
Some(StopReason::Clean),
"the reason is kept"
);
let signoff = run.signoff.clone().unwrap();
assert_eq!(signoff.picked.len(), 1);
assert!(signoff.left.is_empty());
assert_eq!(
run.suggestions_batch.unwrap().final_check,
Some(Verdict::Clean)
);
assert!(
sign(&rig, &[], false).is_err(),
"a second sign-off is refused"
);
done(&rig);
}
#[test]
fn a_signed_off_run_cannot_continue() {
let Some(rig) = capped("signed-continue", ReviewSetup::default(), 3) else {
return;
};
sign(&rig, &[], false).unwrap();
let err = go_on(&rig).unwrap_err();
assert!(err.contains("signed off"), "{err}");
done(&rig);
}
fn spec_run(project: &Path, scope: ReviewScope, spec: Option<&str>) -> ReviewRun {
let setup = ReviewSetup {
scope,
spec: spec.map(str::to_string),
..ReviewSetup::default()
};
let mut run = ReviewRun::new(
project.to_path_buf(),
setup,
fake_agent_launch(),
Mode::Commit,
Shape::OneSession,
Boundary::Commit("0".repeat(40)),
PathBuf::new(),
BTreeMap::new(),
);
run.stop_reason = Some(StopReason::Clean);
run.running = false;
run
}
#[test]
fn the_report_goes_into_the_spec_folder_only_for_a_spec_launch() {
let base =
std::env::temp_dir().join(format!("plan2code-review-report-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("specs/demo")).unwrap();
let spec = spec_run(&base, ReviewScope::Spec, Some("specs/demo"));
let first = write_spec_report(&spec, "# one").expect("a spec launch writes it");
assert!(first.starts_with(base.join("specs/demo")));
assert!(first
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("REVIEW-LOOP-"));
// A rerun after sign-off replaces the same file.
let mut again = spec.clone();
again.report_file = Some(first.clone());
assert_eq!(write_spec_report(&again, "# two"), Some(first.clone()));
assert_eq!(std::fs::read_to_string(&first).unwrap(), "# two");
// Another run the same day takes a new name.
let second = write_spec_report(&spec, "# three").unwrap();
assert_ne!(second, first);
assert!(second.to_string_lossy().ends_with("-2.md"));
for scope in [ReviewScope::Branch, ReviewScope::Uncommitted] {
let run = spec_run(&base, scope, Some("specs/demo"));
assert_eq!(write_spec_report(&run, "# no"), None, "{scope:?}");
}
let escaping = spec_run(&base, ReviewScope::Spec, Some("../elsewhere"));
assert_eq!(write_spec_report(&escaping, "# no"), None);
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn the_report_list_gains_a_review_entry_and_old_entries_still_load() {
let base =
std::env::temp_dir().join(format!("plan2code-review-list-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(&base).unwrap();
let project = base.join("project");
std::fs::create_dir_all(&project).unwrap();
let mut old = crate::loop_report::LoopReport::new("specs/old", "2026-11-01 09:00");
old.entries.push(ReportEntry {
phase: 4,
name: "P4".into(),
..ReportEntry::default()
});
report_list::save_report(&base, &project, &old).unwrap();
// A report written before the kind existed reads as an Implementation one.
let file = base.join(crate::loop_report::REPORTS_FILE);
let mut store: Value =
serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
for report in store["reports"].as_object_mut().unwrap().values_mut() {
for entry in report["entries"].as_array_mut().unwrap() {
entry.as_object_mut().unwrap().remove("kind");
entry.as_object_mut().unwrap().remove("rounds");
}
}
std::fs::write(&file, store.to_string()).unwrap();
let mut run = spec_run(&project, ReviewScope::Branch, None);
run.rounds.push(RoundRecord {
n: 1,
critical: 1,
commit: Some("a".repeat(40)),
..RoundRecord::default()
});
save_review_entry(&base, &run).unwrap();
let loaded = report_list::load_reports(&base, &project, "specs/old").unwrap();
assert_eq!(loaded.entries[0].kind, EntryKind::Implementation);
assert_eq!(loaded.entries[0].name, "P4");
let mine = report_list::load_reports(&base, &project, &format!("review-loop:{}", run.id))
.expect("the review run has its own key");
assert_eq!(mine.entries[0].kind, EntryKind::Review);
assert_eq!(mine.entries[0].rounds.len(), 1);
assert_eq!(mine.entries[0].rounds[0].critical, 1);
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn the_end_post_names_the_reason_the_report_continue_and_what_is_open() {
let base =
std::env::temp_dir().join(format!("plan2code-review-end-{}", std::process::id()));
let mut run = spec_run(&base, ReviewScope::Branch, None);
for (n, id) in [(1, "a"), (2, "b")] {
run.rounds.push(RoundRecord {
n,
commit: Some(id.repeat(40)),
unfixed: vec![finding("Missing check", "src/b.rs", Some(40))],
..RoundRecord::default()
});
}
run.cap = 2;
for (reason, key, can) in [
(StopReason::Clean, "clean", false),
(StopReason::Cap, "cap", true),
(StopReason::Person, "person", true),
(StopReason::Failed("tests failed".into()), "failed", true),
] {
run.stop_reason = Some(reason);
let patch = end_patch_for(&run, false, "# Report");
let end = &patch["loopEnd"];
assert_eq!(end["kind"], "review");
assert_eq!(end["reason"], key);
assert_eq!(end["report"], REPORT_DOC);
assert_eq!(end["canContinue"], can, "{key}");
assert_eq!(end["canSquash"], true);
assert_eq!(end["open"][0]["file"], "src/b.rs");
assert_eq!(end["open"][0]["line"], 40);
assert!(end["line"].as_str().unwrap().chars().count() <= 200);
assert!(end.get("signedOff").is_none());
assert_eq!(patch["docs"][0]["id"], REPORT_DOC);
}
run.rounds.clear();
run.cap = 6;
run.stop_reason = Some(StopReason::Cap);
for n in 1..=6 {
run.rounds.push(RoundRecord {
n,
..RoundRecord::default()
});
}
assert!(!can_continue(&run), "never past six rounds");
run.signed_off = true;
run.stop_reason = Some(StopReason::Person);
let patch = end_patch_for(&run, false, "# Report");
assert_eq!(patch["loopEnd"]["signedOff"], true);
assert_eq!(patch["loopEnd"]["canContinue"], false);
}
#[test]
fn partial_changes_ride_the_end_post_and_hide_continue() {
let mut run = spec_run(&std::env::temp_dir(), ReviewScope::Branch, None);
run.stop_reason = Some(StopReason::Person);
run.partial = Some(Partial {
pending: true,
files: 2,
added: 5,
removed: 1,
..Partial::default()
});
let patch = end_patch_for(&run, true, "# Report");
assert_eq!(patch["loopEnd"]["partial"]["files"], 2);
assert_eq!(patch["loopEnd"]["partial"]["diff"], PARTIAL_DOC);
assert_eq!(patch["docs"][1]["blocks"][0]["diff"], "partial.diff");
assert_eq!(patch["loopEnd"]["canContinue"], false);
let without = end_patch_for(&run, false, "# Report");
assert!(without["loopEnd"].get("partial").is_none());
run.partial.as_mut().unwrap().pending = false;
assert!(end_patch_for(&run, true, "# Report")["loopEnd"]
.get("partial")
.is_none());
assert!(can_continue(&run), "settled partial changes allow Continue");
}
#[test]
fn the_finished_screens_next_steps_build_their_prompts_from_the_open_findings() {
let mut run = spec_run(&std::env::temp_dir(), ReviewScope::Branch, None);
run.rounds.push(RoundRecord {
n: 1,
unfixed: vec![
finding("Missing check", "src/b.rs", Some(40)),
finding("Wrong default", "src/c.rs", None),
],
..RoundRecord::default()
});
let slot: ReviewSlot = Arc::new(Mutex::new(Some(run)));
assert_eq!(
next_prompt(&slot, "pr-prep").unwrap(),
"/plan2code-pr-prep --web"
);
let brief = next_prompt(&slot, "quick-task").unwrap();
assert!(brief.starts_with("/plan2code-quick-task --web "), "{brief}");
assert!(brief.contains("1. Missing check (src/b.rs:40)"), "{brief}");
assert!(brief.contains("2. Wrong default (src/c.rs)"), "{brief}");
assert!(next_prompt(&slot, "other").is_err());
lock(&slot).as_mut().unwrap().rounds[0].unfixed.clear();
assert_eq!(
next_prompt(&slot, "quick-task").unwrap_err(),
"Nothing is left open."
);
}
#[test]
fn the_spec_report_needs_a_real_specs_folder_never_the_git_folder_or_src() {
let base =
std::env::temp_dir().join(format!("plan2code-review-spec-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
for folder in [".git", "src", "specs/nested/deep"] {
std::fs::create_dir_all(base.join(folder)).unwrap();
}
for spec in [
".git",
"src",
"specs/nested/deep",
"specs/.hidden",
"specs/missing",
] {
let run = spec_run(&base, ReviewScope::Spec, Some(spec));
assert_eq!(write_spec_report(&run, "# no"), None, "{spec}");
}
assert!(
!base.join(".git").join("REVIEW-LOOP.md").exists()
&& std::fs::read_dir(base.join("src"))
.unwrap()
.next()
.is_none()
);
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn a_spec_scope_run_refuses_a_folder_that_is_not_a_spec() {
let repo = scratch_repo("not-a-spec");
let launch = fake_agent_launch();
let setup = ReviewSetup {
scope: ReviewScope::Spec,
spec: Some("src".to_string()),
..ReviewSetup::default()
};
let err = prepare_run(&repo, &launch, setup, &repo.join("home"))
.map(|_| ())
.unwrap_err();
assert!(err.contains("not a spec folder"), "{err}");
let _ = std::fs::remove_dir_all(repo.parent().unwrap());
}
/// A finished spec-scope run on a scratch repo whose spec folder is
/// committed, so only the report is new in it.
fn spec_capped(name: &str) -> Option<Rig> {
if !harness_ready(name) {
return None;
}
let repo = scratch_repo(name);
std::fs::create_dir_all(repo.join("specs/demo")).unwrap();
std::fs::write(repo.join("specs/demo/overview.md"), "# demo\n").unwrap();
git_in(&repo, &["add", "-A"]);
git_in(&repo, &["commit", "-q", "-m", "spec"]);
let setup = ReviewSetup {
scope: ReviewScope::Spec,
spec: Some("specs/demo".to_string()),
cap: 2,
..ReviewSetup::default()
};
let rig = rig_on(repo, setup, Shape::OneSession);
with_run(&rig.rc, |run| run.last_sid = Some("sx".to_string()));
for n in 1..=2 {
edit(&rig, &format!("f{n}.txt"), "x\n");
let _ = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"]));
}
Some(rig)
}
fn spec_reports(rig: &Rig) -> Vec<PathBuf> {
std::fs::read_dir(rig.repo.join("specs/demo"))
.unwrap()
.flatten()
.map(|e| e.path())
.filter(|p| {
p.file_name()
.unwrap()
.to_string_lossy()
.starts_with("REVIEW-LOOP-")
})
.collect()
}
#[test]
fn the_end_saves_a_report_entry_and_the_spec_file_and_sign_off_rewrites_both() {
let Some(rig) = spec_capped("end-files") else {
return;
};
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Cap));
let kept =
report_list::load_reports(&rig.home, &run.project, &format!("review-loop:{}", run.id))
.expect("the end saved a review entry");
assert_eq!(kept.entries[0].kind, EntryKind::Review);
assert_eq!(kept.entries[0].rounds.len(), 2);
let files = spec_reports(&rig);
assert_eq!(files.len(), 1, "{files:?}");
let first = std::fs::read_to_string(&files[0]).unwrap();
assert!(
first.starts_with("# Review Loop: Stopped at the round cap"),
"{first}"
);
assert!(!first.contains("## Sign-off"), "{first}");
sign(&rig, &[], false).unwrap();
let files = spec_reports(&rig);
assert_eq!(files.len(), 1, "sign-off rewrites the same file: {files:?}");
let after = std::fs::read_to_string(&files[0]).unwrap();
assert!(after.contains("## Sign-off"), "{after}");
assert!(after.contains("not asked for"), "{after}");
done(&rig);
}
#[test]
fn a_picked_fix_never_commits_the_stale_spec_report() {
let Some(rig) = spec_capped("stale-report") else {
return;
};
with_run(&rig.rc, |run| {
run.collected = vec![finding("Name the timer", "a.txt", None)];
});
assert_eq!(spec_reports(&rig).len(), 1);
sign(&rig, &["s1"], false).expect("sign-off starts the fix");
assert!(
spec_reports(&rig).is_empty(),
"the stale report is out of the way before the fixer commits"
);
edit(&rig, "t.txt", "named\n");
assert!(answer(
&rig,
"b1",
outcome(3, "fixer", 0, 0, &["Name the timer"])
));
let committed = git_in(&rig.repo, &["show", "--name-only", "--format=", "HEAD"]);
assert!(!committed.contains("REVIEW-LOOP"), "{committed}");
assert!(!answer(&rig, "c1", outcome(4, "reviewer", 0, 0, &[])));
let run = snap(&rig);
assert!(run.signed_off);
assert_eq!(
spec_reports(&rig).len(),
1,
"a fresh report is written after sign-off"
);
done(&rig);
}
#[test]
fn sign_off_after_a_stop_by_the_person_still_completes_and_keeps_that_reason() {
let Some(rig) = one_session("sign-person", ReviewSetup::default()) else {
return;
};
request_stop_after(&rig.rc.slot, true).unwrap();
let mut found = outcome(1, "both", 0, 1, &["Fix"]);
found["review"]["suggestion"] = json!(1);
found["review"]["suggestions"] = json!([{ "title": "Name the timer", "file": "a.txt" }]);
edit(&rig, "b.txt", "x\n");
assert!(!answer(&rig, "s1", found));
let run = snap(&rig);
assert_eq!(run.stop_reason, Some(StopReason::Person));
assert_eq!(run.collected.len(), 1);
sign(&rig, &["s1"], false).expect("sign-off starts the fix");
edit(&rig, "t.txt", "named\n");
assert!(answer(
&rig,
"b1",
outcome(2, "fixer", 0, 0, &["Name the timer"])
));
assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[])));
let run = snap(&rig);
assert!(run.signed_off, "the sign-off finished");
assert_eq!(
run.stop_reason,
Some(StopReason::Person),
"the reason is kept"
);
assert_eq!(run.signoff.unwrap().problem, None);
done(&rig);
}
#[test]
fn a_failed_round_is_named_even_after_a_sign_off_moves_the_round_on() {
let mut run = spec_run(&std::env::temp_dir(), ReviewScope::Branch, None);
run.stop_reason = Some(StopReason::Failed("tests failed".to_string()));
run.stop_round = 2;
run.round = 5;
assert_eq!(end_line(&run), "Failed in round 2: tests failed.");
}
}