Skip to main content

speccoder_runtime/pipeline/
bug.rs

1//! A bug task inside the pipeline. Before the attempt: reproduce — one
2//! test per *Expected* statement, red on the untouched code by an assertion
3//! twice, held-out variants sealed — and the person's one confirmation;
4//! the confirmed reproductions are then reused at the checkpoint as the
5//! visible acceptance set. After an attempt that passed: every reproduction
6//! green, the pass-to-pass set green by name, the revert rejected, and each
7//! special case rejected. The rules are `speccoder_core::bug`'s.
8
9use std::path::Path;
10use std::time::Instant;
11
12use serde_json::{Value, json};
13use speccoder_core::bug::{
14    self as rules, Basis, BugReport, Final, HeldOutVariant, Outcome, PassToPass, Reproduce,
15    ReproduceTry, Reproduction, Revert, RevertResult, Source, SpecialCase, Stage as BugStage,
16    TryStatement,
17};
18use speccoder_core::context::ContextKind;
19use speccoder_core::stage::{Stage, StageState};
20use speccoder_core::verify::{
21    CheckStatus, HeldOut, RedClass, Verdict, VerifyReport, classify_red, classify_red_one,
22};
23use speccoder_core::{CommandData, CommandResult, CommandStatus};
24
25use super::{AcceptanceSetup, PreparedAcceptance, ReusedTest, bare_report, class_word, stage};
26use crate::approvals::{Approver, ConfirmAnswer, ConfirmRequest, ShownReproduction};
27use crate::bug::{confirm, handoff, state};
28use crate::integrity::sha256_hex;
29use crate::progress::{BugEvent, Event, Progress};
30use crate::tools::policy::{Decision, Policy};
31use crate::{held_out, sandbox, substrate, tools, worktree};
32
33/// What a bug task's stages need from the run.
34pub(crate) struct Ctx<'a> {
35    pub(crate) rt: &'a tokio::runtime::Runtime,
36    pub(crate) plane: &'a substrate::Plane,
37    pub(crate) project: &'a Path,
38    pub(crate) wt_root: &'a Path,
39    pub(crate) wt_path: &'a str,
40    pub(crate) tmp: &'a Path,
41    pub(crate) policy: &'a Policy,
42    pub(crate) runner: &'a sandbox::Runner,
43    /// The project's state directory.
44    pub(crate) state: &'a Path,
45    pub(crate) feature: &'a str,
46    pub(crate) task: &'a str,
47    pub(crate) bundle: &'a Value,
48    pub(crate) instructions: &'a [crate::instructions::Instruction],
49    pub(crate) live: &'a dyn Progress,
50    pub(crate) approver: Option<&'a dyn Approver>,
51    /// `[acceptance] held_out`.
52    pub(crate) held_out: bool,
53    /// `[bug] reproduce_tries`.
54    pub(crate) max_tries: u32,
55    /// `[bug] test`: the command that runs one test of a file.
56    pub(crate) bug_test: Option<&'a [String]>,
57    /// The tree the task started from.
58    pub(crate) start: &'a worktree::Checkpoint,
59}
60
61/// A confirmed bug, ready for its fix.
62pub(crate) struct Fix {
63    pub(crate) bug: BugReport,
64    pub(crate) record: speccoder_core::acceptance::PreFrozenAcceptance,
65    pub(crate) files: Vec<(String, String)>,
66}
67
68/// Where a bug task is.
69pub(crate) enum Phase {
70    /// It needs reproductions (again).
71    Reproduce(Box<BugReport>),
72    /// Its reproductions are confirmed.
73    Fix(Box<Fix>),
74}
75
76fn event(live: &dyn Progress, task: &str, step: BugEvent) {
77    live.event(&Event::Bug {
78        task: task.to_owned(),
79        step,
80    });
81}
82
83/// The triad as the bug's home holds it now (in `project`).
84pub(crate) fn triad_now(
85    format: &dyn crate::format::Adapter,
86    project: &Path,
87    bug: &BugReport,
88) -> Result<rules::Triad, crate::format::BugRefusal> {
89    let key = if bug.home.kind.native() {
90        bug.task.trim_start_matches("bug:").to_owned()
91    } else {
92        bug.requirement.clone()
93    };
94    let read = format.read_bug(project, &bug.home, &key)?;
95    let current = read.current.first().cloned().unwrap_or_default();
96    rules::Triad::new(&current, &read.expected, &read.unchanged, sha256_hex)
97        .map_err(|e| crate::format::BugRefusal::new(e.code(), e.message()))
98}
99
100/// Whether `feature`'s `task` is a bug, and where it is. `Err`: its
101/// confirmed set was tampered with, or its triad cannot be read.
102pub(crate) fn phase(
103    plane: &Path,
104    feature: &str,
105    task: &str,
106    project: &Path,
107    format: &dyn crate::format::Adapter,
108) -> Result<Option<Phase>, String> {
109    let Some(mut bug) = state::load(plane, feature, task) else {
110        return Ok(None);
111    };
112    let now =
113        triad_now(format, project, &bug).map_err(|e| format!("{} ({})", e.message, e.code))?;
114    if now.digest != bug.triad.digest {
115        // Reworded: the confirmation and the freeze lapse.
116        confirm::lapse(plane, &mut bug, now)?;
117        return Ok(Some(Phase::Reproduce(Box::new(bug))));
118    }
119    if bug
120        .confirmation
121        .as_ref()
122        .is_some_and(|c| c.current(&bug.triad.digest))
123    {
124        match crate::pre_frozen::load(plane, &bug.unit, &bug.requirement) {
125            Ok(Some((record, files)))
126                if speccoder_core::acceptance::current(&record, &bug.triad.digest) =>
127            {
128                return Ok(Some(Phase::Fix(Box::new(Fix { bug, record, files }))));
129            }
130            Ok(_) => {}
131            Err(t) => return Err(t.0),
132        }
133    }
134    // A finished stop is tried again with a fresh budget.
135    if matches!(
136        bug.outcome,
137        Outcome::CannotReproduce | Outcome::AlreadySatisfied | Outcome::UnchangedNotHolding
138    ) {
139        bug.tries.clear();
140        bug.rejections.clear();
141    }
142    Ok(Some(Phase::Reproduce(Box::new(bug))))
143}
144
145/// The statements as scenario references: what held-out failures name.
146pub(crate) fn scenarios(bug: &BugReport) -> Vec<speccoder_core::spec::ScenarioRef> {
147    bug.triad
148        .expected
149        .iter()
150        .map(|s| speccoder_core::spec::ScenarioRef {
151            id: s.id.clone(),
152            text: s.text.clone(),
153        })
154        .collect()
155}
156
157/// The run's stop for `bug` in `outcome`.
158fn stop(
159    c: &Ctx<'_>,
160    mut bug: BugReport,
161    outcome: Outcome,
162    code: Option<&str>,
163    message: String,
164    began: Instant,
165) -> CommandResult {
166    let _ = worktree::restore(c.wt_root, c.tmp, c.start);
167    bug.outcome = outcome;
168    bug.stage = if outcome == Outcome::AwaitingConfirmation {
169        BugStage::Confirm
170    } else {
171        BugStage::Done
172    };
173    bug.code = code.map(str::to_owned);
174    if matches!(
175        outcome,
176        Outcome::CannotReproduce | Outcome::AlreadySatisfied | Outcome::UnchangedNotHolding
177    ) {
178        let cost = bug
179            .tries
180            .iter()
181            .filter_map(|t| t.usage.as_ref())
182            .fold(None, |acc: Option<Value>, u| {
183                super::add_usage(acc.as_ref(), Some(u))
184            });
185        bug.handoff = Some(handoff::compose(
186            &bug,
187            outcome,
188            u64::try_from(began.elapsed().as_millis()).unwrap_or(u64::MAX),
189            cost,
190            None,
191        ));
192    }
193    let next = handoff::next(&bug, outcome);
194    let _ = state::save(c.state, &bug);
195    event(
196        c.live,
197        c.task,
198        BugEvent::Outcome {
199            outcome: outcome.as_str().to_owned(),
200            verdict: None,
201            code: bug.code.clone(),
202            next: next.iter().map(|n| n.command.clone()).collect(),
203        },
204    );
205    let status = match outcome {
206        Outcome::AlreadySatisfied => CommandStatus::Ok,
207        _ => CommandStatus::NeedsHuman,
208    };
209    let mut report = bare_report(c.feature, c.task, c.wt_path, outcome.as_str());
210    report.reason = Some(message.clone());
211    report.bug = Some(Box::new(bug));
212    c.live.event(&super::finished_event(
213        c.task,
214        &report,
215        outcome.as_str(),
216        false,
217        message.clone(),
218    ));
219    let mut r = CommandResult::new("run", status, &message)
220        .with_next(next)
221        .with_data(CommandData::Run(Box::new(report)));
222    if let Some(code) = code {
223        r = r.with_code(code);
224    }
225    r
226}
227
228/// One authored test of a try.
229struct Authored {
230    path: String,
231    content: String,
232    statement: String,
233    test: String,
234    argv: Vec<String>,
235}
236
237/// Whether `rel` is a file that configures how tests are collected or run
238/// (a `conftest.py`, a runner's configuration): frozen as a reproduction, it
239/// would change every later test run, pass-to-pass and checks included.
240fn configures_collection(rel: &str) -> bool {
241    let name = rel.rsplit('/').next().unwrap_or(rel);
242    matches!(
243        name,
244        "conftest.py"
245            | "__init__.py"
246            | "pytest.ini"
247            | "tox.ini"
248            | "setup.cfg"
249            | "pyproject.toml"
250            | "package.json"
251            | "Cargo.toml"
252            | "build.rs"
253            | "go.mod"
254    ) || [
255        "jest.config",
256        "jest.setup",
257        "vitest.config",
258        "vitest.setup",
259        "vite.config",
260        "vitest.workspace",
261        "karma.conf",
262        ".mocharc",
263        "babel.config",
264        ".babelrc",
265    ]
266    .iter()
267    .any(|p| name.starts_with(p))
268}
269
270/// The author's files, checked: each a new test file, one per wanted
271/// statement, naming its test. The command is speccoder's, never the
272/// author's: the one that runs only that test (`[bug] test` or the
273/// toolchain's rule), and the policy must allow it. `Err`: why the try is
274/// discarded.
275fn validate(
276    answer: &Value,
277    want: &[String],
278    project: &Path,
279    policy: &Policy,
280    template: Option<&[String]>,
281) -> Result<Vec<Authored>, String> {
282    let protected = policy.protected();
283    let mut out: Vec<Authored> = Vec::new();
284    for f in answer["files"].as_array().into_iter().flatten() {
285        let path = f["path"].as_str().unwrap_or_default();
286        let rel = tools::paths::normalise(path).map_err(|e| format!("`{path}`: {}", e.0))?;
287        if !tools::paths::is_test_path(&rel) || protected.write_class(&rel).is_some() {
288            return Err(format!("wrote outside tests (`{rel}`)"));
289        }
290        if configures_collection(&rel) {
291            return Err(format!(
292                "`{rel}` configures how tests run: a reproduction is a test file"
293            ));
294        }
295        if project.join(&rel).exists() || out.iter().any(|a| a.path == rel) {
296            return Err(format!("`{rel}` already exists"));
297        }
298        let statement = f["statement"].as_str().unwrap_or_default().to_owned();
299        if !want.contains(&statement) || out.iter().any(|a| a.statement == statement) {
300            return Err(format!(
301                "`{rel}` cites `{statement}`: one test per statement asked for"
302            ));
303        }
304        let test = f["test"].as_str().unwrap_or_default().trim().to_owned();
305        if test.is_empty() {
306            return Err(format!("`{rel}` names no test"));
307        }
308        // Only that test runs: a command that runs others could be red by
309        // an unrelated failure.
310        let argv = crate::bug::named::argv(project, &rel, &test, template).ok_or_else(|| {
311            format!(
312                "speccoder has no rule to run only `{test}` of `{rel}`; set `[bug] test` in speccoder.toml"
313            )
314        })?;
315        if policy.classify("run_command", &json!({ "argv": argv }), None) != Decision::Allow {
316            return Err(format!("`{}` is not an allowed command", argv.join(" ")));
317        }
318        out.push(Authored {
319            path: rel,
320            content: f["content"].as_str().unwrap_or_default().to_owned(),
321            statement,
322            test,
323            argv,
324        });
325    }
326    if let Some(missing) = want
327        .iter()
328        .find(|w| !out.iter().any(|a| a.statement == **w))
329    {
330        return Err(format!("no test for {missing}"));
331    }
332    Ok(out)
333}
334
335/// The class and excerpt of one reproduction on the tree as it is: red
336/// only by an assertion of `test` itself, twice; an *Unchanged* test runs
337/// once and must pass.
338fn baseline_class(
339    c: &Ctx<'_>,
340    argv: &[String],
341    test: &str,
342    reproduces: bool,
343) -> (Vec<RedClass>, String) {
344    let (first, summary) = super::acceptance_run(c.project, argv, c.runner);
345    let one = classify_red_one(&first, summary.as_ref(), test);
346    let excerpt = handoff::cut(&format!("{}\n{}", first.stdout_tail, first.stderr_tail), 20);
347    if !reproduces || one != RedClass::Assertion {
348        return (vec![one], excerpt);
349    }
350    let (second, summary) = super::acceptance_run(c.project, argv, c.runner);
351    let two = classify_red_one(&second, summary.as_ref(), test);
352    (vec![one, rules::bug_class(one, Some(two))], excerpt)
353}
354
355/// The context manifest of an author call: the triad (the person's), the
356/// plan and constitution, the task, rejections and the issue.
357fn manifest(
358    c: &Ctx<'_>,
359    bug: &BugReport,
360    issue: Option<&state::IssueText>,
361) -> speccoder_core::context::ContextManifest {
362    let mut m = crate::context::Manifest::new();
363    m.push(
364        ContextKind::Story,
365        "person",
366        "/triad",
367        bug.triad.canonical().as_bytes(),
368    )
369    .push(
370        ContextKind::Constitution,
371        "worktree",
372        "/bundle/constitution",
373        c.bundle["constitution"]
374            .as_str()
375            .unwrap_or_default()
376            .as_bytes(),
377    )
378    .push(
379        ContextKind::Plan,
380        "worktree",
381        "/bundle/plan",
382        c.bundle["plan"].as_str().unwrap_or_default().as_bytes(),
383    )
384    .push(
385        ContextKind::Task,
386        "worktree",
387        "/bundle/task",
388        c.bundle["task"].to_string().as_bytes(),
389    )
390    .push(
391        ContextKind::TestLayout,
392        "worktree",
393        "/test_layout",
394        crate::layout::text_at(c.project).as_bytes(),
395    );
396    for (i, r) in bug.rejections.iter().enumerate() {
397        m.push(
398            ContextKind::Rejection,
399            "person",
400            &format!("/rejections/{i}"),
401            r.reason.as_bytes(),
402        );
403    }
404    if let (Some(i), Some(issue)) = (bug.issue.as_ref(), issue) {
405        m.push(
406            ContextKind::Issue,
407            &format!("github:{}#{}", i.repo.clone().unwrap_or_default(), i.number),
408            &format!("#{}", i.number),
409            format!("{}\n{}", issue.title, issue.body).as_bytes(),
410        );
411    }
412    m.finish()
413}
414
415/// The project's files and manifest, as an author is given them.
416fn project_view(c: &Ctx<'_>) -> (Vec<String>, String) {
417    let setup = AcceptanceSetup {
418        rt: c.rt,
419        plane: c.plane,
420        project: c.project,
421        worktree: c.wt_root,
422        tmp: c.tmp,
423        policy: c.policy,
424        feature: c.feature,
425        task: c.task,
426        bundle: c.bundle.clone(),
427        scenarios: &[],
428        instructions: c.instructions,
429        runner: c.runner,
430        layout: None,
431    };
432    let files: Vec<String> = worktree::checkpoint(setup.worktree, setup.tmp)
433        .and_then(|cp| worktree::files(setup.worktree, &cp))
434        .unwrap_or_default()
435        .into_iter()
436        .take(400)
437        .collect();
438    let manifest = super::MANIFESTS
439        .iter()
440        .find_map(|m| {
441            std::fs::read_to_string(c.project.join(m))
442                .ok()
443                .map(|t| format!("{m}:\n{t}"))
444        })
445        .map(|t| t.chars().take(8192).collect::<String>())
446        .unwrap_or_default();
447    (files, manifest)
448}
449
450/// One author call; `(answer, run id, usage, notes)`.
451fn author(
452    c: &Ctx<'_>,
453    input: agentplane::core::Tainted<Value>,
454) -> Result<(Value, String, Option<Value>, Option<String>), String> {
455    let outcome =
456        c.rt.block_on(c.plane.acceptance(c.feature, c.task, input))
457            .map_err(|e| format!("the author call failed: {}", e.0))?;
458    let output = outcome
459        .output
460        .as_ref()
461        .map(|o| o.peek().clone())
462        .unwrap_or_default();
463    let answer = output["answer"].clone();
464    if !matches!(outcome.status, agentplane::prelude::RunStatus::Succeeded) || answer.is_null() {
465        return Err(format!(
466            "the author did not answer ({})",
467            crate::substrate::why_not(&outcome.status)
468        ));
469    }
470    let notes = answer["notes"].as_array().map(|n| {
471        n.iter()
472            .filter_map(Value::as_str)
473            .collect::<Vec<_>>()
474            .join(" ")
475    });
476    Ok((
477        answer,
478        outcome.run_id.to_string(),
479        Some(output["usage"].clone()).filter(|u| !u.is_null()),
480        notes,
481    ))
482}
483
484/// Reproduce: tries until every *Expected* statement is red by an
485/// assertion (or the tries run out), the held-out variants sealed, then the
486/// confirmation. `Ok`: confirmed (inline, or by naming the tests) — the fix
487/// runs now; `Err`: the run stops with the bug's outcome.
488#[allow(clippy::too_many_lines)] // one linear procedure, in reading order
489pub(crate) fn reproduce(c: &Ctx<'_>, mut bug: BugReport) -> Result<Fix, Box<CommandResult>> {
490    let began = Instant::now();
491    stage(
492        c.live,
493        c.task,
494        Stage::Reproduce,
495        StageState::Started,
496        None,
497        None,
498    );
499    bug.stage = BugStage::Reproduce;
500    bug.max_tries = c.max_tries;
501    let extra = state::extra(c.state, &bug.unit, &bug.task);
502    let expected = bug.expected_ids();
503    let unchanged: Vec<String> = bug.triad.unchanged.iter().map(|s| s.id.clone()).collect();
504    let person: Vec<Reproduction> = bug
505        .reproductions
506        .iter()
507        .filter(|r| r.source == Source::Person)
508        .cloned()
509        .collect();
510    // The person's tests stand for the Expected statements; the author
511    // writes the rest.
512    let want: Vec<String> = if person.is_empty() {
513        expected.iter().chain(&unchanged).cloned().collect()
514    } else {
515        unchanged.clone()
516    };
517    let statements = json!(bug.triad.statements().collect::<Vec<_>>());
518    let person_files = state::repro(
519        c.state,
520        &bug.unit,
521        &bug.task,
522        &person.iter().map(|r| r.file.clone()).collect::<Vec<_>>(),
523    );
524    let stop_now = |bug: BugReport, outcome, code, message: String| {
525        stage(
526            c.live,
527            c.task,
528            Stage::Reproduce,
529            if outcome == Outcome::AlreadySatisfied {
530                StageState::Passed
531            } else {
532                StageState::Failed
533            },
534            Some(outcome_word(outcome)),
535            Some(began),
536        );
537        Box::new(stop(c, bug, outcome, code, message, began))
538    };
539    let kept: Vec<(Reproduction, String)> = loop {
540        // Every try counts, a rejected one too: once they are used up the
541        // author is not called again.
542        if u32::try_from(bug.tries.len()).unwrap_or(u32::MAX) >= c.max_tries.max(1) {
543            let saved = state::save(c.state, &bug);
544            match rules::decide_reproduce(&bug.tries, &expected, c.max_tries) {
545                // Still waiting for the person: the same reproductions.
546                Reproduce::Reproduced { .. } if bug.confirm_digest.is_some() && saved.is_ok() => {
547                    let digest = bug.confirm_digest.clone().unwrap_or_default();
548                    let message = format!(
549                        "the reproductions wait for your confirmation (digest {digest}): speccoder bug confirm {} --digest {digest}",
550                        bug.key()
551                    );
552                    return Err(Box::new(stop(
553                        c,
554                        bug,
555                        Outcome::AwaitingConfirmation,
556                        None,
557                        message,
558                        began,
559                    )));
560                }
561                _ => {
562                    let message = format!(
563                        "cannot reproduce: the {} tries are used up ({} rejected); nothing is fixed",
564                        bug.tries.len(),
565                        bug.tries
566                            .iter()
567                            .filter(|t| t
568                                .discarded
569                                .as_deref()
570                                .is_some_and(|d| d.starts_with("rejected")))
571                            .count()
572                    );
573                    return Err(stop_now(
574                        bug,
575                        Outcome::CannotReproduce,
576                        Some("BUG-CANNOT-REPRODUCE"),
577                        message,
578                    ));
579                }
580            }
581        }
582        let n = u32::try_from(bug.tries.len()).unwrap_or(u32::MAX) + 1;
583        let context = manifest(c, &bug, extra.issue.as_ref());
584        let rejections: Vec<String> = bug.rejections.iter().map(|r| r.reason.clone()).collect();
585        let mut t = ReproduceTry {
586            n,
587            per_statement: Vec::new(),
588            discarded: None,
589            run_id: None,
590            usage: None,
591            rejection: rejections.last().cloned(),
592        };
593        let mut this: Vec<(Reproduction, String)> = Vec::new();
594        // The person's tests: run again on this tree.
595        for (r, (_, content)) in person.iter().zip(&person_files) {
596            let full = c.project.join(&r.file);
597            if !full.exists() {
598                if let Some(parent) = full.parent() {
599                    let _ = std::fs::create_dir_all(parent);
600                }
601                let _ = std::fs::write(&full, content);
602            }
603            let (classes, excerpt) = baseline_class(c, &r.argv, &r.test, true);
604            let class = classes.last().copied().unwrap_or(RedClass::Unclassified);
605            t.per_statement.push(TryStatement {
606                statement: r.statement.clone(),
607                class,
608                excerpt: (class != RedClass::Assertion).then_some(excerpt),
609            });
610            let mut r = r.clone();
611            r.baseline = classes;
612            this.push((r, content.clone()));
613        }
614        if !want.is_empty() {
615            let (files, manifest_text) = project_view(c);
616            let layout_text = crate::layout::text_at(c.project);
617            let input =
618                substrate::acceptance::reproduce_input(&substrate::acceptance::ReproduceParts {
619                    set: "reproduce",
620                    bundle: c.bundle.clone(),
621                    statements: statements.clone(),
622                    want: &want,
623                    files: &files,
624                    manifest: &manifest_text,
625                    visible: &[],
626                    rejections: &rejections,
627                    issue: extra
628                        .issue
629                        .as_ref()
630                        .map(|i| (i.title.as_str(), i.body.as_str())),
631                    instructions: c.instructions,
632                    context: &context,
633                    test_layout: Some(&layout_text),
634                });
635            match author(c, input) {
636                Err(why) => t.discarded = Some(why),
637                Ok((answer, run_id, usage, _notes)) => {
638                    t.run_id = Some(run_id);
639                    t.usage = usage;
640                    match validate(&answer, &want, c.project, c.policy, c.bug_test) {
641                        Err(why) => t.discarded = Some(why),
642                        Ok(files) => {
643                            for f in files {
644                                let full = c.project.join(&f.path);
645                                if let Some(parent) = full.parent() {
646                                    let _ = std::fs::create_dir_all(parent);
647                                }
648                                if std::fs::write(&full, &f.content).is_err() {
649                                    t.discarded =
650                                        Some(format!("`{}` could not be written", f.path));
651                                    break;
652                                }
653                                let reproduces = f.statement.starts_with('E');
654                                let (classes, excerpt) =
655                                    baseline_class(c, &f.argv, &f.test, reproduces);
656                                let class =
657                                    classes.last().copied().unwrap_or(RedClass::Unclassified);
658                                let red_ok = if reproduces {
659                                    class == RedClass::Assertion
660                                } else {
661                                    class == RedClass::Passed
662                                };
663                                t.per_statement.push(TryStatement {
664                                    statement: f.statement.clone(),
665                                    class,
666                                    excerpt: (!red_ok).then_some(excerpt),
667                                });
668                                this.push((
669                                    Reproduction {
670                                        statement: f.statement,
671                                        file: f.path,
672                                        test: f.test,
673                                        source: Source::Author,
674                                        baseline: classes,
675                                        digest: format!(
676                                            "sha256:{}",
677                                            sha256_hex(f.content.as_bytes())
678                                        ),
679                                        argv: f.argv,
680                                        final_: Final::NotRun,
681                                        revert: Revert::NotRun,
682                                    },
683                                    f.content,
684                                ));
685                            }
686                        }
687                    }
688                }
689            }
690        }
691        if t.discarded.is_some() {
692            t.per_statement.clear();
693        }
694        // Nothing of a try stays in the tree.
695        let _ = worktree::restore(c.wt_root, c.tmp, c.start);
696        event(
697            c.live,
698            c.task,
699            BugEvent::ReproduceTry {
700                n,
701                of: c.max_tries,
702                per_statement: t
703                    .per_statement
704                    .iter()
705                    .map(|s| crate::progress::StatementClass {
706                        statement: s.statement.clone(),
707                        class: class_word(s.class),
708                    })
709                    .collect(),
710            },
711        );
712        bug.tries.push(t);
713        if let Err(e) = state::save(c.state, &bug) {
714            return Err(Box::new(stop(
715                c,
716                bug,
717                Outcome::Recorded,
718                None,
719                format!("the try could not be kept: {e}"),
720                began,
721            )));
722        }
723        match rules::decide_reproduce(&bug.tries, &expected, c.max_tries) {
724            Reproduce::Reproduced { .. } => {
725                let last = bug
726                    .tries
727                    .last()
728                    .map(|t| t.per_statement.clone())
729                    .unwrap_or_default();
730                if let Some(u) = last
731                    .iter()
732                    .find(|s| s.statement.starts_with('U') && s.class != RedClass::Passed)
733                {
734                    let words = bug
735                        .triad
736                        .statement(&u.statement)
737                        .map(|s| s.text.clone())
738                        .unwrap_or_default();
739                    return Err(stop_now(
740                        bug,
741                        Outcome::UnchangedNotHolding,
742                        Some("BUG-UNCHANGED-NOT-HOLDING"),
743                        format!(
744                            "{} does not hold today: its test fails on the untouched code ({}) — \"{words}\"; nothing is fixed",
745                            u.statement,
746                            class_word(u.class)
747                        ),
748                    ));
749                }
750                break this;
751            }
752            Reproduce::Retry => {}
753            Reproduce::AlreadySatisfied => {
754                bug.reproductions = person.clone();
755                bug.reproductions
756                    .extend(this.iter().map(|(r, _)| r.clone()));
757                let files: Vec<(String, String)> = this
758                    .iter()
759                    .map(|(r, c)| (r.file.clone(), c.clone()))
760                    .collect();
761                let _ = state::save_repro(c.state, &bug.unit, &bug.task, &files);
762                return Err(stop_now(
763                    bug,
764                    Outcome::AlreadySatisfied,
765                    Some("BUG-ALREADY-SATISFIED"),
766                    format!(
767                        "every reproduction passed on the untouched code on each of {} tries: nothing to fix, nothing ticked",
768                        c.max_tries
769                    ),
770                ));
771            }
772            Reproduce::CannotReproduce {
773                reproduced,
774                satisfied,
775                not_demonstrated,
776            } => {
777                let mut said = vec![format!("after {} tries", bug.tries.len())];
778                if !reproduced.is_empty() {
779                    said.push(format!("reproduced {}", reproduced.join(", ")));
780                }
781                if !satisfied.is_empty() {
782                    said.push(format!(
783                        "{} already pass (narrow the triad)",
784                        satisfied.join(", ")
785                    ));
786                }
787                if !not_demonstrated.is_empty() {
788                    said.push(format!("not reproduced {}", not_demonstrated.join(", ")));
789                }
790                return Err(stop_now(
791                    bug,
792                    Outcome::CannotReproduce,
793                    Some("BUG-CANNOT-REPRODUCE"),
794                    format!("cannot reproduce: {}; nothing is fixed", said.join("; ")),
795                ));
796            }
797        }
798    };
799    stage(
800        c.live,
801        c.task,
802        Stage::Reproduce,
803        StageState::Passed,
804        Some("assertion".to_owned()),
805        Some(began),
806    );
807
808    // Held-out variants: other inputs, the same statements; sealed.
809    bug.held_out.clear();
810    bug.held_out_sealed = None;
811    bug.held_out_reason = None;
812    if c.held_out {
813        let visible: Vec<(String, String)> = kept
814            .iter()
815            .filter(|(r, _)| r.reproduces())
816            .map(|(r, content)| (r.file.clone(), content.clone()))
817            .collect();
818        match seal_variants(c, &mut bug, &visible, &expected, &[]) {
819            Ok(sealed) => bug.held_out_sealed = Some(sealed),
820            Err(why) => bug.held_out_reason = Some(why),
821        }
822    }
823    bug.reproductions = kept.iter().map(|(r, _)| r.clone()).collect();
824    let files: Vec<(String, String)> = kept
825        .iter()
826        .map(|(r, c)| (r.file.clone(), c.clone()))
827        .collect();
828    if let Err(e) = state::save_repro(c.state, &bug.unit, &bug.task, &files) {
829        return Err(Box::new(stop(
830            c,
831            bug,
832            Outcome::Recorded,
833            None,
834            format!("the reproductions could not be kept: {e}"),
835            began,
836        )));
837    }
838    let digest = confirm::digest(&bug.reproductions);
839    bug.confirm_digest = Some(digest.clone());
840    event(
841        c.live,
842        c.task,
843        BugEvent::Reproduced {
844            reproductions: bug
845                .reproductions
846                .iter()
847                .map(|r| crate::progress::ShownReproduction {
848                    statement: r.statement.clone(),
849                    file: r.file.clone(),
850                    test: r.test.clone(),
851                    digest: r.digest.clone(),
852                })
853                .collect(),
854        },
855    );
856    let _ = state::save(c.state, &bug);
857
858    // The person named the tests: that is the confirmation.
859    if !person.is_empty() {
860        let by = extra
861            .by
862            .clone()
863            .unwrap_or_else(|| crate::approvals::who_in(c.project));
864        let via = extra.via.unwrap_or(speccoder_core::actions::Via::Terminal);
865        return freeze(c, bug, &by, via, Basis::NamedTest, began);
866    }
867    stage(
868        c.live,
869        c.task,
870        Stage::Confirm,
871        StageState::Started,
872        None,
873        None,
874    );
875    let request = ConfirmRequest {
876        bug: bug.key(),
877        title: bug.title.clone(),
878        digest: digest.clone(),
879        reproductions: bug
880            .reproductions
881            .iter()
882            .zip(&files)
883            .map(|(r, (_, content))| ShownReproduction {
884                statement: r.statement.clone(),
885                words: bug
886                    .triad
887                    .statement(&r.statement)
888                    .map(|s| s.text.clone())
889                    .unwrap_or_default(),
890                file: r.file.clone(),
891                test: r.test.clone(),
892                argv: r.argv.clone(),
893                excerpt: bug
894                    .tries
895                    .last()
896                    .and_then(|t| t.per_statement.iter().find(|s| s.statement == r.statement))
897                    .and_then(|s| s.excerpt.clone())
898                    .unwrap_or_default(),
899                content: content.clone(),
900            })
901            .collect(),
902        warning: crate::bug::held_out_warning(&bug),
903    };
904    match c
905        .approver
906        .and_then(|a| a.confirm(&request).map(|ans| (ans, a.via())))
907    {
908        Some((ConfirmAnswer::Confirm, via)) => {
909            let by = crate::approvals::who_in(c.project);
910            freeze(c, bug, &by, via, Basis::Shown, began)
911        }
912        Some((ConfirmAnswer::Reject(reason), via)) => {
913            if let Err(e) = reject(c.state, &mut bug, &reason, via) {
914                return Err(Box::new(stop(
915                    c,
916                    bug,
917                    Outcome::Recorded,
918                    None,
919                    format!("the rejection could not be kept: {e}"),
920                    began,
921                )));
922            }
923            event(c.live, c.task, BugEvent::ConfirmRejected { digest, reason });
924            stage(
925                c.live,
926                c.task,
927                Stage::Confirm,
928                StageState::Failed,
929                Some("rejected".to_owned()),
930                None,
931            );
932            if u32::try_from(bug.tries.len()).unwrap_or(u32::MAX) >= c.max_tries {
933                let message = format!(
934                    "cannot reproduce: the reproductions of {} tries were not accepted; nothing is fixed",
935                    bug.tries.len()
936                );
937                return Err(stop_now(
938                    bug,
939                    Outcome::CannotReproduce,
940                    Some("BUG-CANNOT-REPRODUCE"),
941                    message,
942                ));
943            }
944            reproduce(c, bug)
945        }
946        None => {
947            let next = format!("speccoder bug confirm {} --digest {digest}", bug.key());
948            event(
949                c.live,
950                c.task,
951                BugEvent::ConfirmWaiting {
952                    digest: digest.clone(),
953                    next: next.clone(),
954                },
955            );
956            stage(
957                c.live,
958                c.task,
959                Stage::Confirm,
960                StageState::Started,
961                Some("waits for you".to_owned()),
962                None,
963            );
964            let message = format!(
965                "{} reproduction(s) fail on the untouched code by an assertion; they wait for your confirmation (digest {digest}): {next}{}",
966                bug.reproductions.iter().filter(|r| r.reproduces()).count(),
967                crate::bug::held_out_warning(&bug)
968                    .map(|w| format!(" — {w}"))
969                    .unwrap_or_default()
970            );
971            Err(Box::new(stop(
972                c,
973                bug,
974                Outcome::AwaitingConfirmation,
975                None,
976                message,
977                began,
978            )))
979        }
980    }
981}
982
983fn outcome_word(o: Outcome) -> String {
984    o.as_str().replace('_', " ")
985}
986
987/// Records a rejection: the reason goes to the next try, and the try that
988/// wrote what was rejected is discarded (it never reproduces again; it
989/// still counts against the tries). `Err`: it could not be kept.
990pub(crate) fn reject(
991    state_dir: &Path,
992    bug: &mut BugReport,
993    reason: &str,
994    via: speccoder_core::actions::Via,
995) -> Result<(), String> {
996    if let Some(t) = bug.tries.last_mut() {
997        t.discarded = Some(rules::rejected_try(reason));
998    }
999    bug.rejections.push(rules::Rejection {
1000        digest: bug.confirm_digest.clone().unwrap_or_default(),
1001        reason: reason.to_owned(),
1002        by: crate::approvals::who(),
1003        via,
1004        at: confirm::now(),
1005    });
1006    bug.confirm_digest = None;
1007    bug.outcome = Outcome::Recorded;
1008    bug.stage = BugStage::Reproduce;
1009    state::save(state_dir, bug)
1010}
1011
1012fn freeze(
1013    c: &Ctx<'_>,
1014    mut bug: BugReport,
1015    by: &str,
1016    via: speccoder_core::actions::Via,
1017    basis: Basis,
1018    began: Instant,
1019) -> Result<Fix, Box<CommandResult>> {
1020    match confirm::freeze(c.state, &mut bug, by, via, basis) {
1021        Ok((record, files)) => {
1022            event(
1023                c.live,
1024                c.task,
1025                BugEvent::Confirmed {
1026                    digest: record.approval_digest.clone(),
1027                    by: by.to_owned(),
1028                    via: via.as_str().to_owned(),
1029                    basis: if basis == Basis::NamedTest {
1030                        "named_test"
1031                    } else {
1032                        "shown"
1033                    }
1034                    .to_owned(),
1035                },
1036            );
1037            stage(
1038                c.live,
1039                c.task,
1040                Stage::Confirm,
1041                StageState::Passed,
1042                Some(by.to_owned()),
1043                None,
1044            );
1045            Ok(Fix { bug, record, files })
1046        }
1047        Err(e) => Err(Box::new(stop(
1048            c,
1049            bug,
1050            Outcome::Recorded,
1051            None,
1052            format!("the confirmation could not be recorded: {e}"),
1053            began,
1054        ))),
1055    }
1056}
1057
1058/// Writes held-out variants for `statements`, red-checks them on the tree
1059/// as it is (twice, by assertion), and seals the set (keeping variants of
1060/// other statements already sealed). `told`: what a regeneration is told.
1061fn seal_variants(
1062    c: &Ctx<'_>,
1063    bug: &mut BugReport,
1064    visible: &[(String, String)],
1065    statements: &[String],
1066    told: &[String],
1067) -> Result<speccoder_core::acceptance::SealedRef, String> {
1068    let (files, manifest_text) = project_view(c);
1069    let context = manifest(c, bug, None);
1070    let input = substrate::acceptance::reproduce_input(&substrate::acceptance::ReproduceParts {
1071        set: "reproduce_held_out",
1072        bundle: c.bundle.clone(),
1073        statements: json!(bug.triad.statements().collect::<Vec<_>>()),
1074        want: statements,
1075        files: &files,
1076        manifest: &manifest_text,
1077        visible,
1078        rejections: told,
1079        issue: None,
1080        instructions: c.instructions,
1081        context: &context,
1082        test_layout: Some(&crate::layout::text_at(c.project)),
1083    });
1084    let (answer, run_id, _, _) =
1085        author(c, input).map_err(|e| format!("the held-out author: {e}"))?;
1086    let protected = c.policy.protected();
1087    let mut kept: Vec<(held_out::HeldOutFile, String)> = Vec::new();
1088    let mut discarded = Vec::new();
1089    for f in answer["files"].as_array().into_iter().flatten() {
1090        let path = f["path"].as_str().unwrap_or_default();
1091        let content = f["content"].as_str().unwrap_or_default();
1092        let cited: Vec<String> = f["scenarios"]
1093            .as_array()
1094            .into_iter()
1095            .flatten()
1096            .filter_map(|s| s.as_str().map(str::to_owned))
1097            .collect();
1098        let argv: Vec<String> = super::acceptance::argv_of(&f["argv"]);
1099        let Ok(rel) = tools::paths::normalise(path) else {
1100            discarded.push(held_out::Discarded {
1101                path: path.to_owned(),
1102                reason: "path".to_owned(),
1103            });
1104            continue;
1105        };
1106        let ok_path = tools::paths::is_test_path(&rel)
1107            && protected.write_class(&rel).is_none()
1108            && !c.project.join(&rel).exists()
1109            && !visible.iter().any(|(p, _)| *p == rel);
1110        let ok_cites = cited.len() == 1
1111            && statements.contains(&cited[0])
1112            && !kept.iter().any(|(k, _)| k.scenarios == cited);
1113        let ok_argv = c
1114            .policy
1115            .classify("run_command", &json!({ "argv": argv }), None)
1116            == Decision::Allow;
1117        if !(ok_path && ok_cites && ok_argv) {
1118            discarded.push(held_out::Discarded {
1119                path: rel,
1120                reason: if ok_path {
1121                    if ok_cites {
1122                        "command"
1123                    } else {
1124                        "unknown_scenario"
1125                    }
1126                } else {
1127                    "path"
1128                }
1129                .to_owned(),
1130            });
1131            continue;
1132        }
1133        kept.push((
1134            held_out::HeldOutFile {
1135                path: rel,
1136                sha256: sha256_hex(content.as_bytes()),
1137                scenarios: cited,
1138                argv,
1139                composition: false,
1140                red_tests: None,
1141            },
1142            content.to_owned(),
1143        ));
1144    }
1145    // Red twice on the tree as it is, by an assertion.
1146    let mut red: Vec<(held_out::HeldOutFile, String)> = Vec::new();
1147    // Red by what each variant adds: a failure its command shows without it
1148    // is another test's.
1149    let once = held_out::overlay_red(c.wt_root, c.project, c.tmp, &kept, c.runner, c.policy)
1150        .map_err(|e| format!("the held-out variants could not be run: {e}"))?;
1151    let twice = held_out::overlay_red(c.wt_root, c.project, c.tmp, &kept, c.runner, c.policy)
1152        .map_err(|e| format!("the held-out variants could not be run: {e}"))?;
1153    for ((f, content), (a, b)) in kept.into_iter().zip(once.iter().zip(&twice)) {
1154        let class = held_out::red_class;
1155        let c2 = rules::bug_class(class(a), Some(class(b)));
1156        bug.held_out.retain(|h| !f.scenarios.contains(&h.statement));
1157        bug.held_out.push(HeldOutVariant {
1158            statement: f.scenarios[0].clone(),
1159            baseline: c2,
1160            final_: Final::NotRun,
1161        });
1162        if c2 == RedClass::Assertion {
1163            red.push((f, content));
1164        } else {
1165            discarded.push(held_out::Discarded {
1166                path: f.path,
1167                reason: "not_red".to_owned(),
1168            });
1169        }
1170    }
1171    let written = red.len();
1172    // Variants of statements not written again stay.
1173    if let Some(old) = bug.held_out_sealed.clone() {
1174        let (m, contents) = held_out::open_sealed(c.state, &bug.unit, &old)
1175            .map_err(|e| format!("the sealed held-out set could not be opened: {}", e.0))?;
1176        for (f, (_, content)) in m.files.into_iter().zip(contents) {
1177            if !statements.iter().any(|s| f.scenarios.contains(s)) {
1178                red.push((f, content));
1179            }
1180        }
1181    }
1182    if written == 0 {
1183        return Err(if discarded.is_empty() {
1184            "the held-out author wrote no variant".to_owned()
1185        } else {
1186            format!(
1187                "no held-out variant was red on the untouched code by an assertion ({} discarded: {})",
1188                discarded.len(),
1189                discarded
1190                    .iter()
1191                    .map(|d| d.reason.as_str())
1192                    .collect::<Vec<_>>()
1193                    .join(", ")
1194            )
1195        });
1196    }
1197    let checkpoint = worktree::checkpoint(c.wt_root, c.tmp)
1198        .map(|cp| cp.0)
1199        .unwrap_or_default();
1200    let manifest = held_out::Manifest {
1201        version: 1,
1202        feature: bug.unit.clone(),
1203        task: bug.task.clone(),
1204        author_run: run_id,
1205        checkpoint,
1206        visible_scenarios: bug.expected_ids(),
1207        files: red.iter().map(|(f, _)| f.clone()).collect(),
1208        discarded,
1209    };
1210    let contents: Vec<(String, String)> = red
1211        .iter()
1212        .map(|(f, c)| (f.path.clone(), c.clone()))
1213        .collect();
1214    held_out::seal(c.state, &bug.unit, &bug.requirement, &manifest, &contents)
1215        .map_err(|e| format!("the held-out variants could not be sealed: {e}"))
1216}
1217
1218/// The confirmed set at the checkpoint (the one reuse function every
1219/// pre-frozen producer uses), with the bug red rule.
1220pub(crate) fn reuse(c: &Ctx<'_>, fix: &Fix) -> Result<PreparedAcceptance, String> {
1221    let tests: Vec<ReusedTest> = fix
1222        .bug
1223        .reproductions
1224        .iter()
1225        .map(|r| ReusedTest {
1226            path: r.file.clone(),
1227            cites: vec![r.statement.clone()],
1228            argv: r.argv.clone(),
1229            green: !r.reproduces(),
1230        })
1231        .collect();
1232    super::reuse_pre_frozen(
1233        c.project,
1234        &fix.record,
1235        &fix.files,
1236        &tests,
1237        c.runner,
1238        super::RedRule::BugAssertionOnly,
1239        None,
1240    )
1241}
1242
1243/// What judging a bug's attempt decided.
1244pub(crate) struct Judged {
1245    /// The verdict, with the bug rules applied.
1246    pub(crate) verdict: Verdict,
1247    /// A special case survived even its regenerated variant: the person
1248    /// rules (`BUG-REPRO-WEAK`).
1249    pub(crate) weak: Option<speccoder_core::strength::Permitted>,
1250}
1251
1252/// What judging needs besides the context.
1253pub(crate) struct Judging<'a> {
1254    pub(crate) before: &'a worktree::Checkpoint,
1255    pub(crate) baseline: &'a VerifyReport,
1256    pub(crate) verification: Option<&'a VerifyReport>,
1257    pub(crate) base: Verdict,
1258    /// The strength directory (rulings on special cases).
1259    pub(crate) keep: &'a Path,
1260}
1261
1262/// The class of reproduction `r` (its one test) on the tree as it is.
1263fn run_class(c: &Ctx<'_>, r: &Reproduction) -> RedClass {
1264    let (run, summary) = super::acceptance_run(c.project, &r.argv, c.runner);
1265    let class = classify_red_one(&run, summary.as_ref(), &r.test);
1266    if run.status == CheckStatus::Passed && class != RedClass::Unclassified {
1267        RedClass::Passed
1268    } else {
1269        class
1270    }
1271}
1272
1273/// `path` relative to the project, from a repository-relative one.
1274fn in_project(c: &Ctx<'_>, repo_path: &str) -> Option<String> {
1275    let prefix = c
1276        .project
1277        .strip_prefix(c.wt_root)
1278        .map(|p| p.to_string_lossy().replace('\\', "/"))
1279        .unwrap_or_default();
1280    if prefix.is_empty() {
1281        Some(repo_path.to_owned())
1282    } else {
1283        repo_path
1284            .strip_prefix(&format!("{prefix}/"))
1285            .map(str::to_owned)
1286    }
1287}
1288
1289/// Judges a bug task's attempt that passed the ordinary rules: finals,
1290/// pass-to-pass, revert, special cases. `Err`: the tree or a judge input
1291/// did not come back as it was (the measurement is void).
1292#[allow(clippy::too_many_lines)] // one linear procedure, in reading order
1293pub(crate) fn judge(c: &Ctx<'_>, fix: &mut Fix, j: &Judging<'_>) -> Result<Judged, String> {
1294    let began = Instant::now();
1295    stage(
1296        c.live,
1297        c.task,
1298        Stage::Unchanged,
1299        StageState::Started,
1300        None,
1301        None,
1302    );
1303    let fin = worktree::checkpoint(c.wt_root, c.tmp).map_err(|e| e.0)?;
1304    let judged_before = crate::integrity::JudgeSnapshot::take(c.wt_root, c.policy);
1305    // 1. Every reproduction (and Unchanged test) on the final tree.
1306    let mut unchanged_ok: Vec<String> = Vec::new();
1307    for r in &mut fix.bug.reproductions {
1308        let class = run_class(c, r);
1309        r.final_ = if class == RedClass::Passed {
1310            Final::Passed
1311        } else {
1312            Final::Failed
1313        };
1314        if !r.reproduces() && r.final_ == Final::Passed {
1315            unchanged_ok.push(r.statement.clone());
1316        }
1317    }
1318    // 2. The pass-to-pass set from the diff.
1319    let changes = worktree::diff(c.wt_root, j.before, &fin).map_err(|e| e.0)?;
1320    let changed: Vec<String> = changes
1321        .iter()
1322        .filter_map(|ch| in_project(c, &ch.path))
1323        .filter(|p| !tools::paths::is_test_path(p))
1324        .collect();
1325    let test_files: Vec<(String, String)> = worktree::files(c.wt_root, &fin)
1326        .unwrap_or_default()
1327        .into_iter()
1328        .filter_map(|p| in_project(c, &p))
1329        .filter(|p| tools::paths::is_test_path(p) || changed.contains(p))
1330        .take(400)
1331        .filter_map(|p| {
1332            std::fs::read_to_string(c.project.join(&p))
1333                .ok()
1334                .map(|t| (p, t))
1335        })
1336        .collect();
1337    let baseline_tests: Vec<speccoder_core::verify::TestResult> = j
1338        .baseline
1339        .checks
1340        .iter()
1341        .flat_map(|ch| ch.tests.clone().unwrap_or_default())
1342        .collect();
1343    let final_tests: Vec<speccoder_core::verify::TestResult> = j
1344        .verification
1345        .map(|v| {
1346            v.checks
1347                .iter()
1348                .flat_map(|ch| ch.tests.clone().unwrap_or_default())
1349                .collect()
1350        })
1351        .unwrap_or_default();
1352    let crate_name = std::fs::read_to_string(c.project.join("Cargo.toml"))
1353        .ok()
1354        .and_then(|t| {
1355            t.lines().find_map(|l| {
1356                l.trim().strip_prefix("name").map(|r| {
1357                    r.trim_start_matches([' ', '='])
1358                        .trim()
1359                        .trim_matches('"')
1360                        .to_owned()
1361                })
1362            })
1363        });
1364    let unchanged_members: Vec<(String, String, String)> = fix
1365        .bug
1366        .reproductions
1367        .iter()
1368        .filter(|r| !r.reproduces())
1369        .map(|r| (r.statement.clone(), r.file.clone(), r.test.clone()))
1370        .collect();
1371    let mut p2p: PassToPass = crate::bug::unchanged::select(
1372        &changed,
1373        &test_files,
1374        &baseline_tests,
1375        crate_name.as_deref(),
1376        &unchanged_members,
1377    );
1378    crate::bug::unchanged::settle(&mut p2p, &final_tests, &|s| {
1379        unchanged_ok.iter().any(|u| u == s)
1380    });
1381    event(
1382        c.live,
1383        c.task,
1384        BugEvent::UnchangedSelected {
1385            state: if p2p.state == rules::PassToPassState::Selected {
1386                "selected"
1387            } else {
1388                "none_selected"
1389            }
1390            .to_owned(),
1391            count: p2p.members.len(),
1392        },
1393    );
1394
1395    // 3. The revert: the attempt's source changes undone, its tests kept.
1396    worktree::restore(c.wt_root, c.tmp, j.before).map_err(|e| e.0)?;
1397    let git = crate::git::Git::at(c.wt_root);
1398    for ch in &changes {
1399        if !in_project(c, &ch.path).is_some_and(|p| tools::paths::is_test_path(&p)) {
1400            continue;
1401        }
1402        let full = c.wt_root.join(&ch.path);
1403        match ch.kind {
1404            worktree::ChangeKind::Deleted => {
1405                let _ = std::fs::remove_file(&full);
1406            }
1407            _ => {
1408                let content = git
1409                    .run(&["show", &format!("{}:{}", fin.0, ch.path)])
1410                    .map_err(|e| e.0)?;
1411                if let Some(parent) = full.parent() {
1412                    let _ = std::fs::create_dir_all(parent);
1413                }
1414                std::fs::write(&full, content).map_err(|e| e.to_string())?;
1415            }
1416        }
1417    }
1418    let mut rejected_by = Vec::new();
1419    let mut any_unviable = false;
1420    for r in fix.bug.reproductions.iter_mut().filter(|r| r.reproduces()) {
1421        let class = run_class(c, r);
1422        r.revert = match class {
1423            RedClass::Assertion => {
1424                rejected_by.push(r.statement.clone());
1425                Revert::Rejected
1426            }
1427            RedClass::Passed => Revert::Survived,
1428            _ => {
1429                any_unviable = true;
1430                Revert::Unviable
1431            }
1432        };
1433    }
1434    worktree::restore(c.wt_root, c.tmp, &fin).map_err(|e| e.0)?;
1435    let revert = RevertResult {
1436        outcome: if !rejected_by.is_empty() {
1437            Revert::Rejected
1438        } else if any_unviable {
1439            Revert::Unviable
1440        } else {
1441            Revert::Survived
1442        },
1443        rejected_by,
1444    };
1445    stage(
1446        c.live,
1447        c.task,
1448        Stage::Unchanged,
1449        if p2p.held() && !revert.rejected_by.is_empty() {
1450            StageState::Passed
1451        } else {
1452            StageState::Failed
1453        },
1454        Some(format!(
1455            "{} pass-to-pass, revert {}",
1456            p2p.members.len(),
1457            revert_word(revert.outcome)
1458        )),
1459        Some(began),
1460    );
1461
1462    // 4. Special cases: one per statement, against the combined set.
1463    let mut special: Vec<SpecialCase> = Vec::new();
1464    let mut special_error: Option<String> = None;
1465    let mut weak = None;
1466    if !revert.rejected_by.is_empty()
1467        && fix
1468            .bug
1469            .reproductions
1470            .iter()
1471            .all(|r| r.final_ == Final::Passed)
1472    {
1473        let patch = worktree::patch(c.wt_root, c.start, &fin).unwrap_or_default();
1474        let changed_sources = crate::strength::changed_files(c.wt_root, &patch);
1475        let shown: Vec<(String, String, String)> = fix
1476            .bug
1477            .reproductions
1478            .iter()
1479            .filter(|r| r.reproduces())
1480            .filter_map(|r| {
1481                fix.files
1482                    .iter()
1483                    .find(|(p, _)| *p == r.file)
1484                    .map(|(p, content)| (r.statement.clone(), p.clone(), content.clone()))
1485            })
1486            .collect();
1487        if changed_sources.is_empty() {
1488            special_error =
1489                Some("the fix changes no source file a special case could replace".to_owned());
1490        } else {
1491            let context = manifest(c, &fix.bug, None);
1492            let input = substrate::near_miss::special_case_input(
1493                c.bundle,
1494                &changed_sources,
1495                &crate::mutation::source_patch(&patch),
1496                &shown,
1497                &context,
1498            );
1499            // A failed or empty answer is said, never read as "none needed".
1500            let variants = match c.rt.block_on(c.plane.near_miss(c.feature, c.task, input)) {
1501                Err(e) => {
1502                    special_error = Some(format!("the special-case author call failed: {}", e.0));
1503                    Vec::new()
1504                }
1505                Ok(o) => {
1506                    let answer = o
1507                        .output
1508                        .as_ref()
1509                        .map(|v| v.peek()["answer"].clone())
1510                        .unwrap_or_default();
1511                    if !matches!(o.status, agentplane::prelude::RunStatus::Succeeded)
1512                        || answer.is_null()
1513                    {
1514                        special_error = Some(format!(
1515                            "the special-case author did not answer ({})",
1516                            crate::substrate::why_not(&o.status)
1517                        ));
1518                        Vec::new()
1519                    } else {
1520                        let v = special_variants(&answer, &changed_sources);
1521                        if v.is_empty() {
1522                            special_error = Some(
1523                                "the special-case author wrote no candidate that changes the fix's source files".to_owned(),
1524                            );
1525                        }
1526                        v
1527                    }
1528                }
1529            };
1530            let rulings = crate::strength::rulings(j.keep);
1531            for v in variants {
1532                let statement = v.scenario.clone();
1533                if special.iter().any(|s| s.statement == statement) {
1534                    continue;
1535                }
1536                let digest = v.digest();
1537                let ruled = rulings.iter().any(|r| r.digest == digest);
1538                let mut rejected = special_rejected(c, fix, &v, &fin)?;
1539                let mut regenerated = false;
1540                if !rejected && !ruled {
1541                    // One regeneration of the statement's variant, told what got through.
1542                    regenerated = true;
1543                    let visible: Vec<(String, String)> = shown
1544                        .iter()
1545                        .filter(|(s, _, _)| *s == statement)
1546                        .map(|(_, p, content)| (p.clone(), content.clone()))
1547                        .collect();
1548                    worktree::restore(c.wt_root, c.tmp, j.before).map_err(|e| e.0)?;
1549                    let told = vec![format!(
1550                        "a fix that special-cases this input passed the earlier variant: {}",
1551                        v.rationale
1552                    )];
1553                    let resealed = seal_variants(
1554                        c,
1555                        &mut fix.bug,
1556                        &visible,
1557                        std::slice::from_ref(&statement),
1558                        &told,
1559                    );
1560                    worktree::restore(c.wt_root, c.tmp, &fin).map_err(|e| e.0)?;
1561                    match resealed {
1562                        Ok(sealed) => {
1563                            fix.bug.held_out_sealed = Some(sealed.clone());
1564                            fix.record.held_out_sealed = Some(sealed);
1565                            crate::pre_frozen::store(c.state, &fix.record, &fix.files).map_err(
1566                                |e| format!("the re-sealed held-out set could not be kept: {e}"),
1567                            )?;
1568                            rejected = special_rejected(c, fix, &v, &fin)?;
1569                        }
1570                        // No new variant: the special case still stands, and why is said.
1571                        Err(why) => {
1572                            fix.bug.held_out_reason = Some(why);
1573                        }
1574                    }
1575                }
1576                if !rejected && !ruled {
1577                    weak = Some(speccoder_core::strength::Permitted {
1578                        id: format!("special-case-{statement}"),
1579                        scenario: statement.clone(),
1580                        rationale: v.rationale.clone(),
1581                        digest: digest.clone(),
1582                        outcome: speccoder_core::strength::PermittedOutcome::Rejected,
1583                        failing: None,
1584                        patch: None,
1585                    });
1586                }
1587                special.push(SpecialCase {
1588                    statement,
1589                    digest,
1590                    rejected,
1591                    regenerated,
1592                    ruled,
1593                });
1594            }
1595        }
1596    }
1597    // Held-out: every sealed variant — a regenerated one too — runs on the
1598    // final tree and must pass there.
1599    let held = match fix.bug.held_out_sealed.clone() {
1600        Some(sealed) => {
1601            let (m, contents) = held_out::open_sealed(c.state, &fix.bug.unit, &sealed)
1602                .map_err(|e| format!("the sealed held-out set could not be opened: {}", e.0))?;
1603            let files: Vec<(held_out::HeldOutFile, String)> = m
1604                .files
1605                .into_iter()
1606                .zip(contents.into_iter().map(|(_, x)| x))
1607                .collect();
1608            let runs =
1609                held_out::overlay_run(c.wt_root, c.project, c.tmp, &files, c.runner, c.policy)?;
1610            let mut failed: Vec<String> = Vec::new();
1611            let mut passed: Vec<String> = Vec::new();
1612            for ((f, _), r) in files.iter().zip(&runs) {
1613                let ok = r
1614                    .result
1615                    .as_ref()
1616                    .is_some_and(|(res, _)| res.status == CheckStatus::Passed);
1617                for st in &f.scenarios {
1618                    if ok {
1619                        passed.push(st.clone());
1620                    } else {
1621                        failed.push(st.clone());
1622                    }
1623                }
1624            }
1625            if runs.len() != files.len() {
1626                failed.push("held-out".to_owned());
1627            }
1628            for h in &mut fix.bug.held_out {
1629                h.final_ = if failed.contains(&h.statement) {
1630                    Final::Failed
1631                } else if passed.contains(&h.statement) {
1632                    Final::Passed
1633                } else {
1634                    Final::NotRun
1635                };
1636            }
1637            failed.sort();
1638            failed.dedup();
1639            if failed.is_empty() {
1640                HeldOut::Passed { files: files.len() }
1641            } else {
1642                HeldOut::Failed { scenarios: failed }
1643            }
1644        }
1645        None if c.held_out => HeldOut::Absent {
1646            reason: fix
1647                .bug
1648                .held_out_reason
1649                .clone()
1650                .unwrap_or_else(|| "none_kept".to_owned()),
1651        },
1652        None => HeldOut::Off,
1653    };
1654    // The tree and the judge inputs are as they were.
1655    let now = worktree::checkpoint(c.wt_root, c.tmp).map_err(|e| e.0)?;
1656    if now != fin {
1657        return Err("the bug's judging left changes in the worktree".to_owned());
1658    }
1659    let drift = judged_before.drift(
1660        &crate::integrity::JudgeSnapshot::take(c.wt_root, c.policy),
1661        c.policy,
1662        &std::collections::BTreeSet::new(),
1663    );
1664    if let Some(d) = drift.first() {
1665        return Err(format!("the bug's judging changed judge input {}", d.path));
1666    }
1667    event(
1668        c.live,
1669        c.task,
1670        BugEvent::Discrimination {
1671            revert: revert_word(revert.outcome),
1672            special_case: special
1673                .iter()
1674                .map(|s| crate::progress::ShownSpecialCase {
1675                    statement: s.statement.clone(),
1676                    rejected: s.rejected || s.ruled,
1677                })
1678                .collect(),
1679        },
1680    );
1681    let verdict = {
1682        let d = rules::Discrimination {
1683            reproductions: &fix.bug.reproductions,
1684            revert: &revert,
1685            special_case: &special,
1686            special_case_error: special_error.as_deref(),
1687        };
1688        rules::bug_verdict(j.base.clone(), &d, &p2p, &held)
1689    };
1690    fix.bug.pass_to_pass = Some(p2p);
1691    fix.bug.revert = Some(revert);
1692    fix.bug.special_case = special;
1693    state::save(c.state, &fix.bug).map_err(|e| format!("the bug could not be kept: {e}"))?;
1694    Ok(Judged { verdict, weak })
1695}
1696
1697fn revert_word(r: Revert) -> String {
1698    match r {
1699        Revert::Rejected => "rejected",
1700        Revert::Survived => "survived",
1701        Revert::Unviable => "unviable",
1702        Revert::NotRun => "not_run",
1703    }
1704    .to_owned()
1705}
1706
1707/// The author's special cases, checked like any variant: only changed
1708/// source files, each a real change.
1709fn special_variants(answer: &Value, changed: &[(String, String)]) -> Vec<crate::strength::Variant> {
1710    let mut out = Vec::new();
1711    for v in answer["variants"].as_array().into_iter().flatten() {
1712        if v["kind"] != "special_case" {
1713            continue;
1714        }
1715        let mut files = Vec::new();
1716        let mut ok = true;
1717        for f in v["files"].as_array().into_iter().flatten() {
1718            let (Some(path), Some(content)) = (f["path"].as_str(), f["content"].as_str()) else {
1719                ok = false;
1720                break;
1721            };
1722            match tools::paths::normalise(path).ok().and_then(|p| {
1723                changed
1724                    .iter()
1725                    .find(|(c, _)| *c == p)
1726                    .map(|(c, now)| (c.clone(), now.clone()))
1727            }) {
1728                Some((p, now)) if now != content => files.push((p, content.to_owned())),
1729                Some(_) => {}
1730                None => {
1731                    ok = false;
1732                    break;
1733                }
1734            }
1735        }
1736        if ok && !files.is_empty() {
1737            out.push(crate::strength::Variant {
1738                kind: "special_case".to_owned(),
1739                scenario: v["scenario"].as_str().unwrap_or_default().to_owned(),
1740                rationale: v["rationale"].as_str().unwrap_or_default().to_owned(),
1741                files,
1742            });
1743        }
1744    }
1745    out
1746}
1747
1748/// Whether the combined set (the statement's reproduction and its held-out
1749/// variants) rejects the special case by an assertion.
1750fn special_rejected(
1751    c: &Ctx<'_>,
1752    fix: &Fix,
1753    v: &crate::strength::Variant,
1754    fin: &worktree::Checkpoint,
1755) -> Result<bool, String> {
1756    for (p, content) in &v.files {
1757        std::fs::write(c.wt_root.join(p), content).map_err(|e| format!("{p}: {e}"))?;
1758    }
1759    let mut rejected = false;
1760    for r in fix
1761        .bug
1762        .reproductions
1763        .iter()
1764        .filter(|r| r.statement == v.scenario)
1765    {
1766        if run_class(c, r) == RedClass::Assertion {
1767            rejected = true;
1768        }
1769    }
1770    if !rejected
1771        && let Some(sealed) = &fix.bug.held_out_sealed
1772        && let Ok((m, contents)) = held_out::open_sealed(c.state, &fix.bug.unit, sealed)
1773    {
1774        let files: Vec<(held_out::HeldOutFile, String)> = m
1775            .files
1776            .into_iter()
1777            .zip(contents.into_iter().map(|(_, x)| x))
1778            .filter(|(f, _)| f.scenarios.contains(&v.scenario))
1779            .collect();
1780        let runs = held_out::overlay_run(c.wt_root, c.project, c.tmp, &files, c.runner, c.policy)?;
1781        rejected = runs
1782            .iter()
1783            .filter_map(|r| r.result.as_ref())
1784            .any(|(res, s)| classify_red(res, s.as_ref()) == RedClass::Assertion);
1785    }
1786    worktree::restore(c.wt_root, c.tmp, fin).map_err(|e| e.0)?;
1787    Ok(rejected)
1788}
1789
1790/// The trailers a bug task's tick commit carries; `rulings`: the person's
1791/// rulings on special cases (`task rule --tests-right`), named when one
1792/// let a special case through.
1793pub(crate) fn trailers(
1794    fix: &Fix,
1795    verdict_word: &str,
1796    rulings: &[speccoder_core::strength::Ruling],
1797) -> String {
1798    let outcome = if matches!(verdict_word, "verified" | "attested") {
1799        "fixed"
1800    } else {
1801        "failed"
1802    };
1803    let mut out = format!(
1804        "Bug: {outcome} ({}) triad={}\n",
1805        fix.bug.home.kind.as_str(),
1806        fix.bug.triad.digest
1807    );
1808    out.push_str(
1809        &fix.record
1810            .trailer(&crate::pre_frozen::manifest_digest(&fix.record)),
1811    );
1812    for s in fix
1813        .bug
1814        .special_case
1815        .iter()
1816        .filter(|s| s.ruled && !s.rejected)
1817    {
1818        if let Some(r) = rulings.iter().find(|r| r.digest == s.digest) {
1819            out.push_str(&format!(
1820                "Ruling: tests-right {} {} by {} — {}\n",
1821                s.statement, r.digest, r.by, r.reason
1822            ));
1823        }
1824    }
1825    if let Some(i) = fix.bug.issue.as_ref().filter(|_| outcome == "fixed") {
1826        // A trailer git parses (`Fixes #N` without the colon would make
1827        // git read none of the block); GitHub closes on it either way.
1828        out.push_str(&format!("Fixes: #{}\n", i.number));
1829    }
1830    out
1831}
1832
1833/// The predicate's `bug` and `acceptance` fields.
1834pub(crate) fn predicate_fields(
1835    bug: &BugReport,
1836    record: &speccoder_core::acceptance::PreFrozenAcceptance,
1837) -> (Value, Value) {
1838    let b = json!({
1839        "home": bug.home.kind.as_str(),
1840        "triad_sha256": bug.triad.digest,
1841        "outcome": bug.outcome.as_str(),
1842        "reproductions": bug.reproductions.iter().map(|r| json!({
1843            "statement": r.statement, "baseline": r.baseline, "final": r.final_, "revert": r.revert,
1844        })).collect::<Vec<_>>(),
1845        "special_case": bug.special_case.iter().map(|s| json!({
1846            "statement": s.statement, "rejected": s.rejected, "regenerated": s.regenerated,
1847        })).collect::<Vec<_>>(),
1848        "pass_to_pass": bug.pass_to_pass.as_ref().map(|p| json!({ "state": p.state, "count": p.members.len() })),
1849    });
1850    let a = json!({
1851        "source": record.producer.source(),
1852        "pre_frozen": {
1853            "manifest_sha256": crate::pre_frozen::manifest_digest(record),
1854            "approval_sha256": record.approval_digest,
1855            "wording_sha256": record.wording_digest,
1856            "by": record.decided.by,
1857            "via": record.decided.via,
1858        },
1859    });
1860    (b, a)
1861}
1862
1863/// After the run: the bug's outcome from the task's.
1864pub(crate) fn finish(
1865    state_dir: &Path,
1866    fix: &mut Fix,
1867    report: &speccoder_core::RunReport,
1868    passed: bool,
1869) {
1870    // What the attempt recorded of the candidate meanwhile.
1871    if let Some(saved) = state::load(state_dir, &fix.bug.unit, &fix.bug.task) {
1872        fix.bug.candidate = saved.candidate;
1873    }
1874    fix.bug.verdict.clone_from(&report.verdict);
1875    fix.bug.run_id = (!report.run_id.is_empty()).then(|| report.run_id.clone());
1876    fix.bug.commit.clone_from(&report.commit);
1877    fix.bug.outcome = if passed {
1878        Outcome::Fixed
1879    } else {
1880        Outcome::Failed
1881    };
1882    fix.bug.stage = if passed {
1883        BugStage::Done
1884    } else {
1885        BugStage::Fix
1886    };
1887    fix.bug.code = (!passed
1888        && fix
1889            .bug
1890            .revert
1891            .as_ref()
1892            .is_some_and(|r| r.rejected_by.is_empty()))
1893    .then(|| "BUG-NOT-DISCRIMINATING".to_owned());
1894    let _ = state::save(state_dir, &fix.bug);
1895}
1896
1897/// Someone else's fix as the attempt: refused before it is applied when it
1898/// touches a frozen reproduction, a held-out path or a judge input, or
1899/// when it does not apply. `Ok`: `(run id, succeeded, output)` as an
1900/// attempt reports them.
1901pub(crate) fn apply_candidate(
1902    c: &Ctx<'_>,
1903    diff: &str,
1904    candidate: &rules::Candidate,
1905    frozen: &[String],
1906    held_out_paths: &[String],
1907) -> Result<(String, bool, Value), Box<CommandResult>> {
1908    let refused = |code: &str, paths: Vec<String>, status: CommandStatus, message: String| {
1909        let _ = worktree::restore(c.wt_root, c.tmp, c.start);
1910        if let Some(mut bug) = state::load(c.state, c.feature, c.task) {
1911            if let Some(cand) = bug.candidate.as_mut() {
1912                cand.refused = Some(rules::CandidateRefusal {
1913                    code: code.to_owned(),
1914                    paths: paths.clone(),
1915                });
1916            }
1917            bug.outcome = Outcome::Failed;
1918            bug.code = Some(code.to_owned());
1919            let _ = state::save(c.state, &bug);
1920        }
1921        let mut report = bare_report(c.feature, c.task, c.wt_path, "candidate_refused");
1922        report.reason = Some(message.clone());
1923        report.bug = state::load(c.state, c.feature, c.task).map(Box::new);
1924        Box::new(
1925            CommandResult::new("run", status, &message)
1926                .with_code(code)
1927                .with_data(CommandData::Run(Box::new(report))),
1928        )
1929    };
1930    // The paths as git reads the diff: renames, mode changes and quoted
1931    // paths included; a binary hunk or a symbolic link is not applied.
1932    let touched = match crate::bug::candidate::touched(c.wt_root, diff) {
1933        Ok(t) => t,
1934        Err(r) => {
1935            let message = format!("the candidate is not applied: {}", r.paths.join("; "));
1936            return Err(refused(
1937                "BUG-CANDIDATE-APPLY",
1938                r.paths,
1939                CommandStatus::GitPrecondition,
1940                message,
1941            ));
1942        }
1943    };
1944    let judged = crate::bug::candidate::judge_paths(&touched, c.policy, frozen, held_out_paths);
1945    if !judged.is_empty() {
1946        return Err(refused(
1947            "BUG-CANDIDATE-JUDGE",
1948            judged.clone(),
1949            CommandStatus::UsageError,
1950            format!(
1951                "the candidate touches what judges it, so it is not applied: {}",
1952                judged.join(", ")
1953            ),
1954        ));
1955    }
1956    if let Err(r) = crate::bug::candidate::apply(c.wt_root, c.tmp, diff) {
1957        let message = format!(
1958            "the candidate does not apply on the branch: {}",
1959            if r.paths.is_empty() {
1960                "git refused it".to_owned()
1961            } else {
1962                r.paths.join("; ")
1963            }
1964        );
1965        return Err(refused(
1966            "BUG-CANDIDATE-APPLY",
1967            r.paths,
1968            CommandStatus::GitPrecondition,
1969            message,
1970        ));
1971    }
1972    if let Some(mut bug) = state::load(c.state, c.feature, c.task) {
1973        if let Some(cand) = bug.candidate.as_mut() {
1974            cand.applied = true;
1975        }
1976        let _ = state::save(c.state, &bug);
1977    }
1978    let short: String = candidate
1979        .digest
1980        .trim_start_matches("sha256:")
1981        .chars()
1982        .take(12)
1983        .collect();
1984    let from = match (&candidate.path, candidate.number) {
1985        (_, Some(n)) => format!("pull request #{n}"),
1986        (Some(p), None) => p.clone(),
1987        (None, None) => "a patch".to_owned(),
1988    };
1989    Ok((
1990        format!("candidate_{short}"),
1991        true,
1992        json!({
1993            "status": "completed",
1994            "report": { "summary": format!("applied {from} as the attempt"), "status": "completed" },
1995            "tool_calls": [],
1996        }),
1997    ))
1998}
1999
2000/// The run's result for a bug task: the bug's outcome from the task's, its
2001/// codes and the event.
2002pub(crate) fn finished(
2003    c: &Ctx<'_>,
2004    fix: &mut Fix,
2005    mut report: speccoder_core::RunReport,
2006    attempt_status: &str,
2007    passed: bool,
2008    status: CommandStatus,
2009    message: String,
2010) -> CommandResult {
2011    let done = passed && (report.ticked || report.commit.is_some());
2012    finish(c.state, fix, &report, done);
2013    let mut status = status;
2014    let mut code = None;
2015    if attempt_status == "repro_weak" {
2016        status = CommandStatus::NeedsHuman;
2017        code = Some("BUG-REPRO-WEAK");
2018        fix.bug.code = Some("BUG-REPRO-WEAK".to_owned());
2019        let _ = state::save(c.state, &fix.bug);
2020    } else if !done
2021        && fix
2022            .bug
2023            .revert
2024            .as_ref()
2025            .is_some_and(|r| r.rejected_by.is_empty())
2026    {
2027        code = Some("BUG-NOT-DISCRIMINATING");
2028    }
2029    let next = handoff::next(&fix.bug, fix.bug.outcome);
2030    event(
2031        c.live,
2032        c.task,
2033        BugEvent::Outcome {
2034            outcome: fix.bug.outcome.as_str().to_owned(),
2035            verdict: report.verdict.as_ref().map(super::outcome::verdict_word),
2036            code: code.map(str::to_owned),
2037            next: next.iter().map(|n| n.command.clone()).collect(),
2038        },
2039    );
2040    report.bug = Some(Box::new(fix.bug.clone()));
2041    c.live.event(&super::finished_event(
2042        c.task,
2043        &report,
2044        attempt_status,
2045        false,
2046        message.clone(),
2047    ));
2048    let mut r =
2049        CommandResult::new("run", status, &message).with_data(CommandData::Run(Box::new(report)));
2050    if let Some(code) = code {
2051        r = r.with_code(code);
2052    }
2053    r
2054}
2055
2056/// A bug in the format's own bug structure, as a run takes it: the unit
2057/// no task list names, its directory, and what the attempt is given.
2058#[derive(Debug, Clone, PartialEq, Eq)]
2059pub struct NativeBug {
2060    /// The unit (`bugs/<slug>`).
2061    pub unit: String,
2062    /// Its directory, project-relative.
2063    pub dir: String,
2064    /// The task (`bug:<slug>`).
2065    pub task: String,
2066    /// The title.
2067    pub title: String,
2068    /// What the attempt reads as the requirement: the person's triad.
2069    pub story: String,
2070}
2071
2072impl NativeBug {
2073    /// The bug of `bug`.
2074    #[must_use]
2075    pub fn of(bug: &BugReport) -> Self {
2076        Self {
2077            unit: bug.unit.clone(),
2078            dir: bug.home.location.clone(),
2079            task: bug.task.clone(),
2080            title: bug.title.clone(),
2081            story: format!(
2082                "A bug, in the reporter's words.\n\n{}",
2083                bug.triad.labelled()
2084            ),
2085        }
2086    }
2087
2088    /// The context bundle an attempt at it is given.
2089    #[must_use]
2090    pub fn bundle(&self, project: &Path) -> crate::context::Bundle {
2091        let [rules, ..] =
2092            crate::format::at(project).convergence_texts(project, &project.join(&self.dir));
2093        crate::context::Bundle {
2094            feature: self.unit.clone(),
2095            constitution: crate::context::cap(&rules),
2096            plan: String::new(),
2097            story: crate::context::cap(&self.story),
2098            task: crate::context::TaskContext {
2099                id: self.task.clone(),
2100                title: format!("Fix: {}", self.title),
2101                phase: String::new(),
2102                subsection: String::new(),
2103                story: String::new(),
2104                parallel: false,
2105            },
2106            dependencies: Vec::new(),
2107            story_tasks: Vec::new(),
2108        }
2109    }
2110}
2111
2112#[cfg(test)]
2113mod tests {
2114    use super::*;
2115
2116    #[test]
2117    fn a_reproduction_is_a_test_file_run_by_speccoders_own_command() {
2118        let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
2119        let policy = Policy::new(
2120            &[],
2121            &[vec![
2122                "./run-one".to_owned(),
2123                "tests/repro.sh".to_owned(),
2124                "empty".to_owned(),
2125            ]],
2126        );
2127        let template = [
2128            "./run-one".to_owned(),
2129            "{file}".to_owned(),
2130            "{name}".to_owned(),
2131        ];
2132        let want = ["E1".to_owned()];
2133        let answer = |path: &str, test: &str| json!({ "files": [{ "path": path, "content": "x", "statement": "E1", "test": test, "argv": ["sh", "-c", "exit 1"] }] });
2134        // The author's command is never run: speccoder's runs only the test.
2135        let ok = validate(
2136            &answer("tests/repro.sh", "empty"),
2137            &want,
2138            dir.path(),
2139            &policy,
2140            Some(&template),
2141        );
2142        let Ok(files) = ok else {
2143            panic!("{ok:?}", ok = ok.err());
2144        };
2145        assert_eq!(files[0].argv, ["./run-one", "tests/repro.sh", "empty"]);
2146        // A file that configures how every test runs is not a reproduction.
2147        for path in [
2148            "tests/conftest.py",
2149            "tests/__init__.py",
2150            "tests/vitest.setup.ts",
2151        ] {
2152            let e = validate(
2153                &answer(path, "t"),
2154                &want,
2155                dir.path(),
2156                &policy,
2157                Some(&template),
2158            )
2159            .err();
2160            assert!(
2161                e.as_deref()
2162                    .is_some_and(|e| e.contains("configures how tests run")),
2163                "{path}: {e:?}"
2164            );
2165        }
2166        // A test without a name, or with no rule to run it alone, is not one.
2167        assert!(
2168            validate(
2169                &answer("tests/repro.sh", " "),
2170                &want,
2171                dir.path(),
2172                &policy,
2173                Some(&template)
2174            )
2175            .is_err()
2176        );
2177        assert!(
2178            validate(
2179                &answer("tests/repro.unknown", "t"),
2180                &want,
2181                dir.path(),
2182                &policy,
2183                None
2184            )
2185            .err()
2186            .is_some_and(|e| e.contains("[bug] test"))
2187        );
2188    }
2189}