diff --git a/.github/workflows/check-agent-trailers.yml b/.github/workflows/check-agent-trailers.yml index ad36f812..c8330ca2 100644 --- a/.github/workflows/check-agent-trailers.yml +++ b/.github/workflows/check-agent-trailers.yml @@ -26,7 +26,6 @@ jobs: with: base-sha: ${{ github.event.pull_request.base.sha }} head-sha: ${{ github.event.pull_request.head.sha }} - tests: name: tests runs-on: ubuntu-latest @@ -41,5 +40,18 @@ jobs: with: node-version: 20 - - name: Run tests - run: node --test tests/*.test.mjs \ No newline at end of file + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + + - name: Run Rust formatting, clippy, and tests + shell: bash + run: | + set -euo pipefail + NODE20="$(command -v node)" + export ROSTER_NODE20="$NODE20" + export ROSTER_TEST_NODE="$NODE20" + export GITHUB_AGENT_CONTRACTS="$GITHUB_WORKSPACE/vendor/github-agent-contracts" + cargo fmt --all -- --check + cargo clippy --all-targets --locked -- -D warnings + cargo test --locked diff --git a/rust/execution/counterfactual.rs b/rust/execution/counterfactual.rs index 12cee2f9..22acacf4 100644 --- a/rust/execution/counterfactual.rs +++ b/rust/execution/counterfactual.rs @@ -1,4 +1,5 @@ use std::collections::BTreeMap; +use std::fs; use std::path::Path; use super::*; @@ -199,16 +200,25 @@ pub(crate) async fn run_one( } else { approval.timeout() }; + let mut args = Vec::new(); + if target.file.ends_with(".ts") + || target.file.ends_with(".mts") + || target.file.ends_with(".cts") + { + args.push("--import".to_owned()); + args.push(tools::TS_IMPORT_HOOK.to_owned()); + } + args.extend([ + "--test".to_owned(), + "--test-reporter=tap".to_owned(), + format!("--test-timeout={per_test_timeout}"), + target.file.clone(), + ]); return owner .run( directory, node, - &[ - "--test".to_owned(), - "--test-reporter=tap".to_owned(), - format!("--test-timeout={per_test_timeout}"), - target.file.clone(), - ], + &args, &env, approval.timeout(), evidence::MAX_DIFF_BYTES, @@ -247,24 +257,33 @@ pub(crate) async fn run_one( .ok_or_else(|| { unsupported("Rust integration counterfactual requires a direct tests/*.rs target") })?; - owner + let had_lock = directory.join("Cargo.lock").is_file(); + let mut args = vec!["test".to_owned()]; + if had_lock { + args.push("--locked".to_owned()); + } + args.push("--offline".to_owned()); + args.push("--test".to_owned()); + args.push(stem.to_owned()); + args.push("--".to_owned()); + for name in &target.names { + args.push(name.to_utf8()?); + } + args.push("--format=pretty".to_owned()); + let run = owner .run( directory, &cargo.executable, - &[ - "test".to_owned(), - "--locked".to_owned(), - "--offline".to_owned(), - "--test".to_owned(), - stem.to_owned(), - "--".to_owned(), - "--format=pretty".to_owned(), - ], + &args, &env, approval.timeout(), evidence::MAX_DIFF_BYTES, ) - .await + .await; + if !had_lock { + let _ = fs::remove_file(directory.join("Cargo.lock")); + } + run } fn value(status: &str, reasons: &[Text], tests: Vec, runs: Vec) -> Value { @@ -335,8 +354,10 @@ pub async fn run( || crate::planning::forbidden_read(file) || (file.ends_with(".rs") && (!owner.root().join("Cargo.toml").is_file() + || file.starts_with("src/") || file .split_once("/src/") + .or_else(|| file.split_once("/tests/")) .is_some_and(|(sc, _)| owner.root().join(sc).join("Cargo.toml").is_file())) && !file.starts_with("tests/")) { @@ -441,6 +462,16 @@ pub async fn run( let head = text(required(&changes.validation, "head")?, "Captured base revision is missing")?; let base = scratch.base(&head, approval).await?; scratch.overlay_tests(&base, files)?; + if targets.iter().any(|target| target.engine == Engine::Cargo) + && !base.join("Cargo.lock").is_file() + { + let source_lock = owner.root().join("Cargo.lock"); + if let Ok(meta) = fs::symlink_metadata(&source_lock) + && meta.is_file() + { + let _ = fs::copy(&source_lock, base.join("Cargo.lock")); + } + } let mut tests = Vec::new(); let mut runs = Vec::new(); let mut unavailable = false; @@ -456,10 +487,30 @@ pub async fn run( let at_candidate = run_one(owner, approval, &scratch, owner.root(), target, false).await?; runs.push(observed(&at_base, "base", owner)?); runs.push(observed(&at_candidate, "candidate", owner)?); + let base_output = at_base.text()?.to_utf8()?; + let base_missing_api = target.engine == Engine::Cargo + && !at_base.timed_out + && !at_base.overflow + && at_base.exit.is_some_and(|code| code != 0) + && base_output.contains(&target.file) + && [ + "error[E0599]", + "error[E0425]", + "error[E0412]", + "error[E0432]", + "error[E0433]", + "error[E0369]", + "error[E0277]", + ] + .iter() + .any(|code| base_output.contains(code)); let mut target_red_count = 0_usize; for name in &target.names { - let base = verdict(&at_base, name, target.engine)?; let candidate = verdict(&at_candidate, name, target.engine)?; + let mut base = verdict(&at_base, name, target.engine)?; + if base == Verdict::Missing && candidate == Verdict::Pass && base_missing_api { + base = Verdict::Fail; + } unavailable |= base == Verdict::Missing || candidate == Verdict::Missing; if base == Verdict::Fail && candidate == Verdict::Pass { target_red_count += 1; diff --git a/rust/execution/evidence.rs b/rust/execution/evidence.rs index a0afa80b..41473fc3 100644 --- a/rust/execution/evidence.rs +++ b/rust/execution/evidence.rs @@ -242,6 +242,24 @@ pub fn capture( ) -> Result { let root = paths::absolute(root)?; secure::check_components(&root)?; + let is_dotnet_tree = fs::read_dir(&root) + .ok() + .into_iter() + .flatten() + .flatten() + .any(|entry| { + let s = entry.file_name().to_string_lossy().into_owned(); + s.ends_with(".sln") || s.ends_with(".csproj") + }) + || fs::read_dir(root.join("src")) + .ok() + .into_iter() + .flatten() + .flatten() + .any(|entry| entry.path().is_dir() && entry.path().join("bin").is_dir()); + let is_maven_tree = root.join("pom.xml").is_file(); + let is_gradle_tree = + root.join("build.gradle").is_file() || root.join("build.gradle.kts").is_file(); let root_identity = paths::file_information(&root)?.identity; let mut queue = vec![PathBuf::new()]; let mut entries = BTreeMap::new(); @@ -265,6 +283,15 @@ pub fn capture( if name == ".git" || ["RESULT.md", "REVIEW.md"].contains(&name.as_str()) || ignored_notebook(&name, memory) + || name + .split('/') + .any(|part| matches!(part, "obj" | "__pycache__" | ".pytest_cache")) + || (is_dotnet_tree && name.split('/').any(|part| part == "bin")) + || (is_maven_tree && name.split('/').any(|part| part == "target")) + || (is_gradle_tree + && name + .split('/') + .any(|part| matches!(part, "build" | ".gradle"))) { continue; } diff --git a/rust/execution/policy.rs b/rust/execution/policy.rs index c96db779..a8ea3a65 100644 --- a/rust/execution/policy.rs +++ b/rust/execution/policy.rs @@ -117,6 +117,9 @@ pub fn consumer_requires_modern_node(root: &std::path::Path) -> bool { if domain::is_text(pkg.get("name"), "github-agent-roster") { return false; } + if root.join("tsconfig.json").is_file() { + return true; + } let Some(engine_str) = pkg .get("engines") .and_then(|e| e.get("node")) @@ -132,9 +135,10 @@ pub fn relevant_tests(files: &[String]) -> Result, Error> { if docs_only(files)? { return Ok(Vec::new()); } - let pattern = - regex(r"(?:^tests?/.+\.[cm]?js$|(?:^|/)(?:test(?:[._-][^/]+)?|[^/]+[._-]test)\.[cm]?js$)")?; - let extension = regex(r"\.[cm]?js$")?; + let pattern = regex( + r"(?:^tests?/.+\.[cm]?[jt]s$|(?:^|/)(?:test(?:[._-][^/]+)?|[^/]+[._-](?:test|spec))\.[cm]?[jt]s$)", + )?; + let extension = regex(r"\.[cm]?[jt]s$")?; let mut tests = Vec::new(); for file in files { let file = file.replace('\\', "/"); @@ -143,9 +147,29 @@ pub fn relevant_tests(files: &[String]) -> Result, Error> { } let base = file.rsplit('/').next().unwrap_or(""); let base = extension.replace(base, ""); - let candidate = format!("tests/{base}.test.mjs"); - if !base.is_empty() && file.starts_with("src/") && !tests.contains(&candidate) { - tests.push(candidate); + if !base.is_empty() && file.starts_with("src/") { + if file.ends_with(".ts") || file.ends_with(".mts") || file.ends_with(".cts") { + let mut candidates = vec![ + format!("src/test/{base}.test.ts"), + format!("src/test/{base}.spec.ts"), + format!("test/{base}.test.ts"), + format!("tests/{base}.test.ts"), + ]; + if let Some((dir, _)) = file.rsplit_once('/') { + candidates.push(format!("{dir}/{base}.test.ts")); + candidates.push(format!("{dir}/{base}.spec.ts")); + } + for candidate in candidates { + if !tests.contains(&candidate) { + tests.push(candidate); + } + } + } else { + let candidate = format!("tests/{base}.test.mjs"); + if !tests.contains(&candidate) { + tests.push(candidate); + } + } } } Ok(tests) diff --git a/rust/execution/result.rs b/rust/execution/result.rs index 308063e0..bac04495 100644 --- a/rust/execution/result.rs +++ b/rust/execution/result.rs @@ -107,6 +107,24 @@ pub fn declared_test_names(source: &Text) -> Vec { names } +fn bounded_output(units: &[u16], limit: usize) -> Vec { + if units.len() <= limit { + return units.to_vec(); + } + let marker = Text::from("\n...[truncated]...\n").0; + if limit <= marker.len() { + return units.iter().copied().take(limit).collect(); + } + let budget = limit - marker.len(); + let head = budget / 3; + let tail = budget - head; + let mut out = Vec::with_capacity(limit); + out.extend(units.iter().copied().take(head)); + out.extend_from_slice(&marker); + out.extend(units.iter().copied().skip(units.len().saturating_sub(tail))); + out +} + pub fn test_evidence(tests: &Value, changed: &[(String, Vec)]) -> Result { let output = ["stdout", "stderr"] .iter() @@ -190,8 +208,15 @@ pub fn test_evidence(tests: &Value, changed: &[(String, Vec)]) -> Result)]) -> Result = output.encode_utf16().collect(); + bounded_output(&units, 1200) }); Ok(evidence) } @@ -330,7 +356,7 @@ pub fn render( body.push_str("Output:\n"); for name in ["stdout", "stderr"] { if let Some(source) = tests.get(name).and_then(Value::as_string) { - body.0.extend(source.0.iter().take(1200)); + body.0.extend(bounded_output(&source.0, 1200)); body.0.push(10); } } diff --git a/rust/execution/self_review.rs b/rust/execution/self_review.rs index 5e077698..3e5e73ea 100644 --- a/rust/execution/self_review.rs +++ b/rust/execution/self_review.rs @@ -82,7 +82,17 @@ impl Request { .and_then(Value::as_string) .and_then(|t| t.to_utf8().ok()) { - let trimmed: String = out_str.trim().chars().take(1200).collect(); + let clean = out_str.trim(); + let chars: Vec = clean.chars().collect(); + let trimmed: String = if chars.len() <= 1200 { + clean.to_owned() + } else { + let marker = "\n...[truncated]...\n"; + let head: String = chars.iter().take(400).collect(); + let tail: String = + chars.iter().skip(chars.len().saturating_sub(780)).collect(); + format!("{head}{marker}{tail}") + }; if !trimmed.is_empty() { stdout_snip = format!("Observed test output:\n{trimmed}\n\n"); } diff --git a/rust/execution/tests.rs b/rust/execution/tests.rs index 7325aa7b..3f72dab8 100644 --- a/rust/execution/tests.rs +++ b/rust/execution/tests.rs @@ -84,6 +84,11 @@ impl Fixture { if !output.status.success() { return Err(Error::new("Error", tools::bytes_text(&output.stderr)?)); } + if fixture.git(&["symbolic-ref", "--quiet", "HEAD"]).is_err() { + let head = fixture.git(&["rev-parse", "HEAD"])?; + fixture.git(&["update-ref", "refs/heads/fixture-base", head.trim()])?; + fixture.git(&["symbolic-ref", "HEAD", "refs/heads/fixture-base"])?; + } } else { match object_format { None => fixture.git(&["init", "--quiet"])?, @@ -2267,3 +2272,110 @@ async fn focused_review_real_posix_signal_preserves_writer_while_descendant_surv ); Ok(()) } + +#[tokio::test(flavor = "current_thread")] +async fn lock_free_rust_library_verify_passes_offline_and_cleans_generated_lock() +-> Result<(), Error> { + let fixture = Fixture::new(&["Cargo.toml", "src/lib.rs", "tests/smoke.rs"], true)?; + fixture.write( + "Cargo.toml", + "[package]\nname = \"lock-free-fixture\"\nversion = \"0.0.0\"\nedition = \"2024\"\n", + )?; + fixture.write("src/lib.rs", "pub fn answer() -> u8 { 42 }\n")?; + fixture.write( + "tests/smoke.rs", + "#[test]\nfn lock_free_smoke() {\n assert_eq!(lock_free_fixture::answer(), 42);\n}\n", + )?; + assert!(!fixture.root.join("Cargo.lock").exists()); + let mut environment = std::env::vars() + .filter(|(name, _)| { + ["CARGO_HOME", "RUSTUP_HOME", "RUSTFLAGS", "RUSTUP_TOOLCHAIN"].contains(&name.as_str()) + }) + .collect::>(); + environment.insert( + "CARGO_TARGET_DIR".to_owned(), + fixture.root.join("cargo-output").display().to_string(), + ); + let host = tools::Host { + cargo: Some(tools::CargoApproval { + executable: PathBuf::from("cargo"), + environment, + }), + ..tools::Host::default() + }; + let mut boundary = fixture + .open( + tools::Options::default(), + host, + &CancellationSource::default(), + ) + .await?; + let tests = boundary.verify(false).await?; + assert_eq!(tests.get("exit_code"), Some(&Value::Number(0.0))); + assert_eq!(tests.get("native"), Some(&Value::Boolean(true))); + assert!(tests.json().contains("lock_free_smoke")); + let stdout = tests + .get("stdout") + .and_then(Value::as_string) + .map(Text::to_utf8) + .transpose()? + .unwrap_or_default(); + assert!(!stdout.contains("\"packages\":[")); + assert!(!fixture.root.join("Cargo.lock").exists()); + boundary.close().await +} + +#[test] +fn native_result_preserves_trailing_test_summary_when_output_exceeds_limit() -> Result<(), Error> { + let filler = "test noisy::case ... ok\n".repeat(120); + let stdout = format!( + "running 121 tests\n{filler}test regression_tail_target ... ok\ntest result: ok. 121 passed; 0 failed;\n" + ); + let tests = Value::object(vec![ + ("exit_code", Value::Number(0.0)), + ("native", Value::Boolean(true)), + ("cargo_version", Value::string("cargo 1.99.1")), + ( + "commands", + Value::Array(vec![Value::string("cargo test --test test --offline")]), + ), + ("stdout", Value::string(&stdout)), + ("stderr", Value::string("")), + ]); + let report = Value::object(vec![("tests", tests), ("summary", Value::string("done"))]); + let rendered = result::render( + Path::new("."), + &report, + &Value::object(Vec::new()), + None, + &redaction::Config::default(), + )? + .to_utf8()?; + assert!(rendered.contains("...[truncated]...")); + assert!(rendered.contains("test regression_tail_target ... ok")); + assert!(rendered.contains("test result: ok. 121 passed; 0 failed;")); + Ok(()) +} + +#[test] +fn polyglot_intake_extracts_csharp_java_and_typescript_paths() -> Result<(), Error> { + let ask = Value::string( + "Fix src/Validators/CreditCard.cs, src/main/java/App.java, and src/v35.ts with src/test/v35.test.ts.", + ); + let req = crate::planning::intake::requirements(&ask, false)?; + assert_eq!( + req.files, + vec![ + "src/Validators/CreditCard.cs", + "src/main/java/App.java", + "src/v35.ts", + "src/test/v35.test.ts", + ] + ); + let ts_tests = + policy::relevant_tests(&["src/v35.ts".to_owned(), "src/utils/mime.ts".to_owned()])?; + assert!(ts_tests.contains(&"src/test/v35.test.ts".to_owned())); + assert!(ts_tests.contains(&"src/test/v35.spec.ts".to_owned())); + assert!(ts_tests.contains(&"src/utils/mime.test.ts".to_owned())); + Ok(()) +} diff --git a/rust/execution/tools.rs b/rust/execution/tools.rs index a8376d99..1190e76a 100644 --- a/rust/execution/tools.rs +++ b/rust/execution/tools.rs @@ -58,6 +58,7 @@ impl Host { ) -> Command { let mut command = Command::new(executable); command.current_dir(root).env_clear(); + command.env("GIT_OPTIONAL_LOCKS", "0"); for (name, value) in &self.environment { if environment_allowed(name) { command.env(name, value); @@ -118,6 +119,8 @@ fn environment_allowed(name: &str) -> bool { .contains(&name.to_ascii_lowercase().as_str()) } +pub(crate) const TS_IMPORT_HOOK: &str = r#"data:text/javascript,import{registerHooks}from"node:module";import*as T from"node:test";import*as A from"node:assert/strict";registerHooks({resolve(s,c,n){try{return n(s,c);}catch(e){if(c.parentURL&&c.parentURL.startsWith("file:")){const xs=s.endsWith(".js")?[s.slice(0,-3)+".ts"]:(s.startsWith(".")&&!/\.[cm]?[jt]s$/.test(s)?[s+".ts",s+"/index.ts"]:[]);for(const x of xs){try{return n(x,c);}catch{}}}throw e;}}});if(!globalThis.describe){const m=(a,neg)=>({toBe:b=>neg?A.notStrictEqual(a,b):A.strictEqual(a,b),toEqual:b=>neg?A.notDeepStrictEqual(a,b):A.deepStrictEqual(a,b),toStrictEqual:b=>neg?A.notDeepStrictEqual(a,b):A.deepStrictEqual(a,b),toBeUndefined:()=>neg?A.notStrictEqual(a,undefined):A.strictEqual(a,undefined),toBeNull:()=>neg?A.notStrictEqual(a,null):A.strictEqual(a,null),toBeTruthy:()=>A.ok(neg?!a:Boolean(a)),toBeFalsy:()=>A.ok(neg?Boolean(a):!a),toContain:b=>{const ok=typeof a==="string"?a.includes(b):Array.isArray(a)&&a.includes(b);A.ok(neg?!ok:ok);},toHaveLength:b=>neg?A.notStrictEqual(a.length,b):A.strictEqual(a.length,b),toMatch:b=>{const ok=b instanceof RegExp?b.test(String(a)):String(a).includes(String(b));A.ok(neg?!ok:ok);},toThrow:b=>neg?A.doesNotThrow(a,b):A.throws(a,b)});Object.assign(globalThis,{describe:T.describe,it:T.it,test:T.test,beforeEach:T.beforeEach,afterEach:T.afterEach,beforeAll:T.before,afterAll:T.after,expect:a=>Object.assign(m(a,false),{not:m(a,true)})});}"#; + pub(crate) fn unverified_cleanup(failure: &process::Failure, descendants_possible: bool) -> bool { !failure.cleanup_complete || matches!(failure.kind, FailureKind::Exit(None)) @@ -285,11 +288,15 @@ impl TestEvidence { { observed.push("cargo".to_owned()); } - if self - .observed_commands - .iter() - .any(|command| command.starts_with("node --test")) - { + if self.observed_commands.iter().any(|command| { + command.starts_with("node --test") + || command.starts_with("python3 ") + || command.starts_with("dotnet ") + || command.starts_with("mvn ") + || command.starts_with("./mvnw ") + || command.starts_with("gradle ") + || command.starts_with("./gradlew ") + }) { observed.push("node".to_owned()); } Value::object(vec![ @@ -2657,6 +2664,22 @@ impl Boundary { } } } + let is_dotnet_repo = self.written.iter().any(|file| file.ends_with(".cs")) + || self + .document + .files_allowed + .iter() + .any(|file| file.ends_with(".cs")) + || fs::read_dir(&self.root) + .ok() + .into_iter() + .flatten() + .flatten() + .any(|entry| { + let name = entry.file_name(); + let s = name.to_string_lossy(); + s.ends_with(".sln") || s.ends_with(".csproj") + }); let mut queue = vec![self.root.clone()]; let mut audit = BTreeMap::new(); let mut visited = 0; @@ -2682,6 +2705,7 @@ impl Boundary { || file .split('/') .any(|part| matches!(part, "__pycache__" | ".pytest_cache")) + || (is_dotnet_repo && file.split('/').any(|part| matches!(part, "bin" | "obj"))) || file.ends_with(".pyc") || [".roster/locks", ".roster/checkpoints"] .iter() @@ -3244,7 +3268,6 @@ impl Boundary { } } if !test_files.is_empty() { - let filter = "not calibration and not parallel and not remote and not adapter and not wide_rows and not strided_destination and not shared_scalar and not device_budget and not discrete and not tuning_races and not integrated_device and not windows_device and not source_mutation and not history_plane and not dense_qwen and not prompt_scoring and not manifest and not verification_keeps and not rectangular_round and not resident and not durations and not protobuf and not vector and not signature_references and not invalid_execution_signature and not export_includes"; let mut args = vec![ "-B".to_owned(), "-m".to_owned(), @@ -3253,8 +3276,14 @@ impl Boundary { "no:cacheprovider".to_owned(), ]; args.extend(test_files.clone()); - args.push("-k".to_owned()); - args.push(filter.to_owned()); + let has_internal_device_tests = test_files.iter().any(|f| { + f.contains("calibration") || f.contains("execution") || f.contains("contract") + }); + if has_internal_device_tests { + let filter = "not calibration and not parallel and not remote and not adapter and not wide_rows and not strided_destination and not shared_scalar and not device_budget and not discrete and not tuning_races and not integrated_device and not windows_device and not source_mutation and not history_plane and not dense_qwen and not prompt_scoring and not manifest and not verification_keeps and not rectangular_round and not resident and not durations and not protobuf and not vector and not signature_references and not invalid_execution_signature and not export_includes"; + args.push("-k".to_owned()); + args.push(filter.to_owned()); + } result .commands .push(format!("python3 -B -m pytest {}", test_files.join(" "))); @@ -3291,6 +3320,389 @@ impl Boundary { Ok(result) } + async fn dotnet_checks(&self, scope: &[String]) -> Result { + let bin_name = if cfg!(windows) { + "dotnet.exe" + } else { + "dotnet" + }; + let dotnet = std::env::var_os("ROSTER_DOTNET") + .map(PathBuf::from) + .filter(|path| path.is_file()) + .or_else(|| { + std::env::var_os("PATH").and_then(|paths| { + std::env::split_paths(&paths).find_map(|dir| { + let cand = dir.join(bin_name); + cand.is_file().then_some(cand) + }) + }) + }) + .ok_or_else(|| { + unsupported( + "C#/.NET verification requires an installed dotnet SDK; no runtime was substituted", + ) + })?; + let mut environment = BTreeMap::from([ + ("ROSTER_SEAT".to_owned(), "coder".to_owned()), + ("DOTNET_CLI_TELEMETRY_OPTOUT".to_owned(), "1".to_owned()), + ("DOTNET_NOLOGO".to_owned(), "1".to_owned()), + ]); + for var in [ + "HOME", + "USERPROFILE", + "APPDATA", + "LOCALAPPDATA", + "DOTNET_CLI_HOME", + "NUGET_PACKAGES", + "DOTNET_ROOT", + "DOTNET_ROLL_FORWARD", + ] { + if let Ok(val) = std::env::var(var) { + environment.insert(var.to_owned(), val); + } + } + let version = self + .process( + &dotnet, + &["--version".to_owned()], + &environment, + 15_000, + 4096, + ) + .await?; + if version.exit != 0 { + let message = format!( + "dotnet SDK preflight failed in worktree (check global.json): {}", + bytes_text(&version.stderr)?.trim() + ); + return Err(unsupported(&message)); + } + let mut cs_files = scope + .iter() + .chain(self.written.iter()) + .filter(|file| !file.contains('*') && file.ends_with(".cs")) + .cloned() + .collect::>(); + cs_files.sort(); + cs_files.dedup(); + let mut test_projects = Vec::new(); + let mut filters = Vec::new(); + for file in &cs_files { + let lower = file.to_ascii_lowercase(); + let is_test = lower.contains("test"); + if is_test + && let Some(stem) = Path::new(file).file_stem().and_then(|s| s.to_str()) + && !filters.iter().any(|existing: &String| existing == stem) + { + filters.push(stem.to_owned()); + } + let mut dir = self.root.join(file); + while let Some(parent) = dir.parent() { + if !parent.starts_with(&self.root) { + break; + } + if let Ok(rd) = fs::read_dir(parent) { + let mut found_proj = false; + for entry in rd.flatten() { + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) == Some("csproj") { + found_proj = true; + if is_test + && let Ok(rel) = path.strip_prefix(&self.root) + && let Some(rel_str) = rel.to_str() + { + let norm = rel_str.replace('\\', "/"); + if !test_projects.contains(&norm) { + test_projects.push(norm); + } + } + } + } + if found_proj { + break; + } + } + dir = parent.to_path_buf(); + } + } + let Some(test_proj) = test_projects.first().cloned() else { + return Err(unsupported( + "No C# test .csproj discovered for the changed .cs files", + )); + }; + let proj_path = self.root.join(&test_proj); + let proj_text = fs::read_to_string(&proj_path).unwrap_or_default(); + let tfm = ["net10.0", "net8.0", "net9.0", "net6.0"] + .into_iter() + .find(|candidate| proj_text.contains(candidate)); + let use_artifacts = !(proj_text.contains("bin\\$(") || proj_text.contains("bin/$(")); + let artifacts_dir = std::env::temp_dir().join(format!( + "roster-dotnet-artifacts-{}", + sha256_hex(self.root.to_string_lossy().as_bytes()) + .chars() + .take(12) + .collect::() + )); + let use_artifacts_arg = "-p:UseArtifactsOutput=true".to_owned(); + let artifacts_path_arg = format!("-p:ArtifactsPath={}", artifacts_dir.display()); + let mut commands = Vec::new(); + let proj_stem = proj_path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("test"); + let assets_file = if use_artifacts { + artifacts_dir + .join("obj") + .join(proj_stem) + .join("project.assets.json") + } else { + proj_path + .parent() + .map_or_else(PathBuf::new, |p| p.join("obj").join("project.assets.json")) + }; + if !assets_file.is_file() { + let nuget_cache = environment + .get("NUGET_PACKAGES") + .map(PathBuf::from) + .or_else(|| { + environment + .get("HOME") + .or_else(|| environment.get("USERPROFILE")) + .map(|h| PathBuf::from(h).join(".nuget").join("packages")) + }) + .filter(|p| p.is_dir()); + let mut restore_args = vec!["restore".to_owned(), test_proj.clone()]; + if use_artifacts { + restore_args.push(use_artifacts_arg.clone()); + restore_args.push(artifacts_path_arg.clone()); + } + if let Some(cache) = nuget_cache { + restore_args.push("--source".to_owned()); + restore_args.push(cache.display().to_string()); + } + let restore_out = self + .process( + &dotnet, + &restore_args, + &environment, + policy::FULL_TEST_TIMEOUT_MS, + 1024 * 1024, + ) + .await?; + if restore_out.exit != 0 { + return Ok(NodeChecks { + output: restore_out, + skipped: false, + commands: vec![format!("dotnet {}", restore_args.join(" "))], + syntax_file: None, + }); + } + } + let trx_path = + std::env::temp_dir().join(format!("roster-dotnet-{}.trx", std::process::id())); + let _ = fs::remove_file(&trx_path); + let mut args = vec![ + "test".to_owned(), + test_proj.clone(), + "--no-restore".to_owned(), + ]; + if use_artifacts { + args.push(use_artifacts_arg); + args.push(artifacts_path_arg); + } + if let Some(framework) = tfm { + args.push("-f".to_owned()); + args.push(framework.to_owned()); + } + if !filters.is_empty() { + let filter_expr = filters + .iter() + .map(|stem| format!("FullyQualifiedName~{stem}")) + .collect::>() + .join("|"); + args.push("--filter".to_owned()); + args.push(filter_expr); + } + args.push("--logger".to_owned()); + args.push(format!("trx;LogFileName={}", trx_path.display())); + commands.push(format!("dotnet {}", args.join(" "))); + let mut output = self + .process( + &dotnet, + &args, + &environment, + policy::FULL_TEST_TIMEOUT_MS, + 4 * 1024 * 1024, + ) + .await?; + if output.exit == 0 { + let trx = fs::read_to_string(&trx_path).unwrap_or_default(); + let executed = regex(r#"executed="([0-9]+)""#)? + .captures(&trx) + .and_then(|c| c.get(1)) + .and_then(|m| m.as_str().parse::().ok()) + .unwrap_or(0); + let failed = regex(r#"failed="([0-9]+)""#)? + .captures(&trx) + .and_then(|c| c.get(1)) + .and_then(|m| m.as_str().parse::().ok()) + .unwrap_or(0); + if executed == 0 && !filters.is_empty() { + let _ = fs::remove_file(&trx_path); + let mut unfiltered_args = vec![ + "test".to_owned(), + test_proj.clone(), + "--no-restore".to_owned(), + ]; + if use_artifacts { + unfiltered_args.push("-p:UseArtifactsOutput=true".to_owned()); + unfiltered_args.push(format!("-p:ArtifactsPath={}", artifacts_dir.display())); + } + if let Some(framework) = tfm { + unfiltered_args.push("-f".to_owned()); + unfiltered_args.push(framework.to_owned()); + } + unfiltered_args.push("--logger".to_owned()); + unfiltered_args.push(format!("trx;LogFileName={}", trx_path.display())); + commands.push(format!("dotnet {}", unfiltered_args.join(" "))); + output = self + .process( + &dotnet, + &unfiltered_args, + &environment, + policy::FULL_TEST_TIMEOUT_MS, + 4 * 1024 * 1024, + ) + .await?; + } + if output.exit == 0 { + let trx = fs::read_to_string(&trx_path).unwrap_or_default(); + let executed = regex(r#"executed="([0-9]+)""#)? + .captures(&trx) + .and_then(|c| c.get(1)) + .and_then(|m| m.as_str().parse::().ok()) + .unwrap_or(0); + let failed = regex(r#"failed="([0-9]+)""#)? + .captures(&trx) + .and_then(|c| c.get(1)) + .and_then(|m| m.as_str().parse::().ok()) + .unwrap_or(0); + if executed == 0 || failed > 0 { + output.exit = 1; + let msg = format!( + "\nTRX verification failed: executed={executed}, failed={failed} (nonzero executed count required)\n" + ); + output.stderr.extend_from_slice(msg.as_bytes()); + } + } else if failed > 0 { + output.exit = 1; + } + } + let _ = fs::remove_file(&trx_path); + Ok(NodeChecks { + output, + skipped: false, + commands, + syntax_file: None, + }) + } + + fn find_javac() -> Option { + let bin_name = if cfg!(windows) { "javac.exe" } else { "javac" }; + std::env::var_os("ROSTER_JAVAC") + .map(PathBuf::from) + .filter(|path| path.is_file()) + .or_else(|| { + std::env::var_os("JAVA_HOME") + .map(|home| PathBuf::from(home).join("bin").join(bin_name)) + .filter(|path| path.is_file()) + }) + .or_else(|| { + std::env::var_os("PATH").and_then(|paths| { + std::env::split_paths(&paths).find_map(|dir| { + let cand = dir.join(bin_name); + cand.is_file().then_some(cand) + }) + }) + }) + } + + async fn java_checks(&self, scope: &[String]) -> Result { + let _javac = Self::find_javac().ok_or_else(|| { + unsupported( + "Java verification requires an installed JDK (javac); only a JRE or no JDK was found on this host", + ) + })?; + let mvn_bin = if cfg!(windows) { "mvn.cmd" } else { "mvn" }; + let mvn = [self + .root + .join(if cfg!(windows) { "mvnw.cmd" } else { "mvnw" })] + .into_iter() + .find(|p| p.is_file()) + .or_else(|| { + std::env::var_os("PATH").and_then(|paths| { + std::env::split_paths(&paths).find_map(|dir| { + let cand = dir.join(mvn_bin); + cand.is_file().then_some(cand) + }) + }) + }) + .ok_or_else(|| { + unsupported("Java verification requires Maven (mvnw/mvn); no Maven tool was found") + })?; + let mut filters = Vec::new(); + for file in scope.iter().chain(self.written.iter()) { + if file.ends_with(".java") + && file.contains("Test") + && let Some(stem) = Path::new(file).file_stem().and_then(|s| s.to_str()) + && !filters.iter().any(|existing: &String| existing == stem) + { + filters.push(stem.to_owned()); + } + } + let mut args = vec![ + "-B".to_owned(), + "-o".to_owned(), + "test".to_owned(), + "-DfailIfNoTests=false".to_owned(), + "-Drat.skip=true".to_owned(), + ]; + if !filters.is_empty() { + args.push(format!("-Dtest={}", filters.join(","))); + } + let mut environment = BTreeMap::from([("ROSTER_SEAT".to_owned(), "coder".to_owned())]); + for var in ["HOME", "USERPROFILE", "JAVA_HOME", "M2_HOME"] { + if let Ok(val) = std::env::var(var) { + environment.insert(var.to_owned(), val); + } + } + if let Ok(java_home) = std::env::var("JAVA_HOME") { + let sep = if cfg!(windows) { ';' } else { ':' }; + let java_bin = Path::new(&java_home).join("bin"); + let current_path = std::env::var("PATH").unwrap_or_default(); + environment.insert( + "PATH".to_owned(), + format!("{}{sep}{current_path}", java_bin.display()), + ); + } + let command_str = format!("mvn {}", args.join(" ")); + let output = self + .process( + &mvn, + &args, + &environment, + policy::FULL_TEST_TIMEOUT_MS, + 4 * 1024 * 1024, + ) + .await?; + Ok(NodeChecks { + output, + skipped: false, + commands: vec![command_str], + syntax_file: None, + }) + } + async fn node_checks(&self, scope: &[String], full: bool) -> Result { if !self.root.join("package.json").is_file() && scope @@ -3300,6 +3712,22 @@ impl Boundary { { return self.python_checks(scope).await; } + if !self.root.join("package.json").is_file() + && scope + .iter() + .chain(self.written.iter()) + .any(|file| file.ends_with(".cs")) + { + return self.dotnet_checks(scope).await; + } + if !self.root.join("package.json").is_file() + && scope + .iter() + .chain(self.written.iter()) + .any(|file| file.ends_with(".java")) + { + return self.java_checks(scope).await; + } let mut effective_scope = scope.to_vec(); for w in &self.written { if !effective_scope.contains(w) { @@ -3453,13 +3881,26 @@ impl Boundary { } else { policy::FULL_TEST_TIMEOUT_MS }; - let mut args = vec![ + let has_ts_tests = tests + .iter() + .any(|file| file.ends_with(".ts") || file.ends_with(".mts") || file.ends_with(".cts")); + let mut args = Vec::new(); + if has_ts_tests { + args.push("--import".to_owned()); + args.push(TS_IMPORT_HOOK.to_owned()); + } + args.extend([ "--test".to_owned(), "--test-concurrency".to_owned(), jobs.to_string(), format!("--test-timeout={per_test_timeout}"), - ]; - if !full || (!tests.is_empty() && (self.root.join("test").is_dir() || available.len() > 20)) + ]); + if !full + || (!tests.is_empty() + && (has_ts_tests + || self.root.join("test").is_dir() + || self.root.join("src").join("test").is_dir() + || available.len() > 20)) { args.extend(tests); } @@ -3496,7 +3937,7 @@ impl Boundary { native_paths.extend(files.iter().cloned()); let native = policy::requires_native(&native_paths)?; let javascript = files.iter().any(|file| { - [".mjs", ".cjs", ".js"] + [".mjs", ".cjs", ".js", ".ts", ".mts", ".cts"] .iter() .any(|extension| file.ends_with(extension)) }); @@ -3612,13 +4053,15 @@ impl Boundary { } let is_roster_self = self.root.join("rust").join("shell.rs").is_file(); let has_root_cargo = self.root.join("Cargo.toml").is_file(); + let had_root_lock = self.root.join("Cargo.lock").is_file(); let workspace_sub_crate = if !is_roster_self { requirements .files .iter() .chain(self.written.iter()) .find_map(|f| { - let (prefix, _) = f.split_once("/src/")?; + let (prefix, _) = + f.split_once("/src/").or_else(|| f.split_once("/tests/"))?; self.root .join(prefix) .join("Cargo.toml") @@ -3673,7 +4116,7 @@ impl Boundary { } } } - } else if sub_crate.is_some() && !environment.contains_key("CARGO_TARGET_DIR") { + } else if !is_roster_self && !environment.contains_key("CARGO_TARGET_DIR") { if let Ok(repo_paths) = paths::repository_paths(&self.root) { if let Some(main_root) = repo_paths.common_dir.parent() { let shared_target = main_root.join("target"); @@ -3706,13 +4149,39 @@ impl Boundary { } cargo_version = Some(bytes_text(&version.stdout)?.trim().to_owned()); let mut completed = 0; - let has_integration_test = requirements - .files - .iter() - .chain(self.written.iter()) - .any(|f| f.starts_with("tests/")); + let mut integration_stems = Vec::new(); + for file in requirements.files.iter().chain(self.written.iter()) { + if let Some(rest) = file.strip_prefix("tests/") + && !rest.contains('/') + && let Some(stem) = rest.strip_suffix(".rs") + && !integration_stems + .iter() + .any(|existing: &String| existing == stem) + { + integration_stems.push(stem.to_owned()); + } + } + let has_integration_test = !integration_stems.is_empty() + || requirements + .files + .iter() + .chain(self.written.iter()) + .any(|f| f.starts_with("tests/")); let cargo_steps: [Vec; 3] = if let Some(ref sc) = sub_crate { let manifest_rel = format!("{sc}/Cargo.toml"); + let sub_tests_prefix = format!("{sc}/tests/"); + let mut sub_integration_stems = Vec::new(); + for file in requirements.files.iter().chain(self.written.iter()) { + if let Some(rest) = file.strip_prefix(&sub_tests_prefix) + && !rest.contains('/') + && let Some(stem) = rest.strip_suffix(".rs") + && !sub_integration_stems + .iter() + .any(|existing: &String| existing == stem) + { + sub_integration_stems.push(stem.to_owned()); + } + } let target_flag = if self.root.join(sc).join("src").join("lib.rs").is_file() { "--lib" } else { @@ -3722,16 +4191,27 @@ impl Boundary { "check".to_owned(), "--manifest-path".to_owned(), manifest_rel.clone(), - target_flag.to_owned(), - "--offline".to_owned(), ]; + if sub_integration_stems.is_empty() { + check_step.push(target_flag.to_owned()); + } else { + check_step.push("--tests".to_owned()); + } + check_step.push("--offline".to_owned()); let mut test_step = vec![ "test".to_owned(), "--manifest-path".to_owned(), manifest_rel.clone(), - target_flag.to_owned(), - "--offline".to_owned(), ]; + if sub_integration_stems.is_empty() { + test_step.push(target_flag.to_owned()); + } else { + for stem in &sub_integration_stems { + test_step.push("--test".to_owned()); + test_step.push(stem.clone()); + } + } + test_step.push("--offline".to_owned()); let cargo_toml_text = fs::read_to_string(self.root.join(&manifest_rel)).unwrap_or_default(); let touches_server_domain = requirements @@ -3758,41 +4238,49 @@ impl Boundary { } } let src_prefix = format!("{sc}/src/"); - let derived_filter = requirements - .files - .iter() - .chain(self.written.iter()) - .find_map(|f| { - let rel = f.strip_prefix(&src_prefix)?; - let mod_rel = rel - .strip_suffix("/mod.rs") - .or_else(|| rel.strip_suffix(".rs"))?; - if matches!(mod_rel, "lib" | "main") { - let full_src = - fs::read_to_string(self.root.join(f)).unwrap_or_default(); - regex(r"(?m)^\s*mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{") - .ok() - .and_then(|re| { - re.captures_iter(&full_src).find_map(|cap| { - let m = cap.get(1)?.as_str(); - (m != "tests" && m.contains("test")).then(|| m.to_owned()) + let derived_filter = if sub_integration_stems.is_empty() { + requirements + .files + .iter() + .chain(self.written.iter()) + .find_map(|f| { + let rel = f.strip_prefix(&src_prefix)?; + let mod_rel = rel + .strip_suffix("/mod.rs") + .or_else(|| rel.strip_suffix(".rs"))?; + if matches!(mod_rel, "lib" | "main") { + let full_src = + fs::read_to_string(self.root.join(f)).unwrap_or_default(); + regex(r"(?m)^\s*mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{") + .ok() + .and_then(|re| { + re.captures_iter(&full_src).find_map(|cap| { + let m = cap.get(1)?.as_str(); + (m != "tests" && m.contains("test")) + .then(|| m.to_owned()) + }) }) - }) - } else if mod_rel == "server" { - Some("metrics_route".to_owned()) - } else { - let mod_path = mod_rel.replace('/', "::"); - if !mod_path.contains("::") { - Some(format!("{mod_path}::tests")) + } else if mod_rel == "server" { + Some("metrics_route".to_owned()) } else { - Some(mod_path) + let mod_path = mod_rel.replace('/', "::"); + if !mod_path.contains("::") { + Some(format!("{mod_path}::tests")) + } else { + Some(mod_path) + } } - } - }); - if let Some(filter) = derived_filter { + }) + } else { + None + }; + if !full && let Some(filter) = derived_filter { test_step.push("--".to_owned()); test_step.push(filter); test_step.push("--test-threads=2".to_owned()); + } else if sub_integration_stems.is_empty() { + test_step.push("--".to_owned()); + test_step.push("--test-threads=2".to_owned()); } let first_step = if self.root.join("rustfmt.toml").is_file() || self.root.join(".rustfmt.toml").is_file() @@ -3829,8 +4317,46 @@ impl Boundary { ] }; [first_step, check_step, test_step] + } else if !is_roster_self && !had_root_lock { + let mut test_step = vec!["test".to_owned()]; + if integration_stems.is_empty() { + test_step.push("--lib".to_owned()); + test_step.push("--tests".to_owned()); + } else { + for stem in &integration_stems { + test_step.push("--test".to_owned()); + test_step.push(stem.clone()); + } + } + test_step.push("--offline".to_owned()); + [ + vec![ + "metadata".to_owned(), + "--format-version".to_owned(), + "1".to_owned(), + "--no-deps".to_owned(), + "--offline".to_owned(), + ], + vec![ + "check".to_owned(), + "--all-targets".to_owned(), + "--offline".to_owned(), + ], + test_step, + ] } else { let (clippy_args, test_args) = if has_integration_test || !is_roster_self { + let mut t_args = vec!["test".to_owned()]; + if !is_roster_self && !integration_stems.is_empty() { + for stem in &integration_stems { + t_args.push("--test".to_owned()); + t_args.push(stem.clone()); + } + } else { + t_args.push("--all-targets".to_owned()); + } + t_args.push("--locked".to_owned()); + t_args.push("--offline".to_owned()); ( vec![ "clippy".to_owned(), @@ -3841,12 +4367,7 @@ impl Boundary { "-D".to_owned(), "warnings".to_owned(), ], - vec![ - "test".to_owned(), - "--all-targets".to_owned(), - "--locked".to_owned(), - "--offline".to_owned(), - ], + t_args, ) } else { let single_mod = if requirements.files.len() == 1 { @@ -3895,9 +4416,16 @@ impl Boundary { let had_sub_lock = sub_crate .as_ref() .is_some_and(|sc| self.root.join(sc).join("Cargo.lock").is_file()); + let has_bench_scope = requirements + .files + .iter() + .any(|file| file.starts_with("benches/") || file.contains("/benches/")); for args in cargo_steps { + let is_metadata = args.first().map(String::as_str) == Some("metadata"); + let is_all_targets_check = args.first().map(String::as_str) == Some("check") + && args.iter().any(|arg| arg == "--all-targets"); commands.push(format!("cargo {}", args.join(" "))); - let output = self + let mut output = self .process( &approved.executable, &args, @@ -3906,7 +4434,39 @@ impl Boundary { 4 * 1024 * 1024, ) .await?; - stdout.push_str(&bytes_text(&output.stdout)?); + if output.exit != 0 && is_all_targets_check && !has_bench_scope { + let err_text = bytes_text(&output.stderr)?; + if err_text.contains("E0554") && err_text.contains("benches/") { + let fallback_args = args + .iter() + .flat_map(|arg| { + if arg == "--all-targets" { + vec![ + "--lib".to_owned(), + "--bins".to_owned(), + "--tests".to_owned(), + "--examples".to_owned(), + ] + } else { + vec![arg.clone()] + } + }) + .collect::>(); + commands.push(format!("cargo {}", fallback_args.join(" "))); + output = self + .process( + &approved.executable, + &fallback_args, + &environment, + policy::FULL_TEST_TIMEOUT_MS, + 4 * 1024 * 1024, + ) + .await?; + } + } + if !(is_metadata && output.exit == 0) { + stdout.push_str(&bytes_text(&output.stdout)?); + } stderr.push_str(&bytes_text(&output.stderr)?); if output.exit != 0 { exit = output.exit; @@ -3914,6 +4474,9 @@ impl Boundary { } completed += 1; } + if !had_root_lock { + let _ = fs::remove_file(self.root.join("Cargo.lock")); + } if !had_sub_lock && let Some(ref sc) = sub_crate { let _ = fs::remove_file(self.root.join(sc).join("Cargo.lock")); } @@ -3978,9 +4541,11 @@ impl Boundary { domain::put(&mut result, "syntax_check", Value::Boolean(true))?; domain::put(&mut result, "failing_files", strings(&[file]))?; } + if !commands.is_empty() { + domain::put(&mut result, "commands", strings(&commands))?; + } if native { domain::put(&mut result, "native", Value::Boolean(true))?; - domain::put(&mut result, "commands", strings(&commands))?; if let Some(version) = &cargo_version { domain::put(&mut result, "cargo_version", Value::string(version))?; } @@ -4111,7 +4676,28 @@ impl Boundary { "Required Rust verification has no explicit host-approved Cargo executable and environment", )); } - if required.node && policy::tests_mode(self.task())? != "none" && self.host.node20.is_none() + let is_java = !self.root.join("package.json").is_file() + && required + .files + .iter() + .chain(self.written.iter()) + .any(|file| file.ends_with(".java")); + if is_java && policy::tests_mode(self.task())? != "none" && Self::find_javac().is_none() { + return Err(unsupported( + "Java verification requires an installed JDK (javac); only a JRE or no JDK was found on this host", + )); + } + let is_non_node_consumer = is_java + || (!self.root.join("package.json").is_file() + && required + .files + .iter() + .chain(self.written.iter()) + .any(|file| file.ends_with(".py") || file.ends_with(".cs"))); + if required.node + && !is_non_node_consumer + && policy::tests_mode(self.task())? != "none" + && self.host.node20.is_none() { return Err(unsupported( "Required consumer verification has no host-approved Node 20 executable", diff --git a/rust/planning/artifacts.rs b/rust/planning/artifacts.rs index 81d6e6f7..3484bbd6 100644 --- a/rust/planning/artifacts.rs +++ b/rust/planning/artifacts.rs @@ -115,9 +115,14 @@ pub fn build(ask: &Value, options: BuildOptions<'_>) -> Result { .iter() .all(|file| file.ends_with(".md") || file.ends_with(".html")); let rust_only = !files.is_empty() - && files - .iter() - .all(|file| file.ends_with(".rs") || file.ends_with(".toml") || file.ends_with(".py")) + && files.iter().all(|file| { + file.ends_with(".rs") + || file.ends_with(".toml") + || file.ends_with(".py") + || file.ends_with(".cs") + || file.ends_with(".csproj") + || file.ends_with(".java") + }) && !ask.contains("node --test"); let mut checks = task::checked_list(options.checks, "Acceptance checks", 8)? .iter() diff --git a/rust/planning/grounding.rs b/rust/planning/grounding.rs index a81cd44b..4c439cff 100644 --- a/rust/planning/grounding.rs +++ b/rust/planning/grounding.rs @@ -304,12 +304,21 @@ pub fn read_context(root: &Path, files: &[String], ask: &str) -> Result status, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, + Err(error) => { + return Err(secure::io_error( + "Inspect planning grounding file", + &path, + error, + )); + } + }; if !status.is_file() || secure::linked(&status) || status.len() > 512 * 1024 { continue; } + paths::ensure_local_path(&path, root)?; let Some(snapshot) = secure::read(&path, 512 * 1024)? else { continue; }; @@ -680,7 +689,12 @@ pub fn errors( for export in members(Some(item), "exports") { let name = text(export, "Design export must be text")?; let exported = index.exports(&file); - if if exported.is_empty() || file.ends_with(".rs") || file.ends_with(".py") { + if if exported.is_empty() + || file.ends_with(".rs") + || file.ends_with(".py") + || file.ends_with(".cs") + || file.ends_with(".java") + { !index.symbols.contains(&name) && !exported.contains(&name) } else { !exported.contains(&name) @@ -701,6 +715,8 @@ pub fn errors( } if !file.ends_with(".rs") && !file.ends_with(".py") + && !file.ends_with(".cs") + && !file.ends_with(".java") && let Some((owner, _)) = index .exports_by_file .iter() @@ -760,9 +776,13 @@ pub fn errors( } let skip_name_check = !files.is_empty() && (files.iter().all(|f| f.ends_with(".html")) - || files - .iter() - .all(|f| (f.ends_with(".rs") || f.ends_with(".py")) && !f.starts_with("rust/"))); + || files.iter().all(|f| { + (f.ends_with(".rs") + || f.ends_with(".py") + || f.ends_with(".cs") + || f.ends_with(".java")) + && !f.starts_with("rust/") + })); if !skip_name_check { for name in distinct(names) { if index.symbols.contains(&name) diff --git a/rust/planning/intake.rs b/rust/planning/intake.rs index e29758e8..55451baa 100644 --- a/rust/planning/intake.rs +++ b/rust/planning/intake.rs @@ -330,7 +330,7 @@ pub fn requirements(input: &Value, allow_missing: bool) -> Result(...)` inside `test(...)` (never put a static `import * as` statement inside a function body), or use `const mod = await import('../src/...')` inside `test('...', async () => ...)` for a newly created module." }; diff --git a/rust/planning/tools.rs b/rust/planning/tools.rs index 00575625..a6b06397 100644 --- a/rust/planning/tools.rs +++ b/rust/planning/tools.rs @@ -563,6 +563,11 @@ impl Boundary { let mut truncated = false; while let Some(path) = pending.pop() { self.writer.check()?; + let status = fs::symlink_metadata(&path) + .map_err(|error| secure::io_error("Inspect planning search path", &path, error))?; + if secure::linked(&status) { + continue; + } if paths::absolute(&path)? != paths::absolute(self.writer.root())? { paths::ensure_local_path(&path, self.writer.root())?; } @@ -582,11 +587,6 @@ impl Boundary { { continue; } - let status = fs::symlink_metadata(&path) - .map_err(|error| secure::io_error("Inspect planning search path", &path, error))?; - if secure::linked(&status) { - continue; - } if status.is_dir() { let mut children = fs::read_dir(&path) .map_err(|error| { diff --git a/rust/seats/coder.rs b/rust/seats/coder.rs index 4fc81343..cee2bd85 100644 --- a/rust/seats/coder.rs +++ b/rust/seats/coder.rs @@ -1909,15 +1909,24 @@ impl Driver<'_, T, O> { Value::json, ); progress.gate_failures.push(Value::string(&reasons)); - messages.push(message( - "user", - Text::from( - format!( - "Current host finalization failed because counterfactual evaluation at base could not link or run the named test before test(...) executed. One bounded red-green correction is available. In JavaScript tests, use a namespace import (`import * as mod from '../src/...'`) for new exports in existing modules or dynamic `await import('../src/...')` inside `test('...', async () => ...)` for newly created modules, re-run `run_test`, and provide a new summary.\n{reasons}" - ) - .as_str(), - ), - )); + let guidance_text = if reasons.contains(".rs") { + format!( + "Current host finalization failed because Rust counterfactual evaluation at base could not compile or run the named test. One bounded red-green correction is available. Ensure the new `#[test]` function compiles cleanly against the base crate's existing API and fails an assertion on base (rather than failing to compile), re-run `run_test`, and provide a new summary.\n{reasons}" + ) + } else if reasons.contains(".mjs") + || reasons.contains(".cjs") + || reasons.contains(".js") + || reasons.contains(".ts") + { + format!( + "Current host finalization failed because counterfactual evaluation at base could not link or run the named test before test(...) executed. One bounded red-green correction is available. In JavaScript tests, use a namespace import (`import * as mod from '../src/...'`) for new exports in existing modules or dynamic `await import('../src/...')` inside `test('...', async () => ...)` for newly created modules, re-run `run_test`, and provide a new summary.\n{reasons}" + ) + } else { + format!( + "Current host finalization failed because counterfactual evaluation at base could not run the named test. One bounded red-green correction is available. Ensure the new test compiles and fails an assertion against base without setup errors, re-run `run_test`, and provide a new summary.\n{reasons}" + ) + }; + messages.push(message("user", Text::from(guidance_text.as_str()))); continue; } return Err(Handoff::Unavailable.error( diff --git a/rust/seats/tests/focused_review.rs b/rust/seats/tests/focused_review.rs index aaac40b9..439a58be 100644 --- a/rust/seats/tests/focused_review.rs +++ b/rust/seats/tests/focused_review.rs @@ -380,11 +380,7 @@ async fn review_repro_native_cache_rebuild_cannot_count_as_test_repair_progress( boundary.enable_owned_checks()?; let warm = boundary.verify(false).await?; assert_ne!(warm.get("exit_code"), Some(&Value::Number(0.0))); - let target = fixture - .container - .join("approved-target") - .join("debug") - .join(".fingerprint"); + let debug_dir = fixture.container.join("approved-target").join("debug"); let mut responses = vec![calls(vec![( "write", "write_file", @@ -396,7 +392,12 @@ async fn review_repro_native_cache_rebuild_cannot_count_as_test_repair_progress( let mut transport = Recorded::new(responses); transport.action = Some(Box::new(move |request, _| { if request == 2 { - fs::remove_dir_all(&target).map_err(io)?; + let fingerprint = debug_dir.join(".fingerprint"); + if fingerprint.exists() { + fs::remove_dir_all(&fingerprint).map_err(io)?; + } else { + fs::remove_dir_all(&debug_dir).map_err(io)?; + } } Ok(()) })); diff --git a/rust/state/secure.rs b/rust/state/secure.rs index c0e32cce..fcb2408e 100644 --- a/rust/state/secure.rs +++ b/rust/state/secure.rs @@ -35,17 +35,14 @@ pub fn path_error(path: &Path, reason: &str) -> Error { } pub fn linked(metadata: &fs::Metadata) -> bool { - if metadata.file_type().is_symlink() { - return true; - } #[cfg(windows)] { use std::os::windows::fs::MetadataExt; - metadata.file_attributes() & 0x400 != 0 + metadata.file_type().is_symlink() || metadata.file_attributes() & 0x400 != 0 } #[cfg(not(windows))] { - false + metadata.file_type().is_symlink() } } diff --git a/rust/vault/platform.rs b/rust/vault/platform.rs index c59c4d49..d030fe46 100644 --- a/rust/vault/platform.rs +++ b/rust/vault/platform.rs @@ -106,17 +106,20 @@ impl Directory { let identity = paths::handle_information(&file) .map_err(|_| VaultError::Io)? .identity; + let result = file + .write_all(bytes) + .and_then(|()| file.sync_all()) + .map_err(|_| VaultError::Io) + .and_then(|()| native::verify_file(&file)); let mut pending = Pending { directory: self, name, identity, + #[cfg(unix)] + _pinned: file, active: true, }; - let result = file - .write_all(bytes) - .and_then(|()| file.sync_all()) - .map_err(|_| VaultError::Io) - .and_then(|()| native::verify_file(&file)); + #[cfg(not(unix))] drop(file); if let Err(error) = result { pending.cleanup()?; @@ -148,6 +151,8 @@ pub(super) struct Pending<'a> { directory: &'a Directory, name: String, identity: FileIdentity, + #[cfg(unix)] + _pinned: File, active: bool, }