Skip to main content

brep_mcp_core/
script.rs

1//! The `test-mcp` script format (spec Appendix E): a session description plus
2//! a list of tool calls, each with optional expectations on the tool's JSON
3//! result and optional image capture / comparison.
4//!
5//! The script vocabulary is the tool list itself — a step names a tool and
6//! passes its arguments verbatim — so the format never needs to know which
7//! tools exist. Only the `expect` mini-language is defined here.
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
12#[serde(deny_unknown_fields)]
13pub struct Script {
14    pub name: String,
15    /// What the script checks, for the reader; ignored by the runner.
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub note: Option<String>,
18    #[serde(default = "default_backend")]
19    pub backend: String,
20    #[serde(default = "default_size")]
21    pub size: [f32; 2],
22    #[serde(default = "default_ppp")]
23    pub ppp: f32,
24    /// Start on the seed model instead of an empty document.
25    #[serde(default)]
26    pub seed: bool,
27    /// A `.nbrep` to open before the first step (repo-relative or absolute).
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub document: Option<String>,
30    /// Files copied into the session store's `models/` directory before the app
31    /// starts (repo-relative or absolute), so the app's own Open / Import
32    /// dialogs LIST them. This is what a browser verifier's file-chooser
33    /// interception was: a real file the user's picker hands the app. A script
34    /// that instead navigates the explorer to the repo's fixture tree would
35    /// leave the assembly import's part documents THERE, in the checkout.
36    #[serde(default, skip_serializing_if = "Vec::is_empty")]
37    pub fixtures: Vec<String>,
38    #[serde(default = "default_timeout")]
39    pub timeout_ms: u64,
40    /// Record an annotated walkthrough GIF from the steps that carry a
41    /// [`Frame`]. Absent = an ordinary script, and the runner records nothing.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub video: Option<Video>,
44    /// Run a real PLM server beside the session ([`crate::plm_fixture`]):
45    /// `brep-plm serve` on a loopback port over a fresh data directory,
46    /// seeded through its own API before the app starts. Absent = no server,
47    /// and nothing about the session changes.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub plm: Option<PlmSpec>,
50    pub steps: Vec<Step>,
51}
52
53/// The PLM a script runs against. Every account gets a `full` token (or the
54/// scope named), minted through the administrator's session the way a person
55/// would mint one on the web page.
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
57#[serde(deny_unknown_fields)]
58pub struct PlmSpec {
59    /// Accounts to create besides `admin`, each with its own token.
60    #[serde(default, skip_serializing_if = "Vec::is_empty")]
61    pub users: Vec<PlmUser>,
62    /// Calls made through the API once the accounts exist and before the app
63    /// starts. Each must answer below 400 unless it names `status`.
64    #[serde(default, skip_serializing_if = "Vec::is_empty")]
65    pub setup: Vec<PlmCall>,
66    /// The account the APP is configured as: the fixture writes the server's
67    /// URL to `<store>/plm.json` and this account's token to `<store>/plm-token`
68    /// (D5's two files, in the session store, which is the app's config root).
69    /// An empty string configures nothing, so the app starts file-only while
70    /// the server still runs for the script's own `plm_request` steps.
71    #[serde(default = "default_plm_app_user")]
72    pub app_user: String,
73    /// Write `plm-token` for `app_user` (default). `false` writes `plm.json`
74    /// alone: a machine pointed at the PLM that has not signed in yet, which
75    /// is where the Settings PLM tab's sign-in starts.
76    #[serde(default = "default_true")]
77    pub app_token: bool,
78    /// Extra arguments to `brep-plm serve`, after `--bind` and `--data`.
79    #[serde(default, skip_serializing_if = "Vec::is_empty")]
80    pub args: Vec<String>,
81    /// Extra environment for the server process.
82    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
83    pub env: std::collections::BTreeMap<String, String>,
84}
85
86fn default_plm_app_user() -> String {
87    "admin".into()
88}
89
90fn default_true() -> bool {
91    true
92}
93
94/// An account the fixture creates.
95#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
96#[serde(deny_unknown_fields)]
97pub struct PlmUser {
98    pub username: String,
99    /// At least 8 characters; default `test-mcp-password`.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub password: Option<String>,
102    #[serde(default, skip_serializing_if = "Vec::is_empty")]
103    pub groups: Vec<String>,
104    /// The token's scope: `full` (default), `read` or `worker`.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub scope: Option<String>,
107}
108
109/// One call to the PLM's API: a `setup` entry, and the arguments of a
110/// `plm_request` step. Strings may use `${plm:NAME}` (see
111/// [`crate::plm_fixture`]).
112#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
113#[serde(deny_unknown_fields)]
114pub struct PlmCall {
115    #[serde(default = "default_plm_method")]
116    pub method: String,
117    /// Relative to the server, e.g. `/api/store/index`.
118    pub path: String,
119    /// A JSON body.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub body: Option<Value>,
122    /// A raw text body, sent as-is (instead of `body`).
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub raw: Option<String>,
125    /// The `Content-Type` a `raw` body is sent under (an upload's media type,
126    /// e.g. `application/pdf`); without it a raw body carries none.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub content_type: Option<String>,
129    /// Whose token signs the call: `admin` (default), a created user, or
130    /// `anonymous` for none.
131    #[serde(default, rename = "as", skip_serializing_if = "Option::is_none")]
132    pub as_user: Option<String>,
133    /// Call as that account's signed-in BROWSER instead of its token: sign in
134    /// with its password and send the session cookie and CSRF token, as the
135    /// PLM page does. For routes a token may not call (deciding a desktop
136    /// sign-in link).
137    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
138    pub browser: bool,
139    /// Name values in the answer for later strings: `{"part": "/id"}` makes
140    /// `${plm:part}` the answer's `id`. A pointer that finds nothing fails.
141    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
142    pub bind: std::collections::BTreeMap<String, String>,
143    /// The status this call must answer (setup only; a step asserts with
144    /// `expect` on `/status`).
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub status: Option<u16>,
147}
148
149fn default_plm_method() -> String {
150    "GET".into()
151}
152
153/// The walkthrough GIF a script records: where it goes and how it is encoded.
154///
155/// GIF, not a video codec, because the output is embedded in a markdown page
156/// and in the generated help site and has to play there with no player, no
157/// codec negotiation and no autoplay policy — and because the encoder is a
158/// feature flag on `image`, which both this crate and the app already depend
159/// on, rather than a new dependency or a system tool (there is no ffmpeg on the
160/// build machine, and the docs build must work on a plain checkout).
161#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
162#[serde(deny_unknown_fields)]
163pub struct Video {
164    /// Where the GIF is written, relative to the video root (`brep-mcp test
165    /// --video-root`, which `./build.sh docs-videos` sets to the repo root).
166    /// Without a video root the GIF is written into the run's output directory
167    /// only — which is what keeps the test gate unable to write into `docs/`.
168    pub out: String,
169    /// The lead drawn above every caption: the feature's name.
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub title: Option<String>,
172    /// Pixel width of the recorded frames (the surface is 1400 points wide, so
173    /// the default is a downscale). Height follows the aspect ratio.
174    #[serde(default = "default_video_width")]
175    pub width: u32,
176    /// The GIF quantiser's speed knob, 1..=30: 1 weighs quality over time.
177    #[serde(default = "default_video_speed")]
178    pub speed: i32,
179}
180
181fn default_video_width() -> u32 {
182    1000
183}
184fn default_video_speed() -> i32 {
185    15
186}
187fn default_hold_ms() -> u32 {
188    1600
189}
190
191/// One frame of the walkthrough, recorded BEFORE the step it is attached to
192/// runs.
193///
194/// Before, deliberately: the frame a viewer needs is the one where the control
195/// is still unpressed and ringed, with the caption saying what pressing it will
196/// do. A frame showing a RESULT is attached to a step that does nothing (a
197/// `wait_idle`).
198///
199/// Pacing is the `hold_ms` of each frame, not a frame rate. GIF stores a
200/// per-frame delay, so holding a meaningful picture for two seconds costs one
201/// frame, and a walkthrough is ten to twenty frames rather than three hundred.
202#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
203#[serde(deny_unknown_fields)]
204pub struct Frame {
205    /// What is happening, in one sentence.
206    pub caption: String,
207    /// Widget key(s) to ring, exactly as `hit_rects` publishes them. A key the
208    /// app is not publishing FAILS the step.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub highlight: Option<Value>,
211    /// Scene entities (`{kind, name}`, or an array) to ring in the 3D view —
212    /// resolved through the app's own `locate`, so the ring lands where a click
213    /// on them would. An entity that is not on screen FAILS the step.
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub entity: Option<Value>,
216    /// A surface point `[x, y]` in egui points, or an array of them, to ring.
217    /// This is how a sketch click — which has neither a widget rect nor a named
218    /// entity — is pointed at.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub point: Option<Value>,
221    /// How long this frame is held, in milliseconds (GIF's unit is 10 ms).
222    #[serde(default = "default_hold_ms")]
223    pub hold_ms: u32,
224    /// Record the step's DRAG as motion instead of a single still: the
225    /// walkthrough shows the pointer travelling and the model following it.
226    /// Only meaningful on a `drag` / `drag_widget` / `drag_entity` step, and
227    /// refused anywhere else ([`Script::parse`]).
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub motion: Option<Motion>,
230}
231
232/// Film the drag this frame is attached to, rather than holding one picture of
233/// the handle before it moves.
234///
235/// This is the ONE place the walkthroughs record motion, and it exists because
236/// some of what the app offers cannot be shown any other way: a 3D gizmo's
237/// arrowhead is dragged, and a still of a ringed arrowhead beside a caption
238/// saying "drag it" teaches less than eight frames of the block actually
239/// growing. Everything else in a walkthrough is still one held picture per
240/// step — see the module docs on `Frame`.
241///
242/// The step's drag is NOT decomposed into several little drags: it is one
243/// press, `frames` pointer moves with a capture after each, and one release,
244/// so what the GIF shows is the drag the tool would have performed anyway and
245/// the step's own `expect` reads the tool's ordinary result.
246#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
247#[serde(deny_unknown_fields)]
248pub struct Motion {
249    /// How many pictures are taken between the press and the release. The
250    /// still of the handle before the press is captured as well and held for
251    /// the frame's own `hold_ms`, so a `frames: 8` drag costs 9 GIF frames.
252    #[serde(default = "default_motion_frames")]
253    pub frames: u32,
254    /// How long each MOTION frame is held, in milliseconds. Short — this is
255    /// the one place a walkthrough is a film rather than a slide show, and at
256    /// GIF's 10 ms granularity 120 ms reads as a steady pull.
257    #[serde(default = "default_motion_hold_ms")]
258    pub hold_ms: u32,
259    /// How big the drawn pointer is in the recorded frames, as a multiple of
260    /// the 12 px arrow an ordinary screenshot draws. The default is 3: at the
261    /// walkthrough's downscale a 1x pointer is nine pixels tall and a reader
262    /// cannot follow it.
263    #[serde(default = "default_cursor_scale")]
264    pub cursor_scale: u32,
265}
266
267fn default_motion_frames() -> u32 {
268    8
269}
270fn default_motion_hold_ms() -> u32 {
271    120
272}
273fn default_cursor_scale() -> u32 {
274    3
275}
276
277/// The step the runner answers itself, from the script's PLM fixture.
278/// Here, not in `runner`: the script format builds without the server.
279pub const PLM_REQUEST: &str = "plm_request";
280
281/// The other step the runner answers itself: `{"action": "stop" | "start"}`
282/// takes the script's PLM server down and brings the same one back.
283pub const PLM_SERVER: &str = "plm_server";
284
285/// The tools a [`Motion`] can film: the three drag compositions, which are the
286/// only steps that have a press, a travel and a release to film.
287pub const DRAG_TOOLS: [&str; 3] = ["drag", "drag_widget", "drag_entity"];
288
289fn default_backend() -> String {
290    "headless".into()
291}
292fn default_size() -> [f32; 2] {
293    [1400.0, 960.0]
294}
295fn default_ppp() -> f32 {
296    1.0
297}
298fn default_timeout() -> u64 {
299    120_000
300}
301
302#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
303#[serde(deny_unknown_fields)]
304pub struct Step {
305    pub tool: String,
306    #[serde(default)]
307    pub args: Value,
308    #[serde(default, skip_serializing_if = "Vec::is_empty")]
309    pub expect: Vec<Expect>,
310    /// Save the step's image (if the tool produced one) under this name.
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    pub save: Option<String>,
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub compare: Option<Compare>,
315    /// A note for the reader; ignored by the runner.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub note: Option<String>,
318    /// The step is expected to FAIL: the tool must return an error, and the
319    /// error text must match this glob (`*` = anything).
320    #[serde(default, skip_serializing_if = "Option::is_none")]
321    pub expect_error: Option<String>,
322    /// Capture values of this step's result for `${plm:NAME}` in later steps
323    /// (`{"name": "/json/pointer"}`). Needs the script's `plm` block, which
324    /// holds the variables; a pointer that finds nothing fails the step.
325    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
326    pub bind: std::collections::BTreeMap<String, String>,
327    /// Record a walkthrough frame BEFORE this step runs. Only meaningful in a
328    /// script that declares a [`Video`].
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub frame: Option<Frame>,
331}
332
333#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
334#[serde(deny_unknown_fields)]
335pub struct Compare {
336    /// Path under `BREP_mcp/tests/baselines/`.
337    pub baseline: String,
338    #[serde(default = "default_max_diff")]
339    pub max_diff_ratio: f64,
340}
341
342fn default_max_diff() -> f64 {
343    0.002
344}
345
346/// One expectation: a JSON pointer into the tool result plus exactly one
347/// operator. `near` takes a relative tolerance `tol` (default 1e-6).
348#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, schemars::JsonSchema)]
349#[serde(deny_unknown_fields)]
350pub struct Expect {
351    pub path: String,
352    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
353    pub eq: Option<Value>,
354    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
355    pub ne: Option<Value>,
356    #[serde(default, skip_serializing_if = "Option::is_none")]
357    pub gt: Option<f64>,
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub gte: Option<f64>,
360    #[serde(default, skip_serializing_if = "Option::is_none")]
361    pub lt: Option<f64>,
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub lte: Option<f64>,
364    #[serde(default, skip_serializing_if = "Option::is_none")]
365    pub near: Option<f64>,
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub tol: Option<f64>,
368    #[serde(default, skip_serializing_if = "Option::is_none")]
369    pub contains: Option<Value>,
370    #[serde(default, skip_serializing_if = "Option::is_none")]
371    pub matches: Option<String>,
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub exists: Option<bool>,
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub len: Option<usize>,
376}
377
378/// Deserialize an optional field so that a WRITTEN `null` is `Some(Value::Null)`
379/// and only an ABSENT key is `None`.
380///
381/// `Option<Value>` normally collapses the two, which makes `{"eq": null}` read
382/// as "no operator given" — so the one way to assert that a field IS null (an
383/// inactive PMI view, a solid with no colour override) parsed as a script
384/// error. The distinction is exactly what this expectation format needs.
385fn present<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
386where
387    D: serde::Deserializer<'de>,
388{
389    Value::deserialize(deserializer).map(Some)
390}
391
392/// Exit codes of `brep-mcp test`.
393pub mod exit {
394    pub const PASS: i32 = 0;
395    pub const EXPECTATION_FAILED: i32 = 1;
396    pub const TOOL_ERROR: i32 = 2;
397    pub const HOST_ERROR: i32 = 3;
398    pub const TIMEOUT: i32 = 4;
399}
400
401impl Script {
402    pub fn parse(text: &str) -> Result<Self, String> {
403        let s: Script = serde_json::from_str(text).map_err(|e| format!("script parse: {e}"))?;
404        if s.steps.is_empty() {
405            return Err("script has no steps".into());
406        }
407        for (i, step) in s.steps.iter().enumerate() {
408            if let Some(frame) = &step.frame {
409                if let Some(motion) = &frame.motion {
410                    // A `motion` the runner cannot film is a silent nothing:
411                    // the frame would record as an ordinary still and the
412                    // author would be left looking at a GIF that does not move,
413                    // wondering which end was wrong. Name it here instead.
414                    if !DRAG_TOOLS.contains(&step.tool.as_str()) {
415                        return Err(format!(
416                            "step {i}: `frame.motion` films a DRAG, but this step is `{}` (one of {})",
417                            step.tool,
418                            DRAG_TOOLS.join(", ")
419                        ));
420                    }
421                    if s.video.is_none() {
422                        return Err(format!(
423                            "step {i}: `frame.motion` only means something in a script that declares a `video`"
424                        ));
425                    }
426                    if motion.frames == 0 {
427                        return Err(format!("step {i}: `frame.motion.frames` must be at least 1"));
428                    }
429                    if motion.cursor_scale == 0 {
430                        return Err(format!("step {i}: `frame.motion.cursor_scale` must be at least 1"));
431                    }
432                }
433            }
434            // A field the runner cannot honour on this step is refused by
435            // name, never dropped: a plm_request's dropped `bind` once showed
436            // up only as "not known" two steps later.
437            if (step.tool == PLM_REQUEST || step.tool == PLM_SERVER) && (step.save.is_some() || step.compare.is_some()) {
438                return Err(format!(
439                    "step {i}: `{}` is answered by the runner and makes no image, so `save` / `compare` cannot be honoured",
440                    step.tool
441                ));
442            }
443            if !step.bind.is_empty() && step.expect_error.is_some() {
444                return Err(format!(
445                    "step {i}: `bind` reads the step's result, but `expect_error` expects it to fail, so nothing would be bound"
446                ));
447            }
448            if !step.bind.is_empty() && s.plm.is_none() {
449                return Err(format!("step {i}: `bind` needs the script to declare `plm`, which holds the variables"));
450            }
451            for (j, e) in step.expect.iter().enumerate() {
452                if e.operator_count() != 1 {
453                    return Err(format!(
454                        "step {i} (`{}`) expect {j}: exactly one operator is required",
455                        step.tool
456                    ));
457                }
458                if !e.path.starts_with('/') && !e.path.is_empty() {
459                    return Err(format!(
460                        "step {i} expect {j}: `path` must be a JSON pointer starting with `/` (got `{}`)",
461                        e.path
462                    ));
463                }
464            }
465        }
466        Ok(s)
467    }
468
469    /// The JSON Schema of the format (`brep://script/format`), derived from
470    /// these types.
471    pub fn json_schema() -> Value {
472        serde_json::to_value(schemars::schema_for!(Script)).unwrap_or(Value::Null)
473    }
474}
475
476impl Expect {
477    fn operator_count(&self) -> usize {
478        [
479            self.eq.is_some(),
480            self.ne.is_some(),
481            self.gt.is_some(),
482            self.gte.is_some(),
483            self.lt.is_some(),
484            self.lte.is_some(),
485            self.near.is_some(),
486            self.contains.is_some(),
487            self.matches.is_some(),
488            self.exists.is_some(),
489            self.len.is_some(),
490        ]
491        .iter()
492        .filter(|b| **b)
493        .count()
494    }
495
496    /// Evaluate against a tool result. `Ok(())` when satisfied; `Err(why)`
497    /// otherwise, with the actual value in the message.
498    pub fn check(&self, result: &Value) -> Result<(), String> {
499        let actual = result.pointer(&self.path);
500        if let Some(exists) = self.exists {
501            return if actual.is_some() == exists {
502                Ok(())
503            } else {
504                Err(format!("{}: exists == {} expected {exists}", self.path, actual.is_some()))
505            };
506        }
507        let Some(actual) = actual else {
508            return Err(format!("{}: no value at that path", self.path));
509        };
510        let num = |v: &Value| v.as_f64();
511        let shown = {
512            let t = actual.to_string();
513            if t.chars().count() > 160 {
514                format!("{}…", t.chars().take(160).collect::<String>())
515            } else {
516                t
517            }
518        };
519        let fail = |what: &str| Err(format!("{}: {what}; actual {shown}", self.path));
520        if let Some(e) = &self.eq {
521            return if actual == e { Ok(()) } else { fail(&format!("expected {e}")) };
522        }
523        if let Some(e) = &self.ne {
524            return if actual != e { Ok(()) } else { fail(&format!("expected not {e}")) };
525        }
526        if let Some(b) = self.gt {
527            return match num(actual) { Some(a) if a > b => Ok(()), _ => fail(&format!("expected > {b}")) };
528        }
529        if let Some(b) = self.gte {
530            return match num(actual) { Some(a) if a >= b => Ok(()), _ => fail(&format!("expected >= {b}")) };
531        }
532        if let Some(b) = self.lt {
533            return match num(actual) { Some(a) if a < b => Ok(()), _ => fail(&format!("expected < {b}")) };
534        }
535        if let Some(b) = self.lte {
536            return match num(actual) { Some(a) if a <= b => Ok(()), _ => fail(&format!("expected <= {b}")) };
537        }
538        if let Some(b) = self.near {
539            let tol = self.tol.unwrap_or(1e-6);
540            return match num(actual) {
541                Some(a) if (a - b).abs() <= tol * b.abs().max(1.0) => Ok(()),
542                _ => fail(&format!("expected within {tol} (relative) of {b}")),
543            };
544        }
545        if let Some(needle) = &self.contains {
546            let ok = match (actual, needle) {
547                (Value::String(s), Value::String(n)) => s.contains(n.as_str()),
548                (Value::Array(a), n) => a.contains(n),
549                (Value::Object(o), Value::String(n)) => o.contains_key(n),
550                _ => false,
551            };
552            return if ok { Ok(()) } else { fail(&format!("expected to contain {needle}")) };
553        }
554        if let Some(pattern) = &self.matches {
555            let Some(s) = actual.as_str() else { return fail("expected a string to match") };
556            return if glob_match(pattern, s) { Ok(()) } else { fail(&format!("expected to match `{pattern}`")) };
557        }
558        if let Some(n) = self.len {
559            let l = match actual {
560                Value::Array(a) => Some(a.len()),
561                Value::String(s) => Some(s.chars().count()),
562                Value::Object(o) => Some(o.len()),
563                _ => None,
564            };
565            return match l { Some(l) if l == n => Ok(()), _ => fail(&format!("expected length {n}")) };
566        }
567        Err(format!("{}: no operator", self.path))
568    }
569}
570
571/// `matches` uses a small glob (`*` any run, `?` one char) rather than a regex
572/// crate: enough for ids like `E*` and messages like `*cannot determine*`.
573pub fn glob_match(pattern: &str, text: &str) -> bool {
574    fn rec(p: &[char], t: &[char]) -> bool {
575        match (p.first(), t.first()) {
576            (None, None) => true,
577            (Some('*'), _) => rec(&p[1..], t) || (!t.is_empty() && rec(p, &t[1..])),
578            (Some('?'), Some(_)) => rec(&p[1..], &t[1..]),
579            (Some(a), Some(b)) if a == b => rec(&p[1..], &t[1..]),
580            _ => false,
581        }
582    }
583    let p: Vec<char> = pattern.chars().collect();
584    let t: Vec<char> = text.chars().collect();
585    rec(&p, &t)
586}
587