//! Extra review rounds inside an Implementation Loop phase (FR-28). //! //! When a phase's own review leaves a Critical or a Warning, fresh round //! sessions review (and fix) the phase before it is judged and committed: the //! first round looks at the whole phase diff and briefs the fixer with the //! phase agent's unfixed findings, each later round looks only at what the //! round before it changed. The rounds run here, one at a time, inside the //! phase's report handling; the rules are `round_logic`'s, the session pieces //! are `loop_shared`'s and the scope and prompt are the Review Loop's. A phase //! never commits per round: its own commit at the end carries everything //! (NFR-1). use std::path::{Path, PathBuf}; use std::time::{Instant, SystemTime}; use serde_json::Value; use crate::agent_manager::AgentState; use crate::loop_driver::{ self, Finding as PhaseFinding, FixLevel, Left, LoopSetup, RoundWait, StopCause, Strength, }; use crate::loop_report::RoundEntry; use crate::loop_shared::retry::should_retry; use crate::loop_shared::rounds::{ finding_line, page_is_this_round, proofs_for, report_text, reviewer_brief, role_word, round_outcome_in, }; use crate::loop_shared::session::{read_session_state, start_session, Ctx}; use crate::loop_shared::watch::silence_expired; use crate::models::StrengthRow; use crate::review_loop::round_prompt; use crate::round_boundary::{self, Boundary}; use crate::round_logic::{ self, Finding, Next, Role, RoundOutcome, RoundReview, RunView, StopReason, Verdict, MAX_ROUNDS, }; use crate::session_reader; /// What the rounds need, copied out of the loop's record. pub struct RoundsInput { pub project: PathBuf, pub phase: u32, pub setup: LoopSetup, /// The most rounds to run (the setup's Review rounds per phase). pub cap: u32, /// One session per round (the agent starts its own helper) or two. pub helpers: bool, /// The working tree as the phase began. pub start: Boundary, /// The phase agent's findings it left unfixed: the first fixer's brief. pub unfixed: Vec, /// Where each round's scope file and diff are written. pub dir: PathBuf, } /// How the rounds ended. #[derive(Debug)] pub enum RoundsEnd { /// A clean round, or the cap: the last round's counts judge the phase. Done(Done), /// Stop now was pressed. Person { rounds: Vec }, /// A round failed after its retry. Failed { reason: String, rounds: Vec, }, } #[derive(Debug, Default)] pub struct Done { pub rounds: Vec, pub critical: u32, pub warning: u32, pub suggestion: u32, pub unfixed: Vec, } /// How one session of a round ended. enum SessionEnd { Outcome(Box, Value), /// Why it failed, and the cause the retry rule reads (never the words). Failed(StopCause, String), Person, } /// What a finished round gives the next step. struct Played { outcome: RoundOutcome, verdict: Verdict, retried: bool, started: String, strength: String, } fn clock() -> String { chrono::Local::now().format("%Y-%m-%d %H:%M").to_string() } fn one_line(text: &str) -> String { text.split_whitespace().collect::>().join(" ") } /// Whether the loop's agent can start a helper from inside a session. pub fn helpers_for(ctx: &Ctx) -> bool { crate::review_loop::agent_helpers(&ctx.launch.0) } /// The banner's step, "Review round 1 of 2". fn banner(ctx: &Ctx, round: u32, cap: u32) { if let Some(rec) = loop_driver::lock(&ctx.slot) .as_mut() .filter(|r| r.run_id == ctx.run_id) { rec.step_text = Some(format!("Review round {round} of {cap}")); } loop_driver::emit(ctx); } fn clear_wait(ctx: &Ctx) { if let Some(rec) = loop_driver::lock(&ctx.slot) .as_mut() .filter(|r| r.run_id == ctx.run_id) { rec.round_wait = None; } } /// The strength the phase runs on now (a retry steps it up first), as /// `start_phase` reads it. fn strength_now(ctx: &Ctx) -> Option<(Strength, StrengthRow)> { let guard = loop_driver::lock(&ctx.slot); let rec = guard.as_ref().filter(|r| r.run_id == ctx.run_id)?; let word = rec.phase_run(rec.current)?.strength?; Some((word, rec.strength_rows.get(word.word())?.clone())) } fn step_strength_up(ctx: &Ctx) { if let Some(rec) = loop_driver::lock(&ctx.slot) .as_mut() .filter(|r| r.run_id == ctx.run_id) { let at = rec.current; rec.step_strength_up(at); } } /// The text of a round's scope file: the diff to review, the reviewer's report /// for a fixer and, in the first round, what the phase agent left unfixed. fn scope_text( round: u32, role: Role, diff: &Path, report: Option<&Path>, brief: &[PhaseFinding], ) -> String { let mut text = format!( "# Phase review round {round} scope\n\nRole: {}\n", role_word(role) ); if round == 1 { text.push_str(&format!( "\nReview exactly this diff, everything the phase changed, and nothing else:\n\n- {}\n", diff.display() )); } else { text.push_str(&format!( "\nReview exactly this diff, the previous round's changes, and nothing else:\n\n- {}\n", diff.display() )); } if !brief.is_empty() && role != Role::Reviewer { text.push_str("\nThe phase's own review left these findings unfixed (fix them):\n\n"); for finding in brief { text.push_str(&finding_line(&Finding { title: finding.title.clone(), file: finding.file.clone(), line: None, })); text.push('\n'); } } if let Some(report) = report { text.push_str(&format!( "\nThe reviewer's report (fix its Critical and Warning findings):\n\n- {}\n", report.display() )); } text } fn start_one( ctx: &Ctx, input: &RoundsInput, round: u32, role: Role, scope: &str, attempt: u32, ) -> Result { let dir = input .dir .join(format!("round-{round}-{}-t{attempt}", role_word(role))); std::fs::create_dir_all(&dir) .map_err(|err| format!("could not make {}: {err}", dir.display()))?; let scope_file = dir.join("scope.md"); std::fs::write(&scope_file, scope) .map_err(|err| format!("could not write {}: {err}", scope_file.display()))?; let prompt = round_prompt(round, role, &scope_file); // A running session (the phase's own, a silent one being retried) ends first. ctx.agent.stop(); if let Some(rec) = loop_driver::lock(&ctx.slot) .as_mut() .filter(|r| r.run_id == ctx.run_id) { rec.round_wait = Some(RoundWait { round, role, sid: None, candidate: None, }); rec.last_activity = SystemTime::now(); rec.activity_checked = Instant::now(); } let on = strength_now(ctx); let started = start_session(ctx, &prompt, on.as_ref().map(|(word, row)| (*word, row)))?; Ok(started.generation) } /// The round's session id: the page `note_page` handed over, or a candidate /// whose state now shows the agent's lock. fn session_id(ctx: &Ctx, round: u32, role: Role) -> Option { let candidate = { let guard = loop_driver::lock(&ctx.slot); let wait = guard .as_ref() .filter(|r| r.run_id == ctx.run_id)? .round_wait .as_ref()?; if let Some(sid) = &wait.sid { return Some(sid.clone()); } wait.candidate.clone()? }; let state = read_session_state(ctx, &candidate)?; if !page_is_this_round(&state, round, role) { return None; } let mut guard = loop_driver::lock(&ctx.slot); let wait = guard .as_mut() .filter(|r| r.run_id == ctx.run_id)? .round_wait .as_mut()?; wait.sid.get_or_insert(candidate); wait.sid.clone() } fn crashed(ctx: &Ctx, generation: u64) -> Option { let seen = ctx.agent.snapshot(); match seen.state { AgentState::Ended { reason } if seen.generation == generation => Some(reason), _ => None, } } /// Watch one round session until it reports, fails or is stopped. The same /// rules as a phase's watch: a crash, silence or a console that never opens /// fail it, and so does a question (a round cannot be answered). fn watch_session( ctx: &Ctx, setup: &LoopSetup, round: u32, role: Role, generation: u64, ) -> SessionEnd { let began = Instant::now(); let mut last_activity = SystemTime::now(); let mut checked = Instant::now(); loop { std::thread::sleep(ctx.limits.watch_every); { let guard = loop_driver::lock(&ctx.slot); match guard.as_ref().filter(|r| r.run_id == ctx.run_id) { // The loop ended under us (a stop, a restart): nothing to judge. None => return SessionEnd::Person, Some(rec) if rec.stop_now => { drop(guard); ctx.agent.stop(); return SessionEnd::Person; } Some(_) => {} } } let Some(sid) = session_id(ctx, round, role) else { if let Some(reason) = crashed(ctx, generation) { return SessionEnd::Failed( StopCause::Crash, format!("the agent crashed ({reason})"), ); } if began.elapsed() > ctx.limits.notice_wait { return SessionEnd::Failed( StopCause::NoSession, "the round's console never opened".to_string(), ); } continue; }; let state = session_reader::load(&ctx.home, &sid) .ok() .map(|session| (session.state, session.dir)); if let Some((state, _)) = &state { if let Some(found) = round_outcome_in(state, round, role) { ctx.agent.stop(); return match found { Ok(outcome) => SessionEnd::Outcome(Box::new(outcome), state.clone()), Err(reason) => SessionEnd::Failed(StopCause::Refused(reason.clone()), reason), }; } } // An agent that writes its report and exits between two looks is // judged, not called a crash. if let Some(reason) = crashed(ctx, generation) { let again = read_session_state(ctx, &sid); if let Some(Ok(outcome)) = again .as_ref() .and_then(|state| round_outcome_in(state, round, role)) { return SessionEnd::Outcome(Box::new(outcome), again.unwrap_or(Value::Null)); } return SessionEnd::Failed(StopCause::Crash, format!("the agent crashed ({reason})")); } let mut quiet = None; if let Some((state, dir)) = &state { if let Some(question) = loop_driver::first_open_question(state) { ctx.agent.stop(); let reason = format!("the agent asked a question: {}", one_line(&question)); return SessionEnd::Failed(StopCause::Question, reason); } quiet = state["agent"]["quietMinutes"] .as_u64() .and_then(|m| u32::try_from(m).ok()); if checked.elapsed() >= ctx.limits.activity_every { checked = Instant::now(); if let Some(time) = loop_driver::newest_work(dir, &input_project(ctx)) { let time = loop_driver::clamp_to_now(time); if time > last_activity { last_activity = time; } } } } if silence_expired(SystemTime::now(), last_activity, setup, quiet, false) { let minutes = setup.silence_minutes.max(quiet.unwrap_or(0)).min(60); return SessionEnd::Failed( StopCause::Silence, format!("the agent went silent for {minutes} minutes"), ); } } } /// The project the loop builds in, for the silence rule's look at the tree. fn input_project(ctx: &Ctx) -> PathBuf { loop_driver::lock(&ctx.slot) .as_ref() .filter(|r| r.run_id == ctx.run_id) .map(|r| r.project.clone()) .unwrap_or_default() } /// One session with its one retry (a step up in strength): `Ok` with the /// session's outcome, `Err(None)` when stop now ended it, `Err(Some)` with the /// reason when the retry failed too. `retried` says the retry was used. fn session_with_retry( ctx: &Ctx, input: &RoundsInput, round: u32, role: Role, scope: &str, retried: &mut bool, ) -> Result<(RoundOutcome, Value), Option> { let mut attempt = 0; loop { let begun = start_one(ctx, input, round, role, scope, attempt).map_err(Some); let end = match begun { Ok(generation) => watch_session(ctx, &input.setup, round, role, generation), Err(Some(reason)) => SessionEnd::Failed( StopCause::Refused(reason.clone()), format!("the round could not start ({reason})"), ), Err(None) => SessionEnd::Person, }; clear_wait(ctx); match end { SessionEnd::Person => return Err(None), SessionEnd::Outcome(outcome, state) => return Ok((*outcome, state)), SessionEnd::Failed(cause, reason) => { // A crash, silence or a console that never opened gets one // fresh try a strength up, as a phase does; `should_retry` // reads the typed cause, so any other failure (a question, an // unreadable report) fails the round. if !*retried && should_retry(&cause, &input.setup, 0) { *retried = true; attempt += 1; step_strength_up(ctx); continue; } return Err(Some(reason)); } } } } /// Play one round: one session, or a reviewer then a fixer that never saw the /// review. A failed session after its retry comes back as the round's failure. fn play_round( ctx: &Ctx, input: &RoundsInput, round: u32, from: &Boundary, to: &Boundary, ) -> Result> { let dir = input.dir.join(format!("round-{round}")); std::fs::create_dir_all(&dir) .map_err(|err| Some(format!("could not make {}: {err}", dir.display())))?; let diff = dir.join(format!("round-{round}.diff")); round_boundary::diff(&input.project, from, to, &diff).map_err(Some)?; let brief: &[PhaseFinding] = if round == 1 { &input.unfixed } else { &[] }; let started = clock(); let strength = strength_now(ctx).map_or_else(String::new, |(word, _)| word.label().to_string()); let mut retried = false; let (outcome, state) = if input.helpers { let scope = scope_text(round, Role::Both, &diff, None, brief); session_with_retry(ctx, input, round, Role::Both, &scope, &mut retried)? } else { let scope = scope_text(round, Role::Reviewer, &diff, None, &[]); let (reviewed, state) = session_with_retry(ctx, input, round, Role::Reviewer, &scope, &mut retried)?; let proofs = proofs_for(&state, &reviewed, Role::Reviewer); match round_logic::judge_round(&reviewed, &proofs) { Verdict::Failed(reason) => return Err(Some(reason)), Verdict::Clean => (reviewed, state), Verdict::Findings { .. } => { let text = reviewed .report .as_deref() .and_then(|id| report_text(&state, id)) .unwrap_or_default(); let report = dir.join("reviewer-report.md"); std::fs::write(&report, reviewer_brief(&text, &reviewed)) .map_err(|err| Some(format!("could not write {}: {err}", report.display())))?; let scope = scope_text(round, Role::Fixer, &diff, Some(&report), brief); let (mut fixed, state) = session_with_retry(ctx, input, round, Role::Fixer, &scope, &mut retried)?; round_logic::hold_reviewer_counts( &mut fixed.review, reviewed.review.critical, reviewed.review.warning, ); (fixed, state) } } }; let role = outcome.role; let proofs = proofs_for(&state, &outcome, role); let verdict = round_logic::judge_round(&outcome, &proofs); if let Verdict::Failed(reason) = &verdict { return Err(Some(reason.clone())); } Ok(Played { outcome, verdict, retried, started, strength, }) } fn titles(findings: &[Finding]) -> Vec { findings.iter().map(|f| f.title.clone()).collect() } fn entry_of(round: u32, played: &Played) -> RoundEntry { let review: &RoundReview = &played.outcome.review; RoundEntry { n: round, critical: review.critical, warning: review.warning, suggestion: review.suggestion, fixed: titles(&review.fixed), left_open: titles(&review.unfixed), commit: None, tests: played .outcome .tests .as_ref() .map_or_else(String::new, |t| t.summary.clone()), started: played.started.clone(), ended: clock(), strength: played.strength.clone(), retried: played.retried, } } fn snapshot(input: &RoundsInput) -> Result { round_boundary::snapshot(&input.project) } /// Run the phase's extra rounds. Never commits and never marks anything. pub fn run_rounds(ctx: &Ctx, input: &RoundsInput) -> RoundsEnd { let cap = input.cap.clamp(1, MAX_ROUNDS); let mut entries: Vec = Vec::new(); // Where the phase's own work ended: round 1 reviews start to here. let mut round_before = match snapshot(input) { Ok(boundary) => boundary, Err(reason) => { return RoundsEnd::Failed { reason: format!("the phase's work could not be recorded ({reason})"), rounds: entries, } } }; let mut from = input.start.clone(); let mut to = round_before.clone(); let mut round = 1; loop { banner(ctx, round, cap); let played = match play_round(ctx, input, round, &from, &to) { Ok(played) => played, Err(None) => return RoundsEnd::Person { rounds: entries }, Err(Some(reason)) => { return RoundsEnd::Failed { reason, rounds: entries, } } }; entries.push(entry_of(round, &played)); loop_driver::keep_rounds(ctx, &entries); let stop_now = loop_driver::stop_requested(ctx); let view = RunView { round, cap, rounds_run: round, suggestions_on: false, suggestions_pending: false, batch_done: false, // The round's one retry is spent inside `session_with_retry`. retried_this_round: true, stop_after_round: false, stop_now, }; match round_logic::next_step(&view, &played.verdict) { Next::StartRound(next) => { let after = match snapshot(input) { Ok(boundary) => boundary, Err(reason) => { return RoundsEnd::Failed { reason: format!("the round's work could not be recorded ({reason})"), rounds: entries, } } }; // The next round reviews what this one changed. from = round_before; to = after.clone(); round_before = after; round = next; } Next::Stop(StopReason::Person) => return RoundsEnd::Person { rounds: entries }, Next::Stop(StopReason::Failed(reason)) => { return RoundsEnd::Failed { reason, rounds: entries, } } // A clean round or the cap; the suggestions batch and the final // check do not exist inside a phase. Next::Stop(_) | Next::Retry | Next::SuggestionsBatch | Next::FinalCheck => { let review = &played.outcome.review; return RoundsEnd::Done(Done { rounds: entries, critical: review.critical, warning: review.warning, suggestion: review.suggestion, unfixed: review.unfixed.clone(), }); } } } } /// The phase agent's report with the last round's counts in place of its own /// `review.left`, so `judge_outcome` decides on what is left after the rounds. /// A phase that reported `failed` only for its findings reads as passed once /// they are gone; the judge still checks the spec, the tests and the rest. pub fn judged_after(mut outcome: loop_driver::Outcome, done: &Done) -> loop_driver::Outcome { let mut review = outcome.review.take().unwrap_or_default(); review.ran = true; review.recheck = true; review.left = Left { critical: done.critical, warning: done.warning, suggestion: done.suggestion, }; // The agent's own Critical and Warning entries are replaced by the last // round's; Suggestions it left stay. The round's list has no levels: its // first `critical` entries read as Critical, the rest as Warning. review.unfixed.retain(|f| f.level == FixLevel::Suggestion); let mut critical_left = done.critical; for finding in &done.unfixed { let level = if critical_left > 0 { critical_left -= 1; FixLevel::Critical } else { FixLevel::Warning }; review.unfixed.push(PhaseFinding { level, title: finding.title.clone(), file: finding.file.clone(), reason: None, }); } outcome.review = Some(review); if outcome.result == "failed" && outcome.reason.as_deref() == Some("findings") { outcome.result = "passed".to_string(); outcome.reason = None; } outcome }