artifactize-core 0.32.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
use std::process::Stdio;

use artifactize_foundation::platform::process::{
    ResolvedCommand, resolved_command, spawn_detached, spawn_now, spawn_run,
};
use tokio::io::AsyncReadExt;
use windows_sys::Win32::{
    System::Console::GetConsoleWindow, UI::WindowsAndMessaging::IsWindowVisible,
};

const WINDOW_PROBE: &str = "platform::windows::process::console_tests::console_window_probe";
const WORKER_PROBE: &str = "platform::windows::process::console_tests::run_worker_probe";
const HANDOFF_PROBE: &str = "platform::windows::process::console_tests::handoff_probe";
const WINDOW: &str = "console window: ";

/// The desktop app has no console, so the probes run from a detached process: the case in
/// which Windows gives a console program a window of its own. A host probe, a program
/// artifactize owns (a Human output tool, a chat child), a program a Run worker starts (an
/// eval's git or claude), and a console program a handoff starts as any program would (the
/// `node` an `npx` Launch tool's `cmd.exe` starts) each show none.
#[test]
fn console_programs_started_without_a_console_show_no_window() {
    let mut parent = crate::test_os::test_command(
        "platform::windows::process::console_tests::detached_parent_probe",
        &[],
    );
    let output = crate::test_os::detached_launch(parent.arg("--ignored"))
        .output()
        .unwrap();
    assert!(output.status.success(), "{output:?}");
    let stdout = String::from_utf8_lossy(&output.stdout);
    for started in ["host probe", "owned", "run worker", "handoff"] {
        assert!(
            stdout.contains(&format!("{started}: hidden")),
            "{started}: {output:?}"
        );
    }
}

#[tokio::test]
#[ignore = "launched detached by the console window test"]
async fn detached_parent_probe() {
    // SAFETY: GetConsoleWindow only reads this process's console attachment.
    assert!(
        unsafe { GetConsoleWindow() }.is_null(),
        "the parent has no console"
    );
    let exe = std::env::current_exe().unwrap();
    let host = crate::platform::program::tool_output(
        exe.to_str().unwrap(),
        ["--exact", WINDOW_PROBE, "--ignored", "--nocapture"].map(std::ffi::OsStr::new),
    )
    .expect("the window probe runs");
    println!("host probe: {}", window(&host));
    println!("owned: {}", owned_window().await);

    println!(
        "run worker: {}",
        relayed(spawn_run(probe(WORKER_PROBE)).unwrap()).await
    );
    println!(
        "handoff: {}",
        relayed(spawn_detached(probe(HANDOFF_PROBE)).unwrap()).await
    );
}

/// What the console program a detached `child` started saw, as the child relays it.
async fn relayed(mut child: tokio::process::Child) -> String {
    let mut stdout = Vec::new();
    let mut pipe = child.stdout.take().unwrap();
    pipe.read_to_end(&mut stdout).await.unwrap();
    assert!(child.wait().await.unwrap().success());
    window(&stdout).to_owned()
}

/// A Run worker: it reports what the console program it owns saw.
#[tokio::test]
#[ignore = "launched as a Run worker by the detached parent"]
async fn run_worker_probe() {
    println!("{WINDOW}{}", owned_window().await);
}

/// A handed-off program: it starts the window probe as any program does, with no flags of
/// artifactize's, and reports what the probe saw.
#[test]
#[ignore = "launched as a desktop handoff by the detached parent"]
fn handoff_probe() {
    let output = crate::test_os::isolated_test_command(WINDOW_PROBE, &[])
        .arg("--ignored")
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()
        .unwrap();
    assert!(output.status.success(), "{output:?}");
    println!("{WINDOW}{}", window(&output.stdout));
}

#[test]
#[ignore = "launched as a console program by the probes above"]
fn console_window_probe() {
    // SAFETY: both calls only read; IsWindowVisible accepts a null window.
    let visible = unsafe { IsWindowVisible(GetConsoleWindow()) } != 0;
    println!("{WINDOW}{}", if visible { "visible" } else { "hidden" });
}

/// Start the window probe as artifactize starts a program it owns, and return what it saw.
async fn owned_window() -> String {
    let mut child = spawn_now(probe(WINDOW_PROBE)).await.unwrap();
    let mut stdout = Vec::new();
    let mut pipe = child.stdout().take().unwrap();
    pipe.read_to_end(&mut stdout).await.unwrap();
    assert!(child.wait().await.unwrap().success());
    window(&stdout).to_owned()
}

fn probe(test: &str) -> ResolvedCommand {
    let exe = std::env::current_exe().unwrap();
    let mut command =
        resolved_command(&exe, ["--exact", test, "--ignored", "--nocapture"]).unwrap();
    command
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null());
    command
}

/// What a probe's output says of its console window: `visible`, `hidden`, or the whole
/// output when it says nothing.
fn window(stdout: &[u8]) -> &str {
    let text = std::str::from_utf8(stdout).unwrap_or("not UTF-8");
    text.lines()
        .find_map(|line| line.strip_prefix(WINDOW))
        .unwrap_or(text)
}