diff --git a/.github/workflows/rrx-windows-acceptance.yml b/.github/workflows/rrx-windows-acceptance.yml new file mode 100644 index 000000000..0fb18bd95 --- /dev/null +++ b/.github/workflows/rrx-windows-acceptance.yml @@ -0,0 +1,44 @@ +name: RRX Windows acceptance + +on: + push: + branches: ["rrx/integrate-607-610-20260921"] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: rrx-windows-${{ github.ref }} + cancel-in-progress: false + +jobs: + windows-acceptance: + runs-on: windows-2022 + timeout-minutes: 45 + env: + CARGO_TERM_COLOR: never + CARGO_BUILD_JOBS: "2" + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + fetch-depth: 0 + persist-credentials: false + - name: Prepare standard Rust toolchain + shell: pwsh + run: | + rustup toolchain install stable --profile minimal --component rustfmt + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + rustup override set stable + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + rustc --version + cargo --version + git rev-parse HEAD + - name: Formatting + run: cargo fmt --all -- --check + - name: Complete default Runner regression + run: cargo test --locked -p webcodex-runner -- --test-threads=1 + - name: Explicit shell and validation stdin isolation + run: cargo test --locked -p webcodex-runner job_stdin_isolated -- --ignored --test-threads=1 + - name: Startup summary contracts + run: cargo test --locked -p webcodex --lib semantic_navigation -- --test-threads=1 diff --git a/crates/webcodex-runner/Cargo.toml b/crates/webcodex-runner/Cargo.toml index 78e8ca97b..32895a7f6 100644 --- a/crates/webcodex-runner/Cargo.toml +++ b/crates/webcodex-runner/Cargo.toml @@ -43,6 +43,8 @@ windows-sys = { version = "0.61.2", features = [ "Win32_Foundation", "Win32_Globalization", "Win32_Storage_FileSystem", + "Win32_System_IO", + "Win32_System_Pipes", "Win32_System_Threading", ] } @@ -51,5 +53,7 @@ windows-sys = { version = "0.61.2", features = [ [target.'cfg(windows)'.dev-dependencies] windows-sys = { version = "0.61.2", features = [ "Win32_Foundation", + "Win32_Security", + "Win32_System_Pipes", "Win32_System_Threading", ] } diff --git a/crates/webcodex-runner/src/main.rs b/crates/webcodex-runner/src/main.rs index 3e3552ef9..ae1032e7e 100644 --- a/crates/webcodex-runner/src/main.rs +++ b/crates/webcodex-runner/src/main.rs @@ -4699,8 +4699,11 @@ impl JobManager { .map(|(key, value)| (key.as_str(), value.as_str())), ); } + // Raw Shell Jobs and validation steps have no stdin payload. + // Preserve the Runner parent-liveness pipe for the Runner alone. command .current_dir(&cwd_path) + .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); commands.push_back(command); @@ -5734,7 +5737,43 @@ fn handle_one_poll( .map_err(PollError::from_submit) } +#[cfg(windows)] +fn isolate_inherited_standard_pipes() -> std::io::Result<()> { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::{ + SetHandleInformation, HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE, + }; + use windows_sys::Win32::Storage::FileSystem::{GetFileType, FILE_TYPE_PIPE}; + + // Parent leases and capture pipes belong to this process. Explicit child + // stdio is prepared separately by Command; unrelated inheritable copies + // must not keep the Desktop's readers alive after this Runner exits. + for handle in [ + std::io::stdin().as_raw_handle(), + std::io::stdout().as_raw_handle(), + std::io::stderr().as_raw_handle(), + ] { + if handle.is_null() || handle == INVALID_HANDLE_VALUE { + continue; + } + // SAFETY: standard handles are borrowed from this process, never closed + // or retargeted here. Only the inheritance bit of actual pipes changes. + if unsafe { GetFileType(handle) } == FILE_TYPE_PIPE + && unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0) } == 0 + { + return Err(std::io::Error::last_os_error()); + } + } + Ok(()) +} + fn main() { + // Run before threads, providers, or the detached internal mode can spawn. + #[cfg(windows)] + if let Err(error) = isolate_inherited_standard_pipes() { + eprintln!("webcodex-runner cannot isolate parent standard pipes: {error}"); + std::process::exit(1); + } if let Some(code) = webcodex_runner::detached_job::maybe_run_internal_mode(std::env::args().skip(1)) { diff --git a/crates/webcodex-runner/src/main_tests.rs b/crates/webcodex-runner/src/main_tests.rs index 503f0e954..2d45c8201 100644 --- a/crates/webcodex-runner/src/main_tests.rs +++ b/crates/webcodex-runner/src/main_tests.rs @@ -1,4 +1,8 @@ use super::*; + +#[cfg(windows)] +#[path = "main_tests/stdio_inheritance.rs"] +mod stdio_inheritance; use crate::webcodex_runner::config::validate_shell_config; use crate::webcodex_runner::run_shell_with_profiles; use crate::webcodex_runner::{ diff --git a/crates/webcodex-runner/src/main_tests/file_read.rs b/crates/webcodex-runner/src/main_tests/file_read.rs index 51fc29c90..9c60014d9 100644 --- a/crates/webcodex-runner/src/main_tests/file_read.rs +++ b/crates/webcodex-runner/src/main_tests/file_read.rs @@ -130,14 +130,18 @@ fn runner_file_read_range_output_obeys_max_bytes() { #[test] fn runner_file_read_range_rejects_serialized_envelope_expansion_before_stdout() { for (name, byte, len) in [ - ("nul.txt", 0x00, 48 * 1024), + // NUL is a reserved Windows device name even with a .txt suffix. + // Exercise NUL bytes in an ordinary file, not the device namespace. + ("nul-bytes.txt", 0x00, 48 * 1024), ("quote.txt", b'\"', 140 * 1024), ("backslash.txt", b'\\', 140 * 1024), ("control.txt", 0x01, 48 * 1024), ] { let tmp = tempfile::tempdir().unwrap(); let policy = project_policy(tmp.path()); - std::fs::write(tmp.path().join(name), vec![byte; len]).unwrap(); + let fixture = vec![byte; len]; + std::fs::write(tmp.path().join(name), &fixture).unwrap(); + assert_eq!(std::fs::read(tmp.path().join(name)).unwrap(), fixture); let out = handle_file_request( &policy, &file_read_request(tmp.path(), name, Some(1), Some(1), Some(512 * 1024)), @@ -146,7 +150,11 @@ fn runner_file_read_range_rejects_serialized_envelope_expansion_before_stdout() out.exit_code.is_none(), "unexpected success for {name}: {out:?}" ); - assert_eq!(out.error.as_deref(), Some("range output too large")); + assert_eq!( + out.error.as_deref(), + Some("range output too large"), + "unexpected range result for {name}" + ); assert!( out.stdout.is_none(), "oversized envelope reached stdout for {name}" diff --git a/crates/webcodex-runner/src/main_tests/stdio_inheritance.rs b/crates/webcodex-runner/src/main_tests/stdio_inheritance.rs new file mode 100644 index 000000000..21e7c2993 --- /dev/null +++ b/crates/webcodex-runner/src/main_tests/stdio_inheritance.rs @@ -0,0 +1,131 @@ +//! Real Windows pipe inheritance, isolated from the test harness's own stdio. +use super::*; +use std::io::Read; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use webcodex_process::ManagedChild; + +const TEST_NAME: &str = + "tests::stdio_inheritance::standard_pipes_do_not_leak_to_unrelated_descendants"; +const MODE: &str = "WEBCODEX_STDIO_INHERITANCE_FIXTURE"; +const READY: &str = "WEBCODEX_STDIO_INHERITANCE_READY"; + +fn fixture_command(mode: &str) -> Command { + let mut command = Command::new(std::env::current_exe().unwrap()); + command.args(["--exact", TEST_NAME, "--nocapture"]); + command.env(MODE, mode); + command +} + +#[test] +fn standard_pipes_do_not_leak_to_unrelated_descendants() { + match std::env::var(MODE).as_deref() { + Ok("descendant") => { + std::fs::write(std::env::var_os(READY).unwrap(), b"ready").unwrap(); + // The outer ManagedChild owns this whole fixture tree. It terminates + // the still-live descendant only after checking capture EOF. + std::thread::sleep(Duration::from_secs(60)); + return; + } + Ok("explicit-inherit") => { + println!("EXPLICIT_CHILD_STDOUT"); + eprintln!("EXPLICIT_CHILD_STDERR"); + return; + } + Ok("worker") => { + isolate_inherited_standard_pipes().unwrap(); + println!("PARENT_STDOUT_PRESERVED"); + eprintln!("PARENT_STDERR_PRESERVED"); + let status = fixture_command("explicit-inherit") + .stdin(Stdio::null()) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .status() + .unwrap(); + assert!(status.success()); + let ready = PathBuf::from(std::env::var_os(READY).unwrap()); + // Deliberately outlive the direct worker. The external ManagedChild + // owns and reaps both; dropping this Child does not kill it early. + #[allow(clippy::zombie_processes)] + let _descendant = fixture_command("descendant") + .env(READY, &ready) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(15); + while !ready.is_file() { + assert!(Instant::now() < deadline, "descendant did not start"); + std::thread::sleep(Duration::from_millis(10)); + } + return; + } + Ok(other) => panic!("unexpected fixture mode: {other}"), + Err(_) => {} + } + + let temp = tempfile::tempdir().unwrap(); + let mut command = fixture_command("worker"); + command + .env(READY, temp.path().join("ready")) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut worker = ManagedChild::spawn(&mut command).unwrap(); + let stdout = worker.child_mut().stdout.take().unwrap(); + let stderr = worker.child_mut().stderr.take().unwrap(); + let (tx, rx) = mpsc::channel(); + let stdout_tx = tx.clone(); + let stdout_reader = std::thread::spawn(move || { + let mut bytes = Vec::new(); + let result = std::io::BufReader::new(stdout).read_to_end(&mut bytes); + let _ = stdout_tx.send(("stdout", result, bytes)); + }); + let stderr_reader = std::thread::spawn(move || { + let mut bytes = Vec::new(); + let result = std::io::BufReader::new(stderr).read_to_end(&mut bytes); + let _ = tx.send(("stderr", result, bytes)); + }); + let validation = (|| -> Result<(), String> { + let deadline = Instant::now() + Duration::from_secs(20); + let status = loop { + if let Some(status) = worker.try_wait().map_err(|e| e.to_string())? { + break status; + } + if Instant::now() >= deadline { + return Err("stdio worker did not exit".into()); + } + std::thread::sleep(Duration::from_millis(10)); + }; + if !status.success() { + return Err(format!("stdio worker failed: {status}")); + } + if worker.try_tree_exit().map_err(|e| e.to_string())? { + return Err("descendant exited before the pipe inheritance assertion".into()); + } + for _ in 0..2 { + let (stream, read, bytes) = rx + .recv_timeout(Duration::from_secs(2)) + .map_err(|_| "capture pipe stayed open after the direct worker exited")?; + read.map_err(|e| e.to_string())?; + let text = String::from_utf8(bytes).map_err(|e| e.to_string())?; + let expected = if stream == "stdout" { + ["PARENT_STDOUT_PRESERVED", "EXPLICIT_CHILD_STDOUT"] + } else { + ["PARENT_STDERR_PRESERVED", "EXPLICIT_CHILD_STDERR"] + }; + if !expected.iter().all(|marker| text.contains(marker)) { + return Err(format!("explicit {stream} output was lost")); + } + } + Ok(()) + })(); + // Cleanup occurs before asserting the result, including the regression's + // failure path. No unrelated process or numeric process-tree lookup is used. + worker.terminate_tree().unwrap(); + assert!(worker.wait_tree_exit(Duration::from_secs(5)).unwrap()); + stdout_reader.join().unwrap(); + stderr_reader.join().unwrap(); + validation.unwrap(); +} diff --git a/crates/webcodex-runner/src/webcodex_runner/job_manager_tests.rs b/crates/webcodex-runner/src/webcodex_runner/job_manager_tests.rs index 30519e44b..f265b70e2 100644 --- a/crates/webcodex-runner/src/webcodex_runner/job_manager_tests.rs +++ b/crates/webcodex-runner/src/webcodex_runner/job_manager_tests.rs @@ -4716,3 +4716,181 @@ fn runner_real_process_job_timeout_terminates_the_whole_tree() { "delayed grandchild marker must never appear after timeout" ); } + +#[test] +#[ignore = "real-process stdin isolation: runs an isolated JobManager with parent-only input"] +fn runner_real_process_shell_job_stdin_isolated() { + assert_local_job_stdin_isolated("runner_real_process_shell_job_stdin_isolated", false); +} + +#[test] +#[ignore = "real-process stdin isolation: covers every step of a validation Job"] +fn runner_real_process_validation_job_stdin_isolated() { + assert_local_job_stdin_isolated("runner_real_process_validation_job_stdin_isolated", true); +} + +fn assert_local_job_stdin_isolated(test_name: &str, validation: bool) { + const FIXTURE_ENV: &str = "WEBCODEX_TEST_JOB_STDIN_FIXTURE"; + const PARENT_INPUT: &str = "parent-liveness-input-must-not-reach-jobs\n"; + if std::env::var(FIXTURE_ENV).as_deref() == Ok(test_name) { + let root = tempfile::tempdir().unwrap(); + let mut shell = ShellConfig::default(); + #[cfg(windows)] + let probe = + "if ([Console]::In.ReadToEnd().Length -ne 0) { exit 9 }; Write-Output 'JOB_STDIN_EOF'"; + #[cfg(unix)] + let probe = "if IFS= read -r line; then exit 9; fi; printf 'JOB_STDIN_EOF\\n'"; + let mut request: RunnerRequest = serde_json::from_value(json!({ + "request_id": "stdin-isolation-request", + "client_id": "ws-client", + "kind": "start_job", + "job_id": "stdin-isolation-job", + "cwd": root.path(), + "command": probe, + "timeout_secs": 5, + "requested_by": "test", + "created_at": 0, + "job_context": test_job_context(root.path(), Vec::new()), + })) + .unwrap(); + if validation { + let bin = root.path().join("bin"); + std::fs::create_dir(&bin).unwrap(); + std::fs::copy( + &structured_process_helper().path, + bin.join(format!("cargo{}", std::env::consts::EXE_SUFFIX)), + ) + .unwrap(); + shell.path_prepend.push(bin); + let steps = vec![ + ShellJobValidationStep { + name: "format".into(), + program: "cargo".into(), + args: vec!["fmt".into(), "--".into(), "--check".into()], + env: Vec::new(), + }, + ShellJobValidationStep { + name: "check".into(), + program: "cargo".into(), + args: vec!["check".into(), "--all-targets".into()], + env: Vec::new(), + }, + ]; + request.kind = "start_validation_job".to_string(); + request.command = serde_json::to_string(&steps).unwrap(); + request.job_context = Some(test_job_context( + root.path(), + vec!["format".into(), "check".into()], + )); + } + let (tx, mut rx) = tokio::sync::mpsc::channel(64); + let sink = RunnerSink::WebSocket { + tx, + client_id: "ws-client".to_string(), + runner_instance_id: "stdin-isolation-instance".to_string(), + }; + let manager = JobManager::new(1); + manager.enqueue( + sink, + PendingJobStart::from_wire( + 1, + RunnerPolicy { + allow_raw_shell: true, + allow_cwd_anywhere: true, + ..RunnerPolicy::default() + }, + shell, + SshConfig::default(), + root.path().join("project-registry"), + request, + ), + ); + let updates = collect_job_updates(&mut rx, Duration::from_secs(10)); + let terminal = updates.last().expect("Job must emit an update"); + assert!( + terminal.finished, + "Job did not reach terminal: {terminal:?}" + ); + assert_eq!( + terminal.status, "completed", + "Job inherited parent stdin: {terminal:?}" + ); + assert_eq!( + terminal.exit_code, + Some(0), + "Job must receive EOF: {terminal:?}" + ); + if validation { + assert_eq!(terminal.validation_progress.as_ref().unwrap().completed, 2); + } + let stdout = terminal.log_snapshot.as_ref().unwrap().stdout.tail.as_str(); + assert_eq!( + stdout.matches("JOB_STDIN_EOF").count(), + if validation { 2 } else { 1 } + ); + let mut remaining = String::new(); + std::io::stdin().read_to_string(&mut remaining).unwrap(); + assert_eq!( + remaining, PARENT_INPUT, + "Jobs must not consume Runner input" + ); + return; + } + + // Isolate the inherited input in a subprocess; never replace process-global + // stdin in the test runner or depend on an interactive terminal / installed Git. + let root = tempfile::tempdir().unwrap(); + let input = root.path().join("parent-input"); + std::fs::write(&input, PARENT_INPUT).unwrap(); + let mut command = Command::new(std::env::current_exe().unwrap()); + command + .args([ + "--exact", + &format!( + "{}::{test_name}", + module_path!().split_once("::").unwrap().1 + ), + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .env(FIXTURE_ENV, test_name) + .stdin(std::fs::File::open(input).unwrap()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = ManagedChild::spawn(&mut command).unwrap(); + let mut stdout = child.child_mut().stdout.take().unwrap(); + let mut stderr = child.child_mut().stderr.take().unwrap(); + let out = std::thread::spawn(move || { + let mut bytes = Vec::new(); + stdout.read_to_end(&mut bytes).unwrap(); + bytes + }); + let err = std::thread::spawn(move || { + let mut bytes = Vec::new(); + stderr.read_to_end(&mut bytes).unwrap(); + bytes + }); + let deadline = Instant::now() + Duration::from_secs(20); + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break status; + } + if Instant::now() >= deadline { + child.terminate_tree().unwrap(); + break child.wait().unwrap(); + } + std::thread::sleep(Duration::from_millis(10)); + }; + // Reclaim descendants even after a failed fixture before joining pipe readers. + child.terminate_tree().unwrap(); + let stdout = out.join().unwrap(); + let stderr = err.join().unwrap(); + assert!( + status.success(), + "isolated {test_name} failed:\n{}\n{}", + String::from_utf8_lossy(&stdout), + String::from_utf8_lossy(&stderr) + ); + assert!(String::from_utf8_lossy(&stdout).contains("1 passed")); +} diff --git a/crates/webcodex-runner/src/webcodex_runner/lsp/navigation.rs b/crates/webcodex-runner/src/webcodex_runner/lsp/navigation.rs index 2b188f744..c118d7ab4 100644 --- a/crates/webcodex-runner/src/webcodex_runner/lsp/navigation.rs +++ b/crates/webcodex-runner/src/webcodex_runner/lsp/navigation.rs @@ -6,7 +6,7 @@ use super::super::config::RunnerPolicy; use super::super::output::CommandResult; -use super::super::projects::load_runner_project_summaries_from_dir; +use super::super::projects::find_project_shell_context_by_id; use super::super::shell::cwd_allowed; use super::language::{ detected_profiles, primary_profile, route_extension, supported_extensions_label, @@ -237,9 +237,13 @@ fn resolve_runner_project( "project_id cannot be empty", )); } - let projects = load_runner_project_summaries_from_dir(project_registry_dir); - let project = projects.into_iter().find(|p| p.id == id).ok_or_else(|| { - RunnerLspResultEnvelope::err(error_codes::UNKNOWN_PROJECT, "unknown agent project") + // Only registration identity is needed. Inventory summaries execute Git in + // every project and can exhaust the startup status probe's entire budget. + let project = find_project_shell_context_by_id(project_registry_dir, id).ok_or_else(|| { + RunnerLspResultEnvelope::err( + error_codes::UNKNOWN_PROJECT, + "unknown or disabled agent project", + ) })?; Ok(ResolvedProject { path: PathBuf::from(project.path), diff --git a/crates/webcodex-runner/src/webcodex_runner/lsp/navigation_tests.rs b/crates/webcodex-runner/src/webcodex_runner/lsp/navigation_tests.rs index ea0893486..d589f0718 100644 --- a/crates/webcodex-runner/src/webcodex_runner/lsp/navigation_tests.rs +++ b/crates/webcodex-runner/src/webcodex_runner/lsp/navigation_tests.rs @@ -610,6 +610,82 @@ fn call_hierarchy_preserves_unicode_scalar_positions_and_language_profiles() { } } +#[test] +fn lsp_project_lookup_does_not_enrich_unrelated_projects_with_git() { + let _serial = super::serialize_fake_lsp_test(); + let fixture = NavFixture::new("normal"); + for index in 0..7 { + fs::write( + fixture + .project_registry_dir + .join(format!("unrelated-{index}.toml")), + format!( + "id = \"other-{index}\"\npath = {:?}\n", + fixture.root.to_string_lossy() + ), + ) + .unwrap(); + } + let before = + crate::webcodex_runner::projects::PROJECT_GIT_CAPTURE_COUNT.with(|count| count.get()); + let result = fixture.request(RunnerLspPayload { + project_id: "demo".into(), + request: RunnerLspRequest::Status, + }); + assert_eq!(result["success"], true, "{result}"); + let after = + crate::webcodex_runner::projects::PROJECT_GIT_CAPTURE_COUNT.with(|count| count.get()); + assert_eq!( + after, before, + "LSP project lookup must not execute Git in any registered project" + ); + assert!(!fixture.marker.exists(), "status must remain lazy"); +} + +#[test] +fn lsp_project_lookup_rechecks_disabled_and_removed_registrations() { + let _serial = super::serialize_fake_lsp_test(); + let fixture = NavFixture::new("normal"); + let request = || { + fixture.request(RunnerLspPayload { + project_id: "demo".into(), + request: RunnerLspRequest::Status, + }) + }; + assert_eq!(request()["success"], true); + let registration = fixture.project_registry_dir.join("demo.toml"); + fs::write( + ®istration, + format!( + "id = \"demo\"\npath = {:?}\ndisabled = true\n", + fixture.root.to_string_lossy() + ), + ) + .unwrap(); + // A disabled first record must shadow a later duplicate, not enable it. + fs::write( + fixture.project_registry_dir.join("z-duplicate.toml"), + format!( + "id = \"demo\"\npath = {:?}\n", + fixture.root.to_string_lossy() + ), + ) + .unwrap(); + assert_eq!( + request()["success"], + false, + "disabled project must not resolve" + ); + fs::remove_file(fixture.project_registry_dir.join("z-duplicate.toml")).unwrap(); + fs::remove_file(®istration).unwrap(); + assert_eq!( + request()["success"], + false, + "removed registration must not be cached" + ); + assert!(!fixture.marker.exists()); +} + #[test] fn status_does_not_start_server_and_unavailable_succeeds() { let _serial = super::serialize_fake_lsp_test(); diff --git a/crates/webcodex-runner/src/webcodex_runner/mcp_gateway_tests.rs b/crates/webcodex-runner/src/webcodex_runner/mcp_gateway_tests.rs index 43d9af4ce..e48ec35f8 100644 --- a/crates/webcodex-runner/src/webcodex_runner/mcp_gateway_tests.rs +++ b/crates/webcodex-runner/src/webcodex_runner/mcp_gateway_tests.rs @@ -472,9 +472,17 @@ fn malformed_unknown_and_duplicate_responses_fail_closed() { #[test] fn timeout_and_invalid_untrusted_outputs_are_bounded() { - let timeout = Fixture::new("timeout", 1); + // The assertion below exercises a dispatched call timeout, not cold process + // startup. Initialize separately, then retain the one-second call budget. + let mut timeout = Fixture::new("timeout", 5); let provider = timeout.provider(); - assert!(timeout.list(&provider).error.is_none()); + let initial = timeout.list(&provider); + assert!( + initial.error.is_none(), + "initial list failed before timeout scenario: {:?}", + initial.error + ); + timeout.manager.request_timeout = Duration::from_secs(1); let response = timeout.call(&provider); assert_eq!(response.error.as_ref().unwrap().code, "provider_timeout"); assert_eq!( diff --git a/crates/webcodex-runner/src/webcodex_runner/projects.rs b/crates/webcodex-runner/src/webcodex_runner/projects.rs index 00ac97b60..72b46da6a 100644 --- a/crates/webcodex-runner/src/webcodex_runner/projects.rs +++ b/crates/webcodex-runner/src/webcodex_runner/projects.rs @@ -221,7 +221,9 @@ fn load_runner_project_shell_contexts_from_dir(dir: &Path) -> Vec = const { std::cell::Cell::new(0) }; +} + fn run_git_capture(path: &str, args: &[&str], shutdown: Option<&AtomicBool>) -> Option { + #[cfg(test)] + PROJECT_GIT_CAPTURE_COUNT.with(|count| count.set(count.get() + 1)); let output = run_git_bounded(Path::new(path), args, PROJECT_GIT_TIMEOUT, shutdown).ok()?; if !output.status.success() || output.stdout_capped { return None; diff --git a/crates/webcodex-runner/src/webcodex_runner/transport.rs b/crates/webcodex-runner/src/webcodex_runner/transport.rs index c20659a82..148a6c99a 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport.rs @@ -475,7 +475,34 @@ fn install_shutdown_listener( .map_err(|_| "failed to start process shutdown signal listener".to_string()) } +#[cfg(windows)] +const PARENT_PIPE_POLL_INTERVAL: Duration = Duration::from_millis(20); + +#[cfg(windows)] +fn install_parent_liveness_listener(runtime: RunnerRuntimeState) -> Result<(), String> { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Storage::FileSystem::{GetFileType, FILE_TYPE_PIPE}; + + let stdin = std::io::stdin(); + let handle = stdin.as_raw_handle() as usize; + if unsafe { GetFileType(handle as _) } == FILE_TYPE_PIPE { + let listener = spawn_windows_pipe_parent_liveness_listener(handle, runtime)?; + // The process owns stdin for its whole lifetime. The listener stops on + // pipe EOF/error or an already-requested Runner shutdown, so detaching + // the JoinHandle does not transfer ownership of any external resource. + drop(listener); + return Ok(()); + } + + install_blocking_parent_liveness_listener(runtime) +} + +#[cfg(not(windows))] fn install_parent_liveness_listener(runtime: RunnerRuntimeState) -> Result<(), String> { + install_blocking_parent_liveness_listener(runtime) +} + +fn install_blocking_parent_liveness_listener(runtime: RunnerRuntimeState) -> Result<(), String> { use std::io::Read; let listener = std::thread::Builder::new() @@ -494,14 +521,76 @@ fn install_parent_liveness_listener(runtime: RunnerRuntimeState) -> Result<(), S } }) .map_err(|_| "failed to start parent-liveness listener".to_string())?; - // This reader is intentionally detached. A blocking stdin read cannot be - // cancelled portably; joining it during an ordinary signal-driven shutdown - // would hang until the parent closed the lease. Process exit reclaims the - // detached thread, while EOF still triggers exact-generation shutdown. + // Non-pipe stdin may require a genuinely blocking read. Keep the legacy + // detached behavior for consoles and Unix streams; process exit reclaims + // the listener while EOF still triggers exact-generation shutdown. drop(listener); Ok(()) } +#[cfg(windows)] +fn spawn_windows_pipe_parent_liveness_listener( + pipe_handle: usize, + runtime: RunnerRuntimeState, +) -> Result, String> { + use windows_sys::Win32::Storage::FileSystem::ReadFile; + use windows_sys::Win32::System::Pipes::PeekNamedPipe; + + std::thread::Builder::new() + .name("webcodex-runner-parent-lease".to_string()) + .spawn(move || { + let pipe = pipe_handle as windows_sys::Win32::Foundation::HANDLE; + let mut discard = [0_u8; 64]; + loop { + if runtime.shutdown_requested() { + return; + } + + let mut available = 0_u32; + let peeked = unsafe { + PeekNamedPipe( + pipe, + std::ptr::null_mut(), + 0, + std::ptr::null_mut(), + &mut available, + std::ptr::null_mut(), + ) + }; + if peeked == 0 { + // Preserve the historical lease contract: any stdin read + // failure is equivalent to parent EOF and requests Runner + // shutdown. Broken anonymous pipes land here without a + // blocking ReadFile on the Windows startup path. + runtime.request_shutdown_signal(); + return; + } + + if available == 0 { + std::thread::sleep(PARENT_PIPE_POLL_INTERVAL); + continue; + } + + let to_read = available.min(discard.len() as u32); + let mut bytes_read = 0_u32; + let read = unsafe { + ReadFile( + pipe, + discard.as_mut_ptr(), + to_read, + &mut bytes_read, + std::ptr::null_mut(), + ) + }; + if read == 0 || bytes_read == 0 { + runtime.request_shutdown_signal(); + return; + } + } + }) + .map_err(|_| "failed to start parent-liveness listener".to_string()) +} + fn send_polling_offline_best_effort(client: &Client, cfg: &RunnerConfig, runner_instance_id: &str) { let url = format!( "{}{}", diff --git a/crates/webcodex-runner/src/webcodex_runner/transport_tests.rs b/crates/webcodex-runner/src/webcodex_runner/transport_tests.rs index e0126c3df..3da119cf0 100644 --- a/crates/webcodex-runner/src/webcodex_runner/transport_tests.rs +++ b/crates/webcodex-runner/src/webcodex_runner/transport_tests.rs @@ -119,6 +119,149 @@ fn test_runtime(cfg: &RunnerConfig) -> RunnerRuntimeState { RunnerRuntimeState::new(cfg, PathBuf::new()) } +#[cfg(windows)] +struct WindowsTestHandle(usize); + +#[cfg(windows)] +impl WindowsTestHandle { + fn raw(&self) -> windows_sys::Win32::Foundation::HANDLE { + self.0 as windows_sys::Win32::Foundation::HANDLE + } + + fn close(&mut self) { + if self.0 != 0 { + unsafe { + windows_sys::Win32::Foundation::CloseHandle(self.raw()); + } + self.0 = 0; + } + } +} + +#[cfg(windows)] +impl Drop for WindowsTestHandle { + fn drop(&mut self) { + self.close(); + } +} + +#[cfg(windows)] +fn windows_test_pipe() -> (WindowsTestHandle, WindowsTestHandle) { + use windows_sys::Win32::System::Pipes::CreatePipe; + + let mut read = std::ptr::null_mut(); + let mut write = std::ptr::null_mut(); + let created = unsafe { CreatePipe(&mut read, &mut write, std::ptr::null(), 0) }; + assert_ne!(created, 0, "CreatePipe failed"); + ( + WindowsTestHandle(read as usize), + WindowsTestHandle(write as usize), + ) +} + +#[cfg(windows)] +#[tokio::test] +async fn windows_parent_pipe_lease_allows_registration_until_writer_closes() { + use windows_sys::Win32::Storage::FileSystem::WriteFile; + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let (registered_tx, registered_rx) = oneshot::channel(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + let _register = read_register(&mut ws).await; + send_registered_ack(&mut ws).await; + let _ = registered_tx.send(()); + + loop { + let msg = tokio::time::timeout(Duration::from_secs(5), ws.next()) + .await + .expect("Runner did not close after parent stdin EOF") + .expect("WebSocket closed before Runner goodbye") + .expect("Runner shutdown frame is valid"); + if !msg.is_text() { + continue; + } + let envelope = RunnerEnvelope::from_slice(msg.into_text().unwrap().as_bytes()).unwrap(); + if matches!(envelope, RunnerEnvelope::Goodbye { .. }) { + break; + } + } + }); + + let cfg = test_runner_config(format!("http://{}", addr)); + let runtime = test_runtime(&cfg); + let (read_pipe, mut write_pipe) = windows_test_pipe(); + let parent_listener = + spawn_windows_pipe_parent_liveness_listener(read_pipe.0, runtime.clone()).unwrap(); + + // Preserve the historical contract that stdin bytes are ignored. More + // importantly, prove the pipe watcher does not mistake an open idle lease + // for EOF while WebSocket registration and project inventory run. + let payload = b"ignored-parent-lease-data"; + let mut bytes_written = 0_u32; + let wrote = unsafe { + WriteFile( + write_pipe.raw(), + payload.as_ptr(), + payload.len() as u32, + &mut bytes_written, + std::ptr::null_mut(), + ) + }; + assert_ne!(wrote, 0, "WriteFile failed"); + assert_eq!(bytes_written as usize, payload.len()); + tokio::time::sleep(PARENT_PIPE_POLL_INTERVAL * 3).await; + assert!( + !runtime.shutdown_requested(), + "open parent stdin pipe requested shutdown before registration" + ); + + let session_cfg = cfg.clone(); + let session_runtime = runtime.clone(); + let session = tokio::spawn(async move { + websocket_session( + &session_cfg, + vec![test_project("parent-pipe-registration")], + "inst-parent-pipe", + &session_runtime, + ) + .await + }); + + tokio::time::timeout(Duration::from_secs(5), registered_rx) + .await + .expect("Runner registration was blocked by the open parent stdin pipe") + .expect("registration fixture ended before reporting readiness"); + assert!( + !runtime.shutdown_requested(), + "open parent stdin pipe requested shutdown after registration" + ); + assert!( + !session.is_finished(), + "registered Runner session ended while the parent stdin pipe was still open" + ); + + write_pipe.close(); + + let exit = tokio::time::timeout(Duration::from_secs(5), session) + .await + .expect("Runner did not stop after parent stdin EOF") + .expect("Runner session task panicked") + .expect("Runner session returned an error"); + assert_eq!(exit, RunnerSessionExit::Shutdown); + server.await.unwrap(); + + tokio::time::timeout( + Duration::from_secs(1), + tokio::task::spawn_blocking(move || parent_listener.join().unwrap()), + ) + .await + .expect("parent-liveness pipe watcher did not exit after EOF") + .unwrap(); +} + fn wait_for_path(path: &Path, deadline: Instant, context: &str) { while !path.exists() { assert!( diff --git a/crates/webcodex-runner/src/webcodex_runner/validation/mod.rs b/crates/webcodex-runner/src/webcodex_runner/validation/mod.rs index 8cf066903..641ea9644 100644 --- a/crates/webcodex-runner/src/webcodex_runner/validation/mod.rs +++ b/crates/webcodex-runner/src/webcodex_runner/validation/mod.rs @@ -16,7 +16,7 @@ pub(crate) use registry::{adapter_metadata, registered_adapter_ids}; use super::config::RunnerPolicy; use super::output::CommandResult; -use super::projects::load_runner_project_summaries_from_dir; +use super::projects::find_project_shell_context_by_id; use super::shell::cwd_allowed; use crate::validation_bridge::{ failure_kinds, validate_bridge_request, ValidationBridgeRequest, ValidationBridgeResponse, @@ -153,14 +153,11 @@ fn resolve_runner_project( project_registry_dir: &Path, project_id: &str, ) -> Result { - let projects = load_runner_project_summaries_from_dir(project_registry_dir); - let project = projects - .into_iter() - .find(|p| p.id == project_id) - .ok_or_else(|| { + let project = + find_project_shell_context_by_id(project_registry_dir, project_id).ok_or_else(|| { ValidationBridgeResultEnvelope::err( failure_kinds::UNKNOWN_PROJECT, - "unknown agent project", + "unknown or disabled agent project", ) })?; Ok(PathBuf::from(project.path)) diff --git a/crates/webcodex-runner/src/webcodex_runner/validation/tests.rs b/crates/webcodex-runner/src/webcodex_runner/validation/tests.rs index 378716912..b66b95272 100644 --- a/crates/webcodex-runner/src/webcodex_runner/validation/tests.rs +++ b/crates/webcodex-runner/src/webcodex_runner/validation/tests.rs @@ -139,6 +139,35 @@ fn with_path_mode(bin_dir: &std::path::Path, available: bool, f: impl FnOnce( f() } +#[test] +fn validation_project_lookup_is_git_free_and_rejects_disabled() { + let temp = tempfile::tempdir().unwrap(); + let registry = temp.path().join("registry"); + fs::create_dir(®istry).unwrap(); + let registration = registry.join("demo.toml"); + let text = format!( + "id = \"demo\"\npath = {:?}\n", + temp.path().to_string_lossy() + ); + fs::write(®istration, &text).unwrap(); + let before = + crate::webcodex_runner::projects::PROJECT_GIT_CAPTURE_COUNT.with(|count| count.get()); + let resolved = resolve_runner_project(®istry, "demo").unwrap(); + assert_eq!( + resolved.canonicalize().unwrap(), + temp.path().canonicalize().unwrap() + ); + let after = + crate::webcodex_runner::projects::PROJECT_GIT_CAPTURE_COUNT.with(|count| count.get()); + assert_eq!( + after, before, + "validation lookup must not run unrelated Git commands" + ); + fs::write(®istration, format!("{text}disabled = true\n")).unwrap(); + assert!(resolve_runner_project(®istry, "demo").is_err()); + assert!(resolve_runner_project(®istry, "unknown").is_err()); +} + #[test] fn registry_exposes_pyright_only_for_now() { assert_eq!(registered_adapter_ids(), vec!["pyright"]); diff --git a/docs/agent/rrx-maintenance.md b/docs/agent/rrx-maintenance.md new file mode 100644 index 000000000..f70ae7dd9 --- /dev/null +++ b/docs/agent/rrx-maintenance.md @@ -0,0 +1,47 @@ +# Thin maintenance fork + +This branch maintains a small, reviewable patch set on upstream WebCodex v0.4.1. +It is not an upstream release, a replacement architecture, or a business-data store. + +## Branch contract + +- `main` follows `yyjeqhc/webcodex` without local product changes. +- `rrx-stable` points only to the source of the most recently accepted installed runtime. +- `rrx/integrate-*` branches contain candidate backports and validation work. A green build alone does not authorize moving `rrx-stable` or replacing a running installation. +- Use fast-forward updates and explicit refspecs. Never force-push or publish all local refs. + +The initial accepted runtime baseline is `75ae07b16cb4f0c05a1e07f2ac7cad9afbb8c436`. +Its upstream release base is `f080c8f3ea70e37bd9f17fdd0e1b4c3a3aa330f8`. +The reviewed upstream snapshot for this integration is `37098d4624f0000bfab54ad102ecb0df619d7dc6`. + +## Patch inventory + +| Patch | Why it is retained | Retirement condition | +| --- | --- | --- | +| Python/TypeScript startup summary and schema | Report providers supported by the existing native LSP implementation | Equivalent upstream summary and schema pass the same tests | +| Mixed-language LSP, Windows URI identity, diagnostic freshness | Allow mixed projects and reject stale diagnostics without widening the Runner-wide process cap | Equivalent upstream fixes pass Windows error/clean/error and capacity tests | +| Markdown artifact inference | Preserve Markdown filenames and exact bytes through supported artifact transport | Equivalent upstream artifact implementation passes resource readback | +| Registration-only lookup for LSP and validation | Avoid scanning unrelated Git repositories on each bounded status request | Upstream lookup avoids Git enrichment while preserving registration and root policy checks | +| MCP timeout fixture separation | Test call deadlines independently from cold process startup | Equivalent upstream fixture isolates both budgets | +| Upstream PR #607 stdin isolation | Raw shell and validation children receive EOF, not the Runner's parent-liveness input | Integrated upstream source includes ae52912cd599d329d95d619e2a272e427d60ab56 or equivalent | +| Upstream PR #610 Runner parent-pipe observation | Windows pipe monitoring must not block registration and must notice parent EOF | Integrated upstream source includes the relevant 37098d4624f0000bfab54ad102ecb0df619d7dc6 behavior | +| Windows standard-pipe inheritance fence | Detached descendants must not retain unrelated parent capture pipes after the Runner exits | Equivalent upstream startup isolation passes the live-descendant capture-EOF regression | + +The #607 backport maps the upstream JobManager module back to the v0.4.1 `src/main.rs` location and adapts private test fixtures. Its two real-process tests remain ignored by default and are run explicitly during acceptance. +The #610 backport imports the Runner pipe-listener code and original regression, with required Windows API feature declarations. It does not import unrelated Desktop relocation, UI, Goal, or file-transfer refactoring changes. +No production deadline, authentication, authorization, sandbox, or process-lifetime boundary is relaxed to make tests pass. + +The additional standard-pipe fence is a local corrective patch, not part of upstream #607 or #610. It clears only the inheritance flag of this process's existing standard pipe handles before any worker or internal detached mode starts; the handles remain open and usable. The isolated Windows regression keeps a descendant alive while proving parent capture EOF, and separately proves explicitly inherited stdout/stderr still work. Deployment acceptance must also retain a detached Job across Runner replacement with real parent and capture pipes. + +## Validation and deployment + +Run the dedicated Windows acceptance workflow on the exact candidate commit. It uses a clean hosted Windows machine, read-only repository permissions, and no private credentials or runtime state. Local policy-blocked tests remain blocked observations; hosted success does not turn a local denial into a pass. + +Before deployment, additionally verify on the target host: cold and warm startup summaries, mixed-language navigation, fresh diagnostics, guarded writes, artifact byte readback, typed command execution, and actual parent-lease close/restart behavior. Preserve the previous installed binaries and configuration, verify that unrelated tasks are idle, and use the existing Desktop lifecycle. Never retry a failed activation without first inspecting its receipt and current process state. + +Advance `rrx-stable` only after the running CLI, Server, and Runner report the same clean source commit and online functional acceptance succeeds. Keep deployment receipts and rollback data outside this public repository. + +## Publication and trust boundary + +Only generic source, tests, and maintenance documentation belong in this public fork. Do not commit business files, host paths, logs, account identifiers, tokens, certificates, runtime databases, or rollback snapshots. +Do not disable Smart App Control, enterprise application control, antivirus, or code-integrity enforcement. Any local signing or allow-rule change requires identification of the actual policy and approval by its owner. No such policy change is part of this patch set. diff --git a/docs/agent/semantic-navigation-startup.md b/docs/agent/semantic-navigation-startup.md index 5192d705a..3c4f7d83c 100644 --- a/docs/agent/semantic-navigation-startup.md +++ b/docs/agent/semantic-navigation-startup.md @@ -13,6 +13,13 @@ observed status determines `available`, `recommended`, and `position_encoding`. A missing/mismatched provider record remains a malformed result. No server process is launched by the startup status probe. +Project resolution uses the enabled registry record, not a Git-enriched inventory +scan. LSP and validation do not execute Git in unrelated repositories before +handling a request. The selected root is still checked against Runner policy; +disabled/removed registrations are re-read on every request, and a later duplicate +cannot re-enable a disabled first record. The normal inventory retains its Git +metadata; no stale availability cache or wider permissions are introduced. + The two-second shared probe deadline and cancellation behavior are unchanged. Timeout remains `probe_timeout` with `available=null`, not a positive or negative availability claim. Direct `lsp_status` can provide a separate current observation. @@ -21,3 +28,18 @@ observed, to avoid changing unrelated wire compatibility. The diagnostic output schema includes the Python/TypeScript language, provider, and limitation values. No tools, permissions, or response-size bounds are added. + +## Windows shell lifecycle acceptance + +Use an independently installed, signature-verified PowerShell executable for a +Runner whose child-process cleanup must be enforced by Windows Job Objects. On +the inspected host, Store-packaged PowerShell 7.6.6 left native descendants alive +after the owning job was terminated; changing the alias to the package's actual +path did not repair it. The official standalone 7.6.6 distribution and Windows +PowerShell 5.1 passed the same parent/descendant test. A Runner-local `shell.program` +and `shell.path_prepend` can select the verified standalone distribution without +changing the user's global PATH or uninstalling the Store app. + +Do not weaken Windows application-control policy for generated test executables. +A policy denial is an environment-blocked test, not a successful plugin test or +permission to retry the blocked executable through a different route. diff --git a/tests/fixtures/process_argv_helper.rs b/tests/fixtures/process_argv_helper.rs index 14428f953..a863e55c5 100644 --- a/tests/fixtures/process_argv_helper.rs +++ b/tests/fixtures/process_argv_helper.rs @@ -159,6 +159,16 @@ fn main() { println!("{}:{value}", value.len()); } } + // Canonical validation argv for the isolated Job stdin fixture. Tests + // copy this executable to cargo[.exe]; no real Cargo command runs here. + Some("fmt" | "check") => { + let mut input = String::new(); + std::io::stdin().read_to_string(&mut input).unwrap(); + if !input.is_empty() { + std::process::exit(9); + } + println!("JOB_STDIN_EOF"); + } Some("stdin") => { let mut input = String::new(); std::io::stdin().read_to_string(&mut input).unwrap();