Skip to main content

speccoder_runtime/pipeline/
judge.rs

1//! The judge's steps within one attempt: which writes a person approved,
2//! what the integrity audit finds, the verdict from the checks, and whether
3//! a failed attempt is worth retrying.
4
5use std::collections::BTreeSet;
6use std::path::Path;
7
8use serde_json::Value;
9use speccoder_core::RunReport;
10use speccoder_core::verify::{CheckStatus, Verdict, VerifyReport, compare, passes, verdict};
11
12use crate::tools::policy::{Object, Policy};
13use crate::{integrity, sandbox, verify, worktree};
14
15use super::{PreparedAcceptance, run_acceptance};
16
17/// Paths a person granted writing, for the task or inline in this attempt.
18/// A frozen test so approved is not a violation; the audit still flags
19/// removed tests and skip markers in it — approval permits editing a test,
20/// not weakening it.
21pub(crate) fn approved_writes(granted: &[Object], tool_calls: &Value) -> BTreeSet<String> {
22    granted
23        .iter()
24        .filter_map(|g| g.path().map(str::to_owned))
25        .chain(
26            tool_calls
27                .as_array()
28                .into_iter()
29                .flatten()
30                .filter(|c| c["approved_by"] == "person")
31                .filter_map(|c| {
32                    serde_json::from_value::<Object>(c["object"].clone())
33                        .ok()?
34                        .path()
35                        .map(str::to_owned)
36                }),
37        )
38        .collect()
39}
40
41/// What the integrity audit of one attempt reads.
42pub(crate) struct Audited<'a> {
43    pub(crate) wt_root: &'a Path,
44    pub(crate) policy: &'a Policy,
45    /// Judge inputs as the attempt found them.
46    pub(crate) judged_before: &'a integrity::JudgeSnapshot,
47    pub(crate) raw_changes: &'a [worktree::Change],
48    pub(crate) patch: &'a str,
49    pub(crate) frozen: &'a [String],
50    pub(crate) frozen_additions: bool,
51    pub(crate) approved_writes: &'a BTreeSet<String>,
52    /// Judge drift a command caused, reported by the tool (it ended the attempt).
53    pub(crate) command_drift: &'a Value,
54}
55
56/// Every integrity finding of an attempt, each `integrity: …`: the diff
57/// audit, judge inputs the diff cannot show (git-ignored files, whoever
58/// changed them — any executor), and drift a command caused.
59pub(crate) fn attempt_findings(a: &Audited<'_>) -> Vec<String> {
60    let unseen = a
61        .judged_before
62        .drift(
63            &integrity::JudgeSnapshot::take(a.wt_root, a.policy),
64            a.policy,
65            a.approved_writes,
66        )
67        .into_iter()
68        .filter(|d| !a.raw_changes.iter().any(|c| c.path == d.path))
69        .map(|d| format!("integrity: {} input {}: {}", d.class, d.change, d.path));
70    let frozen: BTreeSet<String> = a
71        .frozen
72        .iter()
73        .filter(|p| !a.approved_writes.contains(*p))
74        .cloned()
75        .collect();
76    let mut findings: Vec<String> = integrity::audit_in(
77        a.policy.protected(),
78        a.raw_changes,
79        a.patch,
80        &frozen,
81        a.frozen_additions,
82        a.approved_writes,
83    )
84    .into_iter()
85    .map(|f| format!("integrity: {f}"))
86    .chain(unseen)
87    .collect();
88    for d in a.command_drift.as_array().into_iter().flatten() {
89        let finding = format!(
90            "integrity: judge input changed by a command: {} ({})",
91            d["path"].as_str().unwrap_or_default(),
92            d["change"].as_str().unwrap_or_default()
93        );
94        if !findings.contains(&finding) {
95            findings.push(finding);
96        }
97    }
98    findings
99}
100
101/// `(path, added|modified|deleted)` for the report.
102pub(crate) fn changes_of(raw: Vec<worktree::Change>) -> Vec<(String, String)> {
103    raw.into_iter()
104        .map(|c| {
105            let kind = match c.kind {
106                worktree::ChangeKind::Added => "added",
107                worktree::ChangeKind::Modified => "modified",
108                worktree::ChangeKind::Deleted => "deleted",
109            };
110            (c.path, kind.to_owned())
111        })
112        .collect()
113}
114
115/// The verdict: the fast checks against the baseline, and the acceptance
116/// tests green — task evidence only when they were red first. Any integrity
117/// finding fails it, whatever the checks said.
118pub(crate) fn judge_checks(
119    project: &Path,
120    runner: &sandbox::Runner,
121    baseline: &VerifyReport,
122    acceptance: Option<&PreparedAcceptance>,
123    findings: &[String],
124    report: &mut RunReport,
125) -> Result<(), String> {
126    let mut current = verify::run_checks(project, Some(verify::config::Tier::Fast), runner)?;
127    let mut task_checks: Vec<&str> = Vec::new();
128    let mut uncollected_at_green = false;
129    if let Some(a) = acceptance.filter(|a| a.argv.is_some()) {
130        let argv = a.argv.as_deref().unwrap_or_default();
131        let all: Vec<&[String]> = std::iter::once(argv)
132            .chain(a.more_argv.iter().map(Vec::as_slice))
133            .collect();
134        let counted = std::cell::Cell::new(None);
135        let green = verify::rerun_once(run_all_acceptance(project, &all, runner, &counted), || {
136            run_all_acceptance(project, &all, runner, &counted)
137        });
138        // Green is evidence only when it collected what red did:
139        // red's count, else what the files declare, and at least one; a
140        // green run whose count cannot be read is no evidence.
141        let red_tests = a.report["red_tests"]
142            .as_u64()
143            .and_then(|n| usize::try_from(n).ok());
144        let required = red_tests
145            .unwrap_or_else(|| declared(project, &a.report))
146            .max(1);
147        if let Some(r) = report.acceptance.as_mut() {
148            r["green_tests"] = serde_json::json!(counted.get());
149            r["green_needs"] = serde_json::json!(required);
150        }
151        if a.red
152            && green.status == CheckStatus::Passed
153            && counted.get().is_none_or(|seen| seen < required)
154        {
155            uncollected_at_green = true;
156        }
157        if let Some(r) = report.acceptance.as_mut() {
158            r["green"] = serde_json::json!(green.status == CheckStatus::Passed);
159            if green.flaky {
160                r["green_flaky"] = serde_json::json!(true);
161                r["note"] = serde_json::json!("acceptance passed only on re-run");
162            }
163        }
164        if a.red {
165            task_checks.push("acceptance");
166        }
167        current.checks.push(green);
168    }
169    let cmp = compare(baseline, &current);
170    current.passed = passes(&current.checks, Some(&cmp));
171    let mut judged = verdict(&task_checks, &current.checks, Some(&cmp));
172    if uncollected_at_green {
173        let mut reasons = vec![GREEN_UNCOLLECTED.to_owned()];
174        if let Verdict::Failed { reasons: more } = judged {
175            reasons.extend(more);
176        }
177        judged = Verdict::Failed { reasons };
178    }
179    report.verdict = Some(if findings.is_empty() {
180        judged
181    } else {
182        let mut reasons = findings.to_vec();
183        if let Verdict::Failed { reasons: more } = judged {
184            reasons.extend(more);
185        }
186        Verdict::Failed { reasons }
187    });
188    current.comparison = Some(cmp);
189    report.verification = Some(current);
190    Ok(())
191}
192
193/// The tests the acceptance files declare by their toolchains' markers.
194fn declared(project: &Path, acceptance: &serde_json::Value) -> usize {
195    acceptance["files"]
196        .as_array()
197        .into_iter()
198        .flatten()
199        .filter_map(|f| f.as_str())
200        .filter_map(|f| {
201            let t = speccoder_core::collection::toolchain_of(f)?;
202            let text = std::fs::read_to_string(project.join(f)).ok()?;
203            Some(speccoder_core::collection::declared_tests(t, &text))
204        })
205        .sum()
206}
207
208/// The verdict reason when green collected fewer tests than red did.
209pub(crate) const GREEN_UNCOLLECTED: &str = "acceptance tests not collected at green";
210
211/// Every command of an acceptance set, as one result: passed only when
212/// each passed (the first failure's output is kept). `counted`: the tests
213/// the first command collected.
214fn run_all_acceptance(
215    project: &Path,
216    all: &[&[String]],
217    runner: &sandbox::Runner,
218    counted: &std::cell::Cell<Option<usize>>,
219) -> speccoder_core::verify::CheckResult {
220    let mut first = None;
221    for (i, argv) in all.iter().enumerate() {
222        let (r, summary) = super::acceptance::acceptance_run(project, argv, runner);
223        if i == 0 {
224            counted.set(speccoder_core::verify::collected_count(
225                &r,
226                summary.as_ref(),
227            ));
228        }
229        if r.status != CheckStatus::Passed {
230            return r;
231        }
232        first.get_or_insert(r);
233    }
234    first.unwrap_or_else(|| run_acceptance(project, &[], runner))
235}
236
237/// Why a failed, completed attempt is not retried, if it is not.
238pub(crate) fn retry_stop(
239    findings: &[String],
240    verification: &VerifyReport,
241    last_fingerprint: Option<&str>,
242    fingerprint: &str,
243    attempt_no: u32,
244    max_attempts: u32,
245) -> Option<String> {
246    if !findings.is_empty() {
247        Some("integrity findings are not retried".to_owned())
248    } else if let Some(infra) = speccoder_core::retry::infrastructure(verification) {
249        Some(format!("not retried: {infra}"))
250    } else if last_fingerprint == Some(fingerprint) {
251        Some(format!("same failure twice: {fingerprint}"))
252    } else if attempt_no >= max_attempts {
253        Some(format!("{attempt_no} of {max_attempts} attempts used"))
254    } else {
255        None
256    }
257}
258
259/// The gaming monitor's view of a passing attempt, and whether it suspects
260/// gaming. A monitor that fails blocks nothing: it can only add doubt.
261pub(crate) fn monitor_attempt(
262    rt: &tokio::runtime::Runtime,
263    plane: &crate::substrate::Plane,
264    feature: &str,
265    task: &str,
266    input: agentplane::core::Tainted<Value>,
267    secret: Option<&str>,
268) -> (Value, bool) {
269    match rt.block_on(plane.monitor(feature, task, input)) {
270        Ok(o) => {
271            let out = o
272                .output
273                .as_ref()
274                .map(|v| v.peek().clone())
275                .unwrap_or(Value::Null);
276            let suspected = out["answer"]["suspected"] == true;
277            (
278                serde_json::json!({
279                    "suspected": suspected,
280                    "findings": out["answer"]["findings"],
281                    "usage": out["usage"],
282                    "run_id": o.run_id.to_string(),
283                }),
284                suspected,
285            )
286        }
287        Err(e) => (
288            serde_json::json!({ "error": super::redact(&e.0, secret) }),
289            false,
290        ),
291    }
292}