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    // A planning task's documents are its work, not a change to the spec.
77    let audited: Vec<worktree::Change> = a
78        .raw_changes
79        .iter()
80        .filter(|c| !a.policy.is_planning_write(&c.path))
81        .cloned()
82        .collect();
83    let mut findings: Vec<String> = integrity::audit_in(
84        a.policy.protected(),
85        &audited,
86        a.patch,
87        &frozen,
88        a.frozen_additions,
89        a.approved_writes,
90    )
91    .into_iter()
92    .map(|f| format!("integrity: {f}"))
93    .chain(unseen)
94    .collect();
95    for d in a.command_drift.as_array().into_iter().flatten() {
96        let finding = format!(
97            "integrity: judge input changed by a command: {} ({})",
98            d["path"].as_str().unwrap_or_default(),
99            d["change"].as_str().unwrap_or_default()
100        );
101        if !findings.contains(&finding) {
102            findings.push(finding);
103        }
104    }
105    findings
106}
107
108/// `(path, added|modified|deleted)` for the report.
109pub(crate) fn changes_of(raw: Vec<worktree::Change>) -> Vec<(String, String)> {
110    raw.into_iter()
111        .map(|c| {
112            let kind = match c.kind {
113                worktree::ChangeKind::Added => "added",
114                worktree::ChangeKind::Modified => "modified",
115                worktree::ChangeKind::Deleted => "deleted",
116            };
117            (c.path, kind.to_owned())
118        })
119        .collect()
120}
121
122/// The verdict: the fast checks against the baseline, and the acceptance
123/// tests green — task evidence only when they were red first. Any integrity
124/// finding fails it, whatever the checks said.
125pub(crate) fn judge_checks(
126    project: &Path,
127    runner: &sandbox::Runner,
128    baseline: &VerifyReport,
129    acceptance: Option<&PreparedAcceptance>,
130    findings: &[String],
131    report: &mut RunReport,
132) -> Result<(), String> {
133    let mut current = verify::run_checks(project, Some(verify::config::Tier::Fast), runner)?;
134    let mut task_checks: Vec<&str> = Vec::new();
135    let mut uncollected_at_green = false;
136    if let Some(a) = acceptance.filter(|a| a.argv.is_some()) {
137        let argv = a.argv.as_deref().unwrap_or_default();
138        let all: Vec<&[String]> = std::iter::once(argv)
139            .chain(a.more_argv.iter().map(Vec::as_slice))
140            .collect();
141        let counted = std::cell::Cell::new(None);
142        let green = verify::rerun_once(run_all_acceptance(project, &all, runner, &counted), || {
143            run_all_acceptance(project, &all, runner, &counted)
144        });
145        // Green is evidence only when it collected what red did:
146        // red's count, else what the files declare, and at least one; a
147        // green run whose count cannot be read is no evidence.
148        let red_tests = a.report["red_tests"]
149            .as_u64()
150            .and_then(|n| usize::try_from(n).ok());
151        let required = red_tests
152            .unwrap_or_else(|| declared(project, &a.report))
153            .max(1);
154        if let Some(r) = report.acceptance.as_mut() {
155            r["green_tests"] = serde_json::json!(counted.get());
156            r["green_needs"] = serde_json::json!(required);
157        }
158        if a.red
159            && green.status == CheckStatus::Passed
160            && counted.get().is_none_or(|seen| seen < required)
161        {
162            uncollected_at_green = true;
163        }
164        if let Some(r) = report.acceptance.as_mut() {
165            r["green"] = serde_json::json!(green.status == CheckStatus::Passed);
166            if green.flaky {
167                r["green_flaky"] = serde_json::json!(true);
168                r["note"] = serde_json::json!("acceptance passed only on re-run");
169            }
170        }
171        if a.red {
172            task_checks.push("acceptance");
173        }
174        current.checks.push(green);
175    }
176    let cmp = compare(baseline, &current);
177    current.passed = passes(&current.checks, Some(&cmp));
178    let mut judged = verdict(&task_checks, &current.checks, Some(&cmp));
179    if uncollected_at_green {
180        let mut reasons = vec![GREEN_UNCOLLECTED.to_owned()];
181        if let Verdict::Failed { reasons: more } = judged {
182            reasons.extend(more);
183        }
184        judged = Verdict::Failed { reasons };
185    }
186    report.verdict = Some(if findings.is_empty() {
187        judged
188    } else {
189        let mut reasons = findings.to_vec();
190        if let Verdict::Failed { reasons: more } = judged {
191            reasons.extend(more);
192        }
193        Verdict::Failed { reasons }
194    });
195    current.comparison = Some(cmp);
196    report.verification = Some(current);
197    Ok(())
198}
199
200/// The tests the acceptance files declare by their toolchains' markers.
201fn declared(project: &Path, acceptance: &serde_json::Value) -> usize {
202    acceptance["files"]
203        .as_array()
204        .into_iter()
205        .flatten()
206        .filter_map(|f| f.as_str())
207        .filter_map(|f| {
208            let t = speccoder_core::collection::toolchain_of(f)?;
209            let text = std::fs::read_to_string(project.join(f)).ok()?;
210            Some(speccoder_core::collection::declared_tests(t, &text))
211        })
212        .sum()
213}
214
215/// The verdict reason when green collected fewer tests than red did.
216pub(crate) const GREEN_UNCOLLECTED: &str = "acceptance tests not collected at green";
217
218/// Every command of an acceptance set, as one result: passed only when
219/// each passed (the first failure's output is kept). `counted`: the tests
220/// the first command collected.
221fn run_all_acceptance(
222    project: &Path,
223    all: &[&[String]],
224    runner: &sandbox::Runner,
225    counted: &std::cell::Cell<Option<usize>>,
226) -> speccoder_core::verify::CheckResult {
227    let mut first = None;
228    for (i, argv) in all.iter().enumerate() {
229        let (r, summary) = super::acceptance::acceptance_run(project, argv, runner);
230        if i == 0 {
231            counted.set(speccoder_core::verify::collected_count(
232                &r,
233                summary.as_ref(),
234            ));
235        }
236        if r.status != CheckStatus::Passed {
237            return r;
238        }
239        first.get_or_insert(r);
240    }
241    first.unwrap_or_else(|| run_acceptance(project, &[], runner))
242}
243
244/// Why a failed, completed attempt is not retried, if it is not.
245pub(crate) fn retry_stop(
246    findings: &[String],
247    verification: &VerifyReport,
248    last_fingerprint: Option<&str>,
249    fingerprint: &str,
250    attempt_no: u32,
251    max_attempts: u32,
252) -> Option<String> {
253    if !findings.is_empty() {
254        Some("integrity findings are not retried".to_owned())
255    } else if let Some(infra) = speccoder_core::retry::infrastructure(verification) {
256        Some(format!("not retried: {infra}"))
257    } else if last_fingerprint == Some(fingerprint) {
258        Some(format!("same failure twice: {fingerprint}"))
259    } else if attempt_no >= max_attempts {
260        Some(format!("{attempt_no} of {max_attempts} attempts used"))
261    } else {
262        None
263    }
264}
265
266/// The gaming monitor's view of a passing attempt, and whether it suspects
267/// gaming. A monitor that fails blocks nothing: it can only add doubt.
268pub(crate) fn monitor_attempt(
269    rt: &tokio::runtime::Runtime,
270    plane: &crate::substrate::Plane,
271    feature: &str,
272    task: &str,
273    input: agentplane::core::Tainted<Value>,
274    secret: Option<&str>,
275) -> (Value, bool) {
276    match rt.block_on(plane.monitor(feature, task, input)) {
277        Ok(o) => {
278            let out = o
279                .output
280                .as_ref()
281                .map(|v| v.peek().clone())
282                .unwrap_or(Value::Null);
283            let suspected = out["answer"]["suspected"] == true;
284            (
285                serde_json::json!({
286                    "suspected": suspected,
287                    "findings": out["answer"]["findings"],
288                    "usage": out["usage"],
289                    "run_id": o.run_id.to_string(),
290                }),
291                suspected,
292            )
293        }
294        Err(e) => (
295            serde_json::json!({ "error": super::redact(&e.0, secret) }),
296            false,
297        ),
298    }
299}