mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-29 05:11:19 -08:00
Add the Review Loop: unattended review-and-fix rounds in the desktop app and in loop phases
AI Assisted
This commit is contained in:
1 parent
d6a28b5dc8
commit
57567d7a0b
71 files changed
+11331
-443
No files matched your search
@@ -10,6 +10,13 @@
|
||||
//! REPORT <json> write <json> as `loopOutcome` into the session's state.json
|
||||
//! (PLAN2CODE_CONSOLE_HOME and PLAN2CODE_CONSOLE_SID name it), say
|
||||
//! `REPORT written` (`REPORT unavailable` when either is missing)
|
||||
//! ROUND <json> write <json> as `roundOutcome` the same way; when it names a
|
||||
//! `report` id, first add that doc (`kind: report`) to `docs`.
|
||||
//! Says `ROUND written` (`ROUND unavailable` when it cannot)
|
||||
//! FILE <path> <text> write <text> to <path> under the working directory (`\n`
|
||||
//! in the text is a line break), for a round's "fixes". Says
|
||||
//! `FILE written <path>` (`FILE refused <path>` for a path that
|
||||
//! leaves the folder)
|
||||
//! ENV <name> print the variable as `ENV <name>=<value>`
|
||||
//! HANG say `HANGING`, then go silent for good (no more lines read)
|
||||
//! <other> echoed back as `echo: <line>`
|
||||
@@ -43,6 +50,10 @@ pub enum Command {
|
||||
Env(String),
|
||||
/// `REPORT <json>`: the phase report the loop waits for, as the JSON text.
|
||||
Report(String),
|
||||
/// `ROUND <json>`: a Review Loop round's report, as the JSON text.
|
||||
Round(String),
|
||||
/// `FILE <path> <text>`: a file the agent "fixed", relative to its folder.
|
||||
File(String, String),
|
||||
/// `HANG`: go silent, to model an agent that stops answering.
|
||||
Hang,
|
||||
Echo(String),
|
||||
@@ -65,6 +76,47 @@ fn write_report_to(home: &std::path::Path, sid: &str, json: &str) -> bool {
|
||||
let Ok(outcome) = serde_json::from_str::<serde_json::Value>(json) else {
|
||||
return false;
|
||||
};
|
||||
update_state(home, sid, |state| state["loopOutcome"] = outcome)
|
||||
}
|
||||
|
||||
/// Write the JSON as the `roundOutcome` of the session named by the environment.
|
||||
fn write_round(json: &str) -> bool {
|
||||
let (Ok(home), Ok(sid)) = (
|
||||
std::env::var("PLAN2CODE_CONSOLE_HOME"),
|
||||
std::env::var("PLAN2CODE_CONSOLE_SID"),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
write_round_to(std::path::Path::new(&home), &sid, json)
|
||||
}
|
||||
|
||||
/// `write_round` with the session named. A named `report` is added to `docs`
|
||||
/// first, as the console would hold it, so the app finds the doc it checks for.
|
||||
fn write_round_to(home: &std::path::Path, sid: &str, json: &str) -> bool {
|
||||
let Ok(outcome) = serde_json::from_str::<serde_json::Value>(json) else {
|
||||
return false;
|
||||
};
|
||||
update_state(home, sid, |state| {
|
||||
if let Some(report) = outcome.get("report").and_then(|value| value.as_str()) {
|
||||
let doc =
|
||||
serde_json::json!({ "id": report, "kind": "report", "title": "Review round" });
|
||||
match state.get_mut("docs").and_then(|docs| docs.as_array_mut()) {
|
||||
Some(docs) => docs.push(doc),
|
||||
None => state["docs"] = serde_json::json!([doc]),
|
||||
}
|
||||
}
|
||||
state["roundOutcome"] = outcome;
|
||||
})
|
||||
}
|
||||
|
||||
/// Read `<home>/sessions/<sid>/state.json` (a new object when it is missing or
|
||||
/// not one), let `change` edit it, and write it back through a temp file and a
|
||||
/// rename, so a reader never sees half a file.
|
||||
fn update_state(
|
||||
home: &std::path::Path,
|
||||
sid: &str,
|
||||
change: impl FnOnce(&mut serde_json::Value),
|
||||
) -> bool {
|
||||
let dir = home.join("sessions").join(sid);
|
||||
let file = dir.join("state.json");
|
||||
let mut state = std::fs::read_to_string(&file)
|
||||
@@ -73,7 +125,7 @@ fn write_report_to(home: &std::path::Path, sid: &str, json: &str) -> bool {
|
||||
.filter(|value| value.is_object())
|
||||
// The console's own file always carries its schema number; a new one does too.
|
||||
.unwrap_or_else(|| serde_json::json!({ "schema": 1 }));
|
||||
state["loopOutcome"] = outcome;
|
||||
change(&mut state);
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let temp = dir.join("state.json.tmp");
|
||||
let Ok(text) = serde_json::to_string(&state) else {
|
||||
@@ -109,12 +161,45 @@ pub fn parse(line: &str) -> Command {
|
||||
return Command::Report(json.to_string());
|
||||
}
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix("ROUND ") {
|
||||
let json = rest.trim();
|
||||
if serde_json::from_str::<serde_json::Value>(json).is_ok() {
|
||||
return Command::Round(json.to_string());
|
||||
}
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix("FILE ") {
|
||||
let rest = rest.trim_start();
|
||||
if let Some((path, text)) = rest.split_once(char::is_whitespace) {
|
||||
return Command::File(path.to_string(), text.trim_start().to_string());
|
||||
}
|
||||
}
|
||||
if line == "HANG" {
|
||||
return Command::Hang;
|
||||
}
|
||||
Command::Echo(line.to_string())
|
||||
}
|
||||
|
||||
/// Write `text` to `relative` under the working directory. Refuses a path that
|
||||
/// is absolute or climbs out of it. `\n` in `text` becomes a line break.
|
||||
fn write_file(relative: &str, text: &str) -> bool {
|
||||
use std::path::{Component, Path};
|
||||
let path = Path::new(relative);
|
||||
let inside = !relative.is_empty()
|
||||
&& path
|
||||
.components()
|
||||
.all(|part| matches!(part, Component::Normal(_) | Component::CurDir));
|
||||
if !inside {
|
||||
return false;
|
||||
}
|
||||
if let Some(parent) = path
|
||||
.parent()
|
||||
.filter(|parent| !parent.as_os_str().is_empty())
|
||||
{
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
std::fs::write(path, text.replace("\\n", "\n")).is_ok()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
say("FAKE-AGENT ready");
|
||||
// What the app launched it with: the launch prompt is one of these, so a
|
||||
@@ -169,6 +254,20 @@ fn main() {
|
||||
say("REPORT unavailable")
|
||||
}
|
||||
}
|
||||
Command::Round(json) => {
|
||||
if write_round(&json) {
|
||||
say("ROUND written")
|
||||
} else {
|
||||
say("ROUND unavailable")
|
||||
}
|
||||
}
|
||||
Command::File(path, text) => {
|
||||
if write_file(&path, &text) {
|
||||
say(&format!("FILE written {path}"))
|
||||
} else {
|
||||
say(&format!("FILE refused {path}"))
|
||||
}
|
||||
}
|
||||
Command::Hang => {
|
||||
say("HANGING");
|
||||
loop {
|
||||
@@ -230,6 +329,87 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_round_and_file() {
|
||||
assert_eq!(
|
||||
parse("ROUND {\"round\":1}"),
|
||||
Command::Round("{\"round\":1}".into())
|
||||
);
|
||||
assert_eq!(parse("ROUND {nope"), Command::Echo("ROUND {nope".into()));
|
||||
assert_eq!(
|
||||
parse("FILE src/a.rs fixed it\\nline two"),
|
||||
Command::File("src/a.rs".into(), "fixed it\\nline two".into())
|
||||
);
|
||||
assert_eq!(
|
||||
parse("FILE onlypath"),
|
||||
Command::Echo("FILE onlypath".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_round_lands_with_its_report_doc_beside_what_was_there() {
|
||||
let home = std::env::temp_dir().join(format!("fake-agent-round-{}", std::process::id()));
|
||||
let dir = home.join("sessions").join("s5");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let read = || -> serde_json::Value {
|
||||
serde_json::from_str(&std::fs::read_to_string(dir.join("state.json")).unwrap()).unwrap()
|
||||
};
|
||||
// A report id adds the doc to a state that had none.
|
||||
assert!(write_round_to(
|
||||
&home,
|
||||
"s5",
|
||||
"{\"round\":1,\"role\":\"both\",\"report\":\"rep\"}"
|
||||
));
|
||||
let state = read();
|
||||
assert_eq!(state["roundOutcome"]["round"], 1);
|
||||
assert_eq!(state["docs"][0]["id"], "rep");
|
||||
assert_eq!(state["docs"][0]["kind"], "report");
|
||||
assert_eq!(state["docs"][0]["title"], "Review round");
|
||||
assert_eq!(state["schema"], 1);
|
||||
// Existing docs stay, and the new one is appended.
|
||||
std::fs::write(
|
||||
dir.join("state.json"),
|
||||
"{\"schema\":1,\"docs\":[{\"id\":\"phasefile\"}]}",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(write_round_to(
|
||||
&home,
|
||||
"s5",
|
||||
"{\"round\":2,\"report\":\"r2\"}"
|
||||
));
|
||||
let state = read();
|
||||
assert_eq!(state["docs"][0]["id"], "phasefile");
|
||||
assert_eq!(state["docs"][1]["id"], "r2");
|
||||
// No report id, no doc; a fixer's outcome adds none.
|
||||
std::fs::write(dir.join("state.json"), "{\"schema\":1}").unwrap();
|
||||
assert!(write_round_to(
|
||||
&home,
|
||||
"s5",
|
||||
"{\"round\":3,\"role\":\"fixer\"}"
|
||||
));
|
||||
let state = read();
|
||||
assert!(state.get("docs").is_none());
|
||||
assert_eq!(state["roundOutcome"]["role"], "fixer");
|
||||
// The loop's own report key is untouched by a round.
|
||||
assert!(state.get("loopOutcome").is_none());
|
||||
assert!(!write_round_to(&home, "s5", "not json"));
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_command_writes_under_the_working_folder_only() {
|
||||
let base = format!("fake-agent-file-{}", std::process::id());
|
||||
assert!(write_file(&format!("{base}/sub/a.txt"), "one\\ntwo"));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(format!("{base}/sub/a.txt")).unwrap(),
|
||||
"one\ntwo"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
assert!(!write_file("../escape.txt", "x"));
|
||||
assert!(!write_file("/abs.txt", "x"));
|
||||
assert!(!write_file("", "x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_with_bad_json_is_an_echo() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -78,6 +78,10 @@ pub struct AgentEntry {
|
||||
pub args: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub bypass_args: Vec<String>,
|
||||
/// The agent can start a subagent from inside a session. Missing means it
|
||||
/// cannot, so a custom agent without the key reads `false`.
|
||||
#[serde(default)]
|
||||
pub helpers: bool,
|
||||
#[serde(default)]
|
||||
pub model_args: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -1678,6 +1682,21 @@ mod tests {
|
||||
.all(|e| !e.command.is_empty() && !e.args.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helpers_is_true_for_claude_and_false_for_everything_else() {
|
||||
// The Review Loop picks its round shape from this flag: one session
|
||||
// with a reviewer subagent, or a reviewer session then a fixer one.
|
||||
let list = parse_agent_list(BAKED_AGENTS).expect("the baked list parses");
|
||||
for e in list.builtins.iter().chain(list.templates.iter()) {
|
||||
assert_eq!(e.helpers, e.id == "claude", "helpers for {}", e.id);
|
||||
}
|
||||
// An entry without the key reads false.
|
||||
let text =
|
||||
r#"{"schema":1,"agents":[{"id":"x","name":"X","kind":"template","command":"x"}]}"#;
|
||||
let list = parse_agent_list(text).expect("parses");
|
||||
assert!(!list.templates[0].helpers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_list_loader_rejects_a_bad_file_and_reads_the_installed_path() {
|
||||
// Not JSON, not an object, or the wrong schema is an error: the
|
||||
@@ -1809,6 +1828,7 @@ mod tests {
|
||||
prompt: String::new(),
|
||||
args: vec![],
|
||||
bypass_args: vec![],
|
||||
helpers: false,
|
||||
model_args: vec![],
|
||||
install_url: None,
|
||||
install: PerOs::default(),
|
||||
@@ -1985,10 +2005,11 @@ mod tests {
|
||||
let dir = temp_dir("find");
|
||||
let file = dir.join("agents.json");
|
||||
std::fs::write(&file, GOOSE).unwrap();
|
||||
assert_eq!(
|
||||
find_agent_in("claude", Some(&file)),
|
||||
Some(Agent::Builtin(entry("claude")))
|
||||
);
|
||||
// A built-in wins over the file. Only its identity is compared: the list the
|
||||
// lookup reads is the installed one, which a machine may still hold from before
|
||||
// a field was added, so a whole-entry comparison depended on that machine.
|
||||
let found = find_agent_in("claude", Some(&file));
|
||||
assert!(matches!(&found, Some(Agent::Builtin(e)) if e.id == entry("claude").id));
|
||||
let goose = find_agent_in("goose", Some(&file)).unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
|
||||
@@ -11,13 +11,19 @@ pub mod loop_commit;
|
||||
pub mod loop_driver;
|
||||
pub mod loop_notify;
|
||||
pub mod loop_report;
|
||||
pub mod loop_shared;
|
||||
pub mod loop_tools;
|
||||
pub mod models;
|
||||
pub mod node_check;
|
||||
pub mod phase_rounds;
|
||||
pub mod project;
|
||||
pub mod pty_host;
|
||||
pub mod quit_prompt;
|
||||
pub mod restart_brief;
|
||||
pub mod review_loop;
|
||||
pub mod review_report;
|
||||
pub mod round_boundary;
|
||||
pub mod round_logic;
|
||||
pub mod session_reader;
|
||||
pub mod settings;
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -32,10 +32,42 @@ pub struct Assumption {
|
||||
pub note: String,
|
||||
}
|
||||
|
||||
/// Which loop wrote an entry. Entries saved before the Review Loop existed
|
||||
/// carry no kind and read as `Implementation`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum EntryKind {
|
||||
#[default]
|
||||
Implementation,
|
||||
Review,
|
||||
}
|
||||
|
||||
/// One round of a Review Loop, as its entry keeps it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct RoundEntry {
|
||||
pub n: u32,
|
||||
pub critical: u32,
|
||||
pub warning: u32,
|
||||
pub suggestion: u32,
|
||||
pub fixed: Vec<String>,
|
||||
pub left_open: Vec<String>,
|
||||
pub commit: Option<String>,
|
||||
pub tests: String,
|
||||
pub started: String,
|
||||
pub ended: String,
|
||||
/// "Balanced" and so on, or empty for an agent run as launched.
|
||||
pub strength: String,
|
||||
pub retried: bool,
|
||||
}
|
||||
|
||||
/// One thing that happened to a phase, in the order it happened.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ReportEntry {
|
||||
pub kind: EntryKind,
|
||||
/// A Review Loop's rounds, in order; empty for an Implementation Loop phase.
|
||||
pub rounds: Vec<RoundEntry>,
|
||||
pub at: String,
|
||||
pub phase: u32,
|
||||
pub name: String,
|
||||
@@ -298,6 +330,23 @@ fn entry_markdown(md: &mut String, e: &ReportEntry) {
|
||||
if e.retries > 0 {
|
||||
md.push_str(&format!("- Retries: {}\n", e.retries));
|
||||
}
|
||||
if let Some(last) = e.rounds.last() {
|
||||
md.push_str(&format!(
|
||||
"- Extra review rounds: {} (left after: {} Critical, {} Warning)\n",
|
||||
e.rounds.len(),
|
||||
last.critical,
|
||||
last.warning
|
||||
));
|
||||
for round in &e.rounds {
|
||||
md.push_str(&format!(
|
||||
" - Round {}: {} Critical, {} Warning found, {} fixed\n",
|
||||
round.n,
|
||||
round.critical,
|
||||
round.warning,
|
||||
round.fixed.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
if !e.warnings.is_empty() {
|
||||
let notes: Vec<String> = e.warnings.iter().map(|w| cell(w)).collect();
|
||||
md.push_str(&format!("- Warnings: {}\n", notes.join("; ")));
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Loop machinery both the Implementation Loop (`loop_driver`) and the Review
|
||||
//! Loop call: starting an agent session, the watcher, the retry rule, the
|
||||
//! saved report list and the notification.
|
||||
|
||||
pub mod report_list;
|
||||
pub mod retry;
|
||||
pub mod rounds;
|
||||
pub mod session;
|
||||
pub mod watch;
|
||||
|
||||
use crate::loop_notify::{self, NotifyKind};
|
||||
|
||||
/// Send a notification of `kind` to `url`; the reason it failed, if it did.
|
||||
pub fn notify(kind: NotifyKind, url: &str, param: &str, message: &str) -> Result<(), String> {
|
||||
loop_notify::send(kind, url, param, message)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! The saved report list (`loop-reports.json`): one entry point for both the
|
||||
//! Implementation Loop and the Review Loop.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::loop_report::{self, LoopReport};
|
||||
|
||||
/// The saved report for `spec` in `project`, when there is one.
|
||||
pub fn load_reports(home: &Path, project: &Path, spec: &str) -> Option<LoopReport> {
|
||||
loop_report::load(home, project, spec)
|
||||
}
|
||||
|
||||
/// Save `report` for `project`.
|
||||
pub fn save_report(home: &Path, project: &Path, report: &LoopReport) -> Result<(), String> {
|
||||
loop_report::save(home, project, report)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//! The retry rule and the strength step-up, called by both the Implementation
|
||||
//! Loop and the Review Loop.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::loop_driver::{LoopSetup, StopCause};
|
||||
use crate::models::{self, StrengthRow};
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// The strength word one step above `current`, or `None` when there is none
|
||||
/// (Best stays, an unmapped word stays). A thin wrapper over
|
||||
/// `models::next_strength`, so a caller without a `RunningRecord` can step up.
|
||||
pub fn next_strength_word(
|
||||
resolved: &BTreeMap<String, StrengthRow>,
|
||||
current: &str,
|
||||
) -> Option<String> {
|
||||
models::next_strength(resolved, current)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//! The pieces of a review round both loops read the same way: whether an
|
||||
//! announced page is a round's session, the round's `roundOutcome` in a session
|
||||
//! state, the report text it names, the proofs the app checks for itself, and
|
||||
//! the reviewer's findings as the fixer's brief. The Review Loop and the
|
||||
//! Implementation Loop's extra review rounds (a phase's hook) both call them.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::round_logic::{Finding, Role, RoundOutcome, RoundProofs};
|
||||
|
||||
/// The word a role goes by in a console state and a prompt.
|
||||
pub fn role_word(role: Role) -> &'static str {
|
||||
match role {
|
||||
Role::Both => "both",
|
||||
Role::Reviewer => "reviewer",
|
||||
Role::Fixer => "fixer",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an announced page is this round's session: the agent locked it with
|
||||
/// `open --loop` for this round and role, and it holds no report yet.
|
||||
pub fn page_is_this_round(state: &Value, round: u32, role: Role) -> bool {
|
||||
state["loop"]["driving"].as_bool().unwrap_or(false)
|
||||
&& state["loop"]["round"].as_u64() == Some(u64::from(round))
|
||||
&& state["loop"]["role"].as_str() == Some(role_word(role))
|
||||
&& state.get("roundOutcome").is_none_or(Value::is_null)
|
||||
}
|
||||
|
||||
/// The round's outcome in `state`, when it is this round's and this role's.
|
||||
pub fn round_outcome_in(
|
||||
state: &Value,
|
||||
round: u32,
|
||||
role: Role,
|
||||
) -> Option<Result<RoundOutcome, String>> {
|
||||
let raw = state
|
||||
.get("roundOutcome")
|
||||
.filter(|value| value.is_object())?;
|
||||
match serde_json::from_value::<RoundOutcome>(raw.clone()) {
|
||||
Ok(outcome) => (outcome.round == round && outcome.role == role).then_some(Ok(outcome)),
|
||||
Err(err) => Some(Err(format!("the round's report could not be read ({err})"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of the report doc the outcome names, from the session's `docs`.
|
||||
pub fn report_text(state: &Value, id: &str) -> Option<String> {
|
||||
let doc = state["docs"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.find(|doc| doc["id"].as_str() == Some(id))?;
|
||||
let mut text = String::new();
|
||||
if let Some(blocks) = doc["blocks"].as_array() {
|
||||
for block in blocks {
|
||||
if let Some(md) = block["md"].as_str() {
|
||||
text.push_str(md);
|
||||
text.push_str("\n\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(text)
|
||||
}
|
||||
|
||||
pub fn proofs_for(state: &Value, outcome: &RoundOutcome, role: Role) -> RoundProofs {
|
||||
let report_doc_present = match role {
|
||||
Role::Fixer => true,
|
||||
_ => outcome
|
||||
.report
|
||||
.as_deref()
|
||||
.is_some_and(|id| report_text(state, id).is_some()),
|
||||
};
|
||||
let (tests_ran, tests_passed) = match role {
|
||||
// A reviewer changes nothing and is not asked for tests.
|
||||
Role::Reviewer => (true, true),
|
||||
_ => outcome
|
||||
.tests
|
||||
.as_ref()
|
||||
.map_or((false, false), |t| (t.ran, t.passed)),
|
||||
};
|
||||
RoundProofs {
|
||||
report_doc_present,
|
||||
tests_ran,
|
||||
tests_passed,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finding_line(finding: &Finding) -> String {
|
||||
match finding.line {
|
||||
Some(line) => format!("- {} ({}:{line})", finding.title, finding.file),
|
||||
None => format!("- {} ({})", finding.title, finding.file),
|
||||
}
|
||||
}
|
||||
|
||||
/// The reviewer's findings, as the fixer's brief: the report's text and the
|
||||
/// Critical and Warning findings the reviewer left unfixed.
|
||||
pub fn reviewer_brief(text: &str, outcome: &RoundOutcome) -> String {
|
||||
let mut brief = format!(
|
||||
"# Reviewer report\n\n{}\n\nFound: {} Critical, {} Warning, {} Suggestion.\n\n",
|
||||
text.trim(),
|
||||
outcome.review.critical,
|
||||
outcome.review.warning,
|
||||
outcome.review.suggestion
|
||||
);
|
||||
if !outcome.review.unfixed.is_empty() {
|
||||
brief.push_str("## Fix these\n\n");
|
||||
for finding in &outcome.review.unfixed {
|
||||
brief.push_str(&finding_line(finding));
|
||||
brief.push('\n');
|
||||
}
|
||||
}
|
||||
brief
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
//! What a loop needs to start an agent session and read its console state: the
|
||||
//! shared context, `start_session` and `read_session_state`. Both the
|
||||
//! Implementation Loop and the Review Loop call it.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::agent_manager::AgentManager;
|
||||
use crate::loop_driver::{self, Hooks, Launch, Limits, LoopSlot, Strength};
|
||||
use crate::models::StrengthRow;
|
||||
use crate::session_reader;
|
||||
|
||||
/// What the watch thread needs, shared by every step of one loop.
|
||||
#[derive(Clone)]
|
||||
pub struct Ctx {
|
||||
pub slot: LoopSlot,
|
||||
pub agent: Arc<AgentManager>,
|
||||
pub console_dir: PathBuf,
|
||||
pub home: PathBuf,
|
||||
pub launch: Launch,
|
||||
pub run_id: u64,
|
||||
pub hooks: Arc<Hooks>,
|
||||
pub limits: Limits,
|
||||
}
|
||||
|
||||
/// What a started session reports: the agent's generation and the model and
|
||||
/// effort it started on.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SessionStart {
|
||||
pub generation: u64,
|
||||
pub model: Option<String>,
|
||||
pub effort: Option<String>,
|
||||
}
|
||||
|
||||
/// Start a fresh agent on `prompt`. With `strength` (the word and its row) the
|
||||
/// agent starts on that row's model and effort with `PLAN2CODE_LOOP_STRENGTH`
|
||||
/// set; without it, on the agent's launch choice.
|
||||
pub fn start_session(
|
||||
ctx: &Ctx,
|
||||
prompt: &str,
|
||||
strength: Option<(Strength, &StrengthRow)>,
|
||||
) -> Result<SessionStart, String> {
|
||||
match strength {
|
||||
Some((word, row)) => {
|
||||
loop_driver::start_phase_with(&ctx.agent, &ctx.launch, prompt.to_string(), row, word)?
|
||||
}
|
||||
None => loop_driver::start_with(&ctx.agent, &ctx.launch, prompt.to_string())?,
|
||||
}
|
||||
let snapshot = ctx.agent.snapshot();
|
||||
Ok(SessionStart {
|
||||
generation: snapshot.generation,
|
||||
model: snapshot.model,
|
||||
effort: snapshot.effort,
|
||||
})
|
||||
}
|
||||
|
||||
/// The console state of session `sid`, or `None` when it cannot be read now.
|
||||
pub fn read_session_state(ctx: &Ctx, sid: &str) -> Option<serde_json::Value> {
|
||||
session_reader::load(&ctx.home, sid)
|
||||
.ok()
|
||||
.map(|session| session.state)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! The watcher's timing, the silence rule and the generic watch loop, called by
|
||||
//! both the Implementation Loop and the Review Loop.
|
||||
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use crate::loop_driver::LoopSetup;
|
||||
|
||||
/// How often the watcher looks at the running loop.
|
||||
pub const WATCH_EVERY: Duration = Duration::from_secs(2);
|
||||
/// How often silence looks at the session's files and the tree.
|
||||
pub const ACTIVITY_EVERY: Duration = Duration::from_secs(30);
|
||||
|
||||
/// What a step of the watch loop says to do next.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum WatchStep {
|
||||
Continue,
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// Look every `every` until `step` says `Stop`. A panic in `step` ends the
|
||||
/// watch and comes back as its text (`Some`), so the caller can end its loop
|
||||
/// with the "watcher failed" stop instead of leaving a loop running with
|
||||
/// nothing watching it; a normal stop returns `None`.
|
||||
pub fn watch_loop<F: FnMut() -> WatchStep>(every: Duration, mut step: F) -> Option<String> {
|
||||
loop {
|
||||
std::thread::sleep(every);
|
||||
let seen = std::panic::catch_unwind(std::panic::AssertUnwindSafe(&mut step));
|
||||
match seen {
|
||||
Ok(WatchStep::Continue) => {}
|
||||
Ok(WatchStep::Stop) => return None,
|
||||
Err(payload) => {
|
||||
return Some(
|
||||
payload
|
||||
.downcast_ref::<&str>()
|
||||
.map(|s| (*s).to_string())
|
||||
.or_else(|| payload.downcast_ref::<String>().cloned())
|
||||
.unwrap_or_else(|| "an unknown error".to_string()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::loop_driver::{FixMode, OnQuestion};
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
fn setup() -> LoopSetup {
|
||||
LoopSetup {
|
||||
fix_mode: FixMode::Levels,
|
||||
on_question: OnQuestion::Pause,
|
||||
..LoopSetup::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn at(minutes: u64) -> SystemTime {
|
||||
UNIX_EPOCH + Duration::from_secs(minutes * 60)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_watch_loop_stops_on_stop_and_returns_the_text_of_a_panic() {
|
||||
let none = Duration::ZERO;
|
||||
let mut calls = 0;
|
||||
let stopped = watch_loop(none, || {
|
||||
calls += 1;
|
||||
if calls < 3 {
|
||||
WatchStep::Continue
|
||||
} else {
|
||||
WatchStep::Stop
|
||||
}
|
||||
});
|
||||
assert_eq!((stopped, calls), (None, 3));
|
||||
let quiet = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(|_| {}));
|
||||
let literal = watch_loop(none, || panic!("literal"));
|
||||
let text = "formatted".to_string();
|
||||
let owned = watch_loop(none, || panic!("{text}"));
|
||||
let other = watch_loop(none, || std::panic::panic_any(1_u8));
|
||||
std::panic::set_hook(quiet);
|
||||
assert_eq!(literal.as_deref(), Some("literal"));
|
||||
assert_eq!(owned.as_deref(), Some("formatted"));
|
||||
assert_eq!(other.as_deref(), Some("an unknown error"));
|
||||
}
|
||||
|
||||
#[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));
|
||||
}
|
||||
}
|
||||
@@ -600,11 +600,17 @@ pub fn git_head_short(project: &Path) -> Option<String> {
|
||||
(run.ok && !hash.is_empty()).then(|| hash.to_string())
|
||||
}
|
||||
|
||||
/// The full hash of `HEAD`, when there is a commit.
|
||||
pub fn git_head_full(project: &Path) -> Option<String> {
|
||||
/// The full hash of `HEAD` (40 or 64 hex characters), or why there is none.
|
||||
pub fn git_head_full(project: &Path) -> Result<String, String> {
|
||||
let run = run_limited(git(project, &["rev-parse", "HEAD"]), None, QUICK_LIMIT);
|
||||
let hash = run.output.trim();
|
||||
(run.ok && !hash.is_empty()).then(|| hash.to_string())
|
||||
if !run.ok {
|
||||
return Err("git could not read the current commit".to_string());
|
||||
}
|
||||
if !matches!(hash.len(), 40 | 64) || !hash.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err("git did not return a full commit id".to_string());
|
||||
}
|
||||
Ok(hash.to_string())
|
||||
}
|
||||
|
||||
/// The paths `git status --porcelain=v1 -z` lists (renames name the new path).
|
||||
@@ -799,6 +805,36 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&repo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_full_head_hash_starts_with_the_short_one() {
|
||||
if Command::new("git").arg("--version").output().is_err() {
|
||||
assert!(std::env::var_os("CI").is_none(), "git is not on PATH");
|
||||
return;
|
||||
}
|
||||
let repo = std::env::temp_dir().join(format!("plan2code-head-full-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&repo);
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
let git_in = |args: &[&str]| {
|
||||
let status = Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@example.com"])
|
||||
.args(args)
|
||||
.current_dir(&repo)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "git {args:?}");
|
||||
};
|
||||
git_in(&["init", "-q"]);
|
||||
assert!(git_head_full(&repo).is_err(), "no commit yet");
|
||||
std::fs::write(repo.join("a.txt"), "x").unwrap();
|
||||
git_in(&["add", "-A"]);
|
||||
git_in(&["commit", "-q", "--no-gpg-sign", "-m", "first"]);
|
||||
let full = git_head_full(&repo).unwrap();
|
||||
let short = git_head_short(&repo).unwrap();
|
||||
assert!(full.starts_with(&short), "{full} / {short}");
|
||||
assert!(matches!(full.len(), 40 | 64));
|
||||
let _ = std::fs::remove_dir_all(&repo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_commit_message_is_read_from_the_scripts_output_without_a_shell() {
|
||||
let ok = r#"{"ok":true,"subject":"Add it","message":"Add it\n\nAI Assisted"}"#;
|
||||
|
||||
@@ -18,6 +18,7 @@ use plan2code_app_lib::node_check;
|
||||
use plan2code_app_lib::project::{self, ProjectDir};
|
||||
use plan2code_app_lib::quit_prompt::{loop_quit_prompt, quit_prompt, QuitCase};
|
||||
use plan2code_app_lib::restart_brief;
|
||||
use plan2code_app_lib::review_loop::{self, ReviewSlot};
|
||||
use plan2code_app_lib::session_reader;
|
||||
use plan2code_app_lib::settings;
|
||||
#[cfg(windows)]
|
||||
@@ -54,6 +55,9 @@ struct AppState {
|
||||
// The Implementation Loop running now, if any: in memory only, so an app
|
||||
// restart ends it (NFR-5).
|
||||
loop_run: LoopSlot,
|
||||
// The Review Loop running now, or the one that stopped and waits for
|
||||
// Continue or its report: in memory only, so an app restart ends it.
|
||||
review_run: ReviewSlot,
|
||||
// The last loop's project, spec, launch choice and confirmed quick check,
|
||||
// kept after the running record is gone so Resume, Fix together with an agent and
|
||||
// Finalize still work. Memory only.
|
||||
@@ -450,7 +454,7 @@ fn sync_agent_env(app: &tauri::AppHandle) {
|
||||
// commands, and `agent_input` stays open so a trust or login prompt can be
|
||||
// answered.
|
||||
fn refuse_while_looping(state: &AppState, what: &str) -> Result<(), String> {
|
||||
if loop_driver::is_running(&state.loop_run) {
|
||||
if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) {
|
||||
return Err(format!(
|
||||
"A loop is running. Stop it before you change the {what}."
|
||||
));
|
||||
@@ -729,6 +733,7 @@ fn confirm_quit(app: &tauri::AppHandle) {
|
||||
fn agent_is_active(app: &tauri::AppHandle) -> bool {
|
||||
let state = app.state::<AppState>();
|
||||
loop_driver::is_running(&state.loop_run)
|
||||
|| review_loop::is_running(&state.review_run)
|
||||
|| current_agent(&state).is_some_and(|agent| agent.is_active())
|
||||
}
|
||||
|
||||
@@ -739,6 +744,7 @@ fn quit_app(app: &tauri::AppHandle) {
|
||||
let restart = RESTART_ON_QUIT.lock().ok().and_then(|mut plan| plan.take());
|
||||
let state = app.state::<AppState>();
|
||||
loop_driver::abandon(&state.loop_run);
|
||||
review_loop::abandon(&state.review_run);
|
||||
if let Some(agent) = current_agent(&state) {
|
||||
agent.stop();
|
||||
}
|
||||
@@ -1410,8 +1416,8 @@ async fn start_loop(
|
||||
spec: String,
|
||||
skip_confirm_if_same: bool,
|
||||
) -> Result<bool, String> {
|
||||
if loop_driver::is_running(&state.loop_run) {
|
||||
return Err("A loop is already running".to_string());
|
||||
if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) {
|
||||
return Err("A loop is already running in this window.".to_string());
|
||||
}
|
||||
let project = state
|
||||
.project
|
||||
@@ -1601,11 +1607,203 @@ fn loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<()
|
||||
#[tauri::command]
|
||||
fn loop_state(state: State<'_, AppState>) -> Option<loop_driver::LoopStateEvent> {
|
||||
loop_driver::current_event(&state.loop_run)
|
||||
.or_else(|| review_loop::current_event(&state.review_run))
|
||||
}
|
||||
|
||||
// The project folder and the agent a Review Loop would use, or why there is none.
|
||||
fn review_target(
|
||||
state: &AppState,
|
||||
) -> Result<(std::path::PathBuf, Arc<AgentManager>, loop_driver::Launch), String> {
|
||||
let project = state
|
||||
.project
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.as_ref()
|
||||
.map(|p| p.dir.clone())
|
||||
.ok_or("no project folder chosen")?;
|
||||
let agent = current_agent(state)
|
||||
.filter(|a| a.folder() == &project)
|
||||
.ok_or("Start an agent first, with permission checks off.")?;
|
||||
// A stopped agent has forgotten its launch choice; the run kept its own.
|
||||
let launch = agent
|
||||
.launch_choice()
|
||||
.or_else(|| {
|
||||
state
|
||||
.review_run
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|run| run.as_ref().map(|r| r.launch.clone()))
|
||||
})
|
||||
.ok_or("Start an agent first, with permission checks off.")?;
|
||||
Ok((project, agent, launch))
|
||||
}
|
||||
|
||||
// What the Review Loop's setup screen shows about the agent a run would use,
|
||||
// and the notification settings the Implementation Loop's setup holds.
|
||||
#[tauri::command]
|
||||
fn review_loop_facts(state: State<'_, AppState>) -> review_loop::ReviewFacts {
|
||||
let running =
|
||||
loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run);
|
||||
let project = state
|
||||
.project
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|guard| guard.as_ref().map(|p| p.dir.clone()));
|
||||
let setup = project
|
||||
.as_deref()
|
||||
.and_then(|dir| loop_driver::read_setup(dir).ok())
|
||||
.unwrap_or_default();
|
||||
let agent = current_agent(&state)
|
||||
.and_then(|a| a.launch_choice())
|
||||
.map(|choice| choice.0)
|
||||
.or_else(|| state.launch.agent.as_deref().and_then(agents::find_agent));
|
||||
review_loop::facts(agent.as_ref(), running, &setup)
|
||||
}
|
||||
|
||||
// Starts a Review Loop. Async and off the main thread: the pre-run commit and
|
||||
// the start boundary run git. The notification comes from the Implementation
|
||||
// Loop's setup file, never from the page's message.
|
||||
#[tauri::command]
|
||||
async fn review_loop_start(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
setup: review_loop::ReviewRequest,
|
||||
) -> Result<bool, String> {
|
||||
let (project, agent, launch) = review_target(&state)?;
|
||||
let loop_setup = loop_driver::read_setup(&project).unwrap_or_default();
|
||||
let setup = setup.into_setup(&loop_setup);
|
||||
let (slot, phases) = (state.review_run.clone(), state.loop_run.clone());
|
||||
let hooks = loop_hooks(&app);
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
review_loop::start_review_loop(&slot, &phases, agent, launch, project, setup, hooks)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// Stop after this round: it finishes, is judged and committed, then the run stops.
|
||||
#[tauri::command]
|
||||
fn review_loop_stop_after(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
on: bool,
|
||||
) -> Result<(), String> {
|
||||
let event = review_loop::request_stop_after(&state.review_run, on)?;
|
||||
let _ = app.emit("loop-state", &event);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Stop now: the flag first, then the agent ends at once. Nothing more is
|
||||
// committed; the stop screen offers Keep or Discard for the partial changes.
|
||||
#[tauri::command]
|
||||
fn review_loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
let agent = current_agent(&state);
|
||||
review_loop::request_stop_now(&state.review_run, agent.as_deref(), |event| {
|
||||
let _ = app.emit("loop-state", event);
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Keep the partial changes of a Stop now, or put the tree back to the last
|
||||
// finished round.
|
||||
#[tauri::command]
|
||||
async fn review_loop_partial(state: State<'_, AppState>, keep: bool) -> Result<(), String> {
|
||||
let home = session_reader::console_home().ok_or("no home folder found")?;
|
||||
let slot = state.review_run.clone();
|
||||
// The end screen is posted through node, so this is not main-thread work.
|
||||
tauri::async_runtime::spawn_blocking(move || review_loop::settle_partial(&slot, keep, &home))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
}
|
||||
|
||||
// Sign off a finished Review Loop: fix the Suggestions the person ticked (one
|
||||
// fixer session and its fresh check), squash the round commits when asked, and
|
||||
// show the finished screen. Async and off the main thread: it runs git.
|
||||
#[tauri::command]
|
||||
async fn review_loop_sign_off(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
picks: Vec<String>,
|
||||
squash: bool,
|
||||
) -> Result<(), String> {
|
||||
let (project, agent, _) = review_target(&state)?;
|
||||
let same_project = state
|
||||
.review_run
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|run| run.as_ref().map(|r| r.project == project));
|
||||
if same_project != Some(true) {
|
||||
return Err("The project changed since that Review Loop.".to_string());
|
||||
}
|
||||
let home = session_reader::console_home().ok_or("no home folder found")?;
|
||||
let (slot, phases) = (state.review_run.clone(), state.loop_run.clone());
|
||||
let hooks = loop_hooks(&app);
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
review_loop::sign_off(
|
||||
&slot,
|
||||
&phases,
|
||||
agent,
|
||||
hooks,
|
||||
loop_driver::Limits::default(),
|
||||
home,
|
||||
&picks,
|
||||
squash,
|
||||
true,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
}
|
||||
|
||||
// The finished screen's PR Prep and Fix what's left by hand: an ordinary
|
||||
// session on the skill, with no `--loop`, so the person talks to the agent.
|
||||
#[tauri::command]
|
||||
fn review_loop_next(state: State<'_, AppState>, next: String) -> Result<(), String> {
|
||||
let prompt = review_loop::next_prompt(&state.review_run, &next)?;
|
||||
let (_, agent, launch) = review_target(&state)?;
|
||||
loop_driver::start_with(&agent, &launch, prompt)
|
||||
}
|
||||
|
||||
// Continue a stopped Review Loop: the next round from the last boundary; past
|
||||
// the cap one round at a time, never above six in all.
|
||||
#[tauri::command]
|
||||
async fn review_loop_continue(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
let (project, agent, _) = review_target(&state)?;
|
||||
// A stopped run stays after a change of project: its git work would run
|
||||
// in the old folder while the agent works in the new one.
|
||||
let same_project = state
|
||||
.review_run
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|run| run.as_ref().map(|r| r.project == project));
|
||||
if same_project != Some(true) {
|
||||
return Err("The project changed since that Review Loop.".to_string());
|
||||
}
|
||||
let home = session_reader::console_home().ok_or("no home folder found")?;
|
||||
let (slot, phases) = (state.review_run.clone(), state.loop_run.clone());
|
||||
let hooks = loop_hooks(&app);
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
review_loop::continue_run(
|
||||
&slot,
|
||||
&phases,
|
||||
agent,
|
||||
hooks,
|
||||
loop_driver::Limits::default(),
|
||||
home,
|
||||
true,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
}
|
||||
|
||||
// The last loop, for the stop and finish screens' buttons.
|
||||
fn last_loop(state: &AppState) -> Result<LastLoop, String> {
|
||||
if loop_driver::is_running(&state.loop_run) {
|
||||
if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) {
|
||||
return Err("A loop is running".to_string());
|
||||
}
|
||||
let last = state
|
||||
@@ -1808,6 +2006,14 @@ fn main() {
|
||||
loop_stop_after_phase,
|
||||
loop_stop_now,
|
||||
loop_state,
|
||||
review_loop_facts,
|
||||
review_loop_start,
|
||||
review_loop_stop_after,
|
||||
review_loop_stop_now,
|
||||
review_loop_partial,
|
||||
review_loop_sign_off,
|
||||
review_loop_next,
|
||||
review_loop_continue,
|
||||
loop_resume,
|
||||
loop_fix,
|
||||
loop_ask,
|
||||
@@ -1848,6 +2054,7 @@ fn main() {
|
||||
.map(|session| session.state)
|
||||
.unwrap_or(serde_json::Value::Null);
|
||||
loop_driver::note_page(&state.loop_run, ¬ice.workflow, ¬ice.sid, &page);
|
||||
review_loop::note_page(&state.review_run, ¬ice.workflow, ¬ice.sid, &page);
|
||||
let _ = handle.emit("console-page", ¬ice);
|
||||
} else {
|
||||
eprintln!(
|
||||
|
||||
@@ -0,0 +1,631 @@
|
||||
//! 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<PhaseFinding>,
|
||||
/// 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<RoundEntry> },
|
||||
/// A round failed after its retry.
|
||||
Failed {
|
||||
reason: String,
|
||||
rounds: Vec<RoundEntry>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Done {
|
||||
pub rounds: Vec<RoundEntry>,
|
||||
pub critical: u32,
|
||||
pub warning: u32,
|
||||
pub suggestion: u32,
|
||||
pub unfixed: Vec<Finding>,
|
||||
}
|
||||
|
||||
/// How one session of a round ended.
|
||||
enum SessionEnd {
|
||||
Outcome(Box<RoundOutcome>, 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::<Vec<_>>().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<u64, String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<String>> {
|
||||
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<Played, Option<String>> {
|
||||
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<String> {
|
||||
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<Boundary, String> {
|
||||
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<RoundEntry> = 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
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,522 @@
|
||||
//! The Review Loop's end report: one markdown page that says why the run
|
||||
//! stopped and what every round found, fixed, committed and tested. Pure, like
|
||||
//! `loop_driver::summary_markdown()`: the driver hands it the run record and
|
||||
//! writes the text where it goes (the page, the report list and, for a spec
|
||||
//! launch, the spec folder).
|
||||
|
||||
use crate::review_loop::{BatchRecord, Mode, ReviewRun, ReviewScope, RoundRecord, Shape, Squash};
|
||||
use crate::round_logic::{Finding, StopReason, Verdict};
|
||||
|
||||
/// The stop reason in the words the report and the end screen lead with.
|
||||
pub fn reason_words(reason: Option<&StopReason>) -> &'static str {
|
||||
match reason {
|
||||
Some(StopReason::Clean) => "Clean",
|
||||
Some(StopReason::Cap) => "Stopped at the round cap",
|
||||
Some(StopReason::Person) => "Stopped by you",
|
||||
Some(StopReason::Failed(_)) => "Failed",
|
||||
None => "Not finished",
|
||||
}
|
||||
}
|
||||
|
||||
/// A commit id as people read it: the first seven characters.
|
||||
pub fn short_id(id: &str) -> &str {
|
||||
id.get(..7).unwrap_or(id)
|
||||
}
|
||||
|
||||
/// `title (file:line)`, leaving out what a finding does not name.
|
||||
pub fn finding_text(finding: &Finding) -> String {
|
||||
let title = one_line(&finding.title);
|
||||
match (finding.file.is_empty(), finding.line) {
|
||||
(true, _) => title,
|
||||
(false, None) => format!("{title} (`{}`)", finding.file),
|
||||
(false, Some(line)) => format!("{title} (`{}:{line}`)", finding.file),
|
||||
}
|
||||
}
|
||||
|
||||
fn one_line(text: &str) -> String {
|
||||
text.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
fn plural(n: usize, one: &str, many: &str) -> String {
|
||||
if n == 1 {
|
||||
format!("1 {one}")
|
||||
} else {
|
||||
format!("{n} {many}")
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_words(run: &ReviewRun) -> String {
|
||||
match (run.scope, run.setup.spec.as_deref()) {
|
||||
(ReviewScope::Spec, Some(spec)) => format!("the spec {spec}"),
|
||||
(ReviewScope::Spec, None) => "a spec".to_string(),
|
||||
(ReviewScope::Branch, _) => "the branch against its base".to_string(),
|
||||
(ReviewScope::Uncommitted, _) => "the uncommitted changes".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn verdict_words(verdict: Option<&Verdict>, critical: u32, warning: u32) -> String {
|
||||
match verdict {
|
||||
Some(Verdict::Clean) => "clean".to_string(),
|
||||
Some(Verdict::Findings { .. }) => format!("{critical} Critical, {warning} Warning"),
|
||||
Some(Verdict::Failed(reason)) => format!("did not finish ({})", one_line(reason)),
|
||||
None => "not checked".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn strength_words(round: &RoundRecord) -> String {
|
||||
let word = match round.strength.as_deref() {
|
||||
Some(word) if !word.is_empty() => word.to_string(),
|
||||
_ => "as launched".to_string(),
|
||||
};
|
||||
let model = match (round.model.as_deref(), round.effort.as_deref()) {
|
||||
(Some(model), Some(effort)) => Some(format!("{model}, {effort}")),
|
||||
(Some(model), None) => Some(model.to_string()),
|
||||
_ => None,
|
||||
};
|
||||
match model {
|
||||
Some(model) => format!("{word} ({model})"),
|
||||
None => word,
|
||||
}
|
||||
}
|
||||
|
||||
fn tests_words(round: &RoundRecord) -> String {
|
||||
match &round.tests {
|
||||
None => "not reported".to_string(),
|
||||
Some(t) => {
|
||||
let result = if !t.ran {
|
||||
"did not run"
|
||||
} else if t.passed {
|
||||
"passed"
|
||||
} else {
|
||||
"failed"
|
||||
};
|
||||
let summary = one_line(&t.summary);
|
||||
if summary.is_empty() {
|
||||
result.to_string()
|
||||
} else {
|
||||
format!("{summary} ({result})")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn commit_words(round_commit: Option<&str>, mode: Mode) -> String {
|
||||
match (round_commit, mode) {
|
||||
(Some(id), _) => format!("`{}`", short_id(id)),
|
||||
(None, Mode::Snapshot) => "not committed (snapshot mode)".to_string(),
|
||||
(None, Mode::Commit) => "not committed (nothing changed)".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn round_section(md: &mut String, round: &RoundRecord, mode: Mode) {
|
||||
md.push_str(&format!("\n## Round {}\n\n", round.n));
|
||||
md.push_str(&format!(
|
||||
"- Found: {} Critical, {} Warning, {} Suggestion ({})\n",
|
||||
round.critical,
|
||||
round.warning,
|
||||
round.suggestion,
|
||||
verdict_words(round.verdict.as_ref(), round.critical, round.warning)
|
||||
));
|
||||
if round.fixed.is_empty() {
|
||||
md.push_str("- Fixed: nothing\n");
|
||||
} else {
|
||||
let fixed: Vec<String> = round.fixed.iter().map(finding_text).collect();
|
||||
md.push_str(&format!("- Fixed: {}\n", fixed.join("; ")));
|
||||
}
|
||||
if !round.unfixed.is_empty() {
|
||||
let open: Vec<String> = round.unfixed.iter().map(finding_text).collect();
|
||||
md.push_str(&format!("- Left open: {}\n", open.join("; ")));
|
||||
}
|
||||
md.push_str(&format!(
|
||||
"- Commit: {}\n",
|
||||
commit_words(round.commit.as_deref(), mode)
|
||||
));
|
||||
md.push_str(&format!("- Targeted tests: {}\n", tests_words(round)));
|
||||
let time = match (round.started_at.is_empty(), round.ended_at.is_empty()) {
|
||||
(false, false) => format!("{} to {}", round.started_at, round.ended_at),
|
||||
(false, true) => format!("started {}", round.started_at),
|
||||
_ => "not recorded".to_string(),
|
||||
};
|
||||
md.push_str(&format!("- Time: {time}\n"));
|
||||
md.push_str(&format!("- Strength: {}\n", strength_words(round)));
|
||||
if round.retried {
|
||||
if round.could_not_step_up {
|
||||
md.push_str(
|
||||
"- Retry: one fresh session after a failure; it could not step up, so it ran at the same level\n",
|
||||
);
|
||||
} else {
|
||||
md.push_str("- Retry: one fresh session after a failure, one strength up\n");
|
||||
}
|
||||
}
|
||||
if !round.summary.trim().is_empty() {
|
||||
md.push_str(&format!("- Summary: {}\n", one_line(&round.summary)));
|
||||
}
|
||||
}
|
||||
|
||||
fn batch_section(md: &mut String, batch: &BatchRecord, mode: Mode, title: &str) {
|
||||
md.push_str(&format!("\n## {title}\n\n"));
|
||||
md.push_str(&format!(
|
||||
"- Briefed with {}\n",
|
||||
plural(batch.briefed.len(), "Suggestion", "Suggestions")
|
||||
));
|
||||
md.push_str(&format!(
|
||||
"- Commit: {}\n",
|
||||
commit_words(batch.commit.as_deref(), mode)
|
||||
));
|
||||
match &batch.final_check {
|
||||
Some(verdict) => md.push_str(&format!(
|
||||
"- Final check by a fresh reviewer: {}\n",
|
||||
verdict_words(Some(verdict), batch.final_critical, batch.final_warning)
|
||||
)),
|
||||
None => md.push_str("- Final check by a fresh reviewer: not run\n"),
|
||||
}
|
||||
if !batch.summary.trim().is_empty() {
|
||||
md.push_str(&format!("- Summary: {}\n", one_line(&batch.summary)));
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole report for `run`, as it stands: after a stop, and again after
|
||||
/// sign-off with what was picked and whether the squash ran.
|
||||
pub fn review_report_markdown(run: &ReviewRun) -> String {
|
||||
let reason = run.stop_reason.as_ref();
|
||||
let mut md = format!("# Review Loop: {}\n\n", reason_words(reason));
|
||||
if let Some(StopReason::Failed(why)) = reason {
|
||||
md.push_str(&format!("Why it failed: {}\n\n", one_line(why)));
|
||||
}
|
||||
let rounds_run = run.rounds.len();
|
||||
md.push_str(&format!(
|
||||
"- Rounds run: {} of at most {}\n",
|
||||
rounds_run, run.cap
|
||||
));
|
||||
md.push_str(&format!("- Reviewed: {}\n", scope_words(run)));
|
||||
md.push_str(&format!(
|
||||
"- Mode: {}\n",
|
||||
match run.mode {
|
||||
Mode::Commit => "each round committed",
|
||||
Mode::Snapshot => "snapshots only, nothing committed",
|
||||
}
|
||||
));
|
||||
md.push_str(&format!(
|
||||
"- Shape: {}\n",
|
||||
match run.shape {
|
||||
Shape::OneSession => "one session per round, with a helper reviewing",
|
||||
Shape::TwoSession => "two sessions per round, a reviewer and then a fixer",
|
||||
}
|
||||
));
|
||||
if let Some(id) = &run.pre_run_commit {
|
||||
md.push_str(&format!(
|
||||
"- Work before the run was committed first: `{}`\n",
|
||||
short_id(id)
|
||||
));
|
||||
}
|
||||
if let Some(evidence) = run
|
||||
.stop_evidence
|
||||
.as_deref()
|
||||
.filter(|e| !e.trim().is_empty())
|
||||
{
|
||||
md.push_str(&format!("- Evidence: {}\n", one_line(evidence)));
|
||||
}
|
||||
|
||||
for round in &run.rounds {
|
||||
round_section(&mut md, round, run.mode);
|
||||
}
|
||||
for batch in run
|
||||
.earlier_batches
|
||||
.iter()
|
||||
.chain(run.suggestions_batch.iter())
|
||||
{
|
||||
batch_section(&mut md, batch, run.mode, "Suggestions batch");
|
||||
}
|
||||
|
||||
md.push_str("\n## Still open\n\n");
|
||||
let open = run.open_findings();
|
||||
if open.is_empty() {
|
||||
md.push_str("No Critical or Warning findings are open.\n");
|
||||
} else {
|
||||
md.push_str("Critical or Warning findings no round fixed:\n\n");
|
||||
for finding in &open {
|
||||
md.push_str(&format!("- {}\n", finding_text(finding)));
|
||||
}
|
||||
}
|
||||
|
||||
md.push_str("\n## Suggestions\n\n");
|
||||
match &run.signoff {
|
||||
Some(signoff) => {
|
||||
if signoff.picked.is_empty() {
|
||||
md.push_str("Nothing was picked at sign-off.\n");
|
||||
} else {
|
||||
md.push_str("Picked at sign-off:\n\n");
|
||||
for finding in &signoff.picked {
|
||||
md.push_str(&format!("- {}\n", finding_text(finding)));
|
||||
}
|
||||
}
|
||||
if let Some(problem) = &signoff.problem {
|
||||
md.push_str(&format!("\nNot all were fixed: {}\n", one_line(problem)));
|
||||
}
|
||||
if !signoff.left.is_empty() {
|
||||
md.push_str("\nLeft alone:\n\n");
|
||||
for finding in &signoff.left {
|
||||
md.push_str(&format!("- {}\n", finding_text(finding)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let applied = run
|
||||
.earlier_batches
|
||||
.iter()
|
||||
.chain(run.suggestions_batch.iter());
|
||||
let applied_count: usize = applied.map(|batch| batch.briefed.len()).sum();
|
||||
if applied_count > 0 {
|
||||
md.push_str(&format!(
|
||||
"{} fixed in the batch above, with its final check.\n",
|
||||
plural(applied_count, "Suggestion was", "Suggestions were")
|
||||
));
|
||||
}
|
||||
if run.collected.is_empty() {
|
||||
if applied_count == 0 {
|
||||
md.push_str("No Suggestions were collected.\n");
|
||||
}
|
||||
} else {
|
||||
md.push_str("Waiting for you to pick at sign-off:\n\n");
|
||||
for finding in &run.collected {
|
||||
md.push_str(&format!("- {}\n", finding_text(finding)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(signoff) = &run.signoff {
|
||||
md.push_str("\n## Sign-off\n\n");
|
||||
let squash = match (&signoff.squash, signoff.squash_asked) {
|
||||
(Squash::Done { commit, commits }, _) => format!(
|
||||
"squashed {} into `{}`",
|
||||
plural(*commits, "commit", "commits"),
|
||||
short_id(commit)
|
||||
),
|
||||
(Squash::Refused(why), _) => format!("not squashed: {}", one_line(why)),
|
||||
(Squash::Off, _) => "not asked for".to_string(),
|
||||
};
|
||||
md.push_str(&format!("- Squash of the round commits: {squash}\n"));
|
||||
}
|
||||
|
||||
if let Some(partial) = run.partial.as_ref().filter(|p| p.pending) {
|
||||
md.push_str(&format!(
|
||||
"\n## Partial changes\n\nStop now left {} changed (+{} -{}) that are not committed, waiting for Keep or Discard.\n",
|
||||
plural(partial.files as usize, "file", "files"),
|
||||
partial.added,
|
||||
partial.removed
|
||||
));
|
||||
}
|
||||
md
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::loop_driver::tests::fake_agent_launch;
|
||||
use crate::review_loop::{ReviewSetup, SignOff};
|
||||
use crate::round_boundary::Boundary;
|
||||
use crate::round_logic::RoundTests;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn run_with(reason: Option<StopReason>) -> ReviewRun {
|
||||
let mut run = ReviewRun::new(
|
||||
PathBuf::from("."),
|
||||
ReviewSetup::default(),
|
||||
fake_agent_launch(),
|
||||
Mode::Commit,
|
||||
Shape::OneSession,
|
||||
Boundary::Commit("0000000000000000000000000000000000000000".to_string()),
|
||||
PathBuf::new(),
|
||||
BTreeMap::new(),
|
||||
);
|
||||
run.stop_reason = reason;
|
||||
run.running = false;
|
||||
run
|
||||
}
|
||||
|
||||
fn finding(title: &str, file: &str, line: Option<u32>) -> Finding {
|
||||
Finding {
|
||||
title: title.to_string(),
|
||||
file: file.to_string(),
|
||||
line,
|
||||
}
|
||||
}
|
||||
|
||||
fn round(n: u32, critical: u32, warning: u32) -> RoundRecord {
|
||||
RoundRecord {
|
||||
n,
|
||||
critical,
|
||||
warning,
|
||||
suggestion: 1,
|
||||
verdict: Some(if critical + warning == 0 {
|
||||
Verdict::Clean
|
||||
} else {
|
||||
Verdict::Findings { critical, warning }
|
||||
}),
|
||||
commit: Some("1234567890abcdef".to_string()),
|
||||
started_at: "2026-11-28 10:00".to_string(),
|
||||
ended_at: "2026-11-28 10:09".to_string(),
|
||||
tests: Some(RoundTests {
|
||||
ran: true,
|
||||
passed: true,
|
||||
summary: "14 pass".to_string(),
|
||||
}),
|
||||
..RoundRecord::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_stop_reason_leads_the_report_in_words() {
|
||||
let cases = [
|
||||
(Some(StopReason::Clean), "# Review Loop: Clean"),
|
||||
(
|
||||
Some(StopReason::Cap),
|
||||
"# Review Loop: Stopped at the round cap",
|
||||
),
|
||||
(Some(StopReason::Person), "# Review Loop: Stopped by you"),
|
||||
(
|
||||
Some(StopReason::Failed("tests failed".to_string())),
|
||||
"# Review Loop: Failed",
|
||||
),
|
||||
];
|
||||
for (reason, heading) in cases {
|
||||
let md = review_report_markdown(&run_with(reason));
|
||||
assert!(md.starts_with(heading), "{md}");
|
||||
}
|
||||
let failed = review_report_markdown(&run_with(Some(StopReason::Failed(
|
||||
"tests failed".to_string(),
|
||||
))));
|
||||
assert!(failed.contains("Why it failed: tests failed"), "{failed}");
|
||||
let clean = review_report_markdown(&run_with(Some(StopReason::Clean)));
|
||||
assert!(clean.contains("Rounds run: 0 of at most 3"), "{clean}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_round_says_its_findings_fixes_commit_tests_time_and_strength() {
|
||||
let mut run = run_with(Some(StopReason::Cap));
|
||||
let mut first = round(1, 2, 1);
|
||||
first.fixed = vec![finding("Close the handle", "src/a.rs", Some(12))];
|
||||
first.strength = Some("Balanced".to_string());
|
||||
first.model = Some("sonnet".to_string());
|
||||
first.effort = Some("low".to_string());
|
||||
run.rounds.push(first);
|
||||
let md = review_report_markdown(&run);
|
||||
assert!(md.contains("## Round 1"), "{md}");
|
||||
assert!(
|
||||
md.contains("Found: 2 Critical, 1 Warning, 1 Suggestion"),
|
||||
"{md}"
|
||||
);
|
||||
assert!(
|
||||
md.contains("Fixed: Close the handle (`src/a.rs:12`)"),
|
||||
"{md}"
|
||||
);
|
||||
assert!(md.contains("Commit: `1234567`"), "{md}");
|
||||
assert!(md.contains("Targeted tests: 14 pass (passed)"), "{md}");
|
||||
assert!(
|
||||
md.contains("Time: 2026-11-28 10:00 to 2026-11-28 10:09"),
|
||||
"{md}"
|
||||
);
|
||||
assert!(md.contains("Strength: Balanced (sonnet, low)"), "{md}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_without_strengths_reads_as_launched_and_a_same_level_retry_says_so() {
|
||||
let mut run = run_with(Some(StopReason::Cap));
|
||||
let mut r = round(1, 1, 0);
|
||||
r.retried = true;
|
||||
r.could_not_step_up = true;
|
||||
run.rounds.push(r);
|
||||
let md = review_report_markdown(&run);
|
||||
assert!(md.contains("Strength: as launched"), "{md}");
|
||||
assert!(
|
||||
md.contains("it could not step up, so it ran at the same level"),
|
||||
"{md}"
|
||||
);
|
||||
let mut stepped = run_with(Some(StopReason::Cap));
|
||||
let mut r = round(1, 1, 0);
|
||||
r.retried = true;
|
||||
r.strength = Some("Best".to_string());
|
||||
stepped.rounds.push(r);
|
||||
let md = review_report_markdown(&stepped);
|
||||
assert!(md.contains("one strength up"), "{md}");
|
||||
assert!(!md.contains("could not step up"), "{md}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_findings_show_their_file_and_line_and_a_clean_run_has_none() {
|
||||
let mut run = run_with(Some(StopReason::Cap));
|
||||
let mut last = round(2, 1, 1);
|
||||
last.unfixed = vec![
|
||||
finding("Missing check", "src/b.rs", Some(40)),
|
||||
finding("Wrong default", "src/c.rs", None),
|
||||
];
|
||||
run.rounds.push(last);
|
||||
let md = review_report_markdown(&run);
|
||||
assert!(md.contains("- Missing check (`src/b.rs:40`)"), "{md}");
|
||||
assert!(md.contains("- Wrong default (`src/c.rs`)"), "{md}");
|
||||
let mut clean = run_with(Some(StopReason::Clean));
|
||||
clean.rounds.push(round(1, 0, 0));
|
||||
let md = review_report_markdown(&clean);
|
||||
assert!(
|
||||
md.contains("No Critical or Warning findings are open."),
|
||||
"{md}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggestions_are_listed_to_pick_or_reported_as_applied_with_the_final_check() {
|
||||
let mut waiting = run_with(Some(StopReason::Clean));
|
||||
waiting.collected = vec![finding("Name the timer", "src/d.rs", Some(3))];
|
||||
let md = review_report_markdown(&waiting);
|
||||
assert!(md.contains("Waiting for you to pick at sign-off"), "{md}");
|
||||
assert!(md.contains("- Name the timer (`src/d.rs:3`)"), "{md}");
|
||||
|
||||
let mut applied = run_with(Some(StopReason::Clean));
|
||||
applied.suggestions_batch = Some(BatchRecord {
|
||||
briefed: vec![finding("Name the timer", "src/d.rs", None)],
|
||||
commit: Some("abcdef0123456789".to_string()),
|
||||
final_check: Some(Verdict::Clean),
|
||||
..BatchRecord::default()
|
||||
});
|
||||
let md = review_report_markdown(&applied);
|
||||
assert!(
|
||||
md.contains("1 Suggestion was fixed in the batch above"),
|
||||
"{md}"
|
||||
);
|
||||
assert!(
|
||||
md.contains("Final check by a fresh reviewer: clean"),
|
||||
"{md}"
|
||||
);
|
||||
assert!(md.contains("Commit: `abcdef0`"), "{md}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sign_off_records_the_picks_and_whether_the_squash_ran_or_was_refused() {
|
||||
let mut run = run_with(Some(StopReason::Cap));
|
||||
run.signoff = Some(SignOff {
|
||||
picked: vec![finding("Name the timer", "src/d.rs", None)],
|
||||
left: vec![finding("Tidy import", "src/e.rs", None)],
|
||||
squash_asked: true,
|
||||
squash: Squash::Done {
|
||||
commit: "fedcba9876543210".to_string(),
|
||||
commits: 3,
|
||||
},
|
||||
problem: None,
|
||||
});
|
||||
let md = review_report_markdown(&run);
|
||||
assert!(md.contains("Picked at sign-off"), "{md}");
|
||||
assert!(md.contains("Left alone"), "{md}");
|
||||
assert!(md.contains("squashed 3 commits into `fedcba9`"), "{md}");
|
||||
run.signoff.as_mut().unwrap().squash = Squash::Refused(
|
||||
"Something else was committed during the run, so the rounds were not squashed."
|
||||
.to_string(),
|
||||
);
|
||||
let md = review_report_markdown(&run);
|
||||
assert!(
|
||||
md.contains("not squashed: Something else was committed"),
|
||||
"{md}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
//! Where a Review Loop round starts and ends: a full commit id (commit mode) or
|
||||
//! a tree id from a snapshot of the working tree (snapshot mode), and the diff
|
||||
//! between any two of them. A snapshot never touches the real index, `HEAD` or
|
||||
//! the working tree: it adds everything to a copy of the index and writes a tree
|
||||
//! from that copy, the same technique as `snapshotTree` in `changes.mjs`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::loop_tools;
|
||||
|
||||
/// A point in the project's history a round can be measured from.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Boundary {
|
||||
/// A full commit id.
|
||||
Commit(String),
|
||||
/// A tree id written from a snapshot of the working tree.
|
||||
Tree(String),
|
||||
}
|
||||
|
||||
impl Boundary {
|
||||
/// The object id, whichever kind it is.
|
||||
pub fn id(&self) -> &str {
|
||||
match self {
|
||||
Boundary::Commit(id) | Boundary::Tree(id) => id,
|
||||
}
|
||||
}
|
||||
|
||||
fn peel(&self) -> String {
|
||||
match self {
|
||||
Boundary::Commit(id) => format!("{id}^{{commit}}"),
|
||||
Boundary::Tree(id) => format!("{id}^{{tree}}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a diff between two boundaries changed.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct DiffStats {
|
||||
pub files: u32,
|
||||
pub added: u32,
|
||||
pub removed: u32,
|
||||
}
|
||||
|
||||
fn git(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
|
||||
}
|
||||
|
||||
/// The first line git said on stderr, or `fallback`.
|
||||
fn why(stderr: &[u8], fallback: &str) -> String {
|
||||
String::from_utf8_lossy(stderr)
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find(|line| !line.is_empty())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| fallback.to_string())
|
||||
}
|
||||
|
||||
/// A hex object id (git's full ids are 40 or 64 characters).
|
||||
fn is_object_id(id: &str) -> bool {
|
||||
matches!(id.len(), 40 | 64) && id.chars().all(|c| c.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// The boundary at `HEAD`, as a full commit id.
|
||||
pub fn head(project: &Path) -> Result<Boundary, String> {
|
||||
loop_tools::git_head_full(project).map(Boundary::Commit)
|
||||
}
|
||||
|
||||
/// Deletes the copied index on every path out of `snapshot`.
|
||||
struct TempIndex(PathBuf);
|
||||
|
||||
impl Drop for TempIndex {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
static SNAPSHOTS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Snapshot the working tree (tracked, changed and untracked, ignored files
|
||||
/// left out) as a tree id, without touching the real index, `HEAD` or any file.
|
||||
pub fn snapshot(project: &Path) -> Result<Boundary, String> {
|
||||
let located = git(project, &["rev-parse", "--git-path", "index"])
|
||||
.output()
|
||||
.map_err(|err| format!("git could not run: {err}"))?;
|
||||
if !located.status.success() {
|
||||
return Err(format!(
|
||||
"git could not find the index: {}",
|
||||
why(&located.stderr, "not a git repository")
|
||||
));
|
||||
}
|
||||
let real = String::from_utf8_lossy(&located.stdout).trim().to_string();
|
||||
let temp = TempIndex(std::env::temp_dir().join(format!(
|
||||
"plan2code-round-index-{}-{}",
|
||||
std::process::id(),
|
||||
SNAPSHOTS.fetch_add(1, Ordering::Relaxed)
|
||||
)));
|
||||
if !real.is_empty() {
|
||||
let source = project.join(&real);
|
||||
if source.is_file() {
|
||||
std::fs::copy(&source, &temp.0)
|
||||
.map_err(|err| format!("could not copy the index: {err}"))?;
|
||||
}
|
||||
}
|
||||
let run = |args: &[&str]| {
|
||||
git(project, args)
|
||||
.env("GIT_INDEX_FILE", &temp.0)
|
||||
.output()
|
||||
.map_err(|err| format!("git could not run: {err}"))
|
||||
};
|
||||
let added = run(&["add", "-A"])?;
|
||||
if !added.status.success() {
|
||||
return Err(format!(
|
||||
"git could not snapshot the working tree: {}",
|
||||
why(&added.stderr, "git add failed")
|
||||
));
|
||||
}
|
||||
let written = run(&["write-tree"])?;
|
||||
let tree = String::from_utf8_lossy(&written.stdout).trim().to_string();
|
||||
if !written.status.success() || !is_object_id(&tree) {
|
||||
return Err(format!(
|
||||
"git could not write the snapshot: {}",
|
||||
why(&written.stderr, "git write-tree failed")
|
||||
));
|
||||
}
|
||||
Ok(Boundary::Tree(tree))
|
||||
}
|
||||
|
||||
/// Whether the boundary's object is still in the repository (git may collect
|
||||
/// an unreferenced snapshot tree).
|
||||
pub fn exists(project: &Path, b: &Boundary) -> bool {
|
||||
if !is_object_id(b.id()) {
|
||||
return false;
|
||||
}
|
||||
git(project, &["cat-file", "-e", &b.peel()])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.map(|status| status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Write the plain unified diff from `from` to `to` into `out`, and say how big
|
||||
/// it is. A boundary gone from the repository is refused by name.
|
||||
pub fn diff(
|
||||
project: &Path,
|
||||
from: &Boundary,
|
||||
to: &Boundary,
|
||||
out: &Path,
|
||||
) -> Result<DiffStats, String> {
|
||||
for side in [from, to] {
|
||||
if !exists(project, side) {
|
||||
return Err(format!("round boundary missing: {}", side.id()));
|
||||
}
|
||||
}
|
||||
// Fixed prefixes and no external driver: a user's diff settings must not
|
||||
// change what the round agent reads.
|
||||
let base = [
|
||||
"--no-color",
|
||||
"--no-ext-diff",
|
||||
"--src-prefix=a/",
|
||||
"--dst-prefix=b/",
|
||||
];
|
||||
let file = std::fs::File::create(out)
|
||||
.map_err(|err| format!("could not write {}: {err}", out.display()))?;
|
||||
let patch = git(project, &["diff"])
|
||||
.args(base)
|
||||
.arg(from.id())
|
||||
.arg(to.id())
|
||||
.stdout(Stdio::from(file))
|
||||
.stderr(Stdio::piped())
|
||||
.output()
|
||||
.map_err(|err| {
|
||||
let _ = std::fs::remove_file(out);
|
||||
format!("git could not run: {err}")
|
||||
})?;
|
||||
if !patch.status.success() {
|
||||
let _ = std::fs::remove_file(out);
|
||||
return Err(format!(
|
||||
"git diff failed: {}",
|
||||
why(&patch.stderr, "no reason given")
|
||||
));
|
||||
}
|
||||
let numstat = git(project, &["diff", "--numstat", "--no-ext-diff"])
|
||||
.arg(from.id())
|
||||
.arg(to.id())
|
||||
.output()
|
||||
.map_err(|err| {
|
||||
let _ = std::fs::remove_file(out);
|
||||
format!("git could not run: {err}")
|
||||
})?;
|
||||
if !numstat.status.success() {
|
||||
let _ = std::fs::remove_file(out);
|
||||
return Err(format!(
|
||||
"git diff failed: {}",
|
||||
why(&numstat.stderr, "no reason given")
|
||||
));
|
||||
}
|
||||
let mut stats = DiffStats::default();
|
||||
for line in String::from_utf8_lossy(&numstat.stdout).lines() {
|
||||
let mut parts = line.split('\t');
|
||||
let (Some(added), Some(removed)) = (parts.next(), parts.next()) else {
|
||||
continue;
|
||||
};
|
||||
stats.files += 1;
|
||||
// A binary file shows `-` for both.
|
||||
stats.added += added.parse::<u32>().unwrap_or(0);
|
||||
stats.removed += removed.parse::<u32>().unwrap_or(0);
|
||||
}
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn git_in(repo: &Path, args: &[&str]) -> String {
|
||||
let out = git(repo, args).output().expect("git runs");
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"git {args:?} failed: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
String::from_utf8_lossy(&out.stdout).to_string()
|
||||
}
|
||||
|
||||
/// A new repository in a unique temp folder with one commit, its config
|
||||
/// scrubbed of anything global (no autocrlf, no hooks, no signing).
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let repo = std::env::temp_dir()
|
||||
.join(format!("plan2code-round-{name}-{}", std::process::id()))
|
||||
.join("repo");
|
||||
let _ = std::fs::remove_dir_all(repo.parent().unwrap());
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git_in(&repo, &["init", "-q"]);
|
||||
for (key, value) in [
|
||||
("user.name", "Round Test"),
|
||||
("user.email", "round@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();
|
||||
git_in(&repo, &["add", "-A"]);
|
||||
git_in(&repo, &["commit", "-q", "-m", "first"]);
|
||||
repo
|
||||
}
|
||||
|
||||
fn cleanup(repo: &Path) {
|
||||
let _ = std::fs::remove_dir_all(repo.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_is_a_full_commit_id() {
|
||||
let repo = scratch("head");
|
||||
let boundary = head(&repo).unwrap();
|
||||
assert!(matches!(&boundary, Boundary::Commit(id) if is_object_id(id)));
|
||||
assert!(exists(&repo, &boundary));
|
||||
cleanup(&repo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_snapshot_leaves_status_and_the_index_unchanged() {
|
||||
let repo = scratch("untouched");
|
||||
std::fs::write(repo.join("a.txt"), "one\ntwo\nthree\n").unwrap();
|
||||
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
|
||||
// Settle git's own stat refresh before measuring.
|
||||
git_in(&repo, &["status", "--porcelain"]);
|
||||
let index = repo.join(".git/index");
|
||||
let before = std::fs::read(&index).unwrap();
|
||||
let head_before = git_in(&repo, &["rev-parse", "HEAD"]);
|
||||
let first = snapshot(&repo).unwrap();
|
||||
let second = snapshot(&repo).unwrap();
|
||||
assert_eq!(first, second, "the same tree twice");
|
||||
assert_eq!(std::fs::read(&index).unwrap(), before, "index bytes");
|
||||
assert_eq!(git_in(&repo, &["rev-parse", "HEAD"]), head_before);
|
||||
let status = git_in(&repo, &["status", "--porcelain"]);
|
||||
assert!(status.contains(" M a.txt"), "{status}");
|
||||
assert!(status.contains("?? new.txt"), "still untracked: {status}");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(repo.join("new.txt")).unwrap(),
|
||||
"new\n"
|
||||
);
|
||||
cleanup(&repo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untracked_file_shows_in_the_next_snapshots_diff() {
|
||||
let repo = scratch("untracked");
|
||||
let one = snapshot(&repo).unwrap();
|
||||
std::fs::write(repo.join("fresh.txt"), "a\nb\nc\n").unwrap();
|
||||
let two = snapshot(&repo).unwrap();
|
||||
assert_ne!(one, two);
|
||||
let out = repo.parent().unwrap().join("round-1.diff");
|
||||
let stats = diff(&repo, &one, &two, &out).unwrap();
|
||||
let text = std::fs::read_to_string(&out).unwrap();
|
||||
assert!(text.contains("+++ b/fresh.txt"), "{text}");
|
||||
assert_eq!(
|
||||
stats,
|
||||
DiffStats {
|
||||
files: 1,
|
||||
added: 3,
|
||||
removed: 0
|
||||
}
|
||||
);
|
||||
cleanup(&repo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_diff_between_two_commits_equals_git_diff() {
|
||||
let repo = scratch("commits");
|
||||
let a = head(&repo).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "one\nTWO\nthree\n").unwrap();
|
||||
git_in(&repo, &["add", "-A"]);
|
||||
git_in(&repo, &["commit", "-q", "-m", "second"]);
|
||||
let b = head(&repo).unwrap();
|
||||
let out = repo.parent().unwrap().join("between.diff");
|
||||
let stats = diff(&repo, &a, &b, &out).unwrap();
|
||||
let expected = git_in(
|
||||
&repo,
|
||||
&[
|
||||
"diff",
|
||||
"--no-color",
|
||||
"--no-ext-diff",
|
||||
"--src-prefix=a/",
|
||||
"--dst-prefix=b/",
|
||||
a.id(),
|
||||
b.id(),
|
||||
],
|
||||
);
|
||||
assert_eq!(std::fs::read_to_string(&out).unwrap(), expected);
|
||||
assert_eq!(
|
||||
stats,
|
||||
DiffStats {
|
||||
files: 1,
|
||||
added: 2,
|
||||
removed: 1
|
||||
}
|
||||
);
|
||||
cleanup(&repo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_commit_and_a_snapshot_can_be_diffed() {
|
||||
let repo = scratch("mixed");
|
||||
let start = head(&repo).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
let now = snapshot(&repo).unwrap();
|
||||
let out = repo.parent().unwrap().join("mixed.diff");
|
||||
let stats = diff(&repo, &start, &now, &out).unwrap();
|
||||
assert_eq!(stats.removed, 1);
|
||||
cleanup(&repo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_made_up_id_does_not_exist_and_the_diff_refuses_it() {
|
||||
let repo = scratch("missing");
|
||||
let real = head(&repo).unwrap();
|
||||
let ghost = Boundary::Tree("0123456789abcdef0123456789abcdef01234567".to_string());
|
||||
assert!(!exists(&repo, &ghost));
|
||||
assert!(!exists(&repo, &Boundary::Commit("--output=x".to_string())));
|
||||
let out = repo.parent().unwrap().join("ghost.diff");
|
||||
let err = diff(&repo, &real, &ghost, &out).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
"round boundary missing: 0123456789abcdef0123456789abcdef01234567"
|
||||
);
|
||||
// Either side is checked.
|
||||
assert!(diff(&repo, &ghost, &real, &out).is_err());
|
||||
assert!(!out.exists(), "nothing written for a refused diff");
|
||||
cleanup(&repo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_snapshot_outside_a_repository_fails_with_a_reason() {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-round-none-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// A `.git` file naming a gitdir that is not there: git stops here
|
||||
// whatever repository sits above the temp folder.
|
||||
std::fs::write(
|
||||
dir.join(".git"),
|
||||
"gitdir: /plan2code-no-such-gitdir
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
let err = snapshot(&dir).unwrap_err();
|
||||
assert!(err.starts_with("git could not"), "{err}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,675 @@
|
||||
//! The Review Loop's round rules, with no agent, git, file or clock in them:
|
||||
//! judging a round, picking the next step, and the wording of a round's commit
|
||||
//! subject and banner detail. The driver passes everything in.
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
/// The most rounds a run may ever reach, Continue included.
|
||||
pub const MAX_ROUNDS: u32 = 6;
|
||||
|
||||
/// The longest commit subject a round writes, in characters.
|
||||
const SUBJECT_LIMIT: usize = 72;
|
||||
|
||||
/// Which part of a round a session plays.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Role {
|
||||
Both,
|
||||
Reviewer,
|
||||
Fixer,
|
||||
}
|
||||
|
||||
/// One finding in a round's report.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
|
||||
pub struct Finding {
|
||||
#[serde(default)]
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub file: String,
|
||||
#[serde(default)]
|
||||
pub line: Option<u32>,
|
||||
}
|
||||
|
||||
/// The counts and lists a round reports.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
|
||||
pub struct RoundReview {
|
||||
#[serde(default)]
|
||||
pub critical: u32,
|
||||
#[serde(default)]
|
||||
pub warning: u32,
|
||||
#[serde(default)]
|
||||
pub suggestion: u32,
|
||||
#[serde(default)]
|
||||
pub fixed: Vec<Finding>,
|
||||
#[serde(default)]
|
||||
pub unfixed: Vec<Finding>,
|
||||
#[serde(default)]
|
||||
pub suggestions: Vec<Finding>,
|
||||
}
|
||||
|
||||
/// The tests a round ran.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
|
||||
pub struct RoundTests {
|
||||
#[serde(default)]
|
||||
pub ran: bool,
|
||||
#[serde(default)]
|
||||
pub passed: bool,
|
||||
#[serde(default)]
|
||||
pub summary: String,
|
||||
}
|
||||
|
||||
/// A round session's `roundOutcome`, as the console validated it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
pub struct RoundOutcome {
|
||||
pub round: u32,
|
||||
pub role: Role,
|
||||
/// `passed` or `failed`.
|
||||
pub result: String,
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
#[serde(default)]
|
||||
pub summary: String,
|
||||
/// Id of the report doc in the session.
|
||||
#[serde(default)]
|
||||
pub report: Option<String>,
|
||||
#[serde(default)]
|
||||
pub review: RoundReview,
|
||||
#[serde(default)]
|
||||
pub tests: Option<RoundTests>,
|
||||
#[serde(default)]
|
||||
pub subject: Option<String>,
|
||||
}
|
||||
|
||||
/// What the app checked for itself, so a report cannot vouch for its own work.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RoundProofs {
|
||||
pub report_doc_present: bool,
|
||||
pub tests_ran: bool,
|
||||
pub tests_passed: bool,
|
||||
}
|
||||
|
||||
/// How a round came out.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
Clean,
|
||||
Findings { critical: u32, warning: u32 },
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// Judge a round from its report and the app's own proofs. Suggestions never
|
||||
/// change the verdict.
|
||||
pub fn judge_round(outcome: &RoundOutcome, proofs: &RoundProofs) -> Verdict {
|
||||
if outcome.result == "failed" {
|
||||
let reason = outcome
|
||||
.reason
|
||||
.as_deref()
|
||||
.filter(|reason| !reason.is_empty())
|
||||
.unwrap_or("other");
|
||||
return Verdict::Failed(reason.to_string());
|
||||
}
|
||||
if !proofs.report_doc_present {
|
||||
return Verdict::Failed("no reviewer report in the session".to_string());
|
||||
}
|
||||
if !proofs.tests_ran {
|
||||
return Verdict::Failed("targeted tests did not run".to_string());
|
||||
}
|
||||
if !proofs.tests_passed {
|
||||
return Verdict::Failed("targeted tests failed".to_string());
|
||||
}
|
||||
let (critical, warning) = (outcome.review.critical, outcome.review.warning);
|
||||
if critical == 0 && warning == 0 {
|
||||
Verdict::Clean
|
||||
} else {
|
||||
Verdict::Findings { critical, warning }
|
||||
}
|
||||
}
|
||||
|
||||
/// A fixer's counts never vouch for its own fix: in the two-session shape the
|
||||
/// round is judged on what the separate reviewer found, so a fixer that sends
|
||||
/// lower counts than its reviewer cannot end the run as clean.
|
||||
pub fn hold_reviewer_counts(review: &mut RoundReview, critical: u32, warning: u32) {
|
||||
review.critical = review.critical.max(critical);
|
||||
review.warning = review.warning.max(warning);
|
||||
}
|
||||
|
||||
/// Why a run stopped.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum StopReason {
|
||||
Clean,
|
||||
Cap,
|
||||
Person,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// What the run looks like when a round has just been judged.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RunView {
|
||||
/// The round just judged.
|
||||
pub round: u32,
|
||||
pub cap: u32,
|
||||
pub rounds_run: u32,
|
||||
pub suggestions_on: bool,
|
||||
pub suggestions_pending: bool,
|
||||
/// The Suggestions batch round has run.
|
||||
pub batch_done: bool,
|
||||
pub retried_this_round: bool,
|
||||
pub stop_after_round: bool,
|
||||
pub stop_now: bool,
|
||||
}
|
||||
|
||||
/// What the driver does next.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Next {
|
||||
StartRound(u32),
|
||||
Retry,
|
||||
SuggestionsBatch,
|
||||
FinalCheck,
|
||||
Stop(StopReason),
|
||||
}
|
||||
|
||||
/// Pick the next step after a round with `verdict`.
|
||||
///
|
||||
/// Once the batch has run, its verdict leads to one `FinalCheck` (outside the
|
||||
/// cap); the driver then ends the run with `after_final_check`, carrying the
|
||||
/// reason the run was going to stop for.
|
||||
pub fn next_step(run: &RunView, verdict: &Verdict) -> Next {
|
||||
if run.stop_now {
|
||||
return Next::Stop(StopReason::Person);
|
||||
}
|
||||
let batch_due = run.suggestions_on && run.suggestions_pending && !run.batch_done;
|
||||
match verdict {
|
||||
Verdict::Failed(reason) => {
|
||||
if run.retried_this_round {
|
||||
Next::Stop(StopReason::Failed(reason.clone()))
|
||||
} else {
|
||||
Next::Retry
|
||||
}
|
||||
}
|
||||
_ if run.batch_done => Next::FinalCheck,
|
||||
Verdict::Clean => {
|
||||
// A stop after this round means no more work, the batch included.
|
||||
if batch_due && !run.stop_after_round {
|
||||
Next::SuggestionsBatch
|
||||
} else {
|
||||
Next::Stop(StopReason::Clean)
|
||||
}
|
||||
}
|
||||
Verdict::Findings { .. } => {
|
||||
if run.stop_after_round {
|
||||
Next::Stop(StopReason::Person)
|
||||
} else if run.round >= run.cap.min(MAX_ROUNDS) {
|
||||
if batch_due {
|
||||
Next::SuggestionsBatch
|
||||
} else {
|
||||
Next::Stop(StopReason::Cap)
|
||||
}
|
||||
} else {
|
||||
Next::StartRound(run.round + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The step after the final check, whatever its verdict: the run ends for the
|
||||
/// reason it was already ending for (FR-19).
|
||||
pub fn after_final_check(original: StopReason) -> Next {
|
||||
Next::Stop(original)
|
||||
}
|
||||
|
||||
/// The cap Continue may use after a run stopped at its cap: one more round,
|
||||
/// and never above `MAX_ROUNDS`.
|
||||
pub fn continue_cap(cap: u32, rounds_run: u32) -> Option<u32> {
|
||||
if rounds_run < cap {
|
||||
return None;
|
||||
}
|
||||
let next = rounds_run + 1;
|
||||
(next <= MAX_ROUNDS).then_some(next)
|
||||
}
|
||||
|
||||
/// The subject of a round's commit: the fix titles after the round number,
|
||||
/// trailing titles dropped for "and N more" to stay within 72 characters.
|
||||
pub fn round_commit_message(round: u32, titles: &[String]) -> String {
|
||||
let prefix = format!("Review Loop round {round}");
|
||||
let titles: Vec<&str> = titles
|
||||
.iter()
|
||||
.map(|title| title.trim())
|
||||
.filter(|title| !title.is_empty())
|
||||
.collect();
|
||||
if titles.is_empty() {
|
||||
return prefix;
|
||||
}
|
||||
let total = titles.len();
|
||||
for kept in (1..=total).rev() {
|
||||
let mut body = titles[..kept].join(", ");
|
||||
if kept < total {
|
||||
body.push_str(&format!(" and {} more", total - kept));
|
||||
}
|
||||
let subject = format!("{prefix}: {body}");
|
||||
if subject.chars().count() <= SUBJECT_LIMIT {
|
||||
return subject;
|
||||
}
|
||||
}
|
||||
// Even one title is too long: cut it.
|
||||
let subject = format!("{prefix}: {}", titles[0]);
|
||||
let mut cut: String = subject.chars().take(SUBJECT_LIMIT - 3).collect();
|
||||
cut = cut.trim_end().to_string();
|
||||
cut.push_str("...");
|
||||
cut
|
||||
}
|
||||
|
||||
/// The banner's detail line for a round, such as
|
||||
/// "Round 2 of 3: Fixing 3 findings (1 Critical, 2 Warning)".
|
||||
pub fn round_detail(round: u32, cap: u32, step: &str, critical: u32, warning: u32) -> String {
|
||||
let head = format!("Round {round} of {cap}: {step}");
|
||||
let total = critical + warning;
|
||||
if total == 0 {
|
||||
return head;
|
||||
}
|
||||
let mut parts = Vec::new();
|
||||
if critical > 0 {
|
||||
parts.push(format!("{critical} Critical"));
|
||||
}
|
||||
if warning > 0 {
|
||||
parts.push(format!("{warning} Warning"));
|
||||
}
|
||||
let noun = if total == 1 { "finding" } else { "findings" };
|
||||
format!("{head} {total} {noun} ({})", parts.join(", "))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_fixer_reporting_zero_is_judged_on_its_reviewers_counts() {
|
||||
let mut fixer = outcome(0, 0, 0);
|
||||
fixer.role = Role::Fixer;
|
||||
hold_reviewer_counts(&mut fixer.review, 1, 2);
|
||||
let proofs = RoundProofs {
|
||||
report_doc_present: true,
|
||||
tests_ran: true,
|
||||
tests_passed: true,
|
||||
};
|
||||
assert_eq!(
|
||||
judge_round(&fixer, &proofs),
|
||||
Verdict::Findings {
|
||||
critical: 1,
|
||||
warning: 2
|
||||
}
|
||||
);
|
||||
let mut honest = outcome(0, 3, 0);
|
||||
hold_reviewer_counts(&mut honest.review, 0, 1);
|
||||
assert_eq!(honest.review.warning, 3, "a higher own count stands");
|
||||
}
|
||||
|
||||
fn outcome(critical: u32, warning: u32, suggestion: u32) -> RoundOutcome {
|
||||
RoundOutcome {
|
||||
round: 1,
|
||||
role: Role::Both,
|
||||
result: "passed".into(),
|
||||
reason: None,
|
||||
summary: "done".into(),
|
||||
report: Some("report".into()),
|
||||
review: RoundReview {
|
||||
critical,
|
||||
warning,
|
||||
suggestion,
|
||||
..RoundReview::default()
|
||||
},
|
||||
tests: Some(RoundTests {
|
||||
ran: true,
|
||||
passed: true,
|
||||
summary: "ok".into(),
|
||||
}),
|
||||
subject: None,
|
||||
}
|
||||
}
|
||||
|
||||
const ALL: RoundProofs = RoundProofs {
|
||||
report_doc_present: true,
|
||||
tests_ran: true,
|
||||
tests_passed: true,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn a_round_with_every_proof_and_no_findings_is_clean() {
|
||||
assert_eq!(judge_round(&outcome(0, 0, 0), &ALL), Verdict::Clean);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_missing_proof_fails_with_its_own_message_even_at_zero_counts() {
|
||||
let no_doc = RoundProofs {
|
||||
report_doc_present: false,
|
||||
..ALL
|
||||
};
|
||||
let no_run = RoundProofs {
|
||||
tests_ran: false,
|
||||
tests_passed: false,
|
||||
..ALL
|
||||
};
|
||||
let failed = RoundProofs {
|
||||
tests_passed: false,
|
||||
..ALL
|
||||
};
|
||||
let round = outcome(0, 0, 0);
|
||||
assert_eq!(
|
||||
judge_round(&round, &no_doc),
|
||||
Verdict::Failed("no reviewer report in the session".into())
|
||||
);
|
||||
assert_eq!(
|
||||
judge_round(&round, &no_run),
|
||||
Verdict::Failed("targeted tests did not run".into())
|
||||
);
|
||||
assert_eq!(
|
||||
judge_round(&round, &failed),
|
||||
Verdict::Failed("targeted tests failed".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn critical_or_warning_left_is_findings() {
|
||||
assert_eq!(
|
||||
judge_round(&outcome(1, 0, 0), &ALL),
|
||||
Verdict::Findings {
|
||||
critical: 1,
|
||||
warning: 0
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
judge_round(&outcome(0, 2, 0), &ALL),
|
||||
Verdict::Findings {
|
||||
critical: 0,
|
||||
warning: 2
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggestions_alone_are_still_clean() {
|
||||
assert_eq!(judge_round(&outcome(0, 0, 9), &ALL), Verdict::Clean);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_result_passes_its_reason_through() {
|
||||
let mut round = outcome(0, 0, 0);
|
||||
round.result = "failed".into();
|
||||
round.reason = Some("blocked".into());
|
||||
assert_eq!(judge_round(&round, &ALL), Verdict::Failed("blocked".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_outcome_reads_from_the_console_json() {
|
||||
let json = r#"{"round":2,"role":"fixer","result":"passed","reason":null,
|
||||
"summary":"s","tests":{"ran":true,"passed":true,"summary":"3 pass"},
|
||||
"review":{"critical":0,"warning":1,"suggestion":0,
|
||||
"fixed":[{"title":"t","file":"a.rs","line":4}]}}"#;
|
||||
let parsed: RoundOutcome = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(parsed.role, Role::Fixer);
|
||||
assert_eq!(parsed.review.fixed[0].line, Some(4));
|
||||
assert_eq!(parsed.report, None);
|
||||
let reviewer: RoundOutcome =
|
||||
serde_json::from_str(r#"{"round":1,"role":"reviewer","result":"passed"}"#).unwrap();
|
||||
assert_eq!(reviewer.role, Role::Reviewer);
|
||||
}
|
||||
|
||||
fn view() -> RunView {
|
||||
RunView {
|
||||
round: 1,
|
||||
cap: 3,
|
||||
rounds_run: 1,
|
||||
suggestions_on: false,
|
||||
suggestions_pending: false,
|
||||
batch_done: false,
|
||||
retried_this_round: false,
|
||||
stop_after_round: false,
|
||||
stop_now: false,
|
||||
}
|
||||
}
|
||||
|
||||
const FINDINGS: Verdict = Verdict::Findings {
|
||||
critical: 1,
|
||||
warning: 0,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn stop_now_always_stops_for_the_person() {
|
||||
let run = RunView {
|
||||
stop_now: true,
|
||||
suggestions_on: true,
|
||||
suggestions_pending: true,
|
||||
..view()
|
||||
};
|
||||
let done = RunView {
|
||||
batch_done: true,
|
||||
..run
|
||||
};
|
||||
assert_eq!(
|
||||
next_step(&done, &Verdict::Clean),
|
||||
Next::Stop(StopReason::Person)
|
||||
);
|
||||
for verdict in [Verdict::Clean, FINDINGS, Verdict::Failed("tests".into())] {
|
||||
assert_eq!(next_step(&run, &verdict), Next::Stop(StopReason::Person));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failure_retries_once_then_stops_failed() {
|
||||
let failed = Verdict::Failed("tests".into());
|
||||
assert_eq!(next_step(&view(), &failed), Next::Retry);
|
||||
let retried = RunView {
|
||||
retried_this_round: true,
|
||||
..view()
|
||||
};
|
||||
assert_eq!(
|
||||
next_step(&retried, &failed),
|
||||
Next::Stop(StopReason::Failed("tests".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_stops_unless_a_suggestions_batch_is_due() {
|
||||
assert_eq!(
|
||||
next_step(&view(), &Verdict::Clean),
|
||||
Next::Stop(StopReason::Clean)
|
||||
);
|
||||
let on_none_pending = RunView {
|
||||
suggestions_on: true,
|
||||
..view()
|
||||
};
|
||||
assert_eq!(
|
||||
next_step(&on_none_pending, &Verdict::Clean),
|
||||
Next::Stop(StopReason::Clean)
|
||||
);
|
||||
let due = RunView {
|
||||
suggestions_on: true,
|
||||
suggestions_pending: true,
|
||||
..view()
|
||||
};
|
||||
assert_eq!(next_step(&due, &Verdict::Clean), Next::SuggestionsBatch);
|
||||
let off = RunView {
|
||||
suggestions_pending: true,
|
||||
..view()
|
||||
};
|
||||
assert_eq!(
|
||||
next_step(&off, &Verdict::Clean),
|
||||
Next::Stop(StopReason::Clean)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findings_start_the_next_round_below_the_cap() {
|
||||
assert_eq!(next_step(&view(), &FINDINGS), Next::StartRound(2));
|
||||
let second = RunView {
|
||||
round: 2,
|
||||
rounds_run: 2,
|
||||
..view()
|
||||
};
|
||||
assert_eq!(next_step(&second, &FINDINGS), Next::StartRound(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findings_at_the_cap_stop_or_run_the_batch() {
|
||||
let at_cap = RunView {
|
||||
round: 3,
|
||||
rounds_run: 3,
|
||||
..view()
|
||||
};
|
||||
assert_eq!(next_step(&at_cap, &FINDINGS), Next::Stop(StopReason::Cap));
|
||||
let due = RunView {
|
||||
suggestions_on: true,
|
||||
suggestions_pending: true,
|
||||
..at_cap
|
||||
};
|
||||
assert_eq!(next_step(&due, &FINDINGS), Next::SuggestionsBatch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cap_above_the_most_rounds_is_held_to_the_most() {
|
||||
let run = RunView {
|
||||
round: MAX_ROUNDS,
|
||||
rounds_run: MAX_ROUNDS,
|
||||
cap: 9,
|
||||
..view()
|
||||
};
|
||||
assert_eq!(next_step(&run, &FINDINGS), Next::Stop(StopReason::Cap));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_with_cap_one_stops_after_round_one() {
|
||||
let run = RunView { cap: 1, ..view() };
|
||||
assert_eq!(next_step(&run, &FINDINGS), Next::Stop(StopReason::Cap));
|
||||
assert_eq!(
|
||||
next_step(&run, &Verdict::Clean),
|
||||
Next::Stop(StopReason::Clean)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_after_this_round_stops_for_the_person_and_skips_the_batch() {
|
||||
let run = RunView {
|
||||
stop_after_round: true,
|
||||
suggestions_on: true,
|
||||
suggestions_pending: true,
|
||||
..view()
|
||||
};
|
||||
assert_eq!(next_step(&run, &FINDINGS), Next::Stop(StopReason::Person));
|
||||
// Clean is clean, but nothing more is started, the batch included.
|
||||
assert_eq!(
|
||||
next_step(&run, &Verdict::Clean),
|
||||
Next::Stop(StopReason::Clean)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_batch_never_runs_after_a_failure() {
|
||||
let run = RunView {
|
||||
suggestions_on: true,
|
||||
suggestions_pending: true,
|
||||
round: 3,
|
||||
rounds_run: 3,
|
||||
retried_this_round: true,
|
||||
..view()
|
||||
};
|
||||
assert_eq!(
|
||||
next_step(&run, &Verdict::Failed("tests".into())),
|
||||
Next::Stop(StopReason::Failed("tests".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_the_batch_one_final_check_runs_and_the_original_reason_stands() {
|
||||
let run = RunView {
|
||||
suggestions_on: true,
|
||||
suggestions_pending: true,
|
||||
batch_done: true,
|
||||
round: 3,
|
||||
rounds_run: 4,
|
||||
..view()
|
||||
};
|
||||
assert_eq!(next_step(&run, &Verdict::Clean), Next::FinalCheck);
|
||||
assert_eq!(next_step(&run, &FINDINGS), Next::FinalCheck);
|
||||
// A batch that fails is retried or stops failed like any round.
|
||||
assert_eq!(
|
||||
next_step(&run, &Verdict::Failed("tests".into())),
|
||||
Next::Retry
|
||||
);
|
||||
// Whatever the final check finds, the run ends as it was ending.
|
||||
assert_eq!(
|
||||
after_final_check(StopReason::Cap),
|
||||
Next::Stop(StopReason::Cap)
|
||||
);
|
||||
assert_eq!(
|
||||
after_final_check(StopReason::Clean),
|
||||
Next::Stop(StopReason::Clean)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continue_adds_one_round_and_never_a_seventh() {
|
||||
assert_eq!(continue_cap(3, 3), Some(4));
|
||||
assert_eq!(continue_cap(1, 1), Some(2));
|
||||
assert_eq!(continue_cap(5, 5), Some(6));
|
||||
assert_eq!(continue_cap(6, 6), None);
|
||||
assert_eq!(continue_cap(3, 2), None, "did not stop at the cap");
|
||||
}
|
||||
|
||||
fn titles(list: &[&str]) -> Vec<String> {
|
||||
list.iter().map(|title| title.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_commit_subject_joins_the_titles() {
|
||||
assert_eq!(
|
||||
round_commit_message(
|
||||
2,
|
||||
&titles(&["fix null check in loop_tools", "restore test map row"])
|
||||
),
|
||||
"Review Loop round 2: fix null check in loop_tools, restore test map row"
|
||||
);
|
||||
assert_eq!(
|
||||
round_commit_message(1, &titles(&["one fix"])),
|
||||
"Review Loop round 1: one fix"
|
||||
);
|
||||
assert_eq!(round_commit_message(3, &[]), "Review Loop round 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_commit_subject_drops_trailing_titles() {
|
||||
let subject = round_commit_message(
|
||||
2,
|
||||
&titles(&[
|
||||
"close the file handle before renaming",
|
||||
"name the timer",
|
||||
"restore the test map row",
|
||||
"tidy the report",
|
||||
]),
|
||||
);
|
||||
assert!(subject.chars().count() <= 72, "{subject}");
|
||||
assert!(subject.starts_with("Review Loop round 2: close the file handle"));
|
||||
assert!(subject.contains(" more"), "{subject}");
|
||||
// One title that is too long on its own is cut.
|
||||
let one = round_commit_message(1, &titles(&[&"x".repeat(200)]));
|
||||
assert_eq!(one.chars().count(), 72);
|
||||
assert!(one.ends_with("..."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_detail_line_counts_findings() {
|
||||
assert_eq!(
|
||||
round_detail(2, 3, "Fixing", 1, 2),
|
||||
"Round 2 of 3: Fixing 3 findings (1 Critical, 2 Warning)"
|
||||
);
|
||||
assert_eq!(
|
||||
round_detail(1, 3, "Fixing", 0, 1),
|
||||
"Round 1 of 3: Fixing 1 finding (1 Warning)"
|
||||
);
|
||||
assert_eq!(
|
||||
round_detail(1, 3, "Fixing", 1, 0),
|
||||
"Round 1 of 3: Fixing 1 finding (1 Critical)"
|
||||
);
|
||||
assert_eq!(
|
||||
round_detail(1, 3, "Reviewing", 0, 0),
|
||||
"Round 1 of 3: Reviewing"
|
||||
);
|
||||
}
|
||||
}
|
||||
+99
-5
@@ -1038,6 +1038,85 @@ window.addEventListener('message', (event) => {
|
||||
invoke('loop_facts')
|
||||
.then((facts) => source.postMessage({ plan2code: 'loop-facts', facts }, '*'))
|
||||
.catch(() => {});
|
||||
} else if (kind === 'review-loop-facts') {
|
||||
// The Review Loop's setup screen asks what agent a run would use and
|
||||
// whether it has helpers. Facts only; the page sends no setup value.
|
||||
const source = event.source;
|
||||
invoke('review_loop_facts')
|
||||
.then((facts) => source.postMessage({ plan2code: 'review-loop-facts', facts }, '*'))
|
||||
.catch(() => {});
|
||||
} else if (kind === 'review-loop-start') {
|
||||
// Start: the setup screen's picks, only the known fields and kinds. The
|
||||
// notification address is never taken from the page; the app reads it.
|
||||
const source = event.source;
|
||||
const picked = event.data.setup && typeof event.data.setup === 'object' ? event.data.setup : {};
|
||||
const text = (value) => (typeof value === 'string' ? value : '');
|
||||
const flag = (value) => value === true;
|
||||
const setup = {
|
||||
scope: text(picked.scope),
|
||||
spec: text(picked.spec),
|
||||
cap: Number.isInteger(picked.cap) ? picked.cap : 3,
|
||||
commit: picked.commit !== false,
|
||||
preRunCommitAgreed: flag(picked.preRunCommitAgreed),
|
||||
suggestions: flag(picked.suggestions),
|
||||
strength: text(picked.strength),
|
||||
silenceMinutes: Number.isInteger(picked.silenceMinutes) ? picked.silenceMinutes : 20,
|
||||
notifyRounds: flag(picked.notifyRounds),
|
||||
};
|
||||
invoke('review_loop_start', { setup })
|
||||
.then((started) => source.postMessage({ plan2code: 'review-loop-start-result', ok: true, started, error: null }, '*'))
|
||||
.catch((error) =>
|
||||
source.postMessage({ plan2code: 'review-loop-start-result', ok: false, started: false, error: String(error) }, '*')
|
||||
);
|
||||
} else if (kind === 'review-loop-continue') {
|
||||
const source = event.source;
|
||||
invoke('review_loop_continue')
|
||||
.then(() => source.postMessage({ plan2code: 'review-loop-continue-result', ok: true, error: null }, '*'))
|
||||
.catch((error) =>
|
||||
source.postMessage({ plan2code: 'review-loop-continue-result', ok: false, error: String(error) }, '*')
|
||||
);
|
||||
} else if (kind === 'review-loop-partial') {
|
||||
// Keep or Discard what Stop now left: one boolean, nothing else.
|
||||
const source = event.source;
|
||||
if (typeof event.data.keep !== 'boolean') {
|
||||
// Discard cannot be undone: only an explicit true or false is a choice.
|
||||
source.postMessage({ plan2code: 'review-loop-partial-result', ok: false, error: 'keep must be true or false' }, '*');
|
||||
return;
|
||||
}
|
||||
invoke('review_loop_partial', { keep: event.data.keep })
|
||||
.then(() => source.postMessage({ plan2code: 'review-loop-partial-result', ok: true, error: null }, '*'))
|
||||
.catch((error) =>
|
||||
source.postMessage({ plan2code: 'review-loop-partial-result', ok: false, error: String(error) }, '*')
|
||||
);
|
||||
} else if (kind === 'review-loop-sign-off') {
|
||||
// Sign off: the ticked Suggestions by id and the squash switch, nothing else.
|
||||
const source = event.source;
|
||||
const { picks, squash } = event.data;
|
||||
const refuse = (error) => source.postMessage({ plan2code: 'review-loop-sign-off-result', ok: false, error }, '*');
|
||||
if (!Array.isArray(picks) || picks.length > 50 || !picks.every((id) => typeof id === 'string' && /^s[0-9]{1,3}$/.test(id))) {
|
||||
refuse('picks must be a list of up to 50 suggestion ids');
|
||||
return;
|
||||
}
|
||||
if (typeof squash !== 'boolean') {
|
||||
refuse('squash must be true or false');
|
||||
return;
|
||||
}
|
||||
invoke('review_loop_sign_off', { picks, squash })
|
||||
.then(() => source.postMessage({ plan2code: 'review-loop-sign-off-result', ok: true, error: null }, '*'))
|
||||
.catch((error) => refuse(String(error)));
|
||||
} else if (kind === 'review-loop-next') {
|
||||
// The finished screen's launch: one of two words, the app builds the brief.
|
||||
const source = event.source;
|
||||
const next = event.data.next;
|
||||
if (next !== 'pr-prep' && next !== 'quick-task') {
|
||||
source.postMessage({ plan2code: 'review-loop-next-result', ok: false, error: 'next must be pr-prep or quick-task' }, '*');
|
||||
return;
|
||||
}
|
||||
invoke('review_loop_next', { next })
|
||||
.then(() => source.postMessage({ plan2code: 'review-loop-next-result', ok: true, error: null }, '*'))
|
||||
.catch((error) =>
|
||||
source.postMessage({ plan2code: 'review-loop-next-result', ok: false, error: String(error) }, '*')
|
||||
);
|
||||
} else if (kind === 'loop-resume' || kind === 'loop-ask' || kind === 'loop-fix' || kind === 'loop-finalize') {
|
||||
// Fixed requests, no free text: the page answers with ok or the error.
|
||||
const source = event.source;
|
||||
@@ -1628,6 +1707,19 @@ async function syncLoopState() {
|
||||
}
|
||||
}
|
||||
|
||||
// Which loop the strip is showing, so the stop buttons press the right commands.
|
||||
let loopKind = 'phases';
|
||||
|
||||
// A pip's hover text: "Phase 2", or for a Review Loop round the counts it found
|
||||
// ("Round 1: 2 Critical, 1 Warning"), "Round 3" for one not finished yet.
|
||||
function roundPipTitle(state, i) {
|
||||
if (state.kind !== 'rounds') return `Phase ${i + 1}`;
|
||||
const counts = Array.isArray(state.roundCounts) ? state.roundCounts[i] : null;
|
||||
if (!counts) return `Round ${i + 1}`;
|
||||
const found = [counts.critical > 0 ? `${counts.critical} Critical` : '', counts.warning > 0 ? `${counts.warning} Warning` : ''].filter(Boolean);
|
||||
return `Round ${i + 1}: ${found.length ? found.join(', ') : 'nothing found'}`;
|
||||
}
|
||||
|
||||
function applyLoopState(state) {
|
||||
if (!state || !state.running) {
|
||||
const wasRunning = loopRunning;
|
||||
@@ -1664,13 +1756,14 @@ function applyLoopState(state) {
|
||||
...banner.pips.map((kind, i) => {
|
||||
const pip = document.createElement('span');
|
||||
pip.className = `loop-pip ${kind}`;
|
||||
pip.title = `Phase ${i + 1}`;
|
||||
pip.title = roundPipTitle(state, i);
|
||||
return pip;
|
||||
})
|
||||
);
|
||||
setLoopTitle(loopWindowTitle(projectPathEl.textContent, state));
|
||||
const stopLabels = loopStopLabels(state);
|
||||
loopStopAfterOn = !!state.stopAfterPhase;
|
||||
loopStopAfterOn = !!(state.kind === 'rounds' ? state.stopAfterRound : state.stopAfterPhase);
|
||||
loopKind = state.kind === 'rounds' ? 'rounds' : 'phases';
|
||||
loopStopAfterBtn.disabled = stopLabels.afterDisabled;
|
||||
loopStopAfterBtn.textContent = stopLabels.afterText;
|
||||
loopStopNowBtn.disabled = stopLabels.nowDisabled;
|
||||
@@ -1730,15 +1823,16 @@ function pressLoop(command, args) {
|
||||
loopRetryBtn.onclick = () => {
|
||||
if (loopRetryAction) loopRetryAction();
|
||||
};
|
||||
loopStopAfterBtn.onclick = () => pressLoop('loop_stop_after_phase', { on: !loopStopAfterOn });
|
||||
loopStopAfterBtn.onclick = () => pressLoop(loopKind === 'rounds' ? 'review_loop_stop_after' : 'loop_stop_after_phase', { on: !loopStopAfterOn });
|
||||
loopStopNowBtn.onclick = async () => {
|
||||
const rounds = loopKind === 'rounds';
|
||||
const yes = await confirmModal({
|
||||
title: 'End the agent now?',
|
||||
lines: [{ kind: 'text', text: "This phase's changes stay uncommitted." }],
|
||||
lines: [{ kind: 'text', text: rounds ? "This round's changes stay uncommitted until you choose to keep or discard them." : "This phase's changes stay uncommitted." }],
|
||||
primary: 'Stop now',
|
||||
danger: true,
|
||||
});
|
||||
if (yes) pressLoop('loop_stop_now');
|
||||
if (yes) pressLoop(rounds ? 'review_loop_stop_now' : 'loop_stop_now');
|
||||
};
|
||||
|
||||
// The right end of the bar: whether the console stopped answering and where
|
||||
|
||||
@@ -210,6 +210,11 @@ export function windowTitleFor(dir) {
|
||||
*/
|
||||
export function loopWindowTitle(dir, state) {
|
||||
const name = lastSegment(dir);
|
||||
if (state.kind === "rounds") {
|
||||
const where = state.afterRounds || `Round ${state.round}`;
|
||||
const round = state.step === "Waiting on you" ? `Review Loop needs you: ${where}` : state.afterRounds ? `Review Loop: ${state.afterRounds}` : `Review Loop: Round ${state.round} of ${state.rounds}`;
|
||||
return name ? `${round} - ${name}` : round;
|
||||
}
|
||||
const what = state.step === "Waiting on you" ? `Loop needs you: Phase ${state.phase}` : `Loop: Phase ${state.phase} of ${state.phases}`;
|
||||
return name ? `${what} - ${name}` : what;
|
||||
}
|
||||
@@ -221,6 +226,7 @@ export function loopWindowTitle(dir, state) {
|
||||
* of the spec up to the last this run builds.
|
||||
*/
|
||||
export function loopBanner(state) {
|
||||
if (state.kind === "rounds") return roundsBanner(state);
|
||||
const { phase, phases, phaseName, step } = state;
|
||||
const named = phaseName ? `Phase ${phase} of ${phases}: ${phaseName}` : `Phase ${phase} of ${phases}`;
|
||||
const pips = Array.from({ length: Math.max(phases, 0) }, (_, i) => (i + 1 < phase ? "done" : i + 1 === phase ? "current" : "todo"));
|
||||
@@ -247,6 +253,40 @@ export function loopBanner(state) {
|
||||
return { ...base, title: "Implementation loop running", detail: ran ? `${where} \u00b7 ${ran}` : where };
|
||||
}
|
||||
|
||||
/**
|
||||
* The Review Loop's banner (`kind: "rounds"`): the same words as the phase banner
|
||||
* with "round" for "phase", one pip per round up to the cap, and the detail line
|
||||
* the app builds from the round, step and counts ("Round 2 of 3: Fixing 3 findings
|
||||
* (1 Critical, 2 Warning)", carried in `phaseName`). After the rounds,
|
||||
* `afterRounds` names the Suggestions batch or the final check, and every pip
|
||||
* shows done.
|
||||
*/
|
||||
function roundsBanner(state) {
|
||||
const { round, rounds, step } = state;
|
||||
const after = state.afterRounds || "";
|
||||
const named = after || `Round ${round} of ${rounds}`;
|
||||
const detailLine = state.phaseName || (step ? `${named}: ${step}` : named);
|
||||
const pips = Array.from({ length: Math.max(rounds, 0) }, (_, i) => (after || i + 1 < round ? "done" : i + 1 === round ? "current" : "todo"));
|
||||
const base = { tone: "running", pips, hint: "Working on its own. You can walk away." };
|
||||
if (state.stopping) {
|
||||
return { ...base, title: "Stopping", detail: "The agent is ending. You will be asked what to do with the round's changes.", hint: "The stop screen follows in a moment." };
|
||||
}
|
||||
if (step === "Waiting on you") {
|
||||
return { ...base, tone: "waiting", title: "The Review Loop needs your answer", detail: `${named} is waiting on the question below.`, hint: "Nothing is lost while it waits." };
|
||||
}
|
||||
if (state.stopAfterRound) {
|
||||
return { ...base, title: "Stopping after this round", detail: `${named} finishes, is judged and committed, then the Review Loop stops.`, hint: "Stop now ends the agent at once." };
|
||||
}
|
||||
if (step === "Starting") {
|
||||
if (state.phaseRetried) return { ...base, title: after ? `Retrying the ${after.toLowerCase()}` : `Retrying round ${round}`, detail: `The agent crashed or went quiet, so a fresh one is picking up ${after ? `the ${after.toLowerCase()}` : named}.` };
|
||||
if (after) return { ...base, title: "Rounds done", detail: `Opening a fresh agent for the ${after.toLowerCase()}.` };
|
||||
if (round > 1) return { ...base, title: `Round ${round - 1} done`, detail: `Opening a fresh agent for ${named}.` };
|
||||
return { ...base, title: "Starting the Review Loop", detail: `Opening a fresh agent for ${named}.` };
|
||||
}
|
||||
const ran = loopRunText(state);
|
||||
return { ...base, title: "Review Loop running", detail: ran ? `${detailLine} · ${ran}` : detailLine };
|
||||
}
|
||||
|
||||
/**
|
||||
* What the running phase runs on, from the app's `loop-state`: "Thrifty (sonnet,
|
||||
* low)" for a phase on a strength, "(opus, high)" for a Match my session phase
|
||||
@@ -267,9 +307,11 @@ export function loopRunText(state) {
|
||||
*/
|
||||
export function loopStopLabels(state) {
|
||||
const stopping = Boolean(state.stopping);
|
||||
const on = Boolean(state.stopAfterPhase);
|
||||
const rounds = state.kind === "rounds";
|
||||
const on = Boolean(rounds ? state.stopAfterRound : state.stopAfterPhase);
|
||||
const unit = rounds ? "round" : "phase";
|
||||
return {
|
||||
afterText: on ? "Cancel stop after this phase" : "Stop after this phase",
|
||||
afterText: on ? `Cancel stop after this ${unit}` : `Stop after this ${unit}`,
|
||||
afterDisabled: stopping || (!on && state.canStopAfter === false),
|
||||
nowDisabled: stopping,
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user