Skip to main content

brep_mcp_core/
runner.rs

1//! The `test-mcp` script runner: plays a [`Script`] through a [`ToolSet`],
2//! checks every `expect`, saves and compares images, and writes the per-step
3//! artefacts (`NNNN-<tool>.json`, images, `result.json`) under an output
4//! directory. It knows nothing about hosts or sessions: the tool set it is
5//! handed is whatever the session generated, so a script written against the
6//! running app and one written against the catalogue tools run the same way.
7use crate::image;
8use crate::script::{exit, Frame, Script, Step};
9use crate::tools::ToolSet;
10use serde::Serialize;
11use serde_json::{json, Value};
12use std::path::{Path, PathBuf};
13use std::time::Instant;
14
15#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
16#[serde(rename_all = "snake_case")]
17pub enum Outcome {
18    Pass,
19    ExpectationFailed,
20    ToolError,
21    Timeout,
22}
23
24#[derive(Debug, Clone, Serialize)]
25pub struct StepResult {
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub group: Option<String>,
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub expected_error: Option<bool>,
30    pub index: usize,
31    pub tool: String,
32    pub outcome: Outcome,
33    pub elapsed_ms: u128,
34    #[serde(skip_serializing_if = "Vec::is_empty")]
35    pub failures: Vec<String>,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub image: Option<String>,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub diff_ratio: Option<f64>,
40}
41
42/// What a script's walkthrough recording produced.
43#[derive(Debug, Clone, Serialize)]
44pub struct VideoResult {
45    /// The GIF's path as the script declared it.
46    pub out: String,
47    /// Where it was actually written (one entry per destination).
48    pub written: Vec<String>,
49    pub frames: usize,
50    pub bytes: usize,
51    /// Pixel size of every frame.
52    pub size: [u32; 2],
53    /// How long the whole GIF plays, in milliseconds.
54    pub duration_ms: u32,
55    /// Encode time alone — not the capture, which is most of the wall clock.
56    pub encode_ms: u128,
57}
58
59#[derive(Debug, Clone, Serialize)]
60pub struct RunResult {
61    pub script: String,
62    pub passed: bool,
63    pub exit_code: i32,
64    pub steps: Vec<StepResult>,
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub failed_step: Option<usize>,
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub video: Option<VideoResult>,
69}
70
71pub use crate::script::{PLM_REQUEST, PLM_SERVER};
72
73pub struct RunOptions {
74    pub out_dir: PathBuf,
75    pub baselines_dir: PathBuf,
76    pub update_baselines: bool,
77    pub stop_on_fail: bool,
78    /// Where a script's `video.out` is resolved, when a walkthrough GIF is to
79    /// reach the repository at all. `None` — every ordinary run, including the
80    /// `test-mcp` gate — still records and encodes, but writes the GIF into the
81    /// run's own output directory only: the gate cannot touch `docs/`.
82    pub video_root: Option<PathBuf>,
83    /// The script's PLM server, when it declares one: `plm_request` steps are
84    /// answered from it, and `${plm:NAME}` resolves in every step's strings.
85    pub plm: Option<std::sync::Arc<crate::plm_fixture::PlmFixture>>,
86}
87
88/// `__brepPerf.staleFrames` when the session's app publishes it (automation
89/// builds carry the check), else None.
90pub(crate) async fn stale_frames(tools: &ToolSet) -> Option<u64> {
91    let get = tools.get("state_get")?;
92    let out = (get.handler)(json!({ "names": ["__brepPerf"] })).await.ok()?;
93    out.json.get("__brepPerf")?.get("staleFrames")?.as_u64()
94}
95
96/// Play `script` through `tools`. Returns the result (also written to
97/// `<out_dir>/result.json`).
98pub async fn run(script: &Script, tools: &ToolSet, opts: &RunOptions) -> RunResult {
99    let _ = std::fs::create_dir_all(&opts.out_dir);
100    let deadline = Instant::now() + std::time::Duration::from_millis(script.timeout_ms);
101    let mut steps = Vec::new();
102    let mut failed_step = None;
103    // THE WALKTHROUGH: every step carrying a `frame` contributes one held GIF
104    // frame, recorded before the step runs. The total is counted up front so
105    // the `n / total` counter on the band cannot drift from the script.
106    let total_frames = script.steps.iter().filter(|s| s.frame.is_some()).count();
107    let mut shots: Vec<image::GifFrame> = Vec::new();
108    // The counter on the caption band is the step's ordinal among the framed
109    // steps, NOT the GIF frame number: a FILMED drag contributes a still plus
110    // its motion frames and is still ONE step of the walkthrough, so `shots`
111    // cannot stand in for it.
112    let mut framed = 0usize;
113    let mut recording_failed = false;
114    let stale_before = stale_frames(tools).await;
115    for (index, step) in script.steps.iter().enumerate() {
116        if Instant::now() > deadline {
117            steps.push(StepResult {
118                group: None, expected_error: None,
119                index,
120                tool: step.tool.clone(),
121                outcome: Outcome::Timeout,
122                elapsed_ms: 0,
123                failures: vec![format!("script timeout ({} ms) reached before step {index}", script.timeout_ms)],
124                image: None,
125                diff_ratio: None,
126            });
127            failed_step = Some(index);
128            break;
129        }
130        // A framed step is recorded one of two ways. An ORDINARY one is a single
131        // still, captured before the step runs — the control unpressed and
132        // ringed, with the caption saying what pressing it will do. A step whose
133        // frame carries a `motion` is a DRAG, and it is FILMED: the annotation
134        // is set here, the tool is asked to capture as it drags, and the
135        // pictures it hands back become the frames. Either way the step is one
136        // `n / total` on the band.
137        //
138        // The filming branch is gated on the script RECORDING as well as on the
139        // frame: `Script::parse` refuses `motion` without a `video`, but a
140        // `Script` built in code (the tests build them) would otherwise reach it
141        // with no `capture` sent and fail on a picture count rather than simply
142        // running the drag.
143        let motion = script
144            .video
145            .as_ref()
146            .and(step.frame.as_ref())
147            .and_then(|f| f.motion.as_ref());
148        let mut capture_args = None;
149        if let (Some(video), Some(frame)) = (&script.video, &step.frame) {
150            framed += 1;
151            let recorded = match motion {
152                None => capture_frame(tools, video, frame, framed, total_frames)
153                    .await
154                    .map(|shot| shots.push(shot)),
155                Some(motion) => {
156                    capture_args = Some(json!({ "capture": {
157                        "frames": motion.frames,
158                        "max_width": video.width,
159                        "cursor_scale": motion.cursor_scale,
160                    }}));
161                    // Set ONCE, for the whole drag. The overlay re-resolves a
162                    // `highlight` from the live publication on every frame it
163                    // paints, so the ring FOLLOWS the handle as the drag moves
164                    // it — and re-annotating per frame could fail mid-drag, with
165                    // the button still down, on a handle whose pick momentarily
166                    // answers something else.
167                    set_annotation(tools, video, frame, framed, total_frames).await
168                }
169            };
170            if let Err(why) = recorded {
171                steps.push(StepResult {
172                    group: None, expected_error: None,
173                    index,
174                    tool: "annotate+screenshot".into(),
175                    outcome: Outcome::ToolError,
176                    elapsed_ms: 0,
177                    failures: vec![format!("recording the walkthrough frame before step {index}: {why}")],
178                    image: None,
179                    diff_ratio: None,
180                });
181                recording_failed = true;
182                failed_step = Some(index);
183                break;
184            }
185        }
186        let (result, images) = run_step(index, step, tools, opts, capture_args).await;
187        if let (Some(motion), Some(frame)) = (motion, step.frame.as_ref()) {
188            // Clear the overlay whatever happened, so a failed drag cannot leave
189            // the rest of the script captioned.
190            if let Some(annotate) = tools.get("annotate") {
191                let _ = (annotate.handler)(json!({})).await;
192            }
193            match motion_frames(&images, frame, motion) {
194                Ok(mut filmed) => shots.append(&mut filmed),
195                Err(why) => {
196                    // The drag's OWN result goes in first: it says whether the
197                    // drag itself worked, which is the first thing anyone
198                    // reading `result.json` about a failed filming wants.
199                    steps.push(result);
200                    steps.push(StepResult {
201                        group: None, expected_error: None,
202                        index,
203                        tool: "annotate+screenshot".into(),
204                        outcome: Outcome::ToolError,
205                        elapsed_ms: 0,
206                        failures: vec![format!("filming the drag at step {index}: {why}")],
207                        image: None,
208                        diff_ratio: None,
209                    });
210                    recording_failed = true;
211                    failed_step = Some(index);
212                    break;
213                }
214            }
215        }
216        let failed = result.outcome != Outcome::Pass;
217        steps.push(result);
218        if failed {
219            failed_step = Some(index);
220            if opts.stop_on_fail {
221                break;
222            }
223        }
224    }
225    // THE STALE-FRAME CHECK: the app counts frames whose render inputs changed
226    // without a render (a producer that forgot to mark the frame dirty). The
227    // count is process-wide, so the script is charged with what it added.
228    match (stale_before, stale_frames(tools).await) {
229        (Some(before), Some(after)) => {
230            eprintln!("stale-frame check: {} {}", script.name, after - before);
231            if after > before {
232                steps.push(StepResult {
233                    group: None, expected_error: None,
234                    index: script.steps.len(),
235                    tool: "stale-frame check".into(),
236                    outcome: Outcome::ExpectationFailed,
237                    elapsed_ms: 0,
238                    failures: vec![format!(
239                        "{} frame(s) changed what the viewport draws without a render (BREP_STALE_FRAME lines on stderr name the inputs)",
240                        after - before
241                    )],
242                    image: None,
243                    diff_ratio: None,
244                });
245                failed_step.get_or_insert(script.steps.len());
246            }
247        }
248        _ => eprintln!("stale-frame check: {} unavailable", script.name),
249    }
250    let mut video = None;
251    if let Some(spec) = &script.video {
252        if !recording_failed {
253            match write_video(spec, &shots, opts) {
254                Ok(v) => video = Some(v),
255                Err(why) => {
256                    steps.push(StepResult {
257                        group: None, expected_error: None,
258                        index: script.steps.len(),
259                        tool: "video".into(),
260                        outcome: Outcome::ToolError,
261                        elapsed_ms: 0,
262                        failures: vec![why],
263                        image: None,
264                        diff_ratio: None,
265                    });
266                    failed_step.get_or_insert(script.steps.len());
267                }
268            }
269        }
270    }
271    let exit_code = steps
272        .iter()
273        .map(|s| match s.outcome {
274            Outcome::Pass => exit::PASS,
275            Outcome::ExpectationFailed => exit::EXPECTATION_FAILED,
276            Outcome::ToolError => exit::TOOL_ERROR,
277            Outcome::Timeout => exit::TIMEOUT,
278        })
279        .max()
280        .unwrap_or(exit::PASS);
281    let result = RunResult {
282        script: script.name.clone(),
283        passed: exit_code == exit::PASS,
284        exit_code,
285        steps,
286        failed_step,
287        video,
288    };
289    if let Ok(text) = serde_json::to_string_pretty(&result) {
290        let _ = std::fs::write(opts.out_dir.join("result.json"), text);
291    }
292    result
293}
294
295/// Record ONE walkthrough frame: set the annotation, capture the surface,
296/// clear the annotation again.
297///
298/// The capture goes through the ordinary `screenshot` tool at the video's
299/// width, so the frame is the tool's inline image — already downscaled, with
300/// the overlay scaled with it because the overlay was painted by the app's own
301/// egui context before the pixels existed.
302///
303/// The annotation is CLEARED afterwards so the session is left as it was found
304/// and an ordinary `save`/`compare` screenshot elsewhere in the same script is
305/// not silently captioned.
306async fn capture_frame(
307    tools: &ToolSet,
308    video: &crate::script::Video,
309    frame: &Frame,
310    n: usize,
311    total: usize,
312) -> Result<image::GifFrame, String> {
313    let screenshot = tools.get("screenshot").ok_or("no `screenshot` tool in this session")?;
314    set_annotation(tools, video, frame, n, total).await?;
315    let shot = (screenshot.handler)(json!({
316        "region": "full",
317        "max_width": video.width,
318        "cursor": false
319    }))
320    .await?;
321    let png = &shot.images.first().ok_or("the screenshot tool produced no image")?.png;
322    let image = image::decode_png(png)?;
323    let annotate = tools.get("annotate").ok_or("no `annotate` tool in this session")?;
324    (annotate.handler)(json!({})).await?;
325    Ok(image::GifFrame { image, hold_ms: frame.hold_ms })
326}
327
328/// Set the overlay the host paints over the app's next frames — the caption
329/// band, the `n / total` counter and the rings — and LEAVE it set.
330///
331/// Its own function because a FILMED drag sets it once and captures many frames
332/// under it, where an ordinary still sets it, captures, and clears it again in
333/// one go.
334async fn set_annotation(
335    tools: &ToolSet,
336    video: &crate::script::Video,
337    frame: &Frame,
338    n: usize,
339    total: usize,
340) -> Result<(), String> {
341    let annotate = tools
342        .get("annotate")
343        .ok_or("no `annotate` tool in this session: a walkthrough needs a live app host")?;
344    let mut spec = json!({ "caption": frame.caption, "step": [n, total] });
345    if let Some(title) = &video.title {
346        spec["title"] = json!(title);
347    }
348    if let Some(highlight) = &frame.highlight {
349        spec["highlight"] = highlight.clone();
350    }
351    if let Some(entity) = &frame.entity {
352        spec["entity"] = entity.clone();
353    }
354    if let Some(point) = &frame.point {
355        spec["point"] = point.clone();
356    }
357    (annotate.handler)(spec).await?;
358    Ok(())
359}
360
361/// Turn the pictures a FILMED drag handed back into walkthrough frames.
362///
363/// The tool returns `motion.frames + 1` of them: the pointer parked on the
364/// handle with the button still up, then one per waypoint as it travels. The
365/// first is held for the frame's own `hold_ms` — it is the still a reader needs
366/// in order to see WHAT is about to be dragged — and the rest for the motion's,
367/// which is short, because that stretch is a film rather than a slide.
368///
369/// A count that does not match is a hard error rather than a quietly shorter
370/// video: it means the tool did not honour the `capture` it was given, and the
371/// whole point of the step was the movement.
372fn motion_frames(
373    images: &[crate::tools::ToolImage],
374    frame: &Frame,
375    motion: &crate::script::Motion,
376) -> Result<Vec<image::GifFrame>, String> {
377    let expected = motion.frames as usize + 1;
378    if images.len() != expected {
379        return Err(format!(
380            "the drag returned {} pictures, expected {expected} (the still plus {} motion frames) — does this tool take a `capture`?",
381            images.len(),
382            motion.frames
383        ));
384    }
385    images
386        .iter()
387        .enumerate()
388        .map(|(i, img)| {
389            Ok(image::GifFrame {
390                image: image::decode_png(&img.png)?,
391                hold_ms: if i == 0 { frame.hold_ms } else { motion.hold_ms },
392            })
393        })
394        .collect()
395}
396
397/// Encode the recorded frames and write the GIF.
398///
399/// Always into the run's own output directory; additionally to
400/// `<video_root>/<out>` when a video root was given. Without one the gate
401/// cannot write into the checkout, which is deliberate: `test-mcp` runs every
402/// script and must not rewrite documentation assets as a side effect.
403fn write_video(spec: &crate::script::Video, shots: &[image::GifFrame], opts: &RunOptions) -> Result<VideoResult, String> {
404    if shots.is_empty() {
405        return Err(format!(
406            "the script declares a video (`{}`) but no step carries a `frame`, so there is nothing to record",
407            spec.out
408        ));
409    }
410    // `out` is joined to a root the caller chose, so it stays a relative path
411    // INSIDE it: a script is data, and a `..` in it would let one write outside
412    // the tree the operator pointed the recorder at.
413    let out = Path::new(&spec.out);
414    if out.is_absolute() || out.components().any(|c| matches!(c, std::path::Component::ParentDir)) {
415        return Err(format!("video.out `{}` must be a relative path with no `..`", spec.out));
416    }
417    let started = Instant::now();
418    let bytes = image::encode_gif(shots, spec.speed)?;
419    let encode_ms = started.elapsed().as_millis();
420    let name = out
421        .file_name()
422        .ok_or_else(|| format!("video.out `{}` has no file name", spec.out))?;
423    let mut written = Vec::new();
424    let local = opts.out_dir.join(name);
425    std::fs::write(&local, &bytes).map_err(|e| format!("{}: {e}", local.display()))?;
426    written.push(local.display().to_string());
427    if let Some(root) = &opts.video_root {
428        let dst = root.join(&spec.out);
429        if let Some(parent) = dst.parent() {
430            std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
431        }
432        std::fs::write(&dst, &bytes).map_err(|e| format!("{}: {e}", dst.display()))?;
433        written.push(dst.display().to_string());
434    }
435    let (w, h) = shots[0].image.dimensions();
436    Ok(VideoResult {
437        out: spec.out.clone(),
438        written,
439        frames: shots.len(),
440        bytes: bytes.len(),
441        size: [w, h],
442        duration_ms: shots.iter().map(|f| f.hold_ms).sum(),
443        encode_ms,
444    })
445}
446
447/// Run one step and hand back its result together with every image the tool
448/// produced.
449///
450/// The images come back rather than being dropped because a FILMED drag returns
451/// its motion frames that way — [`run`] folds them into the walkthrough.
452/// `extra_args` is merged over the step's own, which is how the recorder asks a
453/// drag to film itself without the script having to know the video's width.
454async fn run_step(
455    index: usize,
456    step: &Step,
457    tools: &ToolSet,
458    opts: &RunOptions,
459    extra_args: Option<Value>,
460) -> (StepResult, Vec<crate::tools::ToolImage>) {
461    let started = Instant::now();
462    let mut res = StepResult {
463        group: None, expected_error: None,
464        index,
465        tool: step.tool.clone(),
466        outcome: Outcome::Pass,
467        elapsed_ms: 0,
468        failures: Vec::new(),
469        image: None,
470        diff_ratio: None,
471    };
472    // `${plm:NAME}` first, then `${out}`: a value the server handed back that
473    // happens to contain `${out}` would be expanded too. Harmless (it is the
474    // run's own directory), and ids never contain it.
475    let step_args = if step.args.is_null() { json!({}) } else { step.args.clone() };
476    // The expectations too, so a step can assert an id an earlier one bound.
477    let substituted = match &opts.plm {
478        Some(plm) => plm.substitute(step_args).and_then(|args| {
479            let expect = serde_json::to_value(&step.expect).map_err(|e| e.to_string())?;
480            let expect = serde_json::from_value(plm.substitute(expect)?).map_err(|e| e.to_string())?;
481            Ok((args, expect))
482        }),
483        None => Ok((step_args, step.expect.clone())),
484    };
485    let (step_args, expects): (Value, Vec<crate::script::Expect>) = match substituted {
486        Ok(both) => both,
487        Err(e) => {
488            write_step_json(opts, index, &step.tool, &json!({ "error": e }));
489            match &step.expect_error {
490                Some(pattern) if crate::script::glob_match(pattern, &e) => {}
491                Some(pattern) => {
492                    res.outcome = Outcome::ExpectationFailed;
493                    res.failures.push(format!("tool failed as expected but with `{e}`, which does not match `{pattern}`"));
494                }
495                None => {
496                    res.outcome = Outcome::ToolError;
497                    res.failures.push(e);
498                }
499            }
500            res.elapsed_ms = started.elapsed().as_millis();
501            return (res, Vec::new());
502        }
503    };
504    // THE SECOND CLIENT: `plm_request` is answered by the runner from the
505    // script's PLM fixture, not by the app, so a script can seed the server
506    // and read back what the app wrote. Any HTTP status is a result the step's
507    // `expect` reads (`/status`, `/json/...`); only no answer is an error.
508    if step.tool == PLM_REQUEST || step.tool == PLM_SERVER {
509        let outcome = match &opts.plm {
510            None => Err(format!("`{}` needs the script to declare `plm`", step.tool)),
511            Some(plm) if step.tool == PLM_SERVER => {
512                let plm = plm.clone();
513                let action = step_args["action"].as_str().unwrap_or_default().to_string();
514                match tokio::task::spawn_blocking(move || plm.server(&action)).await {
515                    Ok(answer) => answer,
516                    Err(e) => Err(e.to_string()),
517                }
518            }
519            Some(plm) => match serde_json::from_value::<crate::script::PlmCall>(step_args) {
520                Err(e) => Err(format!("plm_request arguments: {e}")),
521                Ok(call) => {
522                    let plm = plm.clone();
523                    match tokio::task::spawn_blocking(move || plm.call(&call).map(|a| a.to_value())).await {
524                        Ok(answer) => answer,
525                        Err(e) => Err(e.to_string()),
526                    }
527                }
528            },
529        };
530        let output = match outcome {
531            Ok(v) => crate::tools::ToolOutput::json(v),
532            Err(e) => crate::tools::ToolOutput::json(json!({ "error": e })),
533        };
534        let failed = output.json.get("error").and_then(Value::as_str).map(str::to_string);
535        write_step_json(opts, index, &step.tool, &output.json);
536        match (failed, &step.expect_error) {
537            (Some(e), Some(pattern)) if crate::script::glob_match(pattern, &e) => {}
538            (Some(e), Some(pattern)) => {
539                res.outcome = Outcome::ExpectationFailed;
540                res.failures.push(format!("tool failed as expected but with `{e}`, which does not match `{pattern}`"));
541            }
542            (Some(e), None) => {
543                res.outcome = Outcome::ToolError;
544                res.failures.push(e);
545            }
546            (None, Some(pattern)) => {
547                res.outcome = Outcome::ExpectationFailed;
548                res.failures.push(format!("expected the tool to fail with `{pattern}` but it succeeded"));
549            }
550            (None, None) => {
551                // `bind` here too: this branch returns before the app tools'
552                // bind below, which used to drop a plm_request's bind silently.
553                if let (Some(plm), false) = (&opts.plm, step.bind.is_empty()) {
554                    if let Err(e) = plm.bind(&output.json, &step.bind) {
555                        res.failures.push(e);
556                    }
557                }
558                for e in &expects {
559                    if let Err(why) = e.check(&output.json) {
560                        res.failures.push(why);
561                    }
562                }
563                if !res.failures.is_empty() {
564                    res.outcome = Outcome::ExpectationFailed;
565                }
566            }
567        }
568        res.elapsed_ms = started.elapsed().as_millis();
569        return (res, Vec::new());
570    }
571    let Some(spec) = tools.get(&step.tool) else {
572        res.outcome = Outcome::ToolError;
573        res.failures.push(format!("no tool `{}` in this session", step.tool));
574        res.elapsed_ms = started.elapsed().as_millis();
575        return (res, Vec::new());
576    };
577    // `${out}` in a string argument is the script's output directory, so a
578    // script can save files without knowing where it runs.
579    let mut args = substitute_out(step_args, &opts.out_dir);
580    if let (Some(Value::Object(extra)), Value::Object(into)) = (extra_args, &mut args) {
581        into.extend(extra);
582    }
583    // A step that never answers fails, naming itself, instead of hanging the
584    // whole run: its own `timeout_ms` plus two minutes, else ten minutes.
585    let limit = args.get("timeout_ms").and_then(Value::as_u64).map_or(600_000, |t| t.saturating_add(120_000));
586    let answered = match tokio::time::timeout(std::time::Duration::from_millis(limit), (spec.handler)(args)).await {
587        Ok(answered) => answered,
588        Err(_) => Err(format!("step {index} (`{}`) gave no answer within {} s", step.tool, limit / 1000)),
589    };
590    let output = match answered {
591        Ok(o) => {
592            if let Some(pattern) = &step.expect_error {
593                res.outcome = Outcome::ExpectationFailed;
594                res.failures.push(format!("expected the tool to fail with `{pattern}` but it succeeded"));
595                res.elapsed_ms = started.elapsed().as_millis();
596                write_step_json(opts, index, &step.tool, &o.json);
597                return (res, Vec::new());
598            }
599            o
600        }
601        Err(e) => {
602            write_step_json(opts, index, &step.tool, &json!({ "error": e }));
603            if let Some(pattern) = &step.expect_error {
604                if !crate::script::glob_match(pattern, &e) {
605                    res.outcome = Outcome::ExpectationFailed;
606                    res.failures.push(format!("tool failed as expected but with `{e}`, which does not match `{pattern}`"));
607                }
608                res.elapsed_ms = started.elapsed().as_millis();
609                return (res, Vec::new());
610            }
611            res.outcome = Outcome::ToolError;
612            res.failures.push(e);
613            res.elapsed_ms = started.elapsed().as_millis();
614            return (res, Vec::new());
615        }
616    };
617    write_step_json(opts, index, &step.tool, &output.json);
618    if !step.bind.is_empty() {
619        let bound = match &opts.plm {
620            Some(plm) => plm.bind(&output.json, &step.bind),
621            None => Err("`bind` needs the script to declare `plm`, which holds the variables".to_string()),
622        };
623        if let Err(e) = bound {
624            res.failures.push(e);
625        }
626    }
627    for e in &expects {
628        if let Err(why) = e.check(&output.json) {
629            res.failures.push(why);
630        }
631    }
632    keep_image(
633        index,
634        &step.tool,
635        output.images.first().map(|i| i.png.as_slice()),
636        step.save.as_deref(),
637        step.compare.as_ref(),
638        &opts.out_dir,
639        &opts.baselines_dir,
640        opts.update_baselines,
641        &mut res,
642    );
643    if !res.failures.is_empty() {
644        res.outcome = Outcome::ExpectationFailed;
645    }
646    res.elapsed_ms = started.elapsed().as_millis();
647    (res, output.images)
648}
649
650/// A step's image: written under its `save` name (or `NNNN-<tool>.png`),
651/// and compared with its baseline when the step asks — shared by the JSON
652/// runner and script mode's step records.
653#[allow(clippy::too_many_arguments)]
654pub(crate) fn keep_image(
655    index: usize,
656    tool: &str,
657    png: Option<&[u8]>,
658    save: Option<&str>,
659    compare: Option<&crate::script::Compare>,
660    out_dir: &Path,
661    baselines_dir: &Path,
662    update_baselines: bool,
663    res: &mut StepResult,
664) {
665    if let Some(png) = png {
666        let name = save.map(str::to_string).unwrap_or_else(|| format!("{index:04}-{tool}.png"));
667        let path = out_dir.join(&name);
668        let _ = std::fs::write(&path, png);
669        res.image = Some(name.clone());
670        if let Some(cmp) = compare {
671            let baseline = baselines_dir.join(&cmp.baseline);
672            match (image::decode_png(png), std::fs::read(&baseline)) {
673                (Ok(actual), Ok(base_bytes)) => match image::decode_png(&base_bytes) {
674                    Ok(base) => {
675                        let d = image::diff(&base, &actual, 8);
676                        res.diff_ratio = Some(d.ratio);
677                        if d.ratio > cmp.max_diff_ratio {
678                            if update_baselines {
679                                let _ = std::fs::create_dir_all(baseline.parent().unwrap_or(Path::new(".")));
680                                let _ = std::fs::write(&baseline, png);
681                            } else {
682                                let _ = std::fs::write(out_dir.join(format!("{name}.diff.png")), image::encode_png(&d.mask).unwrap_or_default());
683                                res.failures.push(format!(
684                                    "image differs from baseline `{}` by {:.4} (max {:.4})",
685                                    cmp.baseline, d.ratio, cmp.max_diff_ratio
686                                ));
687                            }
688                        }
689                    }
690                    Err(e) => res.failures.push(format!("baseline `{}`: {e}", cmp.baseline)),
691                },
692                (Ok(_), Err(_)) => {
693                    if update_baselines {
694                        let _ = std::fs::create_dir_all(baseline.parent().unwrap_or(Path::new(".")));
695                        let _ = std::fs::write(&baseline, png);
696                    } else {
697                        res.failures.push(format!(
698                            "no baseline `{}` (run with --update-baselines to create it)",
699                            cmp.baseline
700                        ));
701                    }
702                }
703                (Err(e), _) => res.failures.push(format!("step image: {e}")),
704            }
705        }
706    } else if compare.is_some() || save.is_some() {
707        res.failures.push(format!("step {index} asked to save/compare an image but `{tool}` produced none"));
708    }
709}
710
711/// The SESSION STORE for a run: `<out_dir>/store`, emptied first.
712///
713/// The runner hands this to `session_start` as `store_root`, so the app's own
714/// file store is what the file modal lists, what Save writes into and what the
715/// autosave blob lands in — the real code path, one fresh directory per script.
716/// Without it every session gets a private `store-<stamp>` nobody can reach,
717/// and no script can open a document through the interface.
718/// `fixtures` are copied into `<store>/models` before the app starts, so the
719/// Open and Import dialogs list them: the native counterpart of the browser
720/// verifier's file-chooser interception, and the only way to drive a real
721/// import through the real explorer without pointing it at the checkout — the
722/// STEP assembly import writes its part documents to whatever directory the
723/// explorer is browsing.
724pub fn prepare_store(out_dir: &Path, fixtures: &[String]) -> Result<PathBuf, String> {
725    let store = out_dir.join("store");
726    if store.exists() {
727        // A run must not inherit the last one's saved models, settings or
728        // recovery blob: those are exactly what the file and recovery scripts
729        // assert the absence of on a cold boot.
730        std::fs::remove_dir_all(&store).map_err(|e| format!("clear store {}: {e}", store.display()))?;
731    }
732    std::fs::create_dir_all(&store).map_err(|e| format!("store {}: {e}", store.display()))?;
733    if !fixtures.is_empty() {
734        let models = store.join("models");
735        std::fs::create_dir_all(&models).map_err(|e| format!("store models {}: {e}", models.display()))?;
736        for fixture in fixtures {
737            let from = Path::new(fixture);
738            let name = from
739                .file_name()
740                .ok_or_else(|| format!("fixture `{fixture}` has no file name"))?;
741            std::fs::copy(from, models.join(name)).map_err(|e| format!("fixture {fixture}: {e}"))?;
742        }
743    }
744    Ok(store)
745}
746
747/// One script's START, recorded by an order check: which pass recorded it and
748/// what the session looked like before the script's first step ran.
749///
750/// The order check exists because a test-mcp run plays many scripts through one
751/// PROCESS — a fresh app and a fresh store each time, but the same address
752/// space, the same warmed allocator and kernel caches, the same statics. "Every
753/// script runs through its own headless app session" is only true of the things
754/// a session owns; anything else a script leaves behind reaches the next one,
755/// and the symptom is a red in a script that passes on its own.
756#[derive(Debug, Clone)]
757pub struct BootSample {
758    pub script: String,
759    /// Which pass of the order check this sample came from (`forward`, `reverse`).
760    pub pass: String,
761    /// The session's state before step 0: the camera and the published viewport
762    /// rect + probe points, with the frame counter dropped.
763    pub state: Value,
764}
765
766/// Every script whose START moved between the passes of an order check — one
767/// message per script, naming the passes and the fields that differ. An empty
768/// list is the pass condition.
769///
770/// Two samples of the same script must be IDENTICAL: the script has not run
771/// yet, so nothing it does can explain a difference. What it catches is the
772/// state a *previous* script left where this one can see it; what it does NOT
773/// catch is a leak that only shows once the script is under way, and a leak
774/// that reaches the next script only sometimes is caught with the probability
775/// it shows in one of the passes — repetition raises that (pass the same list
776/// twice and each script gets four samples), position does not.
777pub fn order_check_failures(samples: &[BootSample]) -> Vec<String> {
778    let mut by_script: std::collections::BTreeMap<&str, Vec<&BootSample>> = std::collections::BTreeMap::new();
779    for s in samples {
780        by_script.entry(s.script.as_str()).or_default().push(s);
781    }
782    let mut failures = Vec::new();
783    for (script, group) in by_script {
784        let Some(first) = group.first() else { continue };
785        for other in group.iter().skip(1) {
786            if other.state == first.state {
787                continue;
788            }
789            let mut diffs = Vec::new();
790            diff_paths(&first.state, &other.state, "", &mut diffs);
791            if diffs.len() > 8 {
792                let rest = diffs.len() - 8;
793                diffs.truncate(8);
794                diffs.push(format!("    (+{rest} more)"));
795            }
796            failures.push(format!(
797                "{script}: the session it starts in differs between pass `{}` and pass `{}`\n{}",
798                first.pass,
799                other.pass,
800                diffs.join("\n")
801            ));
802            break;
803        }
804    }
805    failures
806}
807
808/// Every JSON-pointer path at which two values differ, as `    /a/b: x vs y`.
809fn diff_paths(a: &Value, b: &Value, at: &str, out: &mut Vec<String>) {
810    match (a, b) {
811        (Value::Object(x), Value::Object(y)) => {
812            let mut keys: Vec<&String> = x.keys().chain(y.keys()).collect();
813            keys.sort();
814            keys.dedup();
815            for k in keys {
816                let null = Value::Null;
817                diff_paths(x.get(k).unwrap_or(&null), y.get(k).unwrap_or(&null), &format!("{at}/{k}"), out);
818            }
819        }
820        (Value::Array(x), Value::Array(y)) if x.len() == y.len() => {
821            for (i, (xi, yi)) in x.iter().zip(y).enumerate() {
822                diff_paths(xi, yi, &format!("{at}/{i}"), out);
823            }
824        }
825        _ if a != b => out.push(format!("    {at}: {a} vs {b}")),
826        _ => {}
827    }
828}
829
830pub(crate) fn substitute_out(v: Value, out: &Path) -> Value {
831    match v {
832        Value::String(s) if s.contains("${out}") => Value::String(s.replace("${out}", &out.display().to_string())),
833        Value::Array(a) => Value::Array(a.into_iter().map(|x| substitute_out(x, out)).collect()),
834        Value::Object(o) => Value::Object(o.into_iter().map(|(k, x)| (k, substitute_out(x, out))).collect()),
835        other => other,
836    }
837}
838
839pub(crate) fn write_step_json(opts: &RunOptions, index: usize, tool: &str, value: &Value) {
840    if let Ok(text) = serde_json::to_string_pretty(value) {
841        let _ = std::fs::write(opts.out_dir.join(format!("{index:04}-{tool}.json")), text);
842    }
843}
844