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 {
46                critique: output,
47                policy,
48            })
49        }
50    }
51}
52
53/// An AI evaluator: a worker reviews the work and ends with a machine-readable
54/// verdict. Absent or `FAIL` fails closed; an explicit `REPLAN` triggers a replan.
55pub struct AiEvaluator;
56
57#[async_trait(?Send)]
58impl Evaluator for AiEvaluator {
59    async fn grade(&self, node: &Node, ctx: &dyn EvalContext) -> Result<Gate> {
60        let Some(review) = ctx.run_ai(node, AI_VERDICT_INSTRUCTION).await? else {
61            return Ok(Gate::Fail {
62                critique: format!("no worker for AI evaluator needs {:?}", node.needs),
63                policy: node.parsed_on_fail().unwrap_or(OnFail::Replan),
64            });
65        };
66        // A model can explicitly call for a replan ("wrong approach").
67        if review.to_uppercase().contains("VERDICT: REPLAN") {
68            return Ok(Gate::Fail {
69                critique: review,
70                policy: OnFail::Replan,
71            });
72        }
73        let verdict = parse_ai_verdict(&review);
74        if verdict.passed {
75            Ok(Gate::Pass)
76        } else {
77            Ok(Gate::Fail {
78                critique: verdict.output,
79                policy: node.parsed_on_fail().unwrap_or(OnFail::Replan),
80            })
81        }
82    }
83}
84
85/// A human evaluator: there is no automatic verdict, so it parks for the user.
86pub struct HumanEvaluator;
87
88#[async_trait(?Send)]
89impl Evaluator for HumanEvaluator {
90    async fn grade(&self, node: &Node, _ctx: &dyn EvalContext) -> Result<Gate> {
91        Ok(Gate::Park {
92            question: node.instruction.clone(),
93        })
94    }
95}
96
97/// Run a tool evaluator's acceptance command in `workspace`, passing iff the
98/// process exits with `must_exit`. The combined output becomes the critique on
99/// failure (`CONTEXT.md` §10 acceptance).
100pub async fn run_tool(
101    workspace: &Path,
102    command: &str,
103    must_exit: i32,
104    timeout: Duration,
105) -> Result<EvalVerdict> {
106    let mut cmd = Command::new("sh");
107    cmd.arg("-c")
108        .arg(command)
109        .current_dir(workspace)
110        .stdin(Stdio::null())
111        .stdout(Stdio::piped())
112        .stderr(Stdio::piped())
113        .kill_on_drop(true);
114
115    let output = match tokio::time::timeout(timeout, cmd.output()).await {
116        Ok(Ok(o)) => o,
117        Ok(Err(e)) => {
118            return Ok(EvalVerdict {
119                passed: false,
120                output: format!("failed to run `{command}`: {e}"),
121            });
122        }
123        Err(_) => {
124            return Ok(EvalVerdict {
125                passed: false,
126                output: format!("acceptance command timed out: `{command}`"),
127            });
128        }
129    };
130
131    let code = output.status.code().unwrap_or(-1);
132    let stdout = String::from_utf8_lossy(&output.stdout);
133    let stderr = String::from_utf8_lossy(&output.stderr);
134    let passed = code == must_exit;
135
136    let combined = format!(
137        "$ {command}\nexit: {code} (required {must_exit})\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}"
138    );
139
140    Ok(EvalVerdict {
141        passed,
142        output: combined,
143    })
144}
145
146/// Parse an AI evaluator's review into a verdict. The engine instructs AI
147/// evaluators to end with `VERDICT: PASS` or `VERDICT: FAIL`; absent or
148/// `FAIL` is treated as a failure (fail-closed), and the full review is the
149/// critique.
150pub fn parse_ai_verdict(review: &str) -> EvalVerdict {
151    let upper = review.to_uppercase();
152    let passed = upper.contains("VERDICT: PASS") || upper.contains("VERDICT:PASS");
153    EvalVerdict {
154        passed,
155        output: review.to_string(),
156    }
157}
158
159/// The instruction suffix appended to AI-evaluator prompts so their verdict is
160/// machine-readable.
161pub const AI_VERDICT_INSTRUCTION: &str =
162    "\n\nEnd your review with a final line that is exactly `VERDICT: PASS` or `VERDICT: FAIL`.";