diff --git a/services/worker/src/clients/sandbox.rs b/services/worker/src/clients/sandbox.rs index 44f0d56f0..667c31a07 100644 --- a/services/worker/src/clients/sandbox.rs +++ b/services/worker/src/clients/sandbox.rs @@ -256,9 +256,15 @@ impl EgressBlocks { const MARKER_CODEGEN_END: &str = "CODERHELM_CODEGEN_END exit="; const MARKER_CODEGEN_UPLOADED: &str = "===CODERHELM_CODEGEN_UPLOADED==="; const MARKER_CODEGEN_UPLOAD_FAILED: &str = "===CODERHELM_CODEGEN_UPLOAD_FAILED==="; -/// Caps on captured codegen output (regenerated files are large but bounded). -const MAX_CODEGEN_FILES: usize = 40; -const MAX_CODEGEN_FILE_BYTES: u64 = 5 * 1024 * 1024; +/// Caps on captured codegen output (regenerated files are large but +/// bounded). A generated types file for a large CMS schema passed the old +/// 5 MB cap and was dropped without a word: the run committed one of the two +/// files the generator changed and called it regenerated. A file past a cap +/// is now named in `CodegenOutcome::dropped`, never left out silently. The +/// size cap stays well under GitHub's 100 MB blob limit and the worker's +/// memory. +const MAX_CODEGEN_FILES: usize = 200; +const MAX_CODEGEN_FILE_BYTES: u64 = 50 * 1024 * 1024; /// Result of a sandbox codegen run — the files the repo's codegen CHANGED, /// captured for the worker to commit back to the branch (making the sandbox @@ -270,6 +276,10 @@ pub struct CodegenOutcome { pub passed: bool, /// (path, content) for each file codegen created or modified. pub changed: Vec<(String, String)>, + /// Files codegen changed that couldn't be brought back (too large, not + /// text, past the file cap), each with why. A run with any is not a + /// complete regeneration. + pub dropped: Vec, /// Tail of the codegen output. pub output: String, } @@ -280,11 +290,61 @@ impl CodegenOutcome { ran: false, passed: false, changed: Vec::new(), + dropped: Vec::new(), output: reason.into(), } } } +/// The files of a codegen build's changed-files archive: the text files to +/// commit, and the ones left out with why. +#[derive(Debug, Default, PartialEq)] +pub struct Captured { + pub files: Vec<(String, String)>, + pub dropped: Vec, +} + +/// Reads a changed-files archive (tar.gz, paths from the repository root). +pub fn read_changed_tar( + bytes: &[u8], + max_files: usize, + max_bytes: u64, +) -> Result> { + let gz = flate2::read::GzDecoder::new(bytes); + let mut ar = tar::Archive::new(gz); + let mut out = Captured::default(); + for entry in ar.entries()? { + let mut entry = entry?; + if entry.header().entry_type() != tar::EntryType::Regular { + continue; + } + let path = entry.path()?.to_string_lossy().replace('\\', "/"); + let path = path.trim_start_matches("./").to_string(); + if out.files.len() >= max_files { + out.dropped + .push(format!("`{path}` (more than {max_files} changed files)")); + continue; + } + if entry.size() > max_bytes { + warn!(path = %path, bytes = entry.size(), "codegen: changed file over the size cap"); + out.dropped.push(format!( + "`{path}` ({} MB, over the {} MB cap)", + entry.size() / (1024 * 1024), + max_bytes / (1024 * 1024) + )); + continue; + } + let mut content = String::new(); + use std::io::Read; + if entry.read_to_string(&mut content).is_err() { + out.dropped.push(format!("`{path}` (not a text file)")); + continue; + } + out.files.push((path, content)); + } + Ok(out) +} + /// Thin driver over CodeBuild + S3 + CloudWatch Logs. Holds only borrows from /// `WorkerState`; construct it per pass. pub struct SandboxClient<'a> { @@ -657,8 +717,8 @@ impl<'a> SandboxClient<'a> { // for builds that had ALREADY succeeded and uploaded the regenerated // files, so the agent re-ran the (expensive, always-succeeding) codegen // build over and over until the pass timed out. Check S3 first. - let changed = self.download_changed(out_key).await.unwrap_or_default(); - if !changed.is_empty() { + let captured = self.download_changed(out_key).await.unwrap_or_default(); + if !captured.files.is_empty() || !captured.dropped.is_empty() { let output = self .fetch_log(group, stream) .await @@ -667,7 +727,8 @@ impl<'a> SandboxClient<'a> { return Ok(CodegenOutcome { ran: true, passed: true, - changed, + changed: captured.files, + dropped: captured.dropped, output, }); } @@ -706,11 +767,12 @@ impl<'a> SandboxClient<'a> { // not be dropped as "nothing to regenerate". if printed(&full, MARKER_CODEGEN_UPLOADED) { let retry = self.download_changed(out_key).await.unwrap_or_default(); - if !retry.is_empty() { + if !retry.files.is_empty() || !retry.dropped.is_empty() { return Ok(CodegenOutcome { ran: true, passed: true, - changed: retry, + changed: retry.files, + dropped: retry.dropped, output, }); } @@ -725,16 +787,18 @@ impl<'a> SandboxClient<'a> { ran: true, passed, changed: Vec::new(), + dropped: Vec::new(), output, }) } /// Download the captured tar.gz of changed files and read them into - /// (path, content) pairs, bounded in count and per-file size. + /// (path, content) pairs, bounded in count and per-file size; what the + /// bounds leave out is named. async fn download_changed( &self, out_key: &str, - ) -> Result, Box> { + ) -> Result> { let obj = self .s3 .get_object() @@ -744,30 +808,7 @@ impl<'a> SandboxClient<'a> { .await .map_err(|e| format!("codegen output download failed: {e}"))?; let bytes = obj.body.collect().await?.into_bytes(); - let gz = flate2::read::GzDecoder::new(&bytes[..]); - let mut ar = tar::Archive::new(gz); - let mut out = Vec::new(); - for entry in ar.entries()? { - let mut entry = entry?; - if entry.header().entry_type() != tar::EntryType::Regular { - continue; - } - if entry.size() > MAX_CODEGEN_FILE_BYTES { - warn!("codegen: skipping oversized changed file"); - continue; - } - let path = entry.path()?.to_string_lossy().replace('\\', "/"); - let mut content = String::new(); - use std::io::Read; - if entry.read_to_string(&mut content).is_err() { - continue; // skip binary/non-utf8 - } - out.push((path, content)); - if out.len() >= MAX_CODEGEN_FILES { - break; - } - } - Ok(out) + read_changed_tar(&bytes, MAX_CODEGEN_FILES, MAX_CODEGEN_FILE_BYTES) } async fn build_and_read( @@ -1406,6 +1447,52 @@ mod tests { assert!(get.contains(&ttl) && put.contains(&ttl), "{get}"); } + /// The production layout: the generator runs in `apps/studio` and writes + /// `../web/src/lib/sanity/sanity.types.ts`; the build lists both changed + /// files from the repository root. Both come back, and a file over a cap + /// is named, never dropped silently. + #[test] + fn both_changed_files_come_back_and_a_dropped_one_is_named() { + fn archive(files: &[(&str, &[u8])]) -> Vec { + let mut b = tar::Builder::new(flate2::write::GzEncoder::new( + Vec::new(), + flate2::Compression::fast(), + )); + for (p, data) in files { + let mut h = tar::Header::new_gnu(); + h.set_size(data.len() as u64); + h.set_mode(0o644); + h.set_cksum(); + b.append_data(&mut h, p, *data).unwrap(); + } + b.into_inner().unwrap().finish().unwrap() + } + let types = vec![b'x'; 7 * 1024 * 1024]; + let tgz = archive(&[ + ("apps/studio/schema.json", b"{}"), + ("apps/web/src/lib/sanity/sanity.types.ts", &types), + ]); + let got = read_changed_tar(&tgz, MAX_CODEGEN_FILES, MAX_CODEGEN_FILE_BYTES).unwrap(); + let paths: Vec<&str> = got.files.iter().map(|(p, _)| p.as_str()).collect(); + assert_eq!( + paths, + [ + "apps/studio/schema.json", + "apps/web/src/lib/sanity/sanity.types.ts" + ], + "the 7 MB types file passed the old 5 MB cap" + ); + assert!(got.dropped.is_empty()); + // Past a cap: named, with why. + let small = read_changed_tar(&tgz, MAX_CODEGEN_FILES, 5 * 1024 * 1024).unwrap(); + assert_eq!(small.files.len(), 1); + assert_eq!(small.dropped.len(), 1); + assert!(small.dropped[0].contains("apps/web/src/lib/sanity/sanity.types.ts")); + assert!(small.dropped[0].contains("over the 5 MB cap")); + let one = read_changed_tar(&tgz, 1, MAX_CODEGEN_FILE_BYTES).unwrap(); + assert!(one.dropped[0].contains("more than 1 changed files")); + } + #[test] fn no_deadline_always_has_time() { let c = aws_sdk_codebuild::Client::from_conf( diff --git a/services/worker/src/passes/completeness.rs b/services/worker/src/passes/completeness.rs index e9bfe24d6..a929b226a 100644 --- a/services/worker/src/passes/completeness.rs +++ b/services/worker/src/passes/completeness.rs @@ -120,16 +120,21 @@ pub enum Section { ReviewFixes, /// What is still open, at the bottom (#238's "Not yet verified"). OpenItems, + /// Planned work the check before the PR still found not done after its + /// fix round, at the top: the PR opens as a draft with it rather than + /// the run ending with no PR (see `proof::unfinished_section`). + Unfinished, } impl Section { - const ALL: [Section; 6] = [ + const ALL: [Section; 7] = [ Section::Links, Section::Mirrors, Section::MergeOrder, Section::NotInPr, Section::ReviewFixes, Section::OpenItems, + Section::Unfinished, ]; /// Its start and end markers. @@ -150,6 +155,7 @@ impl Section { super::review_fix::evidence::END, ), Section::OpenItems => (super::proof::UNVERIFIED_START, super::proof::UNVERIFIED_END), + Section::Unfinished => (super::proof::UNFINISHED_START, super::proof::UNFINISHED_END), } } } @@ -183,6 +189,7 @@ pub struct Owned { pub not_in_pr: String, pub review_fixes: String, pub open_items: String, + pub unfinished: String, } impl Owned { @@ -194,6 +201,7 @@ impl Owned { Section::NotInPr => &mut self.not_in_pr, Section::ReviewFixes => &mut self.review_fixes, Section::OpenItems => &mut self.open_items, + Section::Unfinished => &mut self.unfinished, } } @@ -304,7 +312,8 @@ pub fn normalize_open_items(section: &str) -> String { /// Changes, then the link and redirect checks, the blocks the change mirrors, the merge order and the /// steps not in this PR (before the Risk heading, or before Verification /// when there is no Risk), the writer's Risk and Verification, then Open -/// items at the bottom, above the footer. Empty sections are left out. +/// items at the bottom, above the footer; planned work not done, when any, +/// above everything. Empty sections are left out. pub fn assemble(rest: &str, owned: &Owned) -> String { let (main, footer) = split_footer(rest); let main = main.trim(); @@ -346,6 +355,15 @@ pub fn assemble(rest: &str, owned: &Owned) -> String { format!("{body}\n\n{open}") }; } + // Planned work not done goes first: a reader sees it before anything. + let unfinished = owned.unfinished.trim(); + if !unfinished.is_empty() { + body = if body.is_empty() { + unfinished.to_string() + } else { + format!("{unfinished}\n\n{body}") + }; + } format!("{body}{footer}") } @@ -1080,6 +1098,7 @@ mod tests { fn the_description_is_put_together_in_its_order() { let writer = "Closes #9\n\n**Summary** The report needs a reader.\n\n**Changes**\n* **Users** add `analytics_reader`\n\n**Risk** **Low**: one new user.\n\n**Verification**\n1. Run the plan."; let owned = Owned { + unfinished: String::new(), links: String::new(), mirrors: mirrors_section(&[Mirror { path: "envs/prod/users.tf".into(), @@ -1133,6 +1152,40 @@ mod tests { assert!(!is_heading("Risk is low", "risk")); } + /// Planned work not done after the fix round: the PR opens as a draft + /// with it above everything, and a later rewrite keeps it there. + #[test] + fn unfinished_work_goes_at_the_top() { + let top = crate::passes::proof::unfinished_section(&[crate::passes::proof::Finding { + point: "planned_work".into(), + detail: "The hours block in apps/web/src/components/hours.tsx is not built.".into(), + ..Default::default() + }]); + let owned = Owned { + unfinished: top.clone(), + open_items: crate::passes::proof::gaps_section(&[crate::passes::proof::Finding { + point: "impact".into(), + detail: "not counted".into(), + ..Default::default() + }]), + ..Default::default() + }; + let body = assemble("Closes #4\n\n**Summary** x\n\n**Risk** Low", &owned); + assert!( + body.starts_with(crate::passes::proof::UNFINISHED_START), + "{body}" + ); + assert!(body.contains("hours.tsx")); + assert!( + body.ends_with(crate::passes::proof::UNVERIFIED_END), + "{body}" + ); + let (again, rest) = take_owned(&body); + assert_eq!(again.unfinished, top); + assert_eq!(assemble(&rest, &again), body); + assert!(crate::passes::proof::holds_unfinished(&body)); + } + #[test] fn a_top_warning_from_before_moves_to_the_bottom_as_open_items() { let old = "\n> [!WARNING]\n> **Not yet verified**\n> - **Impact not measured:** not counted. Settle: count them.\n> - **Waiting on CI:** lint did not run \n\n\nCloses #4\n\n**Summary** x\n\n**Risk** Low"; diff --git a/services/worker/src/passes/generators.rs b/services/worker/src/passes/generators.rs index 5352d8cf5..31aa9aa00 100644 --- a/services/worker/src/passes/generators.rs +++ b/services/worker/src/passes/generators.rs @@ -98,15 +98,43 @@ fn parts_match(pat: &[&str], path: &[&str]) -> bool { } } -fn clean(p: &str) -> &str { - p.trim().trim_start_matches("./").trim_start_matches('/') +/// A path (or glob) from the repository root in one spelling: `.` and +/// empty segments dropped and `..` resolved, so a generator run from +/// `apps/studio` writing `../web/src/lib/sanity/sanity.types.ts` names +/// `apps/web/src/lib/sanity/sanity.types.ts`, the path the diff, the plan +/// and the scope use. A trailing `/` (a directory) is kept. +pub fn normalize_path(p: &str) -> String { + let p = p.trim(); + let mut out: Vec<&str> = Vec::new(); + for seg in p.split('/') { + match seg { + "" | "." => {} + ".." => { + if out.last().is_some_and(|l| *l != "..") { + out.pop(); + } else { + out.push(".."); + } + } + s => out.push(s), + } + } + let mut joined = out.join("/"); + if p.ends_with('/') && !joined.is_empty() { + joined.push('/'); + } + joined +} + +fn clean(p: &str) -> String { + normalize_path(p) } /// Whether `path` matches the glob (`**`, `*`, `?`, `{a,b}`). A pattern that /// names a directory (ends in `/`) matches everything under it. pub fn glob_match(pattern: &str, path: &str) -> bool { let path = clean(path); - expand_braces(clean(pattern)).iter().any(|p| { + expand_braces(&clean(pattern)).iter().any(|p| { let p = if p.ends_with('/') { format!("{p}**") } else { @@ -125,11 +153,12 @@ fn any_match(globs: &[String], path: &str) -> bool { /// A glob relative to `dir` (a nested package's directory), as a path from /// the repository root. fn under(dir: &str, glob: &str) -> String { - let g = clean(glob); if dir.is_empty() { - g.to_string() + clean(glob) } else { - format!("{dir}/{g}") + // Joined before normalizing: `../web/x.ts` from `apps/studio` is + // `apps/web/x.ts`. + clean(&format!("{dir}/{}", glob.trim())) } } @@ -492,7 +521,7 @@ fn documented(doc: &str) -> Vec { let inputs: Vec = ticks .iter() .filter(|t| **t != command && !t.contains(' ') && (t.contains('/') || t.contains('*'))) - .map(|t| clean(t).to_string()) + .map(|t| clean(t)) .collect(); if !inputs.is_empty() { out.push(Generator { @@ -1273,8 +1302,14 @@ async fn run_in_sandbox( } Ok(o) if o.ran && o.passed => { EgressBlocks::clear(w.run_id); + // A changed file the sandbox couldn't hand back is a tooling + // failure, named: never "regenerated" with a file missing. + let dropped = (!o.dropped.is_empty()).then(|| dropped_reason(&o.dropped)); if o.changed.is_empty() { - return Ran::Regenerated(Vec::new()); + return match dropped { + Some(why) => Ran::Blocked(ToolingFailure::new(cmd, &why)), + None => Ran::Regenerated(Vec::new()), + }; } let paths: Vec = o.changed.iter().map(|(p, _)| p.clone()).collect(); let ops: Vec = o @@ -1293,7 +1328,10 @@ async fn run_in_sandbox( .batch_write(owner, name, w.branch, &message, &ops) .await { - Ok(_) => Ran::Regenerated(paths), + Ok(_) => match dropped { + Some(why) => Ran::Blocked(ToolingFailure::new(cmd, &why)), + None => Ran::Regenerated(paths), + }, Err(e) => Ran::Failed( format!("its output couldn't be committed ({e})"), String::new(), @@ -1325,6 +1363,21 @@ async fn run_in_sandbox( } } +/// Why a generator run that changed files the sandbox couldn't hand back +/// is not a regeneration. +pub fn dropped_reason(dropped: &[String]) -> String { + format!( + "the generator ran, but {} it changed couldn't be brought back from the sandbox to \ + commit: {}", + if dropped.len() == 1 { + "a file" + } else { + "files" + }, + dropped.join("; ") + ) +} + /// Whether a build that didn't run (or didn't finish) stopped for want of /// this step's time: the sandbox says so, or there is no runway left now. fn out_of_time(output: &str, has_time: impl Fn() -> bool) -> bool { @@ -1365,6 +1418,7 @@ async fn regenerate( attempt: usize, notes: &mut Vec, fresh: Option<&str>, + settled: &mut Vec, ) -> Option { let (owner, name) = (&w.msg.repo_owner, &w.msg.repo_name); let repo = load(w.github, owner, name, w.branch).await; @@ -1409,6 +1463,7 @@ async fn regenerate( "`{}` already ran with this work; nothing it reads changed since", g.name )); + settled.extend(g.outputs.iter().cloned()); continue; } (Some(cmd), true) => match &shared_run { @@ -1430,6 +1485,10 @@ async fn regenerate( Ran::Blocked(f) => return Some(Pass::Blocked(f)), Ran::OutOfTime => return Some(Pass::OutOfTime), Ran::Regenerated(paths) => { + // Ran to the end with every changed file committed (a file + // that couldn't come back is a tooling failure): its outputs + // are settled, changed or verified up to date. + settled.extend(g.outputs.iter().cloned()); if paths.is_empty() { notes.push(format!( "`{}` ran; the generated files are up to date", @@ -1520,6 +1579,9 @@ async fn regenerate( } } } + // A generator with a problem left (its output lacks a new type, a hand + // typed copy) has nothing settled. + settled.retain(|o| !problems.iter().any(|(g, _, _)| g.outputs.contains(o))); Some(Pass::Problems(problems)) } @@ -1599,7 +1661,7 @@ pub enum AfterStep { /// the generator gate before the pull request then only verifies. pub async fn after_step(w: &Work<'_>) -> AfterStep { let mut notes = Vec::new(); - match regenerate(w, 0, &mut notes, None).await { + match regenerate(w, 0, &mut notes, None, &mut Vec::new()).await { None => AfterStep::NotNeeded, Some(Pass::Problems(p)) if p.is_empty() && notes.is_empty() => AfterStep::NotNeeded, Some(Pass::Problems(p)) if p.is_empty() => { @@ -1617,24 +1679,54 @@ pub async fn after_step(w: &Work<'_>) -> AfterStep { } } +/// What the generator check settled. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct GateOk { + /// Notes for the run page. + pub notes: Vec, + /// The output globs (from the repository root) of the generators that + /// ran to the end with their output committed, or verified up to date: + /// a planned task for one of these files is done. + pub settled: Vec, +} + +fn normalized(mut globs: Vec) -> Vec { + for g in globs.iter_mut() { + *g = normalize_path(g); + } + globs.sort(); + globs.dedup(); + globs +} + +/// Whether a file is one a generator settled (`settled`, see [`GateOk`]). +pub fn is_settled(settled: &[String], path: &str) -> bool { + any_match(settled, path) +} + /// Before the pull request: generators whose inputs changed are run (or, /// when they already ran at `fresh` and nothing they read changed since, /// verified) and their output committed; one still out of date gets one fix /// round, then blocks the pull request with a plain reason. Returns notes -/// for the PR's progress, or why it stops: blocked, or this step needs more -/// time (the run then continues in a fresh step at this gate). +/// for the PR's progress and the outputs it settled, or why it stops: +/// blocked, or this step needs more time (the run then continues in a fresh +/// step at this gate). pub async fn gate( w: &Work<'_>, usage: &mut crate::models::TokenUsage, fresh: Option<&str>, -) -> Result, GateStop> { +) -> Result { let mut notes = Vec::new(); - let problems = match regenerate(w, 0, &mut notes, fresh).await { - None => return Ok(notes), + let mut settled = Vec::new(); + let problems = match regenerate(w, 0, &mut notes, fresh, &mut settled).await { + None => return Ok(GateOk { notes, settled }), Some(p) => stop_of(p)?, }; if problems.is_empty() { - return Ok(notes); + return Ok(GateOk { + notes, + settled: normalized(settled), + }); } super::add_progress_note( w.state, @@ -1674,13 +1766,17 @@ pub async fn gate( warn!(run_id = w.run_id, error = %e, "Generator fix round failed"); } let mut notes2 = Vec::new(); - let still = match regenerate(w, 1, &mut notes2, None).await { + let mut settled2 = Vec::new(); + let still = match regenerate(w, 1, &mut notes2, None, &mut settled2).await { Some(p) => stop_of(p)?, None => Vec::new(), }; notes.extend(notes2); match still.first() { - None => Ok(notes), + None => Ok(GateOk { + notes, + settled: normalized(settled.into_iter().chain(settled2).collect()), + }), Some((g, inputs, why)) => Err(GateStop::Blocked(format!( "Stopped before opening a pull request: {}", block_reason(g, inputs, why) @@ -1722,6 +1818,95 @@ mod tests { assert!(!glob_match("*.ts", "src/a.ts")); } + /// The production layout: the generator runs in `apps/studio` and its + /// config writes `../web/src/lib/sanity/sanity.types.ts`. Every output + /// path is in the one spelling the diff and the plan use. + #[test] + fn a_generator_writing_outside_its_directory_names_the_real_path() { + assert_eq!( + normalize_path("apps/studio/../web/src/lib/sanity/sanity.types.ts"), + "apps/web/src/lib/sanity/sanity.types.ts" + ); + assert_eq!(normalize_path("./a/./b//c/"), "a/b/c/"); + assert_eq!(normalize_path("../x"), "../x"); + assert_eq!( + under("apps/studio", "../web/src/lib/sanity/sanity.types.ts"), + "apps/web/src/lib/sanity/sanity.types.ts" + ); + let r = repo( + &[ + ( + "apps/studio/package.json", + r#"{"scripts":{"typegen":"sanity schema extract && sanity typegen generate"}}"#, + ), + ( + "apps/studio/sanity-typegen.json", + r#"{"path":"../web/src/**/*.{ts,tsx}","schema":"schema.json","generates":"../web/src/lib/sanity/sanity.types.ts"}"#, + ), + ], + &[ + "apps/studio/schemaTypes/blocks/hero.ts", + "apps/studio/schema.json", + "apps/web/src/lib/sanity/sanity.types.ts", + ], + ); + let gens = detect(&r); + let g = gens + .iter() + .find(|g| g.kind == GenKind::Sanity) + .expect("the studio's typegen"); + assert!( + g.outputs + .contains(&"apps/web/src/lib/sanity/sanity.types.ts".to_string()), + "{:?}", + g.outputs + ); + assert!( + g.outputs.iter().all(|o| !o.contains("..")), + "{:?}", + g.outputs + ); + // Matching works whichever way a path is spelled. + assert!(glob_match( + "apps/studio/../web/src/lib/sanity/sanity.types.ts", + "apps/web/src/lib/sanity/sanity.types.ts" + )); + // Both files the build changed are its outputs: nothing missing. + let committed = changed(&[ + "apps/studio/schemaTypes/blocks/hero.ts", + "apps/studio/schema.json", + "apps/web/src/lib/sanity/sanity.types.ts", + ]); + assert!(!outputs_missing(g, &committed)); + // Without the types file, the reason names its real path. + let why = not_run_reason(g, "no sandbox"); + assert!( + why.contains("apps/web/src/lib/sanity/sanity.types.ts"), + "{why}" + ); + assert!(!why.contains("studio/../web"), "{why}"); + // What the generator check settles, and what it means for a task. + let settled = normalized(g.outputs.clone()); + assert!(is_settled( + &settled, + "apps/web/src/lib/sanity/sanity.types.ts" + )); + assert!(is_settled( + &settled, + "apps/studio/../web/src/lib/sanity/sanity.types.ts" + )); + assert!(!is_settled(&settled, "apps/web/src/app/page.tsx")); + } + + #[test] + fn a_file_the_sandbox_could_not_hand_back_is_named() { + let why = dropped_reason(&[ + "`apps/web/src/lib/sanity/sanity.types.ts` (60 MB, over the 50 MB cap)".to_string(), + ]); + assert!(why.contains("couldn't be brought back from the sandbox")); + assert!(why.contains("apps/web/src/lib/sanity/sanity.types.ts")); + } + /// A step without time for the build never fails the run: the gate /// says it needs time (the run continues in a fresh step at this gate), /// never "couldn't run here (not enough time left)". @@ -1792,7 +1977,7 @@ mod tests { let src = include_str!("generators.rs"); let after = &src[src.find("pub async fn after_step(").unwrap()..]; let after = &after[..after.find("\n}\n").unwrap()]; - assert!(after.contains("regenerate(w, 0, &mut notes, None)")); + assert!(after.contains("regenerate(w, 0, &mut notes, None,")); } /// The observed case: a CMS schema changed, the typegen script exists, diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index c6879161d..d747b0a17 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -2472,6 +2472,21 @@ impl<'a> WriteToolExecutor<'a> { } Ok(o) if o.ran && o.passed => { crate::clients::sandbox::EgressBlocks::clear(run_id); + // Files it changed that couldn't come back are named, never + // left out of the result. + let dropped = if o.dropped.is_empty() { + String::new() + } else { + format!( + " NOT committed ({}): {}. Don't write these files by hand; the run \ + reports it.", + "the sandbox couldn't hand them back", + o.dropped.join("; ") + ) + }; + if o.changed.is_empty() && !dropped.is_empty() { + return Ok(json!(format!("Codegen ran.{dropped}"))); + } if o.changed.is_empty() { return Ok(json!(format!( "Codegen ran cleanly but changed no files (nothing to regenerate). \ @@ -2512,8 +2527,8 @@ impl<'a> WriteToolExecutor<'a> { self.scope_guard.allow(p); } Ok(json!(format!( - "Regenerated and committed {} file(s): {}. Now call run_checks to \ - confirm the type errors are resolved.", + "Regenerated and committed {} file(s): {}.{dropped} Now call \ + run_checks to confirm the type errors are resolved.", paths.len(), paths.join(", ") ))) diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index bcd256578..5e50fa6cc 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -453,6 +453,26 @@ mod continuation_tests { assert!(gen < test && test < sec); } + /// A finished run always ends with a pull request: planned work the + /// proof check still finds after its fix round opens the PR as a draft + /// with it at the top (single and multi repository), and the generator + /// check's settled outputs reach the proof check. + #[test] + fn unfinished_planned_work_opens_a_draft_not_a_failure() { + // Literals split so this test doesn't count itself. + let src = include_str!("mod.rs"); + assert!(!src.contains(concat!("proof::unfinished", "_reason("))); + let count = |a: &str, b: &str| src.matches(&format!("{a}{b}")).count(); + assert_eq!( + count("let unfinished = proof::", "unfinished_section(&gaps);"), + 2 + ); + assert_eq!(count("unfinished: ", "&unfinished,"), 2); + assert_eq!(count("generated: ", "&settled_generated,"), 2); + let rp = run_passes_src(); + assert!(rp.contains(concat!("plan_coverage::", "settle_generated("))); + } + /// The team's usage limit stops a run between steps: the next step is /// never queued once the meter says so (and a queued one is refused by /// the budget gate every step starts with). @@ -4681,9 +4701,17 @@ async fn run_passes( // What is still open goes under Open items, marked: the PR stays a draft // while any is listed. let security_items = security::open_items(&security_verdict, security_round.is_some()); - let carry = steps::Carry { + // Generated outputs their generator settled: from the generator check + // below, or the step that ran it. + let mut settled_generated: Vec = step_state + .carry + .as_ref() + .map(|c| c.generated.clone()) + .unwrap_or_default(); + let mut carry = steps::Carry { security: security_verdict.clone(), security_round: security_round.clone(), + generated: settled_generated.clone(), }; // Security issues not fixed (or a check that didn't run) are the PR's @@ -4723,10 +4751,45 @@ async fn run_passes( ) .await { - Ok(notes) => { - for n in notes { + Ok(ok) => { + for n in ok.notes { add_progress_note(state, &msg.team_id, run_id, &n).await; } + // A generated task the generator settled is done: the plan + // check's record says so too. + if !ok.settled.is_empty() { + settled_generated = ok.settled; + carry.generated = settled_generated.clone(); + let tasks = plan_coverage::tasks_for( + &github, + &msg.repo_owner, + &msg.repo_name, + &branch_name, + &plan_result.tasks, + ) + .await; + if let Some(changed) = plan_coverage::changed_files( + &github, + &msg.repo_owner, + &msg.repo_name, + &msg.base_branch, + &branch_name, + ) + .await + { + let cov = plan_coverage::settle_generated( + plan_coverage::coverage(&tasks, &changed), + &settled_generated, + ); + save_checked_tasks( + state, + msg, + run_id, + &plan_coverage::checked_tasks_md(&plan_result.tasks, &cov), + ) + .await; + } + } } Err(generators::GateStop::NeedsTime) => { close_memory(state, agent_memory.take()).await; @@ -4775,10 +4838,11 @@ async fn run_passes( file_cache: &file_cache, run_id, deadline: implement_deadline, + generated: &settled_generated, }; let mut gaps = proof::prove(&work, &mut evidence, usage, || budget.has_time()).await; - // Planned work the check found not done is never an Open item: the pull - // request doesn't open without it. + // Planned work the check found not done is never an Open item: it goes + // at the top of the pull request, which stays a draft until it's done. if !proof::planned_work(&gaps).is_empty() { if budget.take_denied() { close_memory(state, agent_memory.take()).await; @@ -4795,14 +4859,21 @@ async fn run_passes( ) .await; } - let kept = keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; - close_memory(state, agent_memory.take()).await; - return Err(format!( - "{} The work so far is kept on branch `{kept}`.", - proof::unfinished_reason(&gaps) + // A finished run always ends with a pull request: the planned work + // still not done after the fix round is listed at its top and it + // stays a draft. + add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "{} planned task(s) still not done after the fix round: the pull request opens as a draft with them listed at the top", + proof::planned_work(&gaps).len() + ), ) - .into()); + .await; } + let unfinished = proof::unfinished_section(&gaps); // Tasks the plan marks optional and the change left out, named. gaps.extend(plan_optional); // What the ticket needs that this run didn't do: a person's step (with @@ -4988,6 +5059,7 @@ async fn run_passes( &pr::Proof { evidence: &evidence.for_pr(), gaps: &proof::gaps_section(&gaps), + unfinished: &unfinished, manual: &proof::manual_steps(&gaps), ci: &evidence.ci_commands, mirrors: &completeness::parse_mirrors(&evidence.notes), @@ -5722,7 +5794,7 @@ async fn run_repo_pipeline( // --- Proof check --- check_cancelled(state, &msg.team_id, run_id).await?; // Generated files: regenerated with the change, or this repo's PR waits. - match generators::gate( + let settled_generated = match generators::gate( &plan_coverage::Work { state, msg, @@ -5741,10 +5813,11 @@ async fn run_repo_pipeline( ) .await { - Ok(notes) => { - for n in notes { + Ok(ok) => { + for n in ok.notes { add_progress_note(state, &msg.team_id, run_id, &n).await; } + ok.settled } Err(generators::GateStop::Blocked(why)) => { let kept = keep_wip_branch(github, repo_owner, repo_name, branch_name).await; @@ -5761,7 +5834,7 @@ async fn run_repo_pipeline( ) .into()); } - } + }; update_pass(state, &msg.team_id, run_id, "review").await?; let mut evidence = impl_result.evidence.clone(); let work = proof::Work { @@ -5776,19 +5849,15 @@ async fn run_repo_pipeline( file_cache, run_id, deadline: implement_deadline, + generated: &settled_generated, }; let mut gaps = proof::prove(&work, &mut evidence, usage, || { has_time_for_remediation(start) }) .await; - if !proof::planned_work(&gaps).is_empty() { - let kept = keep_wip_branch(github, repo_owner, repo_name, branch_name).await; - return Err(format!( - "{} The work so far is kept on branch `{kept}`.", - proof::unfinished_reason(&gaps) - ) - .into()); - } + // Planned work still not done after the fix round: this repository's + // pull request opens as a draft with it listed at the top. + let unfinished = proof::unfinished_section(&gaps); gaps.extend(plan_optional); gaps.extend(security_items); let links = link_checks::gate(&work, &mut evidence, usage, || { @@ -5842,6 +5911,7 @@ async fn run_repo_pipeline( &pr::Proof { evidence: &evidence.for_pr(), gaps: &proof::gaps_section(&gaps), + unfinished: &unfinished, manual: &proof::manual_steps(&gaps), ci: &evidence.ci_commands, mirrors: &completeness::parse_mirrors(&evidence.notes), diff --git a/services/worker/src/passes/plan_coverage.rs b/services/worker/src/passes/plan_coverage.rs index 27301b838..ea7a100f8 100644 --- a/services/worker/src/passes/plan_coverage.rs +++ b/services/worker/src/passes/plan_coverage.rs @@ -165,7 +165,7 @@ pub fn plan_tasks(tasks_md: &str) -> Vec { || d.trim_start().starts_with("new ") || d.trim_start().starts_with("add new"); out.push(PlanTask { - path: path.trim_start_matches("./").to_string(), + path: norm(path), task: desc.trim().to_string(), is_new, optional: is_optional(desc), @@ -212,8 +212,9 @@ impl Coverage { } } -fn norm(p: &str) -> &str { - p.trim().trim_start_matches("./").trim_start_matches('/') +/// One spelling for a path (`..` resolved), the one the diff uses. +fn norm(p: &str) -> String { + super::generators::normalize_path(p) } /// Whether the branch changes the task's file (or, for a directory, a file @@ -221,11 +222,28 @@ fn norm(p: &str) -> &str { fn path_changed(path: &str, changed: &[String]) -> bool { let path = norm(path); if path.ends_with('/') { - return changed.iter().any(|c| norm(c).starts_with(path)); + return changed.iter().any(|c| norm(c).starts_with(&path)); } changed.iter().any(|c| norm(c) == path) } +/// The coverage once the generator check has settled generated files: +/// a generated task whose file its generator regenerated and committed, or +/// verified up to date (`settled`: those generators' output globs), is +/// done. The plan check, the proof check and the generator check then agree. +pub fn settle_generated(mut cov: Coverage, settled: &[String]) -> Coverage { + let (now_done, still): (Vec, Vec) = + cov.missing.into_iter().partition(|t| { + t.generated + && settled + .iter() + .any(|g| super::generators::glob_match(g, &t.path)) + }); + cov.done.extend(now_done); + cov.missing = still; + cov +} + /// Each planned task, done when the branch changes its file. Structural, not /// the coder's account: a task whose file the diff doesn't touch is not done /// whatever the coder's summary says. @@ -601,6 +619,41 @@ pub async fn close_gaps( mod tests { use super::*; + /// The production run: 32 of 33 tasks done, the open one the generated + /// types the studio's typegen writes to `../web/...`. Once the + /// generator check settles it, the plan check agrees it is done. + #[test] + fn a_settled_generated_task_is_done() { + let tasks_md = "- [ ] apps/studio/schemaTypes/blocks/hero.ts: add the block\n\ + - [ ] apps/web/src/lib/sanity/sanity.types.ts: (generated: the generator check runs it before the pull request)\n"; + let mut tasks = plan_tasks(tasks_md); + mark_generated( + &mut tasks, + &["apps/studio/../web/src/lib/sanity/sanity.types.ts".to_string()], + ); + assert!(tasks[1].generated); + let cov = coverage( + &tasks, + &["apps/studio/schemaTypes/blocks/hero.ts".to_string()], + ); + assert_eq!(cov.generated_missing().len(), 1); + assert!(cov.required_missing().is_empty()); + let settled = vec!["apps/web/src/lib/sanity/sanity.types.ts".to_string()]; + let cov = settle_generated(cov, &settled); + assert_eq!(cov.done.len(), 2); + assert!(cov.missing.is_empty()); + assert!(checked_tasks_md(tasks_md, &cov).matches("- [x]").count() == 2); + // A path spelled with `..` in the diff counts as the task's file. + let cov = coverage( + &tasks, + &["apps/studio/../web/src/lib/sanity/sanity.types.ts".to_string()], + ); + assert!(cov.done.iter().any(|t| t.path.ends_with("sanity.types.ts"))); + // Nothing settled: still the generator check's. + let cov = settle_generated(coverage(&tasks, &[]), &[]); + assert_eq!(cov.generated_missing().len(), 1); + } + const PLAN: &str = "## Tasks\n\ - [ ] `src/blocks/gallery/index.ts`: Create the gallery block component (new file)\n\ - [ ] `src/blocks/gallery/schema.ts`: Create the block's schema\n\ diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 1153ebf32..1fa51070c 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -30,6 +30,9 @@ pub struct PrResult { pub struct Proof<'a> { pub evidence: &'a str, pub gaps: &'a str, + /// Planned work not done after the check's fix round, for the top of + /// the description (`proof::unfinished_section`); empty when none. + pub unfinished: &'a str, pub manual: &'a str, pub ci: &'a [CiCommand], pub mirrors: &'a [super::completeness::Mirror], @@ -1412,6 +1415,7 @@ fn owned_sections(plan: &PlanResult, proof: &Proof<'_>, repo: &str) -> super::co } else { proof.gaps.to_string() }, + unfinished: proof.unfinished.to_string(), } } @@ -1959,6 +1963,7 @@ mod refresh_tests { let proof = super::Proof { evidence: "", gaps: &gaps, + unfinished: "", manual: "", ci: &[], mirrors: &mirrors, diff --git a/services/worker/src/passes/proof.rs b/services/worker/src/passes/proof.rs index 278401f5a..8f5cec68f 100644 --- a/services/worker/src/passes/proof.rs +++ b/services/worker/src/passes/proof.rs @@ -685,9 +685,10 @@ pub const JUDGE_SYSTEM: &str = "You check a code change before its pull request says it reuses from them.\n\ 19. planned_work: a task in the plan's task checklist (below the plan) that the diff doesn't \ do, or does only in part (a file it creates as an empty shell, a step it skips). Name the \ - task and its file. Not a miss for a task the checklist marks optional. Planned work is \ - never a note for later: it is sent back to the coder, and the pull request doesn't open \ - without it.\n\ + task and its file. Not a miss for a task the checklist marks optional, nor for a generated \ + file listed under \"Generated files their generator settled\". Planned work is never a note \ + for later: it is sent back to the coder, and the pull request stays a draft until it is \ + done.\n\ Many changes touch none of these: a change that relies on nothing outside its own code, \ changes no stored records and adds no logs passes all of them. Judge only what the evidence \ shows and do not invent concerns. A fact the lookups confirm is proven even when the notes \ @@ -771,19 +772,6 @@ pub fn planned_work(findings: &[Finding]) -> Vec<&Finding> { .collect() } -/// Why the run stops when planned work is still not done after its rounds: -/// one plain sentence naming the tasks. -pub fn unfinished_reason(findings: &[Finding]) -> String { - let items: Vec = planned_work(findings) - .iter() - .map(|f| sentence(&f.detail, 120)) - .collect(); - format!( - "Stopped before opening a pull request: the check before it found planned work not done: {}", - items.join("; ") - ) -} - /// How many of `findings` are proof gaps. fn proof_gaps(findings: &[Finding]) -> usize { findings @@ -1216,6 +1204,9 @@ pub fn fix_feedback(findings: &[Finding]) -> String { /// kept whole when the description is rewritten, and read by the reviewer. pub const UNVERIFIED_START: &str = ""; pub const UNVERIFIED_END: &str = ""; +/// Around the planned work not done, at the top of the description. +pub const UNFINISHED_START: &str = ""; +pub const UNFINISHED_END: &str = ""; const CI_MARK: &str = ""; /// The mark on each security item: while one is in the description the pull /// request stays a draft (see `resume::mark_pr_ready`). @@ -1235,6 +1226,36 @@ fn item_line(f: &Finding) -> String { } } +/// Planned work the check still found not done after its fix round, for +/// the top of the description. The run opens the pull request as a draft +/// with it instead of ending without one; it stays a draft while this is +/// there ([`holds_unfinished`]). Empty when there is none. +pub fn unfinished_section(findings: &[Finding]) -> String { + let items: Vec = planned_work(findings) + .iter() + .map(|f| { + let what = sentence(&f.detail, MAX_WHAT); + match sentence(&f.settle, MAX_SETTLE) { + s if s.is_empty() => format!("- {what}"), + s => format!("- {what} {s}"), + } + }) + .collect(); + if items.is_empty() { + return String::new(); + } + format!( + "{UNFINISHED_START}\n## Not finished\nThis pull request stays a draft: the check before \ + it found planned work still not done after its fix round.\n{}\n{UNFINISHED_END}", + items.join("\n") + ) +} + +/// Whether the description still lists planned work not done. +pub fn holds_unfinished(body: &str) -> bool { + body.contains(UNFINISHED_START) +} + /// Whether the description still holds a security item: the pull request /// stays a draft until none is left. pub fn holds_security_items(body: &str) -> bool { @@ -1297,7 +1318,12 @@ pub fn with_security_items(body: &str, items: &[Finding]) -> Option { /// only a person can check never goes here (see [`manual_steps`]). No /// callout banner. Empty when there is nothing open. pub fn gaps_section(findings: &[Finding]) -> String { - let of = |s: Settler| findings.iter().filter(move |f| f.settler() == s); + // Planned work not done has its own section at the top. + let of = |s: Settler| { + findings + .iter() + .filter(move |f| f.settler() == s && f.point.trim() != "planned_work") + }; let items: Vec = of(Settler::Proof) .chain(of(Settler::Owner)) .map(item_line) @@ -1356,7 +1382,7 @@ pub fn settle_by_ci(body: &str) -> Option { } /// What the plan says the change is for, for the judge. -fn plan_context(plan: &PlanResult) -> String { +fn plan_context(plan: &PlanResult, settled: &[String]) -> String { let mut out = plan.proposal.trim().to_string(); if let Some(d) = &plan.fix { out.push_str(&super::fix_location::reviewer_context(d)); @@ -1366,9 +1392,46 @@ fn plan_context(plan: &PlanResult) -> String { out.push_str("\n\n### The plan's task checklist\n"); out.push_str(common::truncate_str(plan.tasks.trim(), 8_000)); } + if !settled.is_empty() { + out.push_str( + "\n\n### Generated files their generator settled\nThe generator check ran these \ + files' generator to the end and committed its output (or verified it up to date). \ + A checklist task for one of them is done, whatever the diff shows of it:\n", + ); + for g in settled { + out.push_str(&format!("- `{g}`\n")); + } + } out } +/// The findings without planned work for a generated file its generator +/// settled (see `generators::GateOk`): the generator owns that file, ran to +/// the end and its output is committed or verified, so the task is done. +/// Paths are compared in one spelling (`..` resolved). +pub fn drop_settled_generated(findings: Vec, settled: &[String]) -> Vec { + if settled.is_empty() { + return findings; + } + findings + .into_iter() + .filter(|f| { + if f.point.trim() != "planned_work" { + return true; + } + let text = format!("{} {}", f.detail, f.settle); + let named = text + .split(|c: char| { + c.is_whitespace() || matches!(c, '`' | '\'' | '"' | '(' | ')' | ',' | ';') + }) + .map(|t| t.trim_end_matches(['.', ':'])) + .filter(|t| t.contains('/') || t.contains('.')) + .any(|t| super::generators::is_settled(settled, t)); + !named + }) + .collect() +} + /// The judge's reading of the change on `branch`. `None` when it couldn't /// judge (an API or model failure, an unreadable reply). `evidence` gains /// the environments the diff changes, read from its paths. @@ -1379,6 +1442,7 @@ pub async fn judge( github: &GitHubClient, branch: &str, plan: &PlanResult, + settled: &[String], evidence: &mut RunEvidence, provider: &ModelProvider, usage: &mut TokenUsage, @@ -1407,7 +1471,7 @@ pub async fn judge( let evidence = &*evidence; let prompt = judge_prompt( &msg.title, - &plan_context(plan), + &plan_context(plan, settled), &diff, evidence, &msg.team_instructions, @@ -1453,6 +1517,9 @@ pub struct Work<'a> { pub run_id: &'a str, /// When the fix round must wrap up (the invocation's deadline). pub deadline: Option, + /// Generated files their generator settled (`generators::GateOk`): + /// never planned work left for the coder. + pub generated: &'a [String], } /// Judges the change, runs the fix round a gap earns, and judges again. @@ -1471,9 +1538,18 @@ pub async fn prove( let pass_start = std::time::Instant::now(); let usage_before = usage.clone(); let judged = judge( - w.state, w.msg, w.github, w.branch, w.plan, evidence, w.provider, usage, + w.state, + w.msg, + w.github, + w.branch, + w.plan, + w.generated, + evidence, + w.provider, + usage, ) - .await; + .await + .map(|f| drop_settled_generated(f, w.generated)); let recorded = recorded_gaps(evidence).len(); let findings = with_checklist( with_recorded(judged, evidence), @@ -1520,7 +1596,7 @@ pub async fn prove( &w.msg.team_id, w.run_id, &format!( - "Proof check: {} planned task(s) still not done; the pull request won't open without them", + "Proof check: {} planned task(s) still not done after the fix round; they go at the top of the pull request, which stays a draft", planned_work(&gaps).len() ), ) @@ -2518,6 +2594,51 @@ mod planned_work_tests { } } + /// The production run: the generator check committed the studio's + /// typegen output, and the judge still called the generated file's task + /// not done. A generated file its generator settled is never planned + /// work; other planned work still is. + #[test] + fn a_settled_generated_file_is_never_planned_work() { + let gaps = vec![ + f( + "planned_work", + "The task to regenerate `apps/web/src/lib/sanity/sanity.types.ts` with `pnpm typegen` is not done, so the generated types lack the new blocks.", + ), + f( + "planned_work", + "The task for apps/studio/../web/src/lib/sanity/sanity.types.ts is not done.", + ), + f( + "planned_work", + "The hours block in `apps/web/src/components/hours.tsx` is not built.", + ), + f("impact", "apps/web/src/lib/sanity/sanity.types.ts size not measured."), + ]; + let settled = vec!["apps/web/src/lib/sanity/sanity.types.ts".to_string()]; + let kept = drop_settled_generated(gaps.clone(), &settled); + let details: Vec<&str> = kept.iter().map(|f| f.detail.as_str()).collect(); + assert_eq!(kept.len(), 2, "{details:?}"); + assert!(details[0].contains("hours.tsx")); + assert_eq!(kept[1].point, "impact"); + // Nothing settled: nothing dropped. + assert_eq!(drop_settled_generated(gaps, &[]).len(), 4); + // The judge is told which files are settled. + let ctx = plan_context( + &PlanResult { + proposal: "p".into(), + tasks: "- [ ] apps/web/src/lib/sanity/sanity.types.ts: (generated)".into(), + spec: String::new(), + design: String::new(), + repo_tasks: vec![], + fix: None, + }, + &settled, + ); + assert!(ctx.contains("Generated files their generator settled")); + assert!(ctx.contains("`apps/web/src/lib/sanity/sanity.types.ts`")); + } + #[test] fn planned_work_gets_a_round_then_holds_the_pr() { let gaps = vec![ @@ -2528,15 +2649,22 @@ mod planned_work_tests { f("impact", "Records affected were not counted."), ]; assert_eq!(next(Some(&gaps), 0, true), Next::FixRound); - // No round left: never "open with the gaps listed". + // No round left: unfinished (the PR opens as a draft with it at + // the top, never without a PR). assert_eq!(next(Some(&gaps), 1, true), Next::Unfinished); assert_eq!(next(Some(&gaps), 0, false), Next::Unfinished); // Other gaps alone still open with Open items. assert_eq!(next(Some(&gaps[1..]), 1, true), Next::OpenWithGaps); - let why = unfinished_reason(&gaps); - assert!(why.starts_with("Stopped before opening a pull request")); - assert!(why.contains("tabs.tsx")); - assert!(!why.contains("Records affected")); + let top = unfinished_section(&gaps); + assert!(top.starts_with(UNFINISHED_START)); + assert!(top.contains("## Not finished")); + assert!(top.contains("tabs.tsx")); + assert!(!top.contains("Records affected")); + assert!(holds_unfinished(&top)); + // Not listed twice: Open items leave planned work to the top. + let open = gaps_section(&gaps); + assert!(!open.contains("tabs.tsx")); + assert!(open.contains("Records affected")); assert_eq!(gaps[0].settler(), Settler::Proof); assert!(fix_feedback(&gaps).contains("Planned work not done")); } @@ -2560,7 +2688,7 @@ mod planned_work_tests { repo_tasks: vec![], fix: None, }; - let ctx = plan_context(&plan); + let ctx = plan_context(&plan, &[]); assert!(ctx.contains("The plan's task checklist")); assert!(ctx.contains("`src/a.ts`")); } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 0a6cc77e2..005abeab0 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -4165,6 +4165,17 @@ async fn mark_ready( ); return; } + // Planned work not done is listed at the top: the PR stays + // a draft until a person (or a later round) settles it. + if super::proof::holds_unfinished( + pr.get("body").and_then(|v| v.as_str()).unwrap_or(""), + ) { + info!( + pr_number, + "Planned work not done is listed in the description; the PR stays a draft" + ); + return; + } // E2E fix and generated-test PRs wait for their repeat runs. if !proven && pr diff --git a/services/worker/src/passes/steps.rs b/services/worker/src/passes/steps.rs index 7013c80f3..17592dfc3 100644 --- a/services/worker/src/passes/steps.rs +++ b/services/worker/src/passes/steps.rs @@ -165,6 +165,9 @@ impl Gate { pub struct Carry { pub security: security::Verdict, pub security_round: Option, + /// Generated outputs the generator check settled (for a step resuming + /// at the checks after it). + pub generated: Vec, } impl Carry { @@ -178,6 +181,7 @@ impl Carry { "security": kind, "text": text, "round": self.security_round, + "generated": self.generated, }) .to_string() } @@ -194,6 +198,14 @@ impl Carry { Some(Carry { security, security_round: v["round"].as_str().map(str::to_string), + generated: v["generated"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|g| g.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(), }) } } @@ -437,14 +449,17 @@ mod tests { Carry { security: security::Verdict::Passed, security_round: None, + generated: vec![], }, Carry { security: security::Verdict::Findings("### SQLi\nFile: a.rs".into()), security_round: Some("fix them".into()), + generated: vec!["apps/web/src/lib/sanity/sanity.types.ts".into()], }, Carry { security: security::Verdict::NotChecked("api down".into()), security_round: Some("recheck".into()), + generated: vec![], }, ] { assert_eq!(Carry::from_json(&c.to_json()), Some(c));