Add the Review Loop: unattended review-and-fix rounds in the desktop app and in loop phases

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-28 21:09:02 -08:00
1 parent d6a28b5dc8
commit 57567d7a0b
71 files changed
+11331 -443

No files matched your search

+536 -126
View File
@@ -27,8 +27,18 @@ use crate::console_supervisor::find_console_dir;
use crate::loop_commit;
use crate::loop_notify::{self, NotifyKind};
use crate::loop_report::{self, EntryResult, LoopReport, ReportEntry};
use crate::loop_shared::notify as notify_call;
use crate::loop_shared::report_list::{load_reports, save_report};
use crate::loop_shared::retry::{next_strength_word, should_retry};
use crate::loop_shared::session::{read_session_state, start_session, Ctx};
use crate::loop_shared::watch::{
silence_expired, watch_loop, WatchStep, ACTIVITY_EVERY, WATCH_EVERY,
};
use crate::loop_tools;
use crate::models::{self, StrengthRow};
use crate::phase_rounds;
use crate::round_boundary::{self, Boundary};
use crate::round_logic::Role;
use crate::session_reader::{self, ReadError};
// ---------------------------------------------------------------- the setup
@@ -132,6 +142,9 @@ pub struct PhasePick {
#[serde(rename_all = "camelCase", default)]
pub struct LoopSetup {
pub review: bool,
/// Extra fresh review rounds a phase gets while its own review leaves a
/// Critical or Warning (0 turns them off). Read through `extra_rounds()`.
pub review_rounds: u32,
// An entry saved before this field existed fixed by level, so it keeps
// doing that (FixMode's own default) rather than taking the new setup's.
#[serde(default)]
@@ -163,6 +176,7 @@ impl Default for LoopSetup {
fn default() -> Self {
LoopSetup {
review: true,
review_rounds: MAX_REVIEW_ROUNDS_DEFAULT,
fix_mode: FixMode::Smart,
fix: vec![FixLevel::Critical, FixLevel::Warning, FixLevel::Suggestion],
commit: true,
@@ -181,7 +195,21 @@ impl Default for LoopSetup {
}
}
/// The Review rounds per phase a setup without the field takes.
const MAX_REVIEW_ROUNDS_DEFAULT: u32 = 2;
/// The most Review rounds per phase the setup allows.
const MAX_REVIEW_ROUNDS: u32 = 6;
impl LoopSetup {
/// The extra review rounds a phase may run: none with Review off, at most 6.
pub fn extra_rounds(&self) -> u32 {
if self.review {
self.review_rounds.min(MAX_REVIEW_ROUNDS)
} else {
0
}
}
/// The levels whose leftovers matter: every level in Smart pick.
fn chosen_levels(&self) -> Vec<FixLevel> {
if !self.review {
@@ -412,6 +440,28 @@ pub struct RunningRecord {
/// not yet locked by the agent's `open --loop`: adopted on a later look
/// once its state shows the lock (`note_page`).
pub page_candidate: Option<String>,
/// The banner's step while a phase's extra review rounds run ("Review round
/// 1 of 2"); it replaces the step's own label and is cleared by `set_step`.
pub step_text: Option<String>,
/// The extra round session the phase is waiting on, so `note_page` can hand
/// it the page that session announces.
pub round_wait: Option<RoundWait>,
/// The working tree as the phase began (a snapshot), kept only when the
/// setup allows extra review rounds: the first round reviews the diff from it.
pub phase_start: Option<Boundary>,
/// The extra review rounds the current phase has run, for its report entry.
pub phase_rounds: Vec<loop_report::RoundEntry>,
}
/// An extra review round session a phase is waiting on.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RoundWait {
pub round: u32,
pub role: Role,
/// The adopted page's session id.
pub sid: Option<String>,
/// A page announced before it showed the agent's lock, adopted once it does.
pub candidate: Option<String>,
}
/// What one phase runs on, for its start, the strip and the report.
@@ -496,6 +546,10 @@ impl RunningRecord {
launch_effort: None,
phase_baseline: None,
page_candidate: None,
step_text: None,
round_wait: None,
phase_start: None,
phase_rounds: Vec::new(),
}
}
@@ -531,7 +585,7 @@ impl RunningRecord {
return;
};
let Some(word) = phase.strength else { return };
if let Some(next) = models::next_strength(&self.strength_rows, word.word())
if let Some(next) = next_strength_word(&self.strength_rows, word.word())
.and_then(|w| Strength::from_word(&w))
{
phase.strength = Some(next);
@@ -567,6 +621,25 @@ pub struct LoopStateEvent {
/// The model and effort the phase runs on, when known.
pub model: Option<String>,
pub effort: Option<String>,
/// `"phases"` for the Implementation Loop, `"rounds"` for the Review Loop.
pub kind: &'static str,
/// A Review Loop's current round and its cap (0 for the phases kind).
pub round: u32,
pub rounds: u32,
/// Critical and Warning per finished round (empty for the phases kind).
pub round_counts: Vec<RoundCount>,
/// Stop after this round is on (a Review Loop).
pub stop_after_round: bool,
/// What a Review Loop runs after its rounds ("Suggestions batch" or
/// "Final check"), empty while a round runs and for the phases kind.
pub after_rounds: &'static str,
}
/// What one finished Review Loop round found, for the banner's dots.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub struct RoundCount {
pub critical: u32,
pub warning: u32,
}
impl LoopStateEvent {
@@ -590,6 +663,12 @@ impl LoopStateEvent {
strength: None,
model: None,
effort: None,
kind: "phases",
round: 0,
rounds: 0,
round_counts: Vec::new(),
stop_after_round: false,
after_rounds: "",
}
}
}
@@ -615,7 +694,10 @@ pub fn state_event(rec: &RunningRecord) -> LoopStateEvent {
previous_phase: previous.map(|p| p.n),
previous_committed: previous.is_some_and(|p| p.commit.is_some()),
phase_retried: current.is_some_and(|p| p.retries > 0),
step: rec.step.label().to_string(),
step: rec
.step_text
.clone()
.unwrap_or_else(|| rec.step.label().to_string()),
started_at_ms: rec.started_at_ms,
retries_used: rec.retries_used,
stop_after_phase: rec.stop_after_phase,
@@ -627,6 +709,12 @@ pub fn state_event(rec: &RunningRecord) -> LoopStateEvent {
.map(|w| w.word().to_string()),
model: run.as_ref().and_then(|r| r.model.clone()),
effort: run.as_ref().and_then(|r| r.effort.clone()),
kind: "phases",
round: 0,
rounds: 0,
round_counts: Vec::new(),
stop_after_round: false,
after_rounds: "",
}
}
@@ -663,7 +751,7 @@ pub enum Verdict {
/// A poisoned mutex is still taken: the watcher catches its own panics (see
/// `watch_with`), and a panic inside a lock poisons it, so the stop that
/// follows must still be able to clear the slot.
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
pub(crate) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
@@ -909,28 +997,6 @@ pub fn judge_outcome(outcome: &Outcome, phase_status: &Value, setup: &LoopSetup)
Verdict::Approve { warnings }
}
/// Whether the agent has been quiet too long. A waiting question never counts
/// (the person may take all night). The limit is the setup's silence minutes
/// or the skill's own `quietMinutes`, whichever is longer, at most 60.
pub fn silence_expired(
now: SystemTime,
last_activity: SystemTime,
setup: &LoopSetup,
quiet_minutes: Option<u32>,
waiting: bool,
) -> bool {
if waiting {
return false;
}
let minutes = setup
.silence_minutes
.max(quiet_minutes.unwrap_or(0))
.min(60);
let limit = Duration::from_secs(u64::from(minutes) * 60);
now.duration_since(last_activity)
.is_ok_and(|quiet| quiet > limit)
}
/// Why a loop ended.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StopCause {
@@ -953,17 +1019,6 @@ pub enum StopCause {
WatcherFailed(String),
}
/// One fresh retry for a crash, silence or an announce notice that never came
/// (a crash), when the setup allows it and the phase has not used it yet. A
/// failed watcher is never retried.
pub fn should_retry(cause: &StopCause, setup: &LoopSetup, retries_used_this_phase: u32) -> bool {
matches!(
cause,
StopCause::Crash | StopCause::Silence | StopCause::NoSession
) && setup.retry_once
&& retries_used_this_phase == 0
}
/// Whether the session state holds a question for the person: an item still
/// open or reopened, required, not handled by the loop and not just a notice.
pub fn open_question(state: &Value) -> bool {
@@ -1172,7 +1227,7 @@ pub fn prepare(
validate_spec(project, spec)?;
let setup = read_setup(project)?;
let report = session_reader::console_home()
.and_then(|home| loop_report::load(&home, project, spec))
.and_then(|home| load_reports(&home, project, spec))
.unwrap_or_default();
prepare_with(project, spec, setup, &report, mode, prompt_ok, resuming)
}
@@ -1266,7 +1321,7 @@ pub fn prepare_with(
rec.rebuilt = rebuilt;
rec.resumed_files = resumed_files;
rec.branch = branch;
rec.start_head = loop_tools::git_head_full(project);
rec.start_head = loop_tools::git_head_full(project).ok();
// On a resumed run this holds the stopped phase's work too, by design: it
// is listed as the person's own, the known limit of a baseline.
rec.own_dirty = own_dirty;
@@ -1289,7 +1344,7 @@ fn phase_pick(setup: &LoopSetup, spec: &str, n: u32, name: &str) -> Option<Stren
/// What each strength word maps to for `agent`, from the shipped and user
/// model files: read once, when the loop begins.
fn strength_rows_for(agent: &Agent) -> BTreeMap<String, StrengthRow> {
pub fn strength_rows_for(agent: &Agent) -> BTreeMap<String, StrengthRow> {
let models: Vec<String> = match agent {
Agent::Builtin(entry) => models::models_for_builtin(&entry.id),
Agent::Custom(custom) => custom.models.clone(),
@@ -1670,7 +1725,7 @@ fn notify(setup: &LoopSetup, message: &str) -> Option<String> {
if setup.notify_url.is_empty() {
return None;
}
loop_notify::send(
notify_call(
setup.notify_kind,
&setup.notify_url,
&setup.notify_param,
@@ -1697,25 +1752,9 @@ pub struct Hooks {
pub attention: Box<dyn Fn() + Send + Sync>,
}
/// What the watch thread needs, shared by every step of one loop.
#[derive(Clone)]
struct Ctx {
slot: LoopSlot,
agent: Arc<AgentManager>,
console_dir: PathBuf,
home: PathBuf,
launch: Launch,
run_id: u64,
hooks: Arc<Hooks>,
limits: Limits,
}
/// A notice that waits for the new agent's console: how long before the phase
/// counts as crashed.
const NOTICE_WAIT: Duration = Duration::from_secs(180);
const WATCH_EVERY: Duration = Duration::from_secs(2);
/// How often silence looks at the session's files and the tree.
const ACTIVITY_EVERY: Duration = Duration::from_secs(30);
/// How long a phase's commit may run: a slow pre-commit hook is allowed this
/// much, where the quick calls keep their one minute.
const COMMIT_LIMIT: Duration = Duration::from_secs(10 * 60);
@@ -1775,7 +1814,7 @@ pub fn begin_with_limits(
}
rec.launch_model.clone_from(&launch.1);
rec.launch_effort.clone_from(&launch.2);
if let Some(report) = loop_report::load(&home, &rec.project, &rec.spec) {
if let Some(report) = load_reports(&home, &rec.project, &rec.spec) {
rec.report = report;
}
let ctx = Ctx {
@@ -1811,6 +1850,11 @@ pub fn begin_with_limits(
/// (`page_is_this_phase`). One without the lock is kept as a candidate the
/// watch adopts once the lock shows; one with a report is ignored.
pub fn note_page(slot: &LoopSlot, workflow: &str, sid: &str, state: &Value) {
// An extra review round's session, while a phase waits for one.
if workflow == "review" {
note_round_page(slot, sid, state);
return;
}
if !matches!(workflow, "implement" | "implement-review") {
return;
}
@@ -1827,6 +1871,27 @@ pub fn note_page(slot: &LoopSlot, workflow: &str, sid: &str, state: &Value) {
}
}
/// Hand a Review page to the extra round a phase is waiting on: the page the
/// agent locked with `open --loop` for that round and role is its session; one
/// without the lock yet is kept as a candidate the round adopts once it shows.
fn note_round_page(slot: &LoopSlot, sid: &str, state: &Value) {
let mut guard = lock(slot);
let Some(rec) = guard.as_mut() else { return };
let Some(wait) = rec.round_wait.as_mut() else {
return;
};
if wait.sid.is_some() {
return;
}
if crate::loop_shared::rounds::page_is_this_round(state, wait.round, wait.role) {
wait.sid = Some(sid.to_string());
wait.candidate = None;
rec.last_activity = SystemTime::now();
} else if state.is_object() && state.get("roundOutcome").is_none_or(Value::is_null) {
wait.candidate = Some(sid.to_string());
}
}
/// Follow `sid` as the phase's session from here.
fn adopt_page(rec: &mut RunningRecord, sid: &str) {
rec.sid = Some(sid.to_string());
@@ -1839,8 +1904,8 @@ fn adopt_page(rec: &mut RunningRecord, sid: &str) {
/// agent's lock; the session to follow, or `None` while there is none yet.
fn adopt_candidate(ctx: &Ctx, candidate: Option<&str>) -> Option<String> {
let sid = candidate?;
let session = session_reader::load(&ctx.home, sid).ok()?;
if !page_is_this_phase(&session.state) {
let state = read_session_state(ctx, sid)?;
if !page_is_this_phase(&state) {
return None;
}
let mut guard = lock(&ctx.slot);
@@ -1938,7 +2003,7 @@ pub fn finalize_prompt(spec: &str) -> String {
format!("/plan2code-4-finalize {spec}/overview.md --web")
}
fn emit(ctx: &Ctx) {
pub(crate) fn emit(ctx: &Ctx) {
let event = {
let guard = lock(&ctx.slot);
guard
@@ -1964,16 +2029,25 @@ fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> {
} else {
Vec::new()
};
(rec.project.clone(), carried)
(rec.project.clone(), carried, rec.setup.extra_rounds() > 0)
})
}
.map(|(project, carried)| phase_baseline(&project, &carried));
.map(|(project, carried, rounds)| {
// The tree as the phase begins, for its extra review rounds; a phase
// that allows none never pays for the snapshot.
let start = rounds.then(|| round_boundary::snapshot(&project).ok());
(phase_baseline(&project, &carried), start)
});
let prompt = {
let mut guard = lock(&ctx.slot);
let rec = guard.as_mut().ok_or("the loop ended")?;
if let Some(baseline) = baseline {
if let Some((baseline, start)) = baseline {
rec.phase_baseline = baseline;
rec.phase_start = start.flatten();
rec.phase_rounds.clear();
}
rec.round_wait = None;
rec.step_text = None;
rec.page_candidate = None;
rec.current = index;
rec.phases[index].status = PhaseStatus::Running;
@@ -1996,11 +2070,8 @@ fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> {
// Said before the agent starts: the banner is up from the moment of Start,
// and says what is happening between phases.
emit(ctx);
match on {
Some((word, row)) => start_phase_with(&ctx.agent, &ctx.launch, prompt, &row, word)?,
None => start_with(&ctx.agent, &ctx.launch, prompt)?,
}
let generation = ctx.agent.snapshot().generation;
let started = start_session(ctx, &prompt, on.as_ref().map(|(word, row)| (*word, row)))?;
let generation = started.generation;
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
rec.generation = generation;
}
@@ -2019,25 +2090,18 @@ fn watch(ctx: Ctx) {
/// is cleared, the agent ended and the page told, never a loop left running
/// with nothing watching it.
fn watch_with(ctx: Ctx, mut step: impl FnMut(&Ctx) -> bool) {
loop {
thread::sleep(ctx.limits.watch_every);
let seen = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| step(&ctx)));
match seen {
Ok(true) => {}
Ok(false) => return,
Err(payload) => {
let text = payload
.downcast_ref::<&str>()
.map(|s| (*s).to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "an unknown error".to_string());
let text: String = one_line(&text).chars().take(200).collect();
let cause = StopCause::WatcherFailed(text);
let line = stop_line(&cause, 0, "", false);
stop_loop(&ctx, cause, line, &["resume", "fix"]);
return;
}
let panicked = watch_loop(ctx.limits.watch_every, || {
if step(&ctx) {
WatchStep::Continue
} else {
WatchStep::Stop
}
});
if let Some(text) = panicked {
let text: String = one_line(&text).chars().take(200).collect();
let cause = StopCause::WatcherFailed(text);
let line = stop_line(&cause, 0, "", false);
stop_loop(&ctx, cause, line, &["resume", "fix"]);
}
}
@@ -2289,7 +2353,7 @@ fn observe(ctx: &Ctx, stage: Option<&str>, asked: bool) {
/// A file time is never later than now: a file dated in the future (a clock
/// that was wrong, a copied file) must not hold the last sign of work ahead of
/// the clock, or silence would never fire.
fn clamp_to_now(time: SystemTime) -> SystemTime {
pub(crate) fn clamp_to_now(time: SystemTime) -> SystemTime {
time.min(SystemTime::now())
}
@@ -2303,7 +2367,7 @@ fn modified(path: &Path) -> Option<SystemTime> {
/// The newest sign of work: the session's own files, or a file `git status`
/// lists (ignored folders never appear, so they never count).
fn newest_work(session_dir: &Path, project: &Path) -> Option<SystemTime> {
pub(crate) fn newest_work(session_dir: &Path, project: &Path) -> Option<SystemTime> {
let mut newest = ["state.json", "events.ndjson"]
.iter()
.filter_map(|name| modified(&session_dir.join(name)))
@@ -2409,12 +2473,91 @@ fn stop_before_mark(ctx: &Ctx, snap: &Snapshot, staged: bool) -> bool {
false
}
fn stop_requested(ctx: &Ctx) -> bool {
pub(crate) fn stop_requested(ctx: &Ctx) -> bool {
lock(&ctx.slot)
.as_ref()
.is_some_and(|r| r.run_id == ctx.run_id && r.stop_now)
}
/// The extra review rounds a phase's own review calls for (FR-28): with Review
/// on, `review_rounds` above zero and a Critical or Warning left in a report
/// that otherwise could pass, fresh round sessions review the phase's diff
/// before it is judged. Returns the report to judge (the phase agent's own when
/// no round ran, else with the last round's counts in its place), or `None`
/// when the loop was stopped here and the stop is already recorded.
fn extra_rounds(ctx: &Ctx, snap: &Snapshot, outcome: Outcome) -> Option<Outcome> {
let review = outcome.review.clone().unwrap_or_default();
let left = leftover(&review, FixLevel::Critical) + leftover(&review, FixLevel::Warning);
// A phase that reports failed only for its findings has no other failure:
// its tests, tasks and conflicts are still checked by the judge afterwards.
let findings_only = outcome.result == "failed"
&& outcome.reason.as_deref() == Some("findings")
&& outcome.conflicts.is_empty();
let tests_hold = outcome
.tests
.as_ref()
.is_none_or(|t| !t.ran || t.passed || excused_failures(t));
if snap.setup.extra_rounds() == 0
|| !review.ran
|| left == 0
|| !(outcome.result == "passed" || findings_only)
|| !tests_hold
{
return Some(outcome);
}
let n = snap.phase_n;
let stop_with = |cause: StopCause, line: String| {
stop_loop(ctx, cause, line, &["resume", "fix"]);
None
};
let start = {
let guard = lock(&ctx.slot);
let rec = guard.as_ref().filter(|r| r.run_id == ctx.run_id)?;
rec.phase_start.clone()
};
let Some(start) = start else {
keep_output(
ctx,
"The extra review rounds were skipped: the tree as the phase began could not be recorded.",
);
return Some(outcome);
};
let input = phase_rounds::RoundsInput {
project: snap.project.clone(),
phase: n,
setup: snap.setup.clone(),
cap: snap.setup.extra_rounds(),
helpers: phase_rounds::helpers_for(ctx),
start,
unfixed: review.unfixed.clone(),
dir: ctx
.home
.join("loop-phase-rounds")
.join(format!("{}-phase-{n}", ctx.run_id)),
};
let end = phase_rounds::run_rounds(ctx, &input);
match end {
phase_rounds::RoundsEnd::Done(done) => {
keep_rounds(ctx, &done.rounds);
Some(phase_rounds::judged_after(outcome, &done))
}
phase_rounds::RoundsEnd::Person { rounds } => {
keep_rounds(ctx, &rounds);
stop_by_person(ctx, snap);
None
}
phase_rounds::RoundsEnd::Failed { reason, rounds } => {
keep_rounds(ctx, &rounds);
let cause = StopCause::Refused(format!(
"an extra review round failed ({})",
one_line(&reason)
));
let line = stop_line(&cause, n, "", false);
stop_with(cause, line)
}
}
}
/// Judge a phase's report and, when it holds, record it: quick check, mark,
/// approval line, commit, stop the agent, then the next phase, a stop the
/// person asked for, or the finish. Returns whether the loop goes on.
@@ -2436,6 +2579,11 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
if outcome.phase != n {
return refused(format!("the report names Phase {}", outcome.phase));
}
// A phase whose own review left a Critical or a Warning gets fresh review
// rounds before it is judged (the hook; nothing else about the phase changes).
let Some(outcome) = extra_rounds(ctx, snap, outcome) else {
return false;
};
let status = match loop_tools::specs_status(&snap.project, &snap.spec) {
Ok(status) => status,
Err(e) => return refused(format!("the spec could not be read ({})", one_line(&e))),
@@ -2595,6 +2743,11 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
retries: snap.phase_retries,
assumed: phase_assumptions(&snap.project, &snap.spec, n, Some(&entry)),
warnings,
rounds: lock(&ctx.slot)
.as_ref()
.filter(|r| r.run_id == ctx.run_id)
.map(|r| r.phase_rounds.clone())
.unwrap_or_default(),
..ReportEntry::default()
}
.with_outcome(&outcome);
@@ -2798,7 +2951,7 @@ fn add_entry(ctx: &Ctx, entry: ReportEntry) {
rec.report.entries.push(entry);
(rec.project.clone(), rec.report.clone())
};
let result = loop_report::save(&ctx.home, &saved.0, &saved.1);
let result = save_report(&ctx.home, &saved.0, &saved.1);
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
rec.report_failure = result.err();
}
@@ -2809,8 +2962,9 @@ fn set_step(ctx: &Ctx, step: Step) {
let mut guard = lock(&ctx.slot);
match guard.as_mut().filter(|r| r.run_id == ctx.run_id) {
Some(rec) => {
let changed = rec.step != step;
let changed = rec.step != step || rec.step_text.is_some();
rec.step = step;
rec.step_text = None;
changed
}
None => false,
@@ -2827,6 +2981,13 @@ fn keep_output(ctx: &Ctx, output: &str) {
}
}
/// Keep the extra rounds the phase has run, for its report entry.
pub(crate) fn keep_rounds(ctx: &Ctx, rounds: &[loop_report::RoundEntry]) {
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
rec.phase_rounds = rounds.to_vec();
}
}
fn keep_report(ctx: &Ctx, outcome: &Outcome, entry: &Value) {
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
rec.last_outcome = Some(outcome.clone());
@@ -3297,6 +3458,7 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) {
if let Some(outcome) = &rec.last_outcome {
entry = entry.with_outcome(outcome);
}
entry.rounds.clone_from(&rec.phase_rounds);
}
// What the phase ran on, as `add_entry` does for every other entry.
if let Some(run) = rec.phase_run(at) {
@@ -3304,7 +3466,7 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) {
entry.model = run.model_text();
}
rec.report.entries.push(entry);
rec.report_failure = loop_report::save(&ctx.home, &rec.project, &rec.report).err();
rec.report_failure = save_report(&ctx.home, &rec.project, &rec.report).err();
let mut evidence = evidence_with_report(&evidence_markdown(&cause, &line, &rec), &rec);
let sent = stop_message(&cause, &Where::of(&rec, at), &line)
.and_then(|message| notify(&rec.setup, &message));
@@ -3681,6 +3843,12 @@ pub fn summary_markdown(rec: &RunningRecord, date: &str, finalize: &FinalizeNote
if setup.review {
md.push_str(&format!("- Fixes: {}\n", levels_text(setup)));
}
if setup.review {
md.push_str(&format!(
"- Review rounds per phase: {}\n",
setup.extra_rounds()
));
}
md.push_str(&format!("- Commit each phase: {}\n", yes(setup.commit)));
let on_question = match setup.on_question {
OnQuestion::Pause => "pause and wait for you",
@@ -3726,7 +3894,7 @@ pub fn summary_markdown(rec: &RunningRecord, date: &str, finalize: &FinalizeNote
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
fn setup() -> LoopSetup {
@@ -4837,31 +5005,6 @@ second line"
// ----------------------------------------------- failures, stops, the strip
fn at(minutes: u64) -> SystemTime {
UNIX_EPOCH + Duration::from_secs(minutes * 60)
}
#[test]
fn silence_waits_past_the_limit_and_never_while_a_question_waits() {
let s = setup(); // 20 minutes
assert!(!silence_expired(at(120), at(100), &s, None, false));
assert!(silence_expired(at(121), at(100), &s, None, false));
// A waiting question has no time limit.
assert!(!silence_expired(at(1000), at(0), &s, None, true));
// The skill's own quiet minutes stretch the limit, never shrink it.
assert!(!silence_expired(at(140), at(100), &s, Some(45), false));
assert!(silence_expired(at(146), at(100), &s, Some(45), false));
assert!(silence_expired(at(121), at(100), &s, Some(5), false));
// Capped at 60 minutes whatever either side asks for.
assert!(silence_expired(at(161), at(100), &s, Some(500), false));
let mut long = setup();
long.silence_minutes = 60;
assert!(!silence_expired(at(160), at(100), &long, Some(90), false));
assert!(silence_expired(at(161), at(100), &long, Some(90), false));
// A clock that went backwards is not silence.
assert!(!silence_expired(at(100), at(200), &s, None, false));
}
#[test]
fn only_a_crash_silence_or_a_missing_console_retries_and_only_once() {
let s = setup();
@@ -5268,7 +5411,7 @@ second line"
/// Whether `program` runs; a test that needs it says so and skips when not.
/// On CI (`CI` is set) a missing program fails the test instead, so a
/// runner without git or node cannot turn the tests into silent passes.
fn program_ready(test: &str, program: &str) -> bool {
pub(crate) fn program_ready(test: &str, program: &str) -> bool {
let found = std::process::Command::new(program)
.arg("--version")
.output()
@@ -5283,13 +5426,13 @@ second line"
found
}
fn git_ready(test: &str) -> bool {
pub(crate) fn git_ready(test: &str) -> bool {
program_ready(test, "git")
}
/// Git, node and the skill scripts (`specs.mjs`, `commit-msg.mjs`) the tick
/// runs. The scripts are the repository's own (see `loop_tools::skill_script`).
fn harness_ready(test: &str) -> bool {
pub(crate) fn harness_ready(test: &str) -> bool {
let scripts = loop_tools::skill_script("specs.mjs").is_some()
&& loop_tools::skill_script("commit-msg.mjs").is_some();
assert!(
@@ -5299,7 +5442,7 @@ second line"
git_ready(test) && program_ready(test, "node")
}
fn git_in(repo: &Path, args: &[&str]) -> String {
pub(crate) fn git_in(repo: &Path, args: &[&str]) -> String {
let out = std::process::Command::new("git")
.args(args)
.current_dir(repo)
@@ -5383,7 +5526,7 @@ second line"
}
/// Where `cargo build -p fake-agent` leaves the fake agent, built on first use.
fn fake_agent_path() -> PathBuf {
pub(crate) fn fake_agent_path() -> PathBuf {
static BUILD: std::sync::Once = std::sync::Once::new();
BUILD.call_once(|| {
let status = std::process::Command::new(env!("CARGO"))
@@ -5406,7 +5549,7 @@ second line"
/// The fake agent as a custom agent. The loop's tests start it this way, not
/// through `PLAN2CODE_APP_AGENT_BIN`: that variable is process-wide, and
/// other tests in this process read it.
fn fake_agent_launch() -> Launch {
pub(crate) fn fake_agent_launch() -> Launch {
let agent = crate::agents::CustomAgent {
id: "fake".into(),
name: "Fake agent".into(),
@@ -5422,7 +5565,7 @@ second line"
/// An agent manager for the fake agent, and everything the agents printed. The pump answers the pseudo-terminal's cursor question,
/// as a terminal does, or Windows holds the output back.
fn fake_agent_manager(folder: &Path) -> (Arc<AgentManager>, Arc<Mutex<String>>) {
pub(crate) fn fake_agent_manager(folder: &Path) -> (Arc<AgentManager>, Arc<Mutex<String>>) {
use crate::agent_manager::AgentEvent;
let (tx, rx) = std::sync::mpsc::channel();
let tx = Mutex::new(tx);
@@ -5449,7 +5592,7 @@ second line"
}
/// Poll until `ready`; the wait ends on state, not on a fixed sleep.
fn wait_until(what: &str, mut ready: impl FnMut() -> bool) {
pub(crate) fn wait_until(what: &str, mut ready: impl FnMut() -> bool) {
let deadline = Instant::now() + Duration::from_secs(30);
while Instant::now() < deadline {
if ready() {
@@ -7858,4 +8001,271 @@ second line"
);
agent.stop();
}
// ------------------------------------------------ extra review rounds in a phase
fn quick_limits() -> Limits {
Limits {
watch_every: Duration::from_millis(20),
notice_wait: Duration::from_secs(20),
..Limits::default()
}
}
/// A `roundOutcome` the way a round agent posts it; the reviewer lists the
/// Warning it found as unfixed, the fixer says what its round left.
fn round_json(round: u32, role: &str, critical: u32, warning: u32) -> Value {
let mut value = json!({
"round": round, "role": role, "result": "passed", "reason": null,
"summary": "Round done",
"review": { "critical": critical, "warning": warning, "suggestion": 0,
"fixed": [], "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");
if warning > 0 {
value["review"]["unfixed"] =
json!([{ "title": "Close the handle", "file": "work.txt" }]);
}
}
value
}
/// What the player saw of a round session before it answered.
struct Seen {
scope: String,
banner: String,
}
/// Answer the phase's extra round sessions in order: wait for each one the
/// driver starts, read its scope file and the banner, hand the driver its
/// page (as the app's notice does) and post its `roundOutcome`.
fn play_rounds(
ctx: &Ctx,
script: Vec<(u32, &'static str, Value)>,
) -> thread::JoinHandle<Vec<Seen>> {
let ctx = ctx.clone();
thread::spawn(move || {
let mut seen = Vec::new();
for (round, role, outcome) in script {
let want = match role {
"reviewer" => Role::Reviewer,
"fixer" => Role::Fixer,
_ => Role::Both,
};
wait_until("a round session to wait for", || {
lock(&ctx.slot)
.as_ref()
.and_then(|rec| rec.round_wait.as_ref())
.is_some_and(|w| w.round == round && w.role == want && w.sid.is_none())
});
let (phase, banner) = {
let guard = lock(&ctx.slot);
let rec = guard.as_ref().unwrap();
(rec.phases[rec.current].n, state_event(rec).step)
};
let dir = ctx
.home
.join("loop-phase-rounds")
.join(format!("{}-phase-{phase}", ctx.run_id))
.join(format!("round-{round}-{role}-t0"));
let scope = std::fs::read_to_string(dir.join("scope.md")).expect("a scope file");
let sid = format!("r{round}{role}");
let folder = ctx.home.join("sessions").join(&sid);
std::fs::create_dir_all(&folder).unwrap();
let post = |state: &Value| {
let mut state = state.clone();
state["schema"] = json!(crate::session_reader::SCHEMA);
std::fs::write(folder.join("state.json.tmp"), state.to_string()).unwrap();
std::fs::rename(folder.join("state.json.tmp"), folder.join("state.json"))
.unwrap();
state
};
let locked =
post(&json!({ "loop": { "driving": true, "round": round, "role": role } }));
note_page(&ctx.slot, "review", &sid, &locked);
let mut done = locked.clone();
done["roundOutcome"] = outcome;
done["docs"] = json!([{ "id": "report", "kind": "report", "title": "Review round",
"blocks": [{ "id": "r", "md": "Found things to fix." }] }]);
post(&done);
seen.push(Seen { scope, banner });
}
seen
})
}
/// A phase report whose own review left one Warning, the way a phase agent
/// that could not fix it reports it.
fn findings_report(phase: u32) -> Value {
let mut report = good_report(phase);
report["result"] = json!("failed");
report["reason"] = json!("findings");
report["review"] = json!({
"ran": true, "recheck": true,
"left": { "critical": 0, "warning": 1, "suggestion": 0 },
"unfixed": [{ "level": "warning", "title": "Close the handle", "file": "work.txt" }],
});
report
}
/// A running loop on a throwaway repo whose Phase 2 is built (tasks ticked,
/// one file written) after the start snapshot the rounds measure from.
fn built_phase(name: &str) -> (Ctx, PathBuf, PathBuf) {
let repo = throwaway_repo(name);
let (ctx, home) = running_loop(&repo, quick_limits());
lock(&ctx.slot).as_mut().unwrap().phase_start =
Some(round_boundary::snapshot(&repo).unwrap());
finish_phase_tasks(&repo, 2);
std::fs::write(repo.join("work.txt"), "phase work\n").unwrap();
(ctx, repo, home)
}
#[test]
fn a_phase_with_a_warning_left_runs_fresh_rounds_then_commits_once() {
if !harness_ready("extra rounds") {
return;
}
let (ctx, repo, home) = built_phase("extra-rounds");
let before = git_in(&repo, &["rev-list", "--count", "HEAD"]);
write_session(&home, json!({ "loopOutcome": findings_report(2) }));
let player = play_rounds(
&ctx,
vec![
(1, "reviewer", round_json(1, "reviewer", 0, 1)),
(1, "fixer", round_json(1, "fixer", 0, 1)),
(2, "reviewer", round_json(2, "reviewer", 0, 0)),
],
);
assert!(tick(&ctx), "the clean round 2 lets the phase pass");
let seen = player.join().unwrap();
assert_eq!(seen[0].banner, "Review round 1 of 2");
assert_eq!(seen[2].banner, "Review round 2 of 2");
assert!(
seen[0].scope.contains("everything the phase changed"),
"{}",
seen[0].scope
);
let diff = seen[0]
.scope
.lines()
.find_map(|l| l.strip_prefix("- "))
.unwrap();
let diff = std::fs::read_to_string(diff).unwrap();
assert!(diff.contains("work.txt"), "the whole phase diff: {diff}");
assert!(
seen[1].scope.contains("Close the handle")
&& seen[1].scope.contains("reviewer-report.md"),
"the fixer is briefed with the unfixed list: {}",
seen[1].scope
);
assert!(
!seen[0].scope.contains("Close the handle"),
"the reviewer sees no brief"
);
assert!(
seen[2].scope.contains("previous round's changes"),
"{}",
seen[2].scope
);
let after = git_in(&repo, &["rev-list", "--count", "HEAD"]);
assert_eq!(
after.parse::<u32>().unwrap(),
before.parse::<u32>().unwrap() + 1,
"one commit for the phase"
);
assert_eq!(
git_in(&repo, &["log", "-1", "--format=%s"]),
"Add the driver"
);
assert!(git_in(&repo, &["show", "--name-only", "--format=", "HEAD"]).contains("work.txt"));
let entry = last_entry_saved(&home, &repo);
assert_eq!(entry.result, EntryResult::Passed);
assert_eq!(entry.rounds.len(), 2);
assert_eq!((entry.rounds[0].warning, entry.rounds[1].warning), (1, 0));
let md = loop_report::body_markdown(&lock(&ctx.slot).as_ref().unwrap().report);
assert!(
md.contains("Extra review rounds: 2 (left after: 0 Critical, 0 Warning)"),
"{md}"
);
end_the_test(&ctx);
}
#[test]
fn findings_left_after_the_rounds_judge_the_phase_with_those_counts() {
if !harness_ready("extra rounds cap") {
return;
}
let (ctx, repo, home) = built_phase("extra-rounds-cap");
lock(&ctx.slot).as_mut().unwrap().setup.review_rounds = 1;
// The phase agent leaves two Warnings; the one round leaves one, so only
// the last round's count can make the stop line say "1 Warning".
let mut report = findings_report(2);
report["review"]["left"]["warning"] = json!(2);
report["review"]["unfixed"]
.as_array_mut()
.unwrap()
.push(json!({ "level": "warning", "title": "Name the timer", "file": "work.txt" }));
write_session(&home, json!({ "loopOutcome": report }));
let player = play_rounds(
&ctx,
vec![
(1, "reviewer", round_json(1, "reviewer", 0, 1)),
(1, "fixer", round_json(1, "fixer", 0, 1)),
],
);
assert!(
!tick(&ctx),
"a Warning left after the only round stops the phase"
);
player.join().unwrap();
let entry = last_entry_saved(&home, &repo);
assert_eq!(entry.result, EntryResult::Stopped);
assert!(
entry.line.contains("1 Warning left after the re-check"),
"{}",
entry.line
);
assert_eq!(entry.rounds.len(), 1);
assert_eq!(
git_in(&repo, &["rev-list", "--count", "HEAD"]),
"1",
"nothing was committed"
);
end_the_test(&ctx);
}
#[test]
fn no_rounds_run_when_nothing_is_left_when_they_are_zero_or_when_review_is_off() {
if !harness_ready("extra rounds skipped") {
return;
}
// Nothing left: the phase commits as before and no round folder appears.
let (ctx, repo, home) = built_phase("extra-none");
write_session(&home, json!({ "loopOutcome": good_report(2) }));
assert!(tick(&ctx));
assert!(last_entry_saved(&home, &repo).rounds.is_empty());
assert!(!home.join("loop-phase-rounds").exists());
end_the_test(&ctx);
// Zero rounds: the Warning stops the phase as it always did.
let (ctx, repo, home) = built_phase("extra-zero");
lock(&ctx.slot).as_mut().unwrap().setup.review_rounds = 0;
write_session(&home, json!({ "loopOutcome": findings_report(2) }));
assert!(!tick(&ctx));
assert!(last_entry_saved(&home, &repo).rounds.is_empty());
assert!(!home.join("loop-phase-rounds").exists());
end_the_test(&ctx);
// Review off: the setting means nothing, and the report judges as before.
let (ctx, repo, home) = built_phase("extra-off");
lock(&ctx.slot).as_mut().unwrap().setup.review = false;
write_session(&home, json!({ "loopOutcome": findings_report(2) }));
let _ = tick(&ctx);
assert!(last_entry_saved(&home, &repo).rounds.is_empty());
assert!(!home.join("loop-phase-rounds").exists());
end_the_test(&ctx);
}
}