Skip to main content

brep_mcp_core/
program.rs

1//! test-mcp's SCRIPT MODE: a `BREP_mcp/tests/scripts/*.js` program played
2//! through code mode, the way an agent drives the app through `run`.
3//!
4//! A program is a script body whose first statement `const meta = {…}`
5//! carries the JSON format's session keys (name, note, document, seed, size,
6//! ppp, fixtures, plm, timeout_ms) and which drives the app with
7//! `await sdk.<namespace>.<action>(args)`, checks with the `test` assertion
8//! library and returns `test.run(…)`'s report. The runner puts [`PRELUDE`] in
9//! front of it, which makes every action call one STEP: each step is reported
10//! back through `sdk.runner.step_record` as it ends, so the per-step
11//! artefacts (`NNNN-<action>.json`, images,
12//! `result.json`) are those of the JSON runner and survive a killed worker.
13//!
14//! The `runner` group exists only while a program runs: the step record, the
15//! PLM fixture's `plm_request` / `plm_server`, `${plm:NAME}` / `${out}`
16//! substitution, `bind`, and `session_restart` (whose own `session` group is
17//! not script-callable).
18use crate::runner::{keep_image, stale_frames, substitute_out, Outcome, RunOptions, RunResult, StepResult};
19use crate::script::{exit, Script};
20use crate::server::ServerState;
21use crate::tools::{Annotations, ToolOutput, ToolSpec};
22use serde_json::{json, Value};
23use std::path::PathBuf;
24use std::sync::{Arc, Mutex};
25use std::time::{Duration, Instant};
26
27/// The step recorder and assertion library put in front of every program.
28pub const PRELUDE: &str = include_str!("test_prelude.js");
29
30/// The group of the tools the runner serves a program.
31pub const RUNNER_GROUP: &str = "runner";
32
33/// The names of `runner_tools`, in its order (the generated SDK mapping
34/// lists them: a headless registry does not hold them).
35pub const RUNNER_TOOL_NAMES: &[&str] = &["step_output_chunk", "step_record", "substitute", "bind", "plm_request", "plm_server", "resource_read", "session_restart"];
36
37/// Catalogue tools: a program that calls only these (and the runner's own)
38/// needs no app session, as with the JSON runner.
39const SESSIONLESS: &[&str] = &["feature_catalogue", "feature_schema"];
40
41/// A converted script: its session description and its program.
42#[derive(Debug)]
43pub struct Program {
44    /// The `meta` keys as a [`Script`] with no steps.
45    pub script: Script,
46    pub source: String,
47}
48
49impl Program {
50    pub fn parse(text: &str) -> Result<Program, String> {
51        const MARK: &str = "const meta = ";
52        let at = text.find(MARK).ok_or("a test-mcp program declares `const meta = {…}` (its name and session)")?;
53        let mut values = serde_json::Deserializer::from_str(&text[at + MARK.len()..]).into_iter::<Value>();
54        let mut meta = match values.next() {
55            Some(Ok(v @ Value::Object(_))) => v,
56            Some(Ok(_)) => return Err("`meta` must be a JSON object".into()),
57            Some(Err(e)) => return Err(format!("`meta` must be plain JSON: {e}")),
58            None => return Err("`meta` is empty".into()),
59        };
60        meta["steps"] = json!([]);
61        let script: Script = serde_json::from_value(meta).map_err(|e| format!("meta: {e}"))?;
62        if script.video.is_some() {
63            return Err("a walkthrough (`video`) records frames between steps; it stays a JSON script under tests/videos".into());
64        }
65        Ok(Program { script, source: text.to_string() })
66    }
67
68    /// Every `sdk.<namespace>.<action>` the program names.
69    pub fn calls(&self) -> Vec<(String, String)> {
70        let ident = |s: &str| s.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect::<String>();
71        let mut out = Vec::new();
72        let mut rest = self.source.as_str();
73        while let Some(i) = rest.find("sdk.") {
74            let preceded = rest[..i].chars().next_back().is_some_and(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.');
75            rest = &rest[i + 4..];
76            if preceded {
77                continue;
78            }
79            let group = ident(rest);
80            let Some(after) = rest[group.len()..].strip_prefix('.') else { continue };
81            let tool = ident(after);
82            if !group.is_empty() && !tool.is_empty() {
83                out.push((group, tool));
84            }
85        }
86        out
87    }
88
89    /// Whether the program needs an app session: anything beyond the
90    /// catalogue tools and the runner's PLM fixture.
91    pub fn needs_app(&self) -> bool {
92        self.calls().iter().any(|(group, tool)| {
93            !(SESSIONLESS.contains(&tool.as_str()) || (group == RUNNER_GROUP && tool.starts_with("plm_")))
94        })
95    }
96}
97
98/// What the runner's tools share for one program.
99struct Cx {
100    state: Arc<ServerState>,
101    out_dir: PathBuf,
102    baselines_dir: PathBuf,
103    update_baselines: bool,
104    plm: Option<Arc<crate::plm_fixture::PlmFixture>>,
105    steps: Mutex<Vec<StepResult>>,
106    output_chunks: Mutex<String>,
107}
108
109fn any_schema() -> Value {
110    json!({ "type": "object", "additionalProperties": true })
111}
112
113fn runner_tool(
114    name: &'static str,
115    doc: &'static str,
116    cx: &Arc<Cx>,
117    f: impl Fn(Arc<Cx>, Value) -> crate::tools::ToolFuture + Send + Sync + 'static,
118) -> ToolSpec {
119    let cx = cx.clone();
120    ToolSpec::new(name, RUNNER_GROUP, doc, any_schema(), Annotations { read_only: false, destructive: false, idempotent: false, waits: false }, move |args| f(cx.clone(), args))
121}
122
123/// The `runner` group for one program.
124fn runner_tools(cx: &Arc<Cx>) -> Vec<ToolSpec> {
125    vec![
126        runner_tool("step_output_chunk", "test-mcp: append a large reply chunk.", cx, |cx, args| Box::pin(async move {
127            let chunk = args["chunk"].as_str().ok_or("missing output chunk")?;
128            let mut output = cx.output_chunks.lock().unwrap();
129            if output.len() + chunk.len() > 256 * 1024 * 1024 { return Err("step output exceeds 256 MiB".into()); }
130            output.push_str(chunk);
131            Ok(ToolOutput::json(json!({})))
132        })),
133        runner_tool("step_record", "test-mcp: record one step (the prelude calls it).", cx, |cx, args| Box::pin(async move { Ok(ToolOutput::json(step_record(&cx, &args))) })),
134        runner_tool("substitute", "test-mcp: `${plm:NAME}` then `${out}` in {value}.", cx, |cx, args| {
135            Box::pin(async move {
136                let value = args.get("value").cloned().unwrap_or(Value::Null);
137                let value = match &cx.plm {
138                    Some(plm) => plm.substitute(value)?,
139                    None => value,
140                };
141                Ok(ToolOutput::json(json!({ "value": substitute_out(value, &cx.out_dir) })))
142            })
143        }),
144        runner_tool("bind", "test-mcp: bind {value} at {bind: {NAME: pointer}} for `${plm:NAME}`.", cx, |cx, args| {
145            Box::pin(async move {
146                let names: std::collections::BTreeMap<String, String> = serde_json::from_value(args.get("bind").cloned().unwrap_or(json!({}))).map_err(|e| e.to_string())?;
147                let bound = match &cx.plm {
148                    Some(plm) => plm.bind(args.get("value").unwrap_or(&Value::Null), &names),
149                    None => Err("`bind` needs the script to declare `plm`, which holds the variables".to_string()),
150                };
151                Ok(ToolOutput::json(json!({ "failures": bound.err().into_iter().collect::<Vec<_>>() })))
152            })
153        }),
154        runner_tool("plm_request", "test-mcp: one call to the script's PLM server ({method, path, body|raw, as, browser, bind}); answers {status, json, …}.", cx, |cx, args| {
155            Box::pin(async move {
156                let plm = cx.plm.clone().ok_or("`plm_request` needs the script to declare `plm`")?;
157                let args = plm.substitute(args)?;
158                let call: crate::script::PlmCall = serde_json::from_value(args).map_err(|e| format!("plm_request arguments: {e}"))?;
159                let answer = tokio::task::spawn_blocking(move || plm.call(&call).map(|a| a.to_value())).await.map_err(|e| e.to_string())??;
160                Ok(ToolOutput::json(answer))
161            })
162        }),
163        runner_tool("plm_server", "test-mcp: {action: stop | start} the script's PLM server.", cx, |cx, args| {
164            Box::pin(async move {
165                let plm = cx.plm.clone().ok_or("`plm_server` needs the script to declare `plm`")?;
166                let args = plm.substitute(args)?;
167                let action = args["action"].as_str().unwrap_or_default().to_string();
168                let answer = tokio::task::spawn_blocking(move || plm.server(&action)).await.map_err(|e| e.to_string())??;
169                Ok(ToolOutput::json(answer))
170            })
171        }),
172        runner_tool("resource_read", "test-mcp: {uri} read as a client's `resources/read` reads a static resource (a skill://… SKILL.md, brep://schema/…); answers {uri, mimeType, text}.", cx, |cx, args| {
173            Box::pin(async move {
174                let uri = args["uri"].as_str().ok_or("`resource_read` needs {uri}")?.to_string();
175                let spec = cx.state.resources.read().await.get(&uri).cloned().ok_or_else(|| format!("no resource `{uri}`"))?;
176                let text = (spec.read)()?;
177                Ok(ToolOutput::json(json!({ "uri": uri, "mimeType": spec.mime, "text": text })))
178            })
179        }),
180        runner_tool("session_restart", "test-mcp: the session's own `session_restart` (stop the app, build it again on the same store).", cx, |cx, args| {
181            Box::pin(async move {
182                let spec = cx.state.tools.read().await.specs.iter().find(|t| t.name == "session_restart" && t.group == "session").cloned();
183                let spec = spec.ok_or("no `session_restart` in this session")?;
184                (spec.handler)(args).await
185            })
186        }),
187    ]
188}
189
190/// One step's record from the prelude: write its JSON and image, compare
191/// it, and keep its result. Answers the failures the image added.
192fn step_record(cx: &Cx, args: &Value) -> Value {
193    let index = args["index"].as_u64().unwrap_or(0) as usize;
194    let tool = args["tool"].as_str().unwrap_or("?").to_string();
195    let outcome = match args["outcome"].as_str() {
196        Some("pass") => Outcome::Pass,
197        Some("tool_error") => Outcome::ToolError,
198        Some("timeout") => Outcome::Timeout,
199        _ => Outcome::ExpectationFailed,
200    };
201    let failures: Vec<String> = args["failures"].as_array().map(|a| a.iter().map(|f| f.as_str().map_or_else(|| f.to_string(), str::to_string)).collect()).unwrap_or_default();
202    let mut res = StepResult {
203        group: args["group"].as_str().map(str::to_string),
204        expected_error: args["expected_error"].as_bool(),
205        index,
206        tool: tool.clone(),
207        outcome,
208        elapsed_ms: args["elapsed_ms"].as_u64().unwrap_or(0) as u128,
209        failures,
210        image: None,
211        diff_ratio: None,
212    };
213    let before = res.failures.len();
214    let chunks = std::mem::take(&mut *cx.output_chunks.lock().unwrap());
215    let text = if args["chunked"].as_bool() == Some(true) {
216        serde_json::from_str::<Value>(&chunks).map(|_| chunks)
217    } else {
218        serde_json::to_string_pretty(&args["output"])
219    };
220    match text {
221        Ok(text) => if let Err(e) = std::fs::write(cx.out_dir.join(format!("{index:04}-{tool}.json")), text) { res.failures.push(e.to_string()); },
222        Err(e) => res.failures.push(e.to_string()),
223    }
224    // Steps that ended in an error, or were expected to, make no image (as
225    // in the JSON runner, which returned before the image).
226    if res.outcome != Outcome::ToolError && !args["skip_image"].as_bool().unwrap_or(false) {
227        let png = args["image"].as_str().and_then(|id| {
228            let owner = crate::cad::artifacts::Owner { scope: crate::cad::tools::caller_of_transport().scope, execution: None };
229            let bytes = cx.state.cad.artifacts.lease(&owner, id).ok().map(|(b, _)| b);
230            cx.state.cad.artifacts.release(id);
231            bytes
232        });
233        let compare: Option<crate::script::Compare> = serde_json::from_value(args["compare"].clone()).ok().flatten();
234        keep_image(index, &tool, png.as_deref(), args["save"].as_str(), compare.as_ref(), &cx.out_dir, &cx.baselines_dir, cx.update_baselines, &mut res);
235    }
236    let added: Vec<String> = res.failures[before..].to_vec();
237    if !res.failures.is_empty() && res.outcome == Outcome::Pass {
238        res.outcome = Outcome::ExpectationFailed;
239    }
240    cx.steps.lock().unwrap().push(res);
241    json!({ "failures": added })
242}
243
244/// Play `program` through code mode on `state`'s session.
245pub async fn run(program: &Program, state: &Arc<ServerState>, opts: &RunOptions) -> RunResult {
246    let script = &program.script;
247    let _ = std::fs::create_dir_all(&opts.out_dir);
248    let stale_before = stale_frames(&*state.tools.read().await).await;
249    let cx = Arc::new(Cx {
250        state: state.clone(),
251        out_dir: opts.out_dir.clone(),
252        baselines_dir: opts.baselines_dir.clone(),
253        update_baselines: opts.update_baselines,
254        plm: opts.plm.clone(),
255        steps: Mutex::new(Vec::new()),
256        output_chunks: Mutex::new(String::new()),
257    });
258    // The runner's tools join the registry for this program only; the slot
259    // keeps them through a `session_restart`'s rebuild.
260    let extra = runner_tools(&cx);
261    *state.extra_tools.lock().unwrap() = extra.clone();
262    state.tools.write().await.extend(extra);
263
264    let out_text = opts.out_dir.display().to_string();
265    let prelude = PRELUDE.replace("__TEST_OUT__", &out_text.replace('\\', "\\\\").replace('"', "\\\""));
266    let source = format!("{prelude}\n{}", program.source);
267    let mut extra_steps: Vec<StepResult> = Vec::new();
268    let next = |cx: &Cx| cx.steps.lock().unwrap().iter().map(|s| s.index + 1).max().unwrap_or(0);
269    let caller = crate::cad::tools::caller_of_transport();
270    let (key, _) = crate::cad::keys::issue(&caller.scope, crate::cad::keys::Purpose::Execution);
271    let req = json!({
272        "manifest": state.cad.catalogue.identity(),
273        "source": source,
274        "initialDocuments": [],
275        "requestedCapabilities": [],
276        "idempotencyKey": key,
277    });
278    // The host's policy for a gate script: its own timeout, and room for a
279    // few hundred steps' replies to be parsed.
280    let limits = crate::cad::code::Limits {
281        source_bytes: 4 << 20,
282        js_cpu_ms: script.timeout_ms.max(60_000),
283        js_heap_bytes: 2 << 30,
284        wall_ms: script.timeout_ms + 30_000,
285        log_bytes: 1 << 20,
286        result_bytes: 1 << 20,
287        artifact_count: 256,
288        artifact_bytes: 256 << 20,
289        ..Default::default()
290    };
291    match state.cad.code.submit_with_limits(&caller, &req, limits) {
292        Err(e) => extra_steps.push(error_step(0, "run", format!("{}: {}", e.code, e.message), Outcome::ToolError)),
293        Ok(status) => {
294            let id = status["executionId"].as_str().unwrap_or_default().to_string();
295            let deadline = Instant::now() + Duration::from_millis(script.timeout_ms);
296            let mut halted = false;
297            let result = loop {
298                match state.cad.code.result(&caller, &json!({ "executionId": id })) {
299                    Ok(r) => break r,
300                    Err(e) if e.code == "not_ready" => {
301                        if !halted && Instant::now() > deadline {
302                            let _ = state.cad.code.cancel(&caller, &json!({ "executionId": id }));
303                            halted = true;
304                        }
305                        tokio::time::sleep(Duration::from_millis(20)).await;
306                    }
307                    Err(e) => break json!({ "state": "failed", "error": { "code": e.code, "message": e.message } }),
308                }
309            };
310            if halted {
311                let index = next(&cx);
312                extra_steps.push(error_step(index, "script", format!("script timeout ({} ms) reached at step {index}", script.timeout_ms), Outcome::Timeout));
313            } else if result["state"] != "succeeded" {
314                // `test.run` reports every step; an execution that still
315                // failed never got that far (a syntax error, a host limit).
316                let error = &result["error"];
317                let message = format!("{}: {}", error["code"].as_str().unwrap_or("error"), error["message"].as_str().unwrap_or_default());
318                extra_steps.push(error_step(next(&cx), "script", message, Outcome::ToolError));
319            } else if result["output"]["steps"].is_null() {
320                extra_steps.push(error_step(next(&cx), "script", "the program did not return test.run(…)'s report".into(), Outcome::ToolError));
321            }
322            state.cad.code.forget(&id);
323        }
324    }
325    state.extra_tools.lock().unwrap().clear();
326    state.tools.write().await.specs.retain(|t| t.group != RUNNER_GROUP);
327
328    let mut steps = std::mem::take(&mut *cx.steps.lock().unwrap());
329    steps.append(&mut extra_steps);
330    let mut failed_step = steps.iter().find(|s| s.outcome != Outcome::Pass).map(|s| s.index);
331    // THE STALE-FRAME CHECK, as in the JSON runner.
332    match (stale_before, stale_frames(&*state.tools.read().await).await) {
333        (Some(before), Some(after)) => {
334            eprintln!("stale-frame check: {} {}", script.name, after - before);
335            if after > before {
336                let index = steps.len();
337                steps.push(error_step(
338                    index,
339                    "stale-frame check",
340                    format!("{} frame(s) changed what the viewport draws without a render (BREP_STALE_FRAME lines on stderr name the inputs)", after - before),
341                    Outcome::ExpectationFailed,
342                ));
343                failed_step.get_or_insert(index);
344            }
345        }
346        _ => eprintln!("stale-frame check: {} unavailable", script.name),
347    }
348    let exit_code = steps
349        .iter()
350        .map(|s| match s.outcome {
351            Outcome::Pass => exit::PASS,
352            Outcome::ExpectationFailed => exit::EXPECTATION_FAILED,
353            Outcome::ToolError => exit::TOOL_ERROR,
354            Outcome::Timeout => exit::TIMEOUT,
355        })
356        .max()
357        .unwrap_or(exit::PASS);
358    let result = RunResult { script: script.name.clone(), passed: exit_code == exit::PASS, exit_code, steps, failed_step, video: None };
359    if let Ok(text) = serde_json::to_string_pretty(&result) {
360        let _ = std::fs::write(opts.out_dir.join("result.json"), text);
361    }
362    result
363}
364
365fn error_step(index: usize, tool: &str, why: String, outcome: Outcome) -> StepResult {
366    StepResult { group: None, expected_error: None, index, tool: tool.into(), outcome, elapsed_ms: 0, failures: vec![why], image: None, diff_ratio: None }
367}
368
369
370