Craft Anything: understand how any software works, and craft your own.
Rust
Stop a build whose checks never find a working build, across Try again (#782)
BFlat1fbff715b517
diff --git a/crates/ai/src/rebuild/mod.rs b/crates/ai/src/rebuild/mod.rsindex 4daa887a..394e8f15 100644--- a/crates/ai/src/rebuild/mod.rs+++ b/crates/ai/src/rebuild/mod.rs@@ -694,6 +694,16 @@ impl Worker {resumed_elsewhere(&brief(kind, &cx, opts.message.as_deref()), &ws.manifest.last_reply, handoff.as_deref())});let mut round = ws.manifest.checks.iter().map(|c| c.round).max().unwrap_or(0);+ // A new request starts the count of checks that found no working build again. "Try again" on+ // a build that already reached the limit stops before another builder turn is paid for (#736).+ if opts.message.is_some() {+ if ws.manifest.not_working_checks != 0 {+ ws.manifest.not_working_checks = 0;+ ws.save()?;+ }+ } else if ws.manifest.not_working_checks >= NOT_WORKING_CHECK_LIMIT {+ return Err(not_working(ws));+ }let mut refinements = 0;// Deep mode on a program: decompiling is required, so a build turn without any gets one reminder.let must_decompile = !self.engine.session().clean_room() && matches!(ws.manifest.target, TargetRef::Local { .. });@@ -766,6 +776,7 @@ impl Worker {if let Some(p) = self.added(ws) {progress.reset();progress.save(&ws.root)?;+ ws.manifest.not_working_checks = 0;prompt = p;continue;}@@ -781,6 +792,9 @@ impl Worker {let checks = self.checks_with_a_retry(ws, kind, round)?;ws.manifest.checks.extend(checks.iter().cloned());ws.manifest.awaiting_check = false;+ // A round in which every check works (built and served) ends the streak; any other+ // round adds to it, across runs, until the limit stops the build.+ ws.manifest.not_working_checks = if checks.iter().all(|c| c.passed) { 0 } else { ws.manifest.not_working_checks.saturating_add(1) };ws.save()?;for c in &checks {self.emit(RunEvent::Checked(c.clone()));@@ -788,6 +802,7 @@ impl Worker {if let Some(p) = self.added(ws) {progress.reset();progress.save(&ws.root)?;+ ws.manifest.not_working_checks = 0;prompt = p;continue;}@@ -804,11 +819,17 @@ impl Worker {}}let Some(check) = not_good else { break };+ if ws.manifest.not_working_checks >= NOT_WORKING_CHECK_LIMIT {+ return Err(not_working(ws));+ }if refinements >= opts.max_rounds {break;}refinements += 1;- prompt = kind.refine(check) + &pictures_reminder(ws);+ // Nothing written yet: a fix for a build that doesn't exist sends the builder looking for one.+ // It is asked to write the project and to show its build output (#736).+ let refined = if app_is_empty(ws) { NO_PROJECT_PROMPT.to_string() } else { kind.refine(check) };+ prompt = refined + &pictures_reminder(ws);if !api_loop {prompt.push_str(CHECK_BEFORE_REPLYING);}@@ -1129,6 +1150,20 @@ impl Worker {}}+/// Checks in a row that may find the build not working before the run stops and asks for a new+/// request. Each "Try again" used to start another `max_rounds` of checks, with nothing counting+/// across runs, so a build that never came up was checked 40 and 49 times (#736).+pub const NOT_WORKING_CHECK_LIMIT: u32 = 10;++fn not_working(ws: &Workspace) -> ToolError {+ ToolError::new(ErrorCode::OverLimit, format!("The build still isn't working after {} checks in a row, so it stopped.", ws.manifest.not_working_checks))+ .with_remediation("Send a new request with a concrete correction to start again. The last check's note in the feed says what it found.")+}++/// The builder's next request when app/ holds no files: write the project first, then say what the+/// build printed. The reporter's agent claimed `npm run build` had passed while app/ was empty (#736).+const NO_PROJECT_PROMPT: &str = "The check found no project: app/ has no files, so nothing has been written yet and nothing can be built. Create the project's files in app/ now (for a website, a package.json and an index.html or the source files), then build it. Reply with the exact command you ran and the last lines of its output. Say something is built only when that output says so.";+fn no_build_progress(ws: &Workspace) -> ToolError {let stop = format!("The build stopped after two builder turns changed no files in {}.", ws.app_place());// #736: an empty app/ means the builder never wrote the project, whatever its replies said.diff --git a/crates/ai/src/rebuild/stall_tests.rs b/crates/ai/src/rebuild/stall_tests.rsnew file mode 100644index 00000000..0d5b433e--- /dev/null+++ b/crates/ai/src/rebuild/stall_tests.rs@@ -0,0 +1,178 @@+use super::*;+use crate::agent::tests::{Scripted, turn};+use crate::agent::{ApiConversation, EngineHost, LoopConfig, ModelSlot};+use crate::model::{Block, ChatModel, Delta, Msg, Stop, StopReason, TurnRequest, TurnResult};++/// A kind whose one check always says the build isn't there yet (as a website with an empty+/// app/ does, #736). The builder is scripted to answer every turn without writing a file.+struct NeverBuilt;++struct NeverBuiltCheck;++impl Check for NeverBuiltCheck {+ fn id(&self) -> &'static str {+ "never-built"+ }+ fn run(&self, cx: &mut CheckCx) -> Result<CheckResult, ToolError> {+ Ok(CheckResult::new(self.id(), cx.round, false, "No built site found in app/ yet."))+ }+}++impl TargetKind for NeverBuilt {+ fn id(&self) -> &'static str {+ "never-built"+ }+ fn words(&self) -> KindWords {+ KindWords { button: "Build it", icon: "code", ready: "It's ready", change_hint: "Ask for a change" }+ }+ fn detect(&self, _cx: &DetectCx) -> Option<u32> {+ Some(1000)+ }+ fn default_stack(&self, _cx: &DetectCx) -> &'static str {+ "Scripted stack"+ }+ fn goal(&self) -> &'static str {+ "a scripted app"+ }+ fn checks(&self, _ws: &Workspace) -> Vec<Box<dyn Check>> {+ vec![Box::new(NeverBuiltCheck)]+ }+}++/// Runs one build whose builder never writes a file, and returns the run's error and how many+/// builder turns the model was asked for.+fn run_idle_builder(create_app_dir: bool) -> (ToolError, Vec<Vec<Msg>>) {+ let dir = tempfile::tempdir().unwrap();+ let mut ws = Workspace::create(dir.path(), "Idle build", "Build an app", TargetRef::None).unwrap();+ if create_app_dir {+ std::fs::create_dir_all(ws.app_dir()).unwrap();+ }+ ws.manifest.stack = "Scripted stack".into();+ ws.save().unwrap();+ let mut worker = check_worker(&ws, false);+ let seen = Arc::default();+ let turns = (0..20).map(|_| turn(vec![Block::Text { text: "Built it and ran npm run build.".into() }], StopReason::EndTurn)).collect();+ let model = Scripted { turns, seen: Arc::clone(&seen) };+ let slot = ModelSlot { name: "Scripted".into(), model: Box::new(model), local: true, effort: None, max_turns: 10, context_tokens: 0 };+ let api = ApiConversation::start(Arc::new(EngineHost(worker.engine.clone())), vec![slot], LoopConfig::default()).unwrap();+ let entry = crate::BackendEntry {+ config: crate::BackendConfig {+ name: "Scripted".into(),+ kind: BackendKind::OpenaiCompatible,+ model: "scripted".into(),+ base_url: None,+ ssh_host: None,+ enabled: true,+ },+ options: Default::default(),+ };+ let mut kinds = KindRegistry::built_in();+ kinds.register(Arc::new(NeverBuilt));+ let opts = RunOptions { message: Some("Build the app".into()), kinds, max_rounds: 6, ..RunOptions::default() };+ let error = worker.run(&mut ws, entry, Some(api), None, &opts).unwrap_err();+ let requests = seen.lock().unwrap().clone();+ (error, requests)+}++#[test]+fn an_idle_builder_with_an_empty_app_stops_after_two_turns() {+ for create_app_dir in [true, false] {+ let (error, requests) = run_idle_builder(create_app_dir);+ assert!(error.message.contains("has no files yet"), "app dir {create_app_dir}: {error:?}");+ assert!(+ requests.len() <= 3,+ "app dir {create_app_dir}: the builder was asked {} times; it should stop after two turns that changed nothing",+ requests.len()+ );+ }+}++/// #736: with app/ empty, the stop says app/ has no files yet, and the builder is told to write+/// the project's files (not to fix a build) and to show the build's output.+#[test]+fn an_empty_app_is_said_to_have_no_project() {+ let (error, requests) = run_idle_builder(true);+ assert!(error.message.contains("has no files yet"), "{error:?}");+ assert!(error.remediation.as_deref().unwrap_or_default().contains("asks for the project's files"), "{error:?}");+ let second = requests.get(1).map(|m| m.iter().map(Msg::text).collect::<String>()).unwrap_or_default();+ assert!(second.contains("app/ has no files"), "the next prompt says so: {second}");+ assert!(second.contains("exact command you ran"), "and asks for the build's output: {second}");+ assert!(!second.contains("Fix this in app/"), "not a fix for a build that doesn't exist: {second}");+}++/// A builder that changes one file in app/ every turn, so the unchanged-turn limit never fires.+struct Busy {+ app: PathBuf,+ turn: usize,+ seen: Arc<Mutex<usize>>,+}++impl ChatModel for Busy {+ fn turn(&mut self, _request: &TurnRequest<'_>, _delta: &mut dyn FnMut(Delta), _stop: &Stop) -> Result<TurnResult, ToolError> {+ self.turn += 1;+ // Numbered across runs too (a shared count), so each turn writes a file the last didn't.+ let mut count = self.seen.lock().unwrap();+ *count += 1;+ std::fs::create_dir_all(&self.app).unwrap();+ std::fs::write(self.app.join(format!("attempt-{}.txt", *count)), "try").unwrap();+ turn(vec![Block::Text { text: "Changed the app.".into() }], StopReason::EndTurn)+ }+ fn model(&self) -> String {+ "busy".into()+ }+}++/// One run of the build (a request, or "Try again" when `message` is `None`), with a builder+/// that keeps changing files and a check that never passes.+fn run_busy_builder(ws: &mut Workspace, seen: &Arc<Mutex<usize>>, message: Option<&str>) -> ToolError {+ let mut worker = check_worker(ws, false);+ let model = Busy { app: ws.app_dir(), turn: 0, seen: Arc::clone(seen) };+ let slot = ModelSlot { name: "Busy".into(), model: Box::new(model), local: true, effort: None, max_turns: 10, context_tokens: 0 };+ let api = ApiConversation::start(Arc::new(EngineHost(worker.engine.clone())), vec![slot], LoopConfig::default()).unwrap();+ let entry = crate::BackendEntry {+ config: crate::BackendConfig {+ name: "Busy".into(),+ kind: BackendKind::OpenaiCompatible,+ model: "busy".into(),+ base_url: None,+ ssh_host: None,+ enabled: true,+ },+ options: Default::default(),+ };+ let mut kinds = KindRegistry::built_in();+ kinds.register(Arc::new(NeverBuilt));+ let opts = RunOptions { message: message.map(str::to_string), continuing: message.is_none(), kinds, max_rounds: 6, ..RunOptions::default() };+ worker.run(ws, entry, Some(api), None, &opts).unwrap_err()+}++#[test]+fn try_again_does_not_restart_a_build_that_never_works() {+ let dir = tempfile::tempdir().unwrap();+ let mut ws = Workspace::create(dir.path(), "Busy build", "Build an app", TargetRef::None).unwrap();+ ws.manifest.stack = "Scripted stack".into();+ ws.save().unwrap();+ let seen = Arc::new(Mutex::new(0));+ let first = run_busy_builder(&mut ws, &seen, Some("Build the app"));+ assert!(first.message.contains("isn't working yet"), "{first:?}");+ // Try again, many times: each press must not buy another full set of rounds.+ for _ in 0..5 {+ run_busy_builder(&mut ws, &seen, None);+ }+ let total = ws.manifest.checks.len();+ assert!(total <= NOT_WORKING_CHECK_LIMIT as usize, "{total} checks over six runs; the build must stop at its limit");+ assert_eq!(ws.manifest.not_working_checks, NOT_WORKING_CHECK_LIMIT, "the count is kept in the project");++ // Once at the limit, Try again stops before paying for another builder turn.+ let turns = *seen.lock().unwrap();+ let stopped = run_busy_builder(&mut ws, &seen, None);+ assert!(stopped.message.contains("in a row"), "{stopped:?}");+ assert_eq!(*seen.lock().unwrap(), turns, "no builder turn is started at the limit");+ assert_eq!(ws.manifest.checks.len(), total, "and no check runs either");++ // A new request starts the count again: the build gets its checks back.+ let restarted = run_busy_builder(&mut ws, &seen, Some("Use a plain page instead"));+ assert!(restarted.message.contains("isn't working yet"), "{restarted:?}");+ assert!(ws.manifest.checks.len() > total, "a new request runs checks again");+ assert!(ws.manifest.not_working_checks <= NOT_WORKING_CHECK_LIMIT, "{}", ws.manifest.not_working_checks);+}diff --git a/crates/ai/src/rebuild/tests.rs b/crates/ai/src/rebuild/tests.rsindex 484adfb7..14b76cad 100644--- a/crates/ai/src/rebuild/tests.rs+++ b/crates/ai/src/rebuild/tests.rs@@ -4,6 +4,9 @@ use super::*;#[path = "note_progress_tests.rs"]mod note_progress;+#[path = "stall_tests.rs"]+mod stall;+// Helpers that take a built-in kind's id, so each test reads as one line.fn kind(id: &str) -> Arc<dyn TargetKind> {KindRegistry::built_in().get(id).unwrap()diff --git a/crates/engine/src/workspace.rs b/crates/engine/src/workspace.rsindex bd650cd5..5d858e0f 100644--- a/crates/engine/src/workspace.rs+++ b/crates/engine/src/workspace.rs@@ -417,6 +417,15 @@ pub struct Manifest {/// that picks this up only needs to check: nothing is left to build.#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub awaiting_check: bool,+ /// Checks in a row, across runs, that found the build not working (it didn't build or serve).+ /// A run stops when this reaches the limit; a new request from the person starts it again.+ /// Kept in the project so "Try again" can't restart the count.+ #[serde(default, skip_serializing_if = "is_zero")]+ pub not_working_checks: u32,+}++fn is_zero(n: &u32) -> bool {+ *n == 0}impl Manifest {@@ -449,6 +458,7 @@ impl Manifest {builder: None,questions: None,awaiting_check: false,+ not_working_checks: 0,}}diff --git a/crates/ui-egui/src/demo.rs b/crates/ui-egui/src/demo.rsindex 2ff5220d..3021a0d4 100644--- a/crates/ui-egui/src/demo.rs+++ b/crates/ui-egui/src/demo.rs@@ -239,6 +239,7 @@ fn workspace(slug: &str, name: &str, request: &str, target: TargetRef, status: Sbuilder: None,questions: None,awaiting_check: false,+ not_working_checks: 0,},}}diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 3f4d8665..3adecd99 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -229,6 +229,16 @@ Every round spends the person's money or quota. One that can't do anything shoulempty-folder wording to the build check (it failed first, before #749's website check) andto the stop message — claimed: claude, branch bugfix/r5.3-empty-app-loop+- [x] A build whose checks keep finding no working build stops after 10 in a row, across "Try again"+ presses, until a new request starts the count again (`NOT_WORKING_CHECK_LIMIT`, kept in craft.json as+ `not_working_checks`). "Try again" used to start six more rounds every time with nothing counted across+ runs, so #736's build went on to check 40 and 49 times. A run at the limit stops before a builder turn.+ The unchanged-turn guard already stops a builder that writes nothing; #736's exact Windows run (gemini-cli)+ is not reproduced here. An empty `app/` is named as having no files yet (#771's wording) and the builder is asked to+ write the project and show its build's output, not to fix a build (`NO_PROJECT_PROMPT`). — claimed: fabox-os, branch bugfix/736-stop-empty-build-loop+- [ ] Live-check #736 on Windows with gemini-cli: an empty app/ and a builder that claims `npm run build`+ stops after two turns (or 10 checks) with the "no files yet" note, and Try again doesn't restart it+### R5.4 Local models can buildOwner: open · Status: todoThe built-in agent loop assumes a capable tool-calling model. Reports #24, #44, #110, #403, #417 anddiff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex 840b8bd9..8c25715e 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -518,6 +518,11 @@ and run `cargo xtask secrets` before every commit (the `.githooks/pre-commit` ho**An empty float sum is `-0.0`.** `iter().map(..).sum::<f64>()` over nothing gives `-0.0`, which`{:.2}` shows as "$-0.00". Sum money with `fold(0.0, ..)`.+**A per-run budget that a retry resets.** The build's refinement cap (`max_rounds`) counted from zero on every+run, while the round numbers carried over, so "Try again" bought six more checks each press and a build that never+worked reached check 40 and 49 (#736). A limit that must hold across runs is a count saved with the project, and+it's reset only by a new request. Test it with several runs in a row, not one.+**Docs that drift.** `STATUS.md` described a branch 25 commits old and the tool count was stale.Update STATUS, the roadmap and generated docs (`cargo xtask tools`, `cargo xtask schemas`) in thesame PR as the change.diff --git a/docs/schemas/craft.schema.json b/docs/schemas/craft.schema.jsonindex 40c26670..3cc619f9 100644--- a/docs/schemas/craft.schema.json+++ b/docs/schemas/craft.schema.json@@ -73,6 +73,12 @@"name": {"type": "string"},+ "not_working_checks": {+ "description": "Checks in a row, across runs, that found the build not working (it didn't build or serve).\nA run stops when this reaches the limit; a new request from the person starts it again.\nKept in the project so \"Try again\" can't restart the count.",+ "type": "integer",+ "format": "uint32",+ "minimum": 0+ },"note": {"description": "One line on what's happening or what went wrong.","type": "string",