artifactize-harness 0.30.0

The Agent evaluation harness for Artifactize.
Documentation
//! A running Claude Code and the JSON lines between it and artifactize.

use std::{io, path::Path, time::Duration};

use serde_json::{Value, json};
use tokio::{
    io::{AsyncRead, AsyncReadExt, AsyncWrite},
    task::JoinHandle,
};

use super::{
    command::{self, Launch},
    mcp::{self, Server},
    wire::{self, ControlResponse, Initialized, Line},
};
use crate::{
    error::{Code, Failure},
    platform::{self, Environment},
};

/// Keep the end of Claude Code's stderr for an error; it rarely writes more.
const STDERR_LIMIT: usize = 16 * 1024;
/// Read stderr a page at a time; it is small and only its end is kept.
const STDERR_READ: usize = 4096;
/// Claude Code exits on its own once its input closes; past this it is stopped.
const STOP_GRACE: Duration = Duration::from_secs(2);

/// Claude Code's stream, with failures and initialization for a Review run.
pub struct Channel<R, W>(wire::Channel<R, W>);

impl<R: AsyncRead + Unpin, W: AsyncWrite + Unpin> Channel<R, W> {
    pub fn new(reader: R, writer: W) -> Self {
        Self(wire::Channel::new(reader, writer))
    }

    pub async fn send(&mut self, line: &Value) -> Result<(), Failure> {
        self.0
            .send(line)
            .await
            .map_err(|error| failure(error.to_string()))
    }

    pub async fn next(&mut self) -> Result<Option<Line>, Failure> {
        self.0
            .next()
            .await
            .map_err(|error| failure(error.to_string()))
    }

    /// Start the session: answer the MCP server's setup, then return what `initialize`
    /// reported. `server` is the MCP server of a review, `None` for a probe. Its version is
    /// checked by the caller, which can ask `claude --version` when it is missing.
    pub async fn initialize(&mut self, server: Option<&Server>) -> Result<Initialized, Failure> {
        let sdk_servers: Vec<_> = server.map(|_| command::SERVER).into_iter().collect();
        self.send(&wire::control(
            "initialize",
            json!({"subtype": "initialize", "sdkMcpServers": sdk_servers}),
        ))
        .await?;
        loop {
            match self.next().await? {
                None => return Err(failure("Claude Code exited while starting.".into())),
                Some(Line::ControlRequest {
                    request_id,
                    request,
                }) => {
                    let reply = match (server, request) {
                        (Some(server), wire::ControlRequest::McpMessage { message, .. }) => {
                            match server.answer(mcp_request(message)?) {
                                mcp::Answer::Reply(reply) => mcp_reply(&request_id, reply),
                                mcp::Answer::Call { id, .. } => mcp_reply(
                                    &request_id,
                                    mcp::call_error(&id, "The review has not started."),
                                ),
                            }
                        }
                        _ => wire::refusal(&request_id, "Not served by artifactize."),
                    };
                    self.send(&reply).await?;
                }
                Some(Line::ControlResponse {
                    response: ControlResponse::Success { response, .. },
                }) => {
                    return response
                        .map(serde_json::from_value)
                        .transpose()
                        .map(Option::unwrap_or_default)
                        .map_err(|error| {
                            failure(format!("Cannot read Claude Code initialization: {error}."))
                        });
                }
                Some(Line::ControlResponse {
                    response: ControlResponse::Error { error, .. },
                }) => {
                    return Err(failure(format!(
                        "Claude Code refused to start the session: {}",
                        super::shown(&error)
                    )));
                }
                Some(_) => {}
            }
        }
    }
}

pub(super) fn mcp_reply(request_id: &wire::ClaudeRequestId, reply: Value) -> Value {
    wire::reply(request_id, json!({"mcp_response": reply}))
}

pub(super) fn mcp_request(message: Value) -> Result<crate::stdio_mcp::Rpc, Failure> {
    serde_json::from_value(message)
        .map_err(|error| failure(format!("Cannot read Claude Code MCP request: {error}.")))
}

/// Older Claude Code ignores verbatim prompts and would add its own context to the review's.
pub const MINIMUM_VERSION: semver::Version = semver::Version::new(2, 1, 248);

/// Claude Code's version as `initialize` reported it, else as `cli` (`claude --version`)
/// tells, which runs only then: some releases, 2.1.283 among them, leave it out of
/// `initialize`. A Claude Code older than [`MINIMUM_VERSION`] is refused.
pub(super) async fn checked_version(
    reported: Option<&str>,
    cli: impl Future<Output = Result<Option<semver::Version>, String>>,
) -> Result<semver::Version, Failure> {
    let version = match reported.and_then(|text| semver::Version::parse(text).ok()) {
        Some(version) => Some(version),
        None => cli
            .await
            .map_err(|error| Failure::new(Code::AgentError, error))?,
    };
    match version {
        Some(version) if version >= MINIMUM_VERSION => Ok(version),
        _ => Err(Failure::new(
            Code::AgentError,
            format!(
                "Claude Code {} is older than {MINIMUM_VERSION}, which the claude backend needs; run `claude update`.",
                version.map_or_else(
                    || "of an unknown version".into(),
                    |version| version.to_string()
                )
            ),
        )),
    }
}

fn failure(message: String) -> Failure {
    Failure::new(Code::ProviderError, message)
}

/// A started Claude Code: its process, owned with its children, and its stderr.
pub struct Running {
    child: platform::Child,
    stderr: JoinHandle<Vec<u8>>,
    _cwd_dir: Option<artifactize_foundation::platform::private::PrivateTempDir>,
}

pub type ProcessChannel = Channel<tokio::process::ChildStdout, tokio::process::ChildStdin>;

/// Start Claude Code in `cwd`, which holds nothing of the review: Claude Code reads files
/// only through the offered tools.
pub async fn start(
    launch: &Launch<'_>,
    cwd: &Path,
    environment: Environment,
) -> Result<(ProcessChannel, Running), Failure> {
    let command = platform::command(
        command::PROGRAM,
        launch.args(),
        cwd,
        &command::environment(environment),
        true,
    );
    let result = match command {
        Ok(command) => Running::spawn(command).await,
        Err(error) => Err(error),
    };
    let (stdout, stdin, running) = result.map_err(|error| match error.kind() {
        io::ErrorKind::NotFound => Failure::new(
            Code::Authentication,
            "Claude Code (`claude`) is not on PATH; install it and sign in with `claude auth login`.",
        ),
        _ => Failure::new(Code::AgentError, format!("Cannot start Claude Code: process could not be spawned: {error}.")),
    })?;
    Ok((Channel::new(stdout, stdin), running))
}

impl Running {
    async fn spawn(
        command: platform::Command,
    ) -> io::Result<(
        tokio::process::ChildStdout,
        tokio::process::ChildStdin,
        Self,
    )> {
        let mut child = platform::spawn_now(command).await?;
        let stdout = child.stdout().take().expect("stdout is piped");
        let stdin = child.stdin().take().expect("stdin is piped");
        let mut stderr = child.stderr().take().expect("stderr is piped");
        let stderr = tokio::spawn(async move {
            let mut kept = Vec::new();
            let mut buffer = [0; STDERR_READ];
            while let Ok(count) = stderr.read(&mut buffer).await {
                if count == 0 {
                    break;
                }
                kept.extend_from_slice(&buffer[..count]);
                if kept.len() > STDERR_LIMIT {
                    kept.drain(..kept.len() - STDERR_LIMIT);
                }
            }
            kept
        });
        Ok((
            stdout,
            stdin,
            Self {
                child,
                stderr,
                _cwd_dir: None,
            },
        ))
    }

    pub(crate) fn with_tempdir(
        mut self,
        dir: artifactize_foundation::platform::private::PrivateTempDir,
    ) -> Self {
        self._cwd_dir = Some(dir);
        self
    }

    /// Let Claude Code exit after its input closed, stop it past a grace, and return the end
    /// of what it wrote on stderr.
    pub async fn stop(self, channel: ProcessChannel) -> Result<String, Failure> {
        drop(channel);
        let stderr = self.reap().await.map_err(|error| {
            Failure::new(
                Code::AgentError,
                format!("Cannot clean up Claude Code: {error}."),
            )
        })?;
        Ok(super::shown(&crate::platform::output_text(&stderr)))
    }

    async fn reap(mut self) -> io::Result<Vec<u8>> {
        let cleanup = match tokio::time::timeout(STOP_GRACE, self.child.wait()).await {
            Ok(Ok(_)) => self.child.cleanup().await.map(|_| ()),
            Ok(Err(_)) | Err(_) => platform::terminate(&mut self.child).await,
        };
        if cleanup.is_err() {
            // A descendant may still hold stderr open if cleanup failed.
            self.stderr.abort();
        }
        let stderr = match self.stderr.await {
            Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
            result => result,
        };
        cleanup?;
        stderr.map_err(io::Error::other)
    }
}

#[cfg(test)]
mod tests;