Skip to main content

rinne_loop/
evaluator.rs

1//! Evaluator execution (`CONTEXT.md` §10, §12).
2//!
3//! Tool evaluators run a command and check its exit code — tool-grounded
4//! grading, preferred where possible. AI evaluators return a review whose
5//! verdict the engine parses. Human evaluators are handled by the engine's
6//! parking logic.
7
8use std::path::Path;
9use std::process::Stdio;
10use std::time::Duration;
11
12use async_trait::async_trait;
13use tokio::process::Command;
14
15use crate::dag::{Acceptance, Node, OnFail};
16use crate::Result;
17use rinne_types::{EvalContext, Evaluator, Gate};
18
19/// The result of grading a node.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct EvalVerdict {
22    pub passed: bool,
23    /// On failure, the concrete critique fed back to the generator.
24    pub output: String,
25}
26
27/// A tool evaluator: run the node's acceptance command, pass iff it exits as
28/// required. The combined output is the critique on failure.
29pub struct ToolEvaluator;
30
31#[async_trait(?Send)]
32impl Evaluator for ToolEvaluator {
33    async fn grade(&self, node: &Node, ctx: &dyn EvalContext) -> Result<Gate> {
34        let policy = node.parsed_on_fail().unwrap_or(OnFail::Replan);
35        let Some(Acceptance { command, must_exit }) = node.acceptance.clone() else {
36            return Ok(Gate::Fail {
37                critique: "tool evaluator has no acceptance command".into(),
38                policy,
39            });
40        };
41        let (passed, output) = ctx.run_tool(node, &command, must_exit).await?;
42        if passed {
43            Ok(Gate::Pass)
44        } else {
45            Ok(Gate::Fail { critique: output, policy })
46        }
47    }
48}
49
50/// An AI evaluator: a worker reviews the work and ends with a machine-readable
51/// verdict. Absent or `FAIL` fails closed; an explicit `REPLAN` triggers a replan.
52pub struct AiEvaluator;
53
54#[async_trait(?Send)]
55impl Evaluator for AiEvaluator {
56    async fn grade(&self, node: &Node, ctx: &dyn EvalContext) -> Result<Gate> {
57        let Some(review) = ctx.run_ai(node, AI_VERDICT_INSTRUCTION).await? else {
58            return Ok(Gate::Fail {
59                critique: format!("no worker for AI evaluator needs {:?}", node.needs),
60                policy: node.parsed_on_fail().unwrap_or(OnFail::Replan),
61            });
62        };
63        // A model can explicitly call for a replan ("wrong approach").
64        if review.to_uppercase().contains("VERDICT: REPLAN") {
65            return Ok(Gate::Fail { critique: review, policy: OnFail::Replan });
66        }
67        let verdict = parse_ai_verdict(&review);
68        if verdict.passed {
69            Ok(Gate::Pass)
70        } else {
71            Ok(Gate::Fail {
72                critique: verdict.output,
73                policy: node.parsed_on_fail().unwrap_or(OnFail::Replan),
74            })
75        }
76    }
77}
78
79/// A human evaluator: there is no automatic verdict, so it parks for the user.
80pub struct HumanEvaluator;
81
82#[async_trait(?Send)]
83impl Evaluator for HumanEvaluator {
84    async fn grade(&self, node: &Node, _ctx: &dyn EvalContext) -> Result<Gate> {
85        Ok(Gate::Park {
86            question: node.instruction.clone(),
87        })
88    }
89}
90
91/// Run a tool evaluator's acceptance command in `workspace`, passing iff the
92/// process exits with `must_exit`. The combined output becomes the critique on
93/// failure (`CONTEXT.md` §10 acceptance).
94pub async fn run_tool(
95    workspace: &Path,
96    command: &str,
97    must_exit: i32,
98    timeout: Duration,
99) -> Result<EvalVerdict> {
100    let mut cmd = Command::new("sh");
101    cmd.arg("-c")
102        .arg(command)
103        .current_dir(workspace)
104        .stdin(Stdio::null())
105        .stdout(Stdio::piped())
106        .stderr(Stdio::piped())
107        .kill_on_drop(true);
108
109    let output = match tokio::time::timeout(timeout, cmd.output()).await {
110        Ok(Ok(o)) => o,
111        Ok(Err(e)) => {
112            return Ok(EvalVerdict {
113                passed: false,
114                output: format!("failed to run `{command}`: {e}"),
115            });
116        }
117        Err(_) => {
118            return Ok(EvalVerdict {
119                passed: false,
120                output: format!("acceptance command timed out: `{command}`"),
121            });
122        }
123    };
124
125    let code = output.status.code().unwrap_or(-1);
126    let stdout = String::from_utf8_lossy(&output.stdout);
127    let stderr = String::from_utf8_lossy(&output.stderr);
128    let passed = code == must_exit;
129
130    let combined = format!(
131        "$ {command}\nexit: {code} (required {must_exit})\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}"
132    );
133
134    Ok(EvalVerdict {
135        passed,
136        output: combined,
137    })
138}
139
140/// Parse an AI evaluator's review into a verdict. The engine instructs AI
141/// evaluators to end with `VERDICT: PASS` or `VERDICT: FAIL`; absent or
142/// `FAIL` is treated as a failure (fail-closed), and the full review is the
143/// critique.
144pub fn parse_ai_verdict(review: &str) -> EvalVerdict {
145    let upper = review.to_uppercase();
146    let passed = upper.contains("VERDICT: PASS") || upper.contains("VERDICT:PASS");
147    EvalVerdict {
148        passed,
149        output: review.to_string(),
150    }
151}
152
153/// The instruction suffix appended to AI-evaluator prompts so their verdict is
154/// machine-readable.
155pub const AI_VERDICT_INSTRUCTION: &str =
156    "\n\nEnd your review with a final line that is exactly `VERDICT: PASS` or `VERDICT: FAIL`.";