artifactize-harness 0.27.1

The Agent evaluation harness for Artifactize.
Documentation
//! The `claude-agent` backend: the user's own Claude Code, signed in with `claude auth login`,
//! runs each review. artifactize starts `claude -p` in stream-json mode, offers the eval's
//! tools as one MCP server it hosts in its own process, and reads the conversation back. It
//! never reads Claude Code's login, performs OAuth itself, or changes Claude Code's requests.

pub mod auth;
mod channel;
pub mod command;
mod conversation;
mod record;
use crate::stdio_mcp as mcp;
mod wire;
pub use wire::{Account, Model};

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

use tokio::time::Instant;
use tokio_util::sync::CancellationToken;

pub use channel::MINIMUM_VERSION;

use artifactize_foundation::platform::{private::PrivateTempDir, probe};
use artifactize_provider::{llm::models::ListedModel, names::ModelId};
use rig_core::{completion::ToolDefinition, message::Message};

use crate::{
    Event, Io, Review,
    api::{self, Api},
    budgets::Limits,
    error::{Code, Failure},
    platform::Environment,
    verdict::{Issues, Judgment},
};
use channel::Running;
use command::Launch;
use conversation::Conversation;
use mcp::Server;

/// Bound one error text from Claude Code shown in output and saved records.
const SHOWN_CHARS: usize = 2000;
/// A probe starts a session and reads its `initialize` answer; Claude Code answers in a few
/// seconds, so a stalled one stops well before the thirty seconds a model listing may take.
const PROBE_TIMEOUT: Duration = Duration::from_secs(25);

/// Claude Code's text cleaned for a terminal and clipped.
fn shown(text: &str) -> String {
    let cleaned = crate::platform::output_text(text.trim().as_bytes());
    match cleaned.char_indices().nth(SHOWN_CHARS) {
        Some((end, _)) => format!("{}…", &cleaned[..end]),
        None => cleaned.into_owned(),
    }
}

/// What a session's `initialize` reports, without sending a message: Claude Code's version,
/// the signed-in account and the models it offers.
pub struct Probe {
    pub version: Option<String>,
    pub account: Option<wire::Account>,
    pub models: Vec<wire::Model>,
}

/// Open a Claude Code session and read its `initialize` answer; no tokens are used.
pub async fn probe(host: Host<'_>, cancellation: &CancellationToken) -> Result<Probe, Failure> {
    let deadline = Instant::now() + PROBE_TIMEOUT;
    let cwd_dir = host
        .directory("artifactize-claude-probe-")
        .map_err(|error| {
            Failure::new(
                Code::AgentError,
                format!("Cannot create isolated directory for Claude Code probe: {error}."),
            )
        })?;
    let (mut channel, running) =
        channel::start(&Launch::default(), cwd_dir.path(), host.environment).await?;
    let running = running.with_tempdir(cwd_dir);
    let initialized = tokio::select! {
        biased;
        _ = cancellation.cancelled() => Err(Failure::cancelled()),
        _ = tokio::time::sleep_until(deadline) => Err(Failure::timeout()),
        initialized = channel.initialize(None) => initialized,
    };
    let initialized = after_stop(initialized, running.stop(channel).await, with_stderr)?;
    Ok(Probe {
        version: initialized.claude_code_version,
        account: initialized.account,
        models: initialized.models,
    })
}

/// The models Claude Code offers, by the id `--model` takes, without a model call. An alias
/// such as `opus` lists the model it runs; `default` is listed only when no other entry runs
/// its model.
pub async fn models(host: Host<'_>) -> Result<Vec<ListedModel>, String> {
    let probe = probe(host, &CancellationToken::new())
        .await
        .map_err(|failure| failure.message)?;
    Ok(listed(probe.models))
}

fn listed(models: Vec<wire::Model>) -> Vec<ListedModel> {
    let entries: Vec<(String, wire::Model)> = models
        .into_iter()
        .map(|model| {
            (
                model
                    .resolved_model
                    .clone()
                    .unwrap_or_else(|| model.value.clone()),
                model,
            )
        })
        .collect();
    let mut listed: Vec<ListedModel> = Vec::new();
    for (id, model) in &entries {
        if model.value == "default"
            && entries
                .iter()
                .any(|(other, entry)| other == id && entry.value != "default")
        {
            continue;
        }
        let Ok(slug) = id.parse::<ModelId>() else {
            continue;
        };
        if listed.iter().any(|entry| entry.slug == slug) {
            continue;
        }
        let entry = ListedModel::new(
            slug,
            model.display_name.clone().unwrap_or_else(|| id.clone()),
        );
        if model.supports_effort == Some(false) {
            listed.push(entry);
            continue;
        }
        // Earlier Claude Code versions only advertised model names. Their `--effort`
        // switch is still available; newer versions publish the allowed levels per model.
        let levels = model.supported_effort_levels.clone().unwrap_or_else(|| {
            ["low", "medium", "high", "xhigh", "max"]
                .map(str::to_owned)
                .into()
        });
        listed.push(entry.with_efforts(levels, model.default_effort.clone()));
    }
    listed
}

/// A failure with what Claude Code wrote on stderr, when it explains more.
pub(crate) fn with_stderr(failure: Failure, stderr: &str) -> Failure {
    if stderr.is_empty() {
        failure
    } else {
        Failure {
            message: format!("{} Claude Code: {stderr}", failure.message),
            ..failure
        }
    }
}

/// Native inputs not owned by the harness. The engine knows its workspace markers and the
/// unbundled environment; Foundation leases and validates the directory before Claude starts.
pub struct Host<'a> {
    pub environment: Environment,
    pub temporary_parent: &'a Path,
    pub workspace: Option<&'a Path>,
    pub markers: probe::Markers<'a>,
}

impl Host<'_> {
    fn directory(&self, prefix: &str) -> Result<PrivateTempDir, probe::Error> {
        probe::directory(
            prefix,
            self.temporary_parent,
            self.workspace.as_slice(),
            &self.markers,
        )
    }
}

/// Run the supplied eval in a new isolated Claude Code session.
pub async fn review(
    review: Review<'_>,
    host: Host<'_>,
    io: &mut impl Io,
) -> Result<Judgment, Failure> {
    let issues = Issues::new(review.red_at);
    let system = crate::verdict::review_system(review.system);
    let mut parameters = api::parameters(Api::ClaudeAgent, review.reasoning, review.cache_key)?;
    api::output_format(Api::ClaudeAgent, &mut parameters, issues.schema.clone());
    io.event(Event::Started {
        parameters,
        tools: &review.tools,
    });
    io.event(Event::Message {
        turn: 1,
        message: &Message::system(system.clone()),
        repair: false,
    });
    io.event(Event::Message {
        turn: 1,
        message: &Message::user(review.prompt.clone()),
        repair: false,
    });
    let turn = Turn {
        model: review.model,
        reasoning: review.reasoning,
        system: &system,
        prompt: &review.prompt,
        tools: &review.tools,
        limits: review.limits,
        cancellation: review.cancellation,
    };
    let (mut conversation, running) = turn.open(host, Some(&issues.schema), io).await?;
    let result = judge(&mut conversation, turn.prompt, &issues).await;
    close(conversation, running, result).await
}

/// Inputs for one free-text exchange. The engine supplies its saved history as evidence
/// in `prompt`; the harness does not load it or record the person's question.
pub struct Turn<'a> {
    pub model: &'a ModelId,
    pub reasoning: Option<&'a str>,
    pub system: &'a str,
    pub prompt: &'a str,
    pub tools: &'a [ToolDefinition],
    pub limits: Limits,
    pub cancellation: &'a CancellationToken,
}

pub async fn converse(turn: Turn<'_>, host: Host<'_>, io: &mut impl Io) -> Result<String, Failure> {
    let (mut conversation, running) = turn.open(host, None, io).await?;
    let answer = conversation.ask(turn.prompt).await;
    close(conversation, running, answer).await
}

impl Turn<'_> {
    async fn open<'a, I: Io>(
        &'a self,
        host: Host<'_>,
        schema: Option<&serde_json::Value>,
        io: &'a mut I,
    ) -> Result<(Started<'a, I>, Running), Failure> {
        let cwd_dir = host.directory("artifactize-claude-").map_err(|error| {
            Failure::new(
                Code::AgentError,
                format!("Cannot create isolated directory for claude-agent eval: {error}."),
            )
        })?;
        let launch = Launch {
            model: Some(self.model.as_str()),
            effort: self.reasoning,
            system: Some(self.system),
            tools: self.tools.iter().map(|tool| tool.name.as_str()).collect(),
            schema,
        };
        let (channel, running) = channel::start(&launch, cwd_dir.path(), host.environment).await?;
        let running = running.with_tempdir(cwd_dir);
        let session = Session {
            server: Server::new(self.tools),
            tools: self.tools,
            model: self.model,
            limits: self.limits,
            cancellation: self.cancellation,
            io,
        };
        let mut conversation = Conversation::new(session, channel);
        match conversation.initialize().await {
            Ok(()) => Ok((conversation, running)),
            Err(failure) => Err(close::<(), I>(conversation, running, Err(failure))
                .await
                .unwrap_err()),
        }
    }
}

struct Session<'a, I> {
    server: Server,
    tools: &'a [ToolDefinition],
    model: &'a ModelId,
    limits: Limits,
    cancellation: &'a CancellationToken,
    io: &'a mut I,
}

type Started<'a, I> = Conversation<'a, I, tokio::process::ChildStdout, tokio::process::ChildStdin>;

/// Ask for the issues and validate them, with one format repair: tools are then refused.
async fn judge<R, W>(
    conversation: &mut Conversation<'_, impl Io, R, W>,
    prompt: &str,
    issues: &Issues,
) -> Result<Judgment, Failure>
where
    R: tokio::io::AsyncRead + Unpin,
    W: tokio::io::AsyncWrite + Unpin,
{
    let answer = conversation.ask(prompt).await?;
    let error = match issues.parse_model(&answer) {
        Ok(result) => return Ok(result),
        Err(error) => error,
    };
    let repair = Issues::repair_prompt(error);
    conversation.session.io.event(Event::Message {
        turn: conversation.turn + 1,
        message: &Message::user(repair.clone()),
        repair: true,
    });
    conversation.tools_open = false;
    let answer = conversation.ask(&repair).await?;
    issues.parse_model(&answer).map_err(Issues::repair_failed)
}

/// Stop Claude Code after its conversation ends and include its stderr on process failures.
async fn close<T, I: Io>(
    mut conversation: Started<'_, I>,
    running: Running,
    result: Result<T, Failure>,
) -> Result<T, Failure> {
    if let Err(failure) = &result {
        conversation.fail(failure);
    }
    after_stop(
        result,
        running.stop(conversation.channel).await,
        |failure, stderr| match failure.code {
            Code::ProviderError | Code::AgentError => with_stderr(failure, stderr),
            _ => failure,
        },
    )
}

/// Keep a failure's classification, but do not report success if cleanup failed.
fn after_stop<T>(
    result: Result<T, Failure>,
    stopped: Result<String, Failure>,
    output: impl FnOnce(Failure, &str) -> Failure,
) -> Result<T, Failure> {
    match (result, stopped) {
        (result, Ok(stderr)) => result.map_err(|failure| output(failure, &stderr)),
        (Ok(_), Err(cleanup)) => Err(cleanup),
        (Err(mut failure), Err(cleanup)) => {
            failure.message.push(' ');
            failure.message.push_str(&cleanup.message);
            Err(failure)
        }
    }
}

#[cfg(test)]
mod tests;