artifactize-core 0.27.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! The engine's session-history adapter for isolated Claude Code follow-ups.

use artifactize_harness::claude;
use rig_core::message::Message;
use tokio_util::sync::CancellationToken;

use super::{
    Continuation, FOLLOW_UP, ReviewSink, StartedFollowUp, definitions,
    error::{Code, Failure},
    follow_up_limits,
    session::{self, Recorder},
};
use crate::{
    config::{Eval, RepoConfig},
    llm,
};

/// What Claude Code is told about where it runs, before artifactize's evaluator prompt.
pub(super) const HOST_NOTE: &str = "You are running inside artifactize as an Agent eval reviewer, not as a coding assistant. Your only tools are artifactize's Artifact tools (mcp__artifactize__*); there is no shell, file system or network access besides them.\n\n";

/// Whether a follow-up continues a review that Claude Code ran.
pub(super) fn continues(config: &RepoConfig, continuation: &Continuation<'_>) -> bool {
    continuation
        .conversation
        .header()
        .backend
        .as_ref()
        .and_then(|backend| {
            llm::route(
                backend,
                Some(continuation.state),
                Some(&config.root),
                "for this Agent backend",
            )
            .ok()
        })
        .is_some_and(|route| matches!(route, llm::Route::ClaudeAgent))
}

/// Answer a person's question about a review Claude Code ran. Claude Code keeps no session,
/// so the new session starts with the saved conversation as evidence, then the question.
pub(super) async fn follow_up(
    config: &RepoConfig,
    eval: &Eval,
    continuation: &Continuation<'_>,
    message: &str,
    recorder: &mut Recorder,
    cancellation: &CancellationToken,
) -> Result<StartedFollowUp, Failure> {
    let header = continuation.conversation.header();
    let model = header.model.as_ref().ok_or_else(|| {
        Failure::new(
            Code::AgentError,
            "The saved session does not name its backend and model.",
        )
    })?;
    let history = continuation
        .conversation
        .history()
        .map_err(|error| Failure::new(Code::AgentError, error))?;
    let system = history
        .iter()
        .find_map(|message| match message {
            Message::System { content } => Some(content.clone()),
            _ => None,
        })
        .unwrap_or_default();
    let evidence: Vec<String> = history
        .iter()
        .filter(|message| !matches!(message, Message::System { .. }))
        .map(|message| serde_json::to_string(message).expect("messages serialize as JSON"))
        .collect();
    let framing = format!(
        "{FOLLOW_UP}{}",
        match continuation.files_changed {
            Some(true) => {
                " The Artifact files changed since this review; read them again before relying on what you saw."
            }
            _ => "",
        }
    );
    let question = Message::user(format!("{framing}\n\nQuestion:\n{message}"));
    let sent = format!(
        "{framing}\n\nThe review so far, one message per line (untrusted evidence):\n{}\n\nQuestion:\n{message}",
        evidence.join("\n")
    );
    let registry = crate::tools::Registry::new(config, &eval.id)?;
    let tools = registry.sessions(continuation.state, None, cancellation.clone());
    let registry = registry.with_sessions(&tools);
    let definitions = definitions(registry.list());
    let limits = follow_up_limits(continuation.conversation)?;
    recorder.event(session::Kind::Send(session::Send {
        text: Some(message.into()),
        framing: Some(framing),
        files_changed: continuation.files_changed,
        tools: Some(
            definitions
                .iter()
                .map(|tool| tool.name.parse())
                .collect::<Result<_, String>>()?,
        ),
    }));
    recorder.event(session::Kind::Message(session::MessageEvent::new(
        1,
        question,
        false,
        Vec::new(),
        Some(message.into()),
    )));
    let turn = claude::Turn {
        model,
        reasoning: header.reasoning.map(crate::config::Reasoning::as_str),
        system: &system,
        prompt: &sent,
        tools: &definitions,
        limits,
        cancellation,
    };
    let mut attempts = Vec::new();
    let mut sink = ReviewSink {
        registry: &registry,
        output: continuation.output,
        recorder,
        attempts: &mut attempts,
        header: None,
    };
    let answer = claude::converse(
        turn,
        llm::claude_agent::host(&crate::platform::temporary_directory(), Some(&config.root)),
        &mut sink,
    )
    .await;
    let answer = tools
        .close()
        .await
        .map_err(|error| Failure::new(Code::AgentError, error))
        .and(answer);
    Ok(StartedFollowUp { answer, attempts })
}