Skip to main content

litz_engine/
runner.rs

1//! Loading a project, booting it and deciding pass or fail.
2
3use crate::config::{
4    BoardSection, Config, DecodeSection, Runtime, TestSpec, WifiSpec, parse_duration, parse_size,
5};
6use crate::image::{self, FirmwareLayout};
7use crate::lock::Lock;
8use crate::scenario::{Scenario, Step};
9use litz_board::chip::{Chip, ImageKind, Input, Stop};
10use litz_board::probe;
11use litz_board::{Board, FlatBoard};
12use litz_catalog::Registry;
13use litz_core::{Level, PartState};
14use litz_diagram::{Circuit, Diagnostic, Severity};
15use litz_net::{AccessPoint, NearbyNetwork, NetworkConfig, Service};
16
17use crate::machine::{Attachments, builtin_chip};
18
19// A wasm guest chip needs wasmtime, which cannot itself be built for a wasm32
20// host. The browser module uses `machine::boot_c3` only, so the runner's wasm
21// chip backend is compiled out there rather than dragging wasmtime along.
22#[cfg(not(target_family = "wasm"))]
23use litz_mcu_wasm::WasmChip;
24use std::collections::BTreeMap;
25use std::io::Write;
26use std::path::{Path, PathBuf};
27
28const DEFAULT_TIMEOUT: &str = "10s";
29const DEFAULT_MAC: [u8; 6] = [0x24, 0x0a, 0xc4, 0x12, 0x34, 0x56];
30const EXIT_TIMEOUT: i32 = 42;
31/// MicroPython's friendly-REPL prompt. It is the only sign the interpreter is
32/// ready to accept a paste; matching a banner would tie the runner to one
33/// build's wording.
34const REPL_PROMPT: &str = ">>> ";
35/// How often a CircuitPython board that has not answered yet is sent a key.
36/// Long enough that one press survives a `code.py` that is still starting,
37/// short enough that a boot which already finished does not wait.
38const CIRCUITPYTHON_NUDGE: u64 = 200_000_000;
39/// A paste is assembled in RAM before it is sent, so it is capped at the size
40/// a REPL session can reasonably swallow. A project that needs more should
41/// ship a filesystem image instead.
42const MAX_SCRIPT: usize = 64 * 1024;
43/// Simulated time granted after a paste is queued before an `expect` that
44/// already matched the boot output may end the run. It gives the UART queue
45/// time to drain and the interpreter time to start the script, so a test that
46/// asserts on the banner cannot pass without the script ever running.
47const PASTE_GRACE_NS: u64 = 200_000_000;
48
49#[derive(Clone, Copy, PartialEq, Eq)]
50pub enum Mode {
51    Run,
52    Test,
53    Check,
54}
55
56/// What the caller wants recorded about a run, beyond pass or fail.
57#[derive(Clone, Default)]
58pub struct Options {
59    /// Write every net transition to this file as a VCD.
60    pub vcd: Option<PathBuf>,
61    /// Stop the first run at this program counter and report the registers.
62    pub break_at: Option<u32>,
63    /// Solve the circuit's analog network alongside the digital run. Off by
64    /// default; `[sim] analog = true` turns it on for the project.
65    pub analog: bool,
66    /// Override the project's Wi-Fi access point for this run.
67    pub wifi: Option<String>,
68    /// Turn on instruction coverage and print the backend's report after the
69    /// run. A backend without coverage ignores it.
70    pub coverage: bool,
71    /// Forward lines typed on stdin to one board's console, so a REPL or a
72    /// firmware that asks a question can be answered from the terminal.
73    pub interactive: Option<Interactive>,
74    /// Write a simulated display here as a PNG: at the end of a `run`, and
75    /// when a test fails.
76    pub screenshot: Option<Screenshot>,
77    /// Points to watch, in addition to the project's `[[probe]]` entries.
78    /// Each is its own channel name.
79    pub probes: Vec<String>,
80    /// Write every probe's record here as a CSV at the end of the run.
81    pub scope: Option<PathBuf>,
82    /// Write every probe as a sigrok session archive (`.sr`) for PulseView
83    /// or `sigrok-cli`. The samples come from the same record the scope
84    /// writes, held at each channel's last transition.
85    pub sr: Option<PathBuf>,
86    /// The samplerate for the sigrok archive, in Hz. `None` uses
87    /// [`litz_board::sigrok::DEFAULT_RATE_HZ`].
88    pub sr_rate: Option<u64>,
89    /// Start the scope's window at a logic-analyzer trigger instead of at
90    /// time zero. The trigger names a probe the run already watches.
91    pub trigger: Option<litz_board::probe::Trigger>,
92    /// Protocols to read off the probed channels, in addition to the project's
93    /// `[[decode]]` entries.
94    pub decodes: Vec<DecodeSection>,
95    /// Serve the GDB remote protocol on one board's chip once it is booted.
96    pub gdb: Option<GdbRequest>,
97    /// Write the simulated network's traffic here as a pcap at the end of the
98    /// run, for Wireshark.
99    pub pcap: Option<PathBuf>,
100    /// Write every 802.11 frame the radio carries into a link-type-105 pcap
101    /// as the run goes.
102    pub pcap_air: Option<PathBuf>,
103    /// Write the Ethernet frames the station's MAC carries into a
104    /// link-type-1 pcap as the run goes.
105    pub pcap_eth: Option<PathBuf>,
106    /// Put host sockets behind the Wi-Fi gateway. Non-deterministic by
107    /// nature; the forwarded ports are `tcp:[host:]port-[guest:]port`.
108    pub host_network: bool,
109    pub host_forwards: Vec<String>,
110    /// Ask the firmware for its free heap at the end of the run and print it.
111    /// A firmware that cannot answer makes the run fail, so CI can gate on it.
112    pub heap_sample: bool,
113    /// Sample the free heap every this many nanoseconds of simulated time.
114    /// `None` keeps the end-of-run sample that `heap_sample` asks for.
115    pub heap_interval: Option<u64>,
116    /// Fail the run when the free heap drops below this many bytes.
117    pub heap_min_free: Option<u32>,
118    /// Append every heap sample to this CSV as it is taken.
119    pub heap_csv: Option<PathBuf>,
120    /// Save the image of every SPI microSD card the guest wrote, after the
121    /// run. One card writes to the path; several treat it as a directory.
122    pub sd_export: Option<PathBuf>,
123    /// Save the MCU's own flash after the run, so a firmware that wrote a
124    /// config sector or a filesystem hands it to the next run.
125    pub flash_export: Option<PathBuf>,
126}
127
128/// `--interactive[=BOARD]`: whose console receives what is typed.
129#[derive(Clone, Debug, Default)]
130pub struct Interactive {
131    /// The board whose console stdin reaches; `None` means the first board.
132    pub board: Option<String>,
133}
134
135/// `--screenshot [<board>@]FILE`: which display to capture, and where.
136#[derive(Clone, Debug)]
137pub struct Screenshot {
138    /// The board whose display to capture; `None` means the first board that
139    /// has a framebuffer.
140    pub board: Option<String>,
141    pub path: PathBuf,
142}
143
144/// Heap samples taken while the run proceeds.
145///
146/// The firmware's own getter is the source, so the numbers are the ones the
147/// firmware sees. Sampling happens at chunk boundaries, which is where the
148/// core is between instructions; a sample never changes the program's state
149/// beyond the simulated time the call itself spends.
150struct HeapLog {
151    label: String,
152    interval_ns: u64,
153    next_ns: u64,
154    limit: Option<u32>,
155    csv: Option<(PathBuf, std::io::BufWriter<std::fs::File>)>,
156    samples: Vec<(u64, u32)>,
157    lowest: Option<u32>,
158    failure: Option<String>,
159    last_error: Option<String>,
160}
161
162impl HeapLog {
163    fn from_options(options: &Options, label: String) -> Result<Option<Self>, String> {
164        let enabled = options.heap_sample
165            || options.heap_interval.is_some()
166            || options.heap_min_free.is_some()
167            || options.heap_csv.is_some();
168        if !enabled {
169            return Ok(None);
170        }
171        let interval_ns = options.heap_interval.unwrap_or(1_000_000_000).max(1);
172        let csv = options
173            .heap_csv
174            .as_ref()
175            .map(|path| {
176                let file =
177                    std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
178                let mut writer = std::io::BufWriter::new(file);
179                writer
180                    .write_all(b"part,time_s,free,min_free\n")
181                    .map_err(|e| format!("{}: {e}", path.display()))?;
182                Ok::<(PathBuf, std::io::BufWriter<std::fs::File>), String>((path.clone(), writer))
183            })
184            .transpose()?;
185        Ok(Some(Self {
186            label,
187            interval_ns,
188            next_ns: 0,
189            limit: options.heap_min_free,
190            csv,
191            samples: Vec::new(),
192            lowest: None,
193            failure: None,
194            last_error: None,
195        }))
196    }
197
198    /// Take a sample when the interval has elapsed. Sampling more than once
199    /// per chunk is pointless: the shape is bounded by the chunk size, not by
200    /// how many times the loop asks.
201    fn sample(&mut self, mcu: &mut Fleet, now_ns: u64) {
202        if now_ns < self.next_ns || self.failure.is_some() {
203            return;
204        }
205        while self.next_ns <= now_ns {
206            self.next_ns = self.next_ns.saturating_add(self.interval_ns);
207        }
208        self.record(mcu, now_ns);
209    }
210
211    /// Record one sample now, regardless of the interval, for the run's end.
212    fn record(&mut self, mcu: &mut Fleet, now_ns: u64) {
213        let free = match mcu.sample_heap() {
214            Ok(free) => free,
215            Err(error) => {
216                self.last_error = Some(error);
217                return;
218            }
219        };
220        self.samples.push((now_ns, free));
221        self.lowest = Some(self.lowest.map_or(free, |lowest| lowest.min(free)));
222        let lowest = self.lowest.unwrap_or(free);
223        if let Some((path, writer)) = &mut self.csv {
224            let line = format!(
225                "{},{:.3},{},{}\n",
226                csv_field(&self.label),
227                now_ns as f64 / 1e9,
228                free,
229                lowest
230            );
231            if let Err(error) = writer.write_all(line.as_bytes()) {
232                self.failure = Some(format!("{}: {error}", path.display()));
233            }
234        }
235        if let Some(limit) = self.limit
236            && free < limit
237        {
238            self.failure = Some(format!(
239                "free heap {free} dropped below {limit} bytes at {:.3}s",
240                now_ns as f64 / 1e9
241            ));
242        }
243    }
244
245    /// The report lines, the failure that should turn the run red, and the
246    /// samples themselves.
247    fn finish(mut self, mcu: &mut Fleet, now_ns: u64) -> (Vec<String>, Option<String>) {
248        // The end of the run is a sample point in its own right: a leak that
249        // only shows after the last interval must not be missed.
250        if !self.samples.iter().any(|(at, _)| *at == now_ns) {
251            self.record(mcu, now_ns);
252        }
253        let mut lines = Vec::new();
254        if self.samples.is_empty() {
255            let why = self
256                .last_error
257                .unwrap_or_else(|| "the firmware never answered".into());
258            let message = format!("no samples: {why}");
259            // A bare `--heap` is informational, as Wokwi's is; a minimum is a
260            // gate, and a gate that cannot read the heap must fail.
261            return if self.limit.is_some() {
262                (Vec::new(), Some(message))
263            } else {
264                (vec![message], None)
265            };
266        }
267        let first = self.samples[0];
268        let last = *self.samples.last().expect("checked non-empty");
269        let mut last_free = None;
270        for (at, free) in &self.samples {
271            if last_free == Some(*free) {
272                continue;
273            }
274            last_free = Some(*free);
275            lines.push(format!(
276                "[heap {}] {:.3}s free={free} min={}",
277                self.label,
278                *at as f64 / 1e9,
279                self.lowest.unwrap_or(*free)
280            ));
281        }
282        let lost = first.1.saturating_sub(last.1);
283        let seconds = (last.0.saturating_sub(first.0)) as f64 / 1e9;
284        let rate = if seconds > 0.0 {
285            lost as f64 / seconds
286        } else {
287            0.0
288        };
289        lines.push(format!(
290            "Heap: {} samples, free {} -> {}, lowest {}, {:.0} bytes/s lost",
291            self.samples.len(),
292            first.1,
293            last.1,
294            self.lowest.unwrap_or(last.1),
295            rate
296        ));
297        (lines, self.failure)
298    }
299}
300
301/// A CSV field is quoted only when it contains a separator or a quote; board
302/// ids are simple, but a project may name one anything.
303fn csv_field(text: &str) -> String {
304    if text.contains([',', '"', '\n']) {
305        format!("\"{}\"", text.replace('"', "\"\""))
306    } else {
307        text.to_string()
308    }
309}
310
311impl HeapLog {
312    /// The failure so far, for the loop to stop early when the limit is hit.
313    fn failed(&self) -> bool {
314        self.failure.is_some()
315    }
316}
317
318/// Which board to debug, and where to listen for the client.
319///
320/// A GDB session owns the chip's clock for as long as the client is attached,
321/// so one session is served at a time: `board` says which chip, and its
322/// absence picks the first board whose backend has a debug target.
323#[derive(Clone, Debug)]
324pub struct GdbRequest {
325    pub board: Option<String>,
326    pub port: u16,
327}
328
329pub struct Outcome {
330    pub exit_code: i32,
331    pub output: String,
332    /// Simulated milliseconds the run reached, for a report that wants to say
333    /// how much of the timeline a passing test actually looked at.
334    pub sim_ms: u32,
335    /// One entry per `[[test]]`; empty for `run` and `check`.
336    pub tests: Vec<TestOutcome>,
337}
338
339pub struct TestOutcome {
340    pub name: String,
341    pub passed: bool,
342    pub exit_code: i32,
343    pub output: String,
344    pub sim_ms: u32,
345}
346
347/// A run whose console was captured instead of streamed.
348///
349/// `run` writes bytes to stdout as they arrive because a person is watching a
350/// terminal. A host that owns stdout — the MCP server is one — cannot allow
351/// that, so this path collects the same serial text and the part states the
352/// UI would read back.
353pub struct CaptureOutcome {
354    pub exit_code: i32,
355    pub output: String,
356    pub sim_ms: u32,
357    /// Parts whose state is not [`litz_core::PartState::None`], by id.
358    pub part_states: BTreeMap<String, PartState>,
359    /// Electrical faults the board found, in net order.
360    pub faults: Vec<String>,
361}
362
363struct Prepared {
364    config: Config,
365    dir: PathBuf,
366    registry: Registry,
367    circuit: Circuit,
368    /// One entry per development board in diagram order; each boots its own
369    /// image onto its own chip pins.
370    boards: Vec<BoardPlan>,
371}
372
373/// Everything one development board boots and asserts against.
374struct BoardPlan {
375    /// The board instance's id in `diagram.json`.
376    id: String,
377    /// The board's own manifest: which MCU it names, and where its files are.
378    manifest: litz_catalog::PartManifest,
379    flash_size: usize,
380    rom: Vec<u8>,
381    firmware: Vec<u8>,
382    /// The firmware's symbol table, when the project names one.
383    elf: Option<Vec<u8>>,
384    /// Whether `firmware` holds a whole flash image or only an application.
385    layout: FirmwareLayout,
386    bootloader: Option<Vec<u8>>,
387    partition_table: Option<Vec<u8>>,
388    /// The runtime this board's console speaks, and the Python pasted into it.
389    /// The first staged file is the entry the REPL executes; the rest are
390    /// written to the device first so the entry can import them.
391    runtime: Runtime,
392    /// Which Python the console speaks, resolved from the runtime and the
393    /// image name: CircuitPython boots `code.py`, MicroPython `main.py`.
394    python: crate::python::PythonRuntime,
395    scripts: Vec<StagedScript>,
396    mac: [u8; 6],
397}
398
399/// One Python file a MicroPython project stages on the device before it runs.
400struct StagedScript {
401    /// The path on the device, relative to the REPL's working directory.
402    name: String,
403    bytes: Vec<u8>,
404}
405
406pub fn execute(dir: &Path, mode: Mode, strict: bool, update_lock: bool) -> Result<Outcome, String> {
407    execute_with(dir, mode, strict, update_lock, &Options::default())
408}
409
410/// `execute` with recording options: a VCD file and a breakpoint.
411pub fn execute_with(
412    dir: &Path,
413    mode: Mode,
414    strict: bool,
415    update_lock: bool,
416    options: &Options,
417) -> Result<Outcome, String> {
418    let config = match Config::load_project(dir) {
419        Ok(config) => config,
420        Err(e) if mode == Mode::Check => {
421            let _ = e;
422            Config::default()
423        }
424        Err(e) => return Err(e),
425    };
426
427    let mut registry = Registry::builtin();
428    for sub in ["parts", "boards"] {
429        let path = dir.join(sub);
430        if path.is_dir() {
431            registry.load_dir(&path).map_err(|e| e.to_string())?;
432        }
433    }
434
435    let diagram_path = dir.join(config.project.diagram());
436    let text = std::fs::read_to_string(&diagram_path)
437        .map_err(|e| format!("{}: {e}", diagram_path.display()))?;
438    let circuit =
439        Circuit::from_json(&text).map_err(|e| format!("{}: {e}", diagram_path.display()))?;
440
441    let diagnostics = circuit.validate(&registry);
442    if blocks(&diagnostics, strict) {
443        return Ok(Outcome {
444            exit_code: 1,
445            output: render(&diagnostics),
446            sim_ms: 0,
447            tests: Vec::new(),
448        });
449    }
450
451    if mode == Mode::Check {
452        let mut output = render(&diagnostics);
453        if output.is_empty() {
454            output.push_str("diagram is valid\n");
455        }
456        return Ok(Outcome {
457            exit_code: 0,
458            output,
459            sim_ms: 0,
460            tests: Vec::new(),
461        });
462    }
463
464    let prepared = prepare(config, dir, registry, circuit)?;
465    enforce_lock(&prepared, update_lock)?;
466
467    match mode {
468        Mode::Run => run_once(&prepared, None, strict, options),
469        Mode::Test => {
470            let specs = if prepared.config.test.is_empty() {
471                vec![TestSpec {
472                    name: "run".into(),
473                    timeout: None,
474                    expect: None,
475                    fail: None,
476                    input: Vec::new(),
477                    expect_state: None,
478                    state_at: None,
479                    state_stays: None,
480                }]
481            } else {
482                prepared.config.test.clone()
483            };
484            let mut output = String::new();
485            let mut tests = Vec::new();
486            let mut failed = 0;
487            let mut sim_ms = 0;
488            for spec in &specs {
489                let outcome = run_once(&prepared, Some(spec), strict, options)?;
490                output.push_str(&format!("== {} ==\n", spec.name));
491                output.push_str(&outcome.output);
492                if !outcome.output.ends_with('\n') {
493                    output.push('\n');
494                }
495                if outcome.exit_code != 0 {
496                    failed += 1;
497                }
498                sim_ms = sim_ms.max(outcome.sim_ms);
499                tests.push(TestOutcome {
500                    name: spec.name.clone(),
501                    passed: outcome.exit_code == 0,
502                    exit_code: outcome.exit_code,
503                    output: outcome.output,
504                    sim_ms: outcome.sim_ms,
505                });
506            }
507            Ok(Outcome {
508                exit_code: if failed == 0 { 0 } else { 1 },
509                output: format!(
510                    "{output}{}/{} tests passed\n",
511                    specs.len() - failed,
512                    specs.len()
513                ),
514                sim_ms,
515                tests,
516            })
517        }
518        Mode::Check => unreachable!(),
519    }
520}
521
522/// Boot a project for bounded simulated time, capturing everything.
523///
524/// This is `run` without the terminal: the serial stream is returned rather
525/// than printed, and the part states are read back when the time limit is
526/// reached. A normal bounded run still exits 42, matching the CLI.
527pub fn execute_capture(
528    dir: &Path,
529    timeout: Option<&str>,
530    strict: bool,
531    update_lock: bool,
532    options: &Options,
533) -> Result<CaptureOutcome, String> {
534    let config = Config::load_project(dir)?;
535    let mut registry = Registry::builtin();
536    for sub in ["parts", "boards"] {
537        let path = dir.join(sub);
538        if path.is_dir() {
539            registry.load_dir(&path).map_err(|e| e.to_string())?;
540        }
541    }
542
543    let diagram_path = dir.join(config.project.diagram());
544    let text = std::fs::read_to_string(&diagram_path)
545        .map_err(|e| format!("{}: {e}", diagram_path.display()))?;
546    let circuit =
547        Circuit::from_json(&text).map_err(|e| format!("{}: {e}", diagram_path.display()))?;
548
549    let diagnostics = circuit.validate(&registry);
550    if blocks(&diagnostics, strict) {
551        return Ok(CaptureOutcome {
552            exit_code: 1,
553            output: render(&diagnostics),
554            sim_ms: 0,
555            part_states: BTreeMap::new(),
556            faults: Vec::new(),
557        });
558    }
559
560    let prepared = prepare(config, dir, registry, circuit)?;
561    enforce_lock(&prepared, update_lock)?;
562    run_capture(&prepared, timeout, options)
563}
564
565/// Run a scenario (`--scenario`) instead of the `[[test]]` entries.
566///
567/// The steps share the boot path with a test and differ only in who decides
568/// when to look at the output: a test polls for its own expectations, a
569/// scenario says what it is waiting for.
570pub fn execute_scenario(
571    dir: &Path,
572    file: &Path,
573    strict: bool,
574    update_lock: bool,
575) -> Result<Outcome, String> {
576    execute_scenario_with(dir, file, strict, update_lock, &Options::default())
577}
578
579/// `execute_scenario` with recording options.
580pub fn execute_scenario_with(
581    dir: &Path,
582    file: &Path,
583    strict: bool,
584    update_lock: bool,
585    options: &Options,
586) -> Result<Outcome, String> {
587    let config = Config::load_project(dir)?;
588    let mut registry = Registry::builtin();
589    for sub in ["parts", "boards"] {
590        let path = dir.join(sub);
591        if path.is_dir() {
592            registry.load_dir(&path).map_err(|e| e.to_string())?;
593        }
594    }
595    let diagram_path = dir.join(config.project.diagram());
596    let text = std::fs::read_to_string(&diagram_path)
597        .map_err(|e| format!("{}: {e}", diagram_path.display()))?;
598    let circuit =
599        Circuit::from_json(&text).map_err(|e| format!("{}: {e}", diagram_path.display()))?;
600
601    let diagnostics = circuit.validate(&registry);
602    if blocks(&diagnostics, strict) {
603        return Ok(Outcome {
604            exit_code: 1,
605            output: render(&diagnostics),
606            sim_ms: 0,
607            tests: Vec::new(),
608        });
609    }
610
611    let prepared = prepare(config, dir, registry, circuit)?;
612    enforce_lock(&prepared, update_lock)?;
613    let scenario = Scenario::load(file)?;
614    run_scenario(&prepared, &scenario, options)
615}
616
617/// How long `wait-serial` waits when the scenario does not say.
618const DEFAULT_WAIT: u64 = 10_000_000_000;
619
620fn run_scenario(
621    prepared: &Prepared,
622    scenario: &Scenario,
623    options: &Options,
624) -> Result<Outcome, String> {
625    let Booted {
626        fleet: mut mcu,
627        board,
628        capture,
629        ..
630    } = boot(prepared, options)?;
631    start_recording(&mut mcu, options, prepared);
632    let mut heap = HeapLog::from_options(
633        options,
634        prepared
635            .boards
636            .first()
637            .map(|plan| plan.id.clone())
638            .unwrap_or_else(|| "esp".into()),
639    )?;
640    let mut serial = String::new();
641    let mut notes = Vec::new();
642    let mut failed = false;
643    // A tap with `wait: false` releases in the background, so the next step
644    // does not jump the simulated clock by the hold time.
645    let mut last_touch: Vec<Option<(u16, u16)>> = vec![None; prepared.boards.len()];
646    let mut pending_touch: Option<(u64, u16, u16, Option<usize>)> = None;
647
648    // A scenario observes the same console a test does, so MicroPython starts
649    // the same way: wait for the prompt, then paste. A scenario has no
650    // `[[test]]` timeout, so the default wait bounds the boot.
651    for (index, plan) in prepared.boards.iter().enumerate() {
652        if !pastes_script(plan) {
653            continue;
654        }
655        // CircuitPython runs `code.py` on boot, so its console is busy until
656        // Ctrl-C reaches it; MicroPython has nothing to interrupt.
657        if !plan.python.interrupt_sequence().is_empty() {
658            mcu.write_console_on(index, plan.python.interrupt_sequence());
659            advance(&mut mcu, &mut serial);
660        }
661        let deadline = now_ns(&mcu).saturating_add(DEFAULT_WAIT);
662        while !mcu.console_text(index).contains(REPL_PROMPT) {
663            if now_ns(&mcu) >= deadline || !advance(&mut mcu, &mut serial) {
664                break;
665            }
666        }
667        if !mcu.console_text(index).contains(REPL_PROMPT) {
668            return Err(format!(
669                "board {:?}: MicroPython REPL prompt did not appear within {DEFAULT_WAIT} ns of \
670                 simulated time; check that its firmware is a MicroPython or CircuitPython build",
671                plan.id
672            ));
673        }
674        paste_script(&mut mcu, index, &plan.scripts, plan.python);
675    }
676
677    for (index, step) in scenario.steps.iter().enumerate() {
678        let number = index + 1;
679        {
680            let now = now_ns(&mcu);
681            service_touch_release(&mut mcu, &mut pending_touch, now);
682        }
683        match step {
684            Step::Delay { ns } => {
685                let target = now_ns(&mcu).saturating_add(*ns);
686                while now_ns(&mcu) < target && advance(&mut mcu, &mut serial) {
687                    {
688                        let now = now_ns(&mcu);
689                        service_touch_release(&mut mcu, &mut pending_touch, now);
690                    }
691                    if let Some(log) = &mut heap {
692                        {
693                            let now = now_ns(&mcu);
694                            log.sample(&mut mcu, now);
695                        }
696                        if log.failed() {
697                            break;
698                        }
699                    }
700                }
701            }
702            Step::WaitSerial { text, timeout } => {
703                let deadline = now_ns(&mcu).saturating_add(timeout.unwrap_or(DEFAULT_WAIT));
704                while !serial.contains(text.as_str()) {
705                    if now_ns(&mcu) >= deadline {
706                        failed = true;
707                        notes.push(format!("step {number}: never saw {text:?}"));
708                        break;
709                    }
710                    if !advance(&mut mcu, &mut serial) {
711                        break;
712                    }
713                    {
714                        let now = now_ns(&mcu);
715                        service_touch_release(&mut mcu, &mut pending_touch, now);
716                    }
717                    if let Some(log) = &mut heap {
718                        {
719                            let now = now_ns(&mcu);
720                            log.sample(&mut mcu, now);
721                        }
722                        if log.failed() {
723                            break;
724                        }
725                    }
726                }
727            }
728            Step::WriteSerial { text } => {
729                // `write-serial` sends the text as written; it is the
730                // author's job to include the newline the firmware expects.
731                mcu.write_console_on(0, text.as_bytes());
732                advance(&mut mcu, &mut serial);
733            }
734            Step::WaitPin {
735                part,
736                pin,
737                value,
738                timeout,
739            } => {
740                let deadline = now_ns(&mcu).saturating_add(timeout.unwrap_or(DEFAULT_WAIT));
741                loop {
742                    let level = pin_level(prepared, &mcu, part, pin.as_deref());
743                    if level.is_some_and(|level| (level == Level::High) == *value) {
744                        break;
745                    }
746                    if now_ns(&mcu) >= deadline {
747                        failed = true;
748                        notes.push(format!(
749                            "step {number}: {part} never reached {} within {} ns",
750                            if *value { "high" } else { "low" },
751                            timeout.unwrap_or(DEFAULT_WAIT)
752                        ));
753                        break;
754                    }
755                    if !advance(&mut mcu, &mut serial) {
756                        break;
757                    }
758                    {
759                        let now = now_ns(&mcu);
760                        service_touch_release(&mut mcu, &mut pending_touch, now);
761                    }
762                }
763            }
764            Step::ExpectPin { part, pin, value } => {
765                match pin_level(prepared, &mcu, part, pin.as_deref()) {
766                    Some(level) => {
767                        let high = level == Level::High;
768                        if high != *value {
769                            failed = true;
770                            notes.push(format!(
771                                "step {number}: {part} is {} but the scenario expects {}",
772                                if high { "high" } else { "low" },
773                                if *value { "high" } else { "low" }
774                            ));
775                        }
776                    }
777                    None => {
778                        failed = true;
779                        notes.push(format!(
780                            "step {number}: no part {part:?} is wired to a chip pin"
781                        ));
782                    }
783                }
784            }
785            Step::SetControl {
786                part,
787                control,
788                value,
789            } => {
790                if mcu.set_named_control(part, control, value) {
791                    // The part understood the control's own name and unit.
792                } else {
793                    match control.as_str() {
794                        // The potentiometer's control is named `value` and
795                        // measured in percent of travel.
796                        "value" | "position" => match value.trim().parse::<f64>() {
797                            Ok(percent) if (0.0..=100.0).contains(&percent) => {
798                                let permille = (percent * 10.0).round() as u16;
799                                if !mcu.set_control(part, permille) {
800                                    failed = true;
801                                    notes.push(format!(
802                                        "step {number}: part {part:?} has no continuous control"
803                                    ));
804                                }
805                            }
806                            _ => {
807                                failed = true;
808                                notes.push(format!(
809                                "step {number}: set-control value {value:?} is not 0 through 100"
810                            ));
811                            }
812                        },
813                        other => {
814                            failed = true;
815                            notes.push(format!(
816                                "step {number}: part {part:?} has no control {other:?}"
817                            ));
818                        }
819                    }
820                }
821            }
822            Step::TakeScreenshot {
823                part,
824                path,
825                board: which,
826                expected,
827                tolerance,
828            } => {
829                let index = match which {
830                    Some(id) => Some(find_board(&prepared.boards, id, "take-screenshot")?),
831                    None => None,
832                };
833                // A capture with only `compare-with` still needs a file to
834                // write; it lands beside the reference so a failing CI job can
835                // show both pictures.
836                let path = match (path, expected) {
837                    (Some(path), _) => path.clone(),
838                    (None, Some(expected)) => expected.with_extension("actual.png"),
839                    (None, None) => unreachable!("the parser requires one of them"),
840                };
841                let capture = match part {
842                    Some(part) if prepared.boards.iter().any(|plan| plan.id == *part) => {
843                        let board = find_board(&prepared.boards, part, "take-screenshot")?;
844                        mcu.save_display(Some(board), &path)
845                    }
846                    Some(part) => mcu.save_part_display(part, &path),
847                    None => mcu.save_display(index, &path),
848                };
849                match capture {
850                    Ok(()) => {
851                        if let Some(expected) = expected {
852                            match compare_images(&path, expected, *tolerance) {
853                                Ok(()) => {}
854                                Err(error) => {
855                                    failed = true;
856                                    notes.push(format!("step {number}: {error}"));
857                                }
858                            }
859                        }
860                    }
861                    Err(error) => {
862                        failed = true;
863                        notes.push(format!("step {number}: {error}"));
864                    }
865                }
866            }
867            Step::Touch {
868                x,
869                y,
870                down,
871                board: which,
872                part,
873            } => {
874                let index = touch_board(prepared, which, part, "touch")?;
875                if let Err(error) = mcu.touch(index, *x, *y, *down) {
876                    failed = true;
877                    notes.push(format!("step {number}: {error}"));
878                } else if *down {
879                    let slot = index.unwrap_or(0);
880                    if let Some(slot) = last_touch.get_mut(slot) {
881                        *slot = Some((*x, *y));
882                    }
883                }
884            }
885            Step::TouchMove {
886                x,
887                y,
888                board: which,
889                part,
890            } => {
891                let index = touch_board(prepared, which, part, "touch-move")?;
892                if let Err(error) = mcu.touch(index, *x, *y, true) {
893                    failed = true;
894                    notes.push(format!("step {number}: {error}"));
895                } else {
896                    let slot = index.unwrap_or(0);
897                    if let Some(slot) = last_touch.get_mut(slot) {
898                        *slot = Some((*x, *y));
899                    }
900                }
901            }
902            Step::TouchTap {
903                x,
904                y,
905                duration,
906                wait,
907                board: which,
908                part,
909            } => {
910                let index = touch_board(prepared, which, part, "touch")?;
911                if let Err(error) = mcu.touch(index, *x, *y, true) {
912                    failed = true;
913                    notes.push(format!("step {number}: {error}"));
914                } else {
915                    let slot = index.unwrap_or(0);
916                    if let Some(slot) = last_touch.get_mut(slot) {
917                        *slot = Some((*x, *y));
918                    }
919                    let release_at = now_ns(&mcu).saturating_add(*duration);
920                    if *wait {
921                        while now_ns(&mcu) < release_at && advance(&mut mcu, &mut serial) {
922                            {
923                                let now = now_ns(&mcu);
924                                service_touch_release(&mut mcu, &mut pending_touch, now);
925                            }
926                        }
927                        let _ = mcu.touch(index, *x, *y, false);
928                    } else {
929                        pending_touch = Some((release_at, *x, *y, index));
930                    }
931                }
932            }
933            Step::TouchRelease {
934                x,
935                y,
936                board: which,
937                part,
938            } => {
939                let index = touch_board(prepared, which, part, "touch-release")?;
940                let previous = last_touch.get(index.unwrap_or(0)).copied().flatten();
941                let (x, y) = match (x, y) {
942                    (Some(x), Some(y)) => (*x, *y),
943                    _ => previous.unwrap_or((0, 0)),
944                };
945                pending_touch = None;
946                if let Err(error) = mcu.touch(index, x, y, false) {
947                    failed = true;
948                    notes.push(format!("step {number}: {error}"));
949                }
950            }
951        }
952        if let Some(log) = &mut heap {
953            {
954                let now = now_ns(&mcu);
955                log.sample(&mut mcu, now);
956            }
957        }
958        let conflicts = mcu.conflicts();
959        if !conflicts.is_empty() {
960            for conflict in &conflicts {
961                notes.push(format!(
962                    "electrical fault on net {}: {}",
963                    conflict.net, conflict.detail
964                ));
965            }
966            failed = true;
967            break;
968        }
969    }
970
971    let mut output = serial;
972    if !output.ends_with('\n') && !output.is_empty() {
973        output.push('\n');
974    }
975    for note in notes {
976        output.push_str(&format!("litz: {note}\n"));
977    }
978    for line in probe_report(&board) {
979        output.push_str(&format!("litz: {line}\n"));
980    }
981    for line in decode_report(&board, prepared, options)? {
982        output.push_str(&format!("litz: {line}\n"));
983    }
984    finish_recording(&mcu, &board, options, capture.as_ref())?;
985    if let Some(log) = heap {
986        let end = now_ns(&mcu);
987        let (lines, failure) = log.finish(&mut mcu, end);
988        for line in lines {
989            output.push_str(&format!("litz: {line}\n"));
990        }
991        if let Some(failure) = failure {
992            failed = true;
993            output.push_str(&format!("litz: heap: {failure}\n"));
994        }
995    }
996    Ok(Outcome {
997        exit_code: if failed { 1 } else { 0 },
998        output,
999        sim_ms: (mcu.seconds() * 1000.0) as u32,
1000        tests: Vec::new(),
1001    })
1002}
1003
1004/// A scenario's pin reference, resolved to a level: `part-id` naming a
1005/// development board with a GPIO number (`esp`/`2`), an explicit pin name
1006/// (`name`), `part:pin` in the part id, or the chip pin the part is on.
1007fn pin_level(prepared: &Prepared, mcu: &Fleet, target: &str, pin: Option<&str>) -> Option<Level> {
1008    if let Some(index) = prepared.boards.iter().position(|plan| plan.id == target)
1009        && let Some(gpio) = pin.and_then(parse_gpio)
1010    {
1011        return mcu.gpio_level(index, gpio);
1012    }
1013    match (target.split_once(':'), pin) {
1014        (Some((part, pin)), _) => mcu.part_pin_level(part, Some(pin)),
1015        (None, Some(pin)) => mcu.part_pin_level(target, Some(pin)),
1016        (None, None) => mcu.part_pin_level(target, None),
1017    }
1018}
1019
1020/// `2`, `GPIO2` or `D2` as a chip pad number.
1021fn parse_gpio(text: &str) -> Option<u8> {
1022    let text = text.trim();
1023    let text = text
1024        .strip_prefix("GPIO")
1025        .or_else(|| text.strip_prefix("gpio"))
1026        .or_else(|| text.strip_prefix('D'))
1027        .or_else(|| text.strip_prefix('d'))
1028        .unwrap_or(text);
1029    text.parse().ok()
1030}
1031
1032fn now_ns(fleet: &Fleet) -> u64 {
1033    fleet.frontier_ns()
1034}
1035
1036/// Release a tap whose hold time has elapsed, so `wait: false` does not stop
1037/// the scenario for the duration of the touch.
1038fn service_touch_release(
1039    mcu: &mut Fleet,
1040    pending: &mut Option<(u64, u16, u16, Option<usize>)>,
1041    now_ns: u64,
1042) {
1043    if let Some((at, x, y, index)) = *pending
1044        && now_ns >= at
1045    {
1046        let _ = mcu.touch(index, x, y, false);
1047        *pending = None;
1048    }
1049}
1050
1051/// Compare a captured image with a golden one, per pixel, so a report names a
1052/// coordinate rather than a byte offset inside a compressed stream. The
1053/// tolerance is per colour channel: 0 demands the same pixels exactly.
1054fn compare_images(actual: &Path, expected: &Path, tolerance: u8) -> Result<(), String> {
1055    let actual_image = decode_png(actual)?;
1056    let expected_image = decode_png(expected)?;
1057    if actual_image.0 != expected_image.0 || actual_image.1 != expected_image.1 {
1058        return Err(format!(
1059            "screenshot {} is {}x{} but {} is {}x{}",
1060            actual.display(),
1061            actual_image.0,
1062            actual_image.1,
1063            expected.display(),
1064            expected_image.0,
1065            expected_image.1
1066        ));
1067    }
1068    let (width, _, actual_pixels) = actual_image;
1069    let (_, _, expected_pixels) = expected_image;
1070    let mut mismatched = 0usize;
1071    let mut first = None;
1072    for (index, (a, b)) in actual_pixels.iter().zip(&expected_pixels).enumerate() {
1073        let differs = a.iter().zip(b).any(|(a, b)| a.abs_diff(*b) > tolerance);
1074        if differs {
1075            mismatched += 1;
1076            first.get_or_insert(index);
1077        }
1078    }
1079    if let Some(index) = first {
1080        let x = index as u32 % width;
1081        let y = index as u32 / width;
1082        return Err(format!(
1083            "screenshot {} differs from {} at ({x}, {y}) in {width}x{} pixels; \
1084             {mismatched} pixels differ",
1085            actual.display(),
1086            expected.display(),
1087            actual_pixels.len() as u32 / width.max(1)
1088        ));
1089    }
1090    Ok(())
1091}
1092
1093/// Decode a PNG to RGBA8. A reference image may use any colour type; the
1094/// comparison runs on the same pixels a display would show.
1095fn decode_png(path: &Path) -> Result<(u32, u32, Vec<[u8; 4]>), String> {
1096    let file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
1097    let mut decoder = png::Decoder::new(std::io::BufReader::new(file));
1098    decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
1099    let mut reader = decoder
1100        .read_info()
1101        .map_err(|e| format!("{}: {e}", path.display()))?;
1102    let size = reader
1103        .output_buffer_size()
1104        .ok_or_else(|| format!("{}: the image is too large to decode", path.display()))?;
1105    let mut buffer = vec![0; size];
1106    let info = reader
1107        .next_frame(&mut buffer)
1108        .map_err(|e| format!("{}: {e}", path.display()))?;
1109    let pixels = match info.color_type {
1110        png::ColorType::Rgba => buffer.as_chunks::<4>().0.to_vec(),
1111        png::ColorType::Rgb => buffer
1112            .as_chunks::<3>()
1113            .0
1114            .iter()
1115            .map(|p| [p[0], p[1], p[2], 255])
1116            .collect(),
1117        png::ColorType::GrayscaleAlpha => buffer
1118            .as_chunks::<2>()
1119            .0
1120            .iter()
1121            .map(|p| [p[0], p[0], p[0], p[1]])
1122            .collect(),
1123        png::ColorType::Grayscale => buffer.iter().map(|p| [*p, *p, *p, 255]).collect(),
1124        png::ColorType::Indexed => {
1125            return Err(format!(
1126                "{}: an indexed PNG did not expand to RGB",
1127                path.display()
1128            ));
1129        }
1130    };
1131    Ok((info.width, info.height, pixels))
1132}
1133
1134/// Arm the breakpoint and the waveform before the first instruction runs, so
1135/// time 0 of the trace is the board as the chip first sees it.
1136fn start_recording(mcu: &mut Fleet, options: &Options, prepared: &Prepared) {
1137    if let Some(pc) = options.break_at {
1138        mcu.break_at(pc);
1139    }
1140    // A probe's record is the net trace, so asking for one starts the same
1141    // recording a VCD does.
1142    let wants_trace = options.vcd.is_some()
1143        || options.scope.is_some()
1144        || options.sr.is_some()
1145        || !prepared.config.probes.is_empty()
1146        || !prepared.config.decodes.is_empty()
1147        || !options.probes.is_empty()
1148        || !options.decodes.is_empty();
1149    if wants_trace {
1150        mcu.start_trace();
1151    }
1152}
1153
1154fn finish_recording(
1155    mcu: &Fleet,
1156    board: &std::rc::Rc<std::cell::RefCell<Board>>,
1157    options: &Options,
1158    capture: Option<&std::rc::Rc<std::cell::RefCell<litz_net::capture::Capture>>>,
1159) -> Result<(), String> {
1160    if let (Some(path), Some(capture)) = (&options.pcap, capture) {
1161        std::fs::write(path, capture.borrow().to_pcap())
1162            .map_err(|e| format!("{}: {e}", path.display()))?;
1163    }
1164    if let Some(path) = &options.vcd {
1165        std::fs::write(path, mcu.vcd()).map_err(|e| format!("{}: {e}", path.display()))?;
1166    }
1167    if let Some(path) = &options.sd_export {
1168        board.borrow_mut().save_sd_images(path)?;
1169    }
1170    board.borrow_mut().save_storage_images()?;
1171    if let Some(path) = &options.flash_export {
1172        let image = mcu.flash_image().ok_or_else(|| {
1173            format!(
1174                "{}: this board's chip has no readable flash",
1175                path.display()
1176            )
1177        })?;
1178        std::fs::write(path, image).map_err(|e| format!("{}: {e}", path.display()))?;
1179    }
1180    if let Some(path) = &options.scope {
1181        let channels = board.borrow().scope();
1182        let csv = match &options.trigger {
1183            Some(trigger) => {
1184                let clipped = probe::triggered(&channels, trigger)?;
1185                probe::to_csv(&clipped)
1186            }
1187            None => probe::to_csv(&channels),
1188        };
1189        std::fs::write(path, csv).map_err(|e| format!("{}: {e}", path.display()))?;
1190    }
1191    if let Some(path) = &options.sr {
1192        let channels = board.borrow().scope();
1193        let clipped = match &options.trigger {
1194            Some(trigger) => probe::triggered(&channels, trigger)?,
1195            None => channels,
1196        };
1197        let rate = options
1198            .sr_rate
1199            .unwrap_or(litz_board::sigrok::DEFAULT_RATE_HZ);
1200        let archive = litz_board::sigrok::to_sr(&clipped, rate)?;
1201        std::fs::write(path, archive).map_err(|e| format!("{}: {e}", path.display()))?;
1202    }
1203    Ok(())
1204}
1205
1206/// One summary line per probe, for a run that wants to say what the wires did.
1207fn probe_report(board: &std::rc::Rc<std::cell::RefCell<Board>>) -> Vec<String> {
1208    board.borrow().scope().iter().map(probe::summary).collect()
1209}
1210
1211/// One line per frame of every configured decoder, project entries first.
1212fn decode_report(
1213    board: &std::rc::Rc<std::cell::RefCell<Board>>,
1214    prepared: &Prepared,
1215    options: &Options,
1216) -> Result<Vec<String>, String> {
1217    let channels = board.borrow().scope();
1218    crate::decode::report(
1219        prepared.config.decodes.iter().chain(options.decodes.iter()),
1220        &channels,
1221    )
1222}
1223
1224/// One chunk of simulated time. False when the board reported a fault.
1225fn advance(mcu: &mut Fleet, serial: &mut String) -> bool {
1226    let _ = mcu.run(1_000_000);
1227    let chunk = mcu.take_console();
1228    if !chunk.is_empty() {
1229        serial.push_str(&String::from_utf8_lossy(&chunk));
1230    }
1231    mcu.conflicts().is_empty()
1232}
1233
1234/// Whether the project asks for a script to be pasted into a Python REPL.
1235/// `runtime = "micropython"` with no `script` still means "run this firmware",
1236/// just without the handshake.
1237fn pastes_script(plan: &BoardPlan) -> bool {
1238    matches!(plan.runtime, Runtime::Micropython | Runtime::CircuitPython)
1239        && !plan.scripts.is_empty()
1240}
1241
1242/// Read one project file as a Python source to stage.
1243fn read_staged(dir: &Path, rel: &str) -> Result<StagedScript, String> {
1244    let path = dir.join(rel);
1245    let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1246    if bytes.len() > MAX_SCRIPT {
1247        return Err(format!(
1248            "{} is {} bytes; a MicroPython raw paste is limited to {MAX_SCRIPT} bytes",
1249            path.display(),
1250            bytes.len()
1251        ));
1252    }
1253    Ok(StagedScript {
1254        name: staged_name(rel)?,
1255        bytes,
1256    })
1257}
1258
1259/// A stage path must stay inside the REPL's working directory, so a project
1260/// file cannot write over `/boot.py` or escape with `..`.
1261fn staged_name(name: &str) -> Result<String, String> {
1262    let name = name.trim().replace('\\', "/");
1263    let invalid = name.is_empty()
1264        || name.starts_with('/')
1265        || name
1266            .split('/')
1267            .any(|part| part.is_empty() || part == "." || part == "..");
1268    if invalid {
1269        return Err(format!(
1270            "staged script {name:?} must be a relative path inside the project, \
1271             like \"main.py\" or \"lib/util.py\""
1272        ));
1273    }
1274    Ok(name)
1275}
1276
1277/// Interrupt whatever is running, then send MicroPython's raw-paste sequence:
1278/// Ctrl-C (0x03), Ctrl-A (0x01) to enter the raw REPL, the script bytes, and
1279/// Ctrl-D (0x04) to compile and run them. The chip queues the bytes and paces
1280/// them at the UART's line rate, so the interpreter sees them in this order
1281/// however small its receive FIFO is.
1282fn paste_script(
1283    mcu: &mut Fleet,
1284    index: usize,
1285    scripts: &[StagedScript],
1286    python: crate::python::PythonRuntime,
1287) {
1288    // One file is the script itself, exactly as before; several become a
1289    // bootstrap that writes each file and then executes the entry.
1290    let body = if scripts.len() == 1 {
1291        scripts[0].bytes.clone()
1292    } else {
1293        let pairs: Vec<(&str, &[u8])> = scripts
1294            .iter()
1295            .map(|script| (script.name.as_str(), script.bytes.as_slice()))
1296            .collect();
1297        crate::python::stage_program(&scripts[0].name, &pairs).into_bytes()
1298    };
1299    let mut bytes = Vec::with_capacity(body.len() + 4);
1300    // Ctrl-C stops whatever CircuitPython started on boot; MicroPython lands
1301    // at a prompt already, but the byte is harmless there.
1302    let interrupt = python.interrupt_sequence();
1303    if interrupt.is_empty() {
1304        bytes.push(0x03);
1305    } else {
1306        bytes.extend_from_slice(interrupt);
1307    }
1308    bytes.extend_from_slice(python.raw_paste_begin());
1309    bytes.extend_from_slice(&body);
1310    bytes.extend_from_slice(python.raw_paste_end());
1311    // The host side of the UART is a queue; a classic ESP32 with a small
1312    // receive FIFO drops a burst that is written all at once. Feeding it in
1313    // small slices and letting the chip run between them keeps the byte
1314    // stream intact without a wall-clock sleep.
1315    for chunk in bytes.chunks(16) {
1316        mcu.write_console_to(index, chunk);
1317        mcu.run_one(index, 1_000_000);
1318    }
1319}
1320
1321fn prepare(
1322    config: Config,
1323    dir: &Path,
1324    registry: Registry,
1325    circuit: Circuit,
1326) -> Result<Prepared, String> {
1327    // Every development board on the diagram is its own chip with its own
1328    // image; the diagram is what says how many there are.
1329    let instances: Vec<litz_diagram::PartInstance> = circuit
1330        .parts
1331        .iter()
1332        .filter(|part| {
1333            registry
1334                .get(&part.type_key)
1335                .and_then(|manifest| manifest.board.as_ref())
1336                .is_some()
1337        })
1338        .cloned()
1339        .collect();
1340    if instances.is_empty() {
1341        return Err("the diagram has no development board".into());
1342    }
1343
1344    // `[[board]]` names each instance. A project with one board keeps using
1345    // `[sim]`; the moment a second board appears there is no sensible default
1346    // for which image goes where, so both boards must be named.
1347    let sections: Vec<BoardSection> = if config.boards.is_empty() {
1348        if instances.len() != 1 {
1349            return Err(format!(
1350                "the diagram has {} development boards; give each one a [[board]] entry with its id and firmware",
1351                instances.len()
1352            ));
1353        }
1354        vec![BoardSection {
1355            id: instances[0].id.clone(),
1356            firmware: config.sim.firmware.clone(),
1357            bootloader: config.sim.bootloader.clone(),
1358            partition_table: config.sim.partition_table.clone(),
1359            rom: config.sim.rom.clone(),
1360            elf: config.sim.elf.clone(),
1361            runtime: Some(config.sim.runtime),
1362            script: config.sim.script.clone(),
1363            scripts: config.sim.scripts.clone(),
1364            flash_size: config.sim.flash_size.clone(),
1365            mac: config.sim.mac.clone(),
1366        }]
1367    } else {
1368        if config.sim.firmware.is_some() {
1369            return Err(
1370                "a project with [[board]] entries names firmware per board; remove [sim] firmware"
1371                    .into(),
1372            );
1373        }
1374        let mut sections = Vec::with_capacity(instances.len());
1375        for instance in &instances {
1376            let mut found: Vec<&BoardSection> = config
1377                .boards
1378                .iter()
1379                .filter(|section| section.id == instance.id)
1380                .collect();
1381            match found.len() {
1382                1 => sections.push(found.remove(0).clone()),
1383                0 => {
1384                    return Err(format!(
1385                        "board {:?} in diagram.json has no [[board]] entry; add `id = {:?}` to one",
1386                        instance.id, instance.id
1387                    ));
1388                }
1389                _ => {
1390                    return Err(format!("[[board]] names {:?} more than once", instance.id));
1391                }
1392            }
1393        }
1394        if let Some(unknown) = config
1395            .boards
1396            .iter()
1397            .find(|section| !instances.iter().any(|instance| instance.id == section.id))
1398        {
1399            return Err(format!(
1400                "[[board]] id {:?} is not a development board in diagram.json",
1401                unknown.id
1402            ));
1403        }
1404        sections
1405    };
1406
1407    let mut boards = Vec::with_capacity(sections.len());
1408    for (section, instance) in sections.iter().zip(&instances) {
1409        boards.push(prepare_board(&config, dir, &registry, instance, section)?);
1410    }
1411    Ok(Prepared {
1412        config,
1413        dir: dir.to_path_buf(),
1414        registry,
1415        circuit,
1416        boards,
1417    })
1418}
1419
1420/// Read one board's images and work out how they boot.
1421fn prepare_board(
1422    config: &Config,
1423    dir: &Path,
1424    registry: &Registry,
1425    instance: &litz_diagram::PartInstance,
1426    section: &BoardSection,
1427) -> Result<BoardPlan, String> {
1428    let manifest = registry
1429        .get(&instance.type_key)
1430        .expect("the caller filtered on boards")
1431        .clone();
1432    let info = manifest
1433        .board
1434        .as_ref()
1435        .expect("the caller filtered on boards");
1436    let chip = info.chip.as_deref();
1437    // A builtin chip is one the adapters carry; anything else must be a
1438    // `[board.simulator]` module, which brings its own boot code.
1439    if let Some(name) = chip
1440        && !is_builtin_chip(name)
1441    {
1442        return Err(format!(
1443            "board {:?}: chip {name:?} is not built in; name a wasm component under \
1444             [board.simulator] instead",
1445            instance.id
1446        ));
1447    }
1448
1449    let flash_size = section
1450        .flash_size
1451        .as_deref()
1452        .or(config.sim.flash_size.as_deref())
1453        .map(parse_size)
1454        .transpose()?
1455        .or_else(|| info.flash_size.as_deref().and_then(|s| parse_size(s).ok()))
1456        .unwrap_or(4 * 1024 * 1024);
1457
1458    // A wasm simulator carries its own boot code and may ship a program in
1459    // flash, so a project can run it with no firmware at all. A built-in chip
1460    // needs an image: there is nothing in the adapter to execute otherwise.
1461    let (firmware, layout) = match section.firmware.as_deref() {
1462        Some(rel) => {
1463            let path = dir.join(rel);
1464            let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
1465            let layout = image::detect(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
1466            (bytes, layout)
1467        }
1468        None if info.simulator.is_some() => (Vec::new(), FirmwareLayout::Application),
1469        None => {
1470            return Err(format!(
1471                "board {:?} has no firmware; give it `firmware = \"...\"`",
1472                instance.id
1473            ));
1474        }
1475    };
1476
1477    let bootloader_rel = section
1478        .bootloader
1479        .as_deref()
1480        .or(config.sim.bootloader.as_deref());
1481    let ptable_rel = section
1482        .partition_table
1483        .as_deref()
1484        .or(config.sim.partition_table.as_deref());
1485    // A merged image already carries the bootloader and partition table; the
1486    // separate files would be written a second time, at different offsets.
1487    if layout == FirmwareLayout::Merged && (bootloader_rel.is_some() || ptable_rel.is_some()) {
1488        return Err(format!(
1489            "board {:?}: the firmware is a merged image (bootloader at 0x0, \
1490             partition table at 0x8000, application at 0x10000); remove \
1491             `bootloader` and `partition_table`",
1492            instance.id
1493        ));
1494    }
1495    let bootloader = read_optional(dir, bootloader_rel)?;
1496    let partition_table = read_optional(dir, ptable_rel)?;
1497
1498    let elf_rel = section.elf.as_deref().or(config.sim.elf.as_deref());
1499    let elf = match elf_rel {
1500        Some(rel) => {
1501            let path = dir.join(rel);
1502            Some(std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?)
1503        }
1504        None => None,
1505    };
1506
1507    let runtime = section.runtime.unwrap_or(config.sim.runtime);
1508    let script_rel = section.script.as_deref().or(config.sim.script.as_deref());
1509    let staged = if section.scripts.is_empty() {
1510        &config.sim.scripts
1511    } else {
1512        &section.scripts
1513    };
1514    let scripts = match runtime {
1515        Runtime::Micropython | Runtime::CircuitPython => {
1516            let mut scripts = Vec::new();
1517            if let Some(rel) = script_rel {
1518                scripts.push(read_staged(dir, rel)?);
1519            }
1520            for spec in staged {
1521                // `name = path` stages a project file under a different name;
1522                // a bare path keeps its own relative path on the device.
1523                let (name, rel) = match spec.split_once('=') {
1524                    Some((name, path)) => (name.trim(), path.trim()),
1525                    None => (spec.trim(), spec.trim()),
1526                };
1527                if scripts.iter().any(|script| script.name == name) {
1528                    return Err(format!(
1529                        "board {:?}: two scripts would be staged as {name:?}",
1530                        instance.id
1531                    ));
1532                }
1533                let mut script = read_staged(dir, rel)?;
1534                script.name = staged_name(name)?;
1535                scripts.push(script);
1536            }
1537            let total: usize = scripts.iter().map(|script| script.bytes.len()).sum();
1538            if total > MAX_SCRIPT {
1539                return Err(format!(
1540                    "board {:?}: the staged scripts total {total} bytes; a Python raw \
1541                     paste is limited to {MAX_SCRIPT} bytes",
1542                    instance.id
1543                ));
1544            }
1545            // CircuitPython boots `code.py` (or `main.py`); whichever the
1546            // project staged as its entry runs first, whatever order it was
1547            // written in.
1548            if runtime == Runtime::CircuitPython {
1549                if let Some(entry) = scripts
1550                    .iter()
1551                    .position(|script| matches!(script.name.as_str(), "code.py" | "main.py"))
1552                {
1553                    let entry = scripts.remove(entry);
1554                    scripts.insert(0, entry);
1555                } else {
1556                    return Err(format!(
1557                        "board {:?}: CircuitPython needs code.py or main.py among its scripts",
1558                        instance.id
1559                    ));
1560                }
1561            }
1562            scripts
1563        }
1564        Runtime::Native => {
1565            if script_rel.is_some() || !staged.is_empty() {
1566                return Err(format!(
1567                    "board {:?}: script/scripts need runtime = \"micropython\" or \
1568                     \"circuitpython\"; a native firmware has no REPL to paste them into",
1569                    instance.id
1570                ));
1571            }
1572            Vec::new()
1573        }
1574    };
1575
1576    // A plain application image boots from a direct jump and never touches the
1577    // mask ROM. A merged image does: its first bytes are the bootloader, which
1578    // only the ROM knows how to start.
1579    let needs_rom = layout == FirmwareLayout::Merged || bootloader.is_some();
1580    let rom_rel = section.rom.as_deref().or(config.sim.rom.as_deref());
1581    let rom_path = rom_rel.map(PathBuf::from).or_else(|| {
1582        chip.and_then(rom_name)
1583            .and_then(|file| std::env::var_os("LITZ_ROM_DIR").map(|d| PathBuf::from(d).join(file)))
1584    });
1585    let rom = match rom_path {
1586        Some(path) => std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?,
1587        None if needs_rom => {
1588            return Err(format!(
1589                "board {:?}: {}; set `rom` in its [[board]] entry or in [sim], or LITZ_ROM_DIR",
1590                instance.id,
1591                if layout == FirmwareLayout::Merged {
1592                    "a merged image runs from the mask ROM"
1593                } else {
1594                    "a bootloader needs the mask ROM"
1595                }
1596            ));
1597        }
1598        None => Vec::new(),
1599    };
1600
1601    // The image name is the cheapest hint; a stock image whose file is named
1602    // generically still announces itself in its banner bytes.
1603    let python = crate::python::detect(runtime, section.firmware.as_deref().unwrap_or(""));
1604    let python = if python == crate::python::PythonRuntime::MicroPython {
1605        crate::python::detect_bytes(runtime, &firmware)
1606    } else {
1607        python
1608    };
1609    Ok(BoardPlan {
1610        id: instance.id.clone(),
1611        manifest,
1612        flash_size,
1613        rom,
1614        firmware,
1615        elf,
1616        layout,
1617        bootloader,
1618        partition_table,
1619        runtime,
1620        python,
1621        scripts,
1622        mac: parse_mac(section.mac.as_deref().or(config.sim.mac.as_deref())),
1623    })
1624}
1625
1626/// Check `litz.lock` against what this run would use, or write it when there
1627/// is none yet. A changed catalog or firmware is refused: the whole point is
1628/// that a green run can be repeated, and silently running a different
1629/// simulation would make the record a lie.
1630fn enforce_lock(prepared: &Prepared, update: bool) -> Result<(), String> {
1631    // One board records the same four hashes as before. Several boards have no
1632    // single `[firmware]` to describe them, so their images are folded into the
1633    // firmware hash in board order, each with its id and length; the run is
1634    // still repeatable when every byte that booted is in that hash.
1635    let (firmware, rom, bootloader, ptable) = if prepared.boards.len() == 1 {
1636        let plan = &prepared.boards[0];
1637        (
1638            Some(plan.firmware.clone()),
1639            (!plan.rom.is_empty()).then(|| plan.rom.clone()),
1640            plan.bootloader.clone(),
1641            plan.partition_table.clone(),
1642        )
1643    } else {
1644        let mut folded = Vec::new();
1645        for plan in &prepared.boards {
1646            folded.extend_from_slice(plan.id.as_bytes());
1647            folded.push(0);
1648            for image in [&plan.firmware, &plan.rom] {
1649                folded.extend_from_slice(&(image.len() as u64).to_le_bytes());
1650                folded.extend_from_slice(image);
1651            }
1652        }
1653        (Some(folded), None, None, None)
1654    };
1655    // Only the manifests this diagram actually expands go in the lock: an
1656    // entry the circuit never names cannot change the result, and hashing it
1657    // would rewrite every lock in the world when an unrelated part is added.
1658    let flat =
1659        FlatBoard::build(&prepared.circuit, &prepared.registry).map_err(|e| e.to_string())?;
1660    // The board itself is consumed by expansion, so its own manifest has to
1661    // come from the diagram rather than from the flattened part list.
1662    let used: std::collections::BTreeSet<&str> = prepared
1663        .circuit
1664        .parts
1665        .iter()
1666        .map(|part| part.type_key.as_str())
1667        .chain(flat.parts.iter().map(|part| part.type_key.as_str()))
1668        .collect();
1669    let manifests: Vec<_> = prepared
1670        .registry
1671        .manifest_texts()
1672        .into_iter()
1673        .filter(|(key, _, _)| used.contains(key.as_str()))
1674        .collect();
1675    let actual = Lock::from_run(
1676        &manifests,
1677        firmware.as_deref(),
1678        rom.as_deref(),
1679        bootloader.as_deref(),
1680        ptable.as_deref(),
1681    );
1682    let path = prepared.dir.join("litz.lock");
1683    if update || !path.exists() {
1684        actual.write(&path)?;
1685        eprintln!("litz: wrote {}", path.display());
1686        return Ok(());
1687    }
1688    let installed = Lock::load(&path)?;
1689    installed.check(&actual)
1690}
1691
1692/// The ROM ELF esp32sim expects for a builtin chip; `None` when the name is
1693/// not one of the adapters this build carries.
1694/// Chips an in-tree adapter can build, whether or not they need a mask ROM.
1695pub(crate) fn is_builtin_chip(chip: &str) -> bool {
1696    matches!(
1697        chip,
1698        "esp32"
1699            | "esp32c3"
1700            | "esp32c6"
1701            | "esp32s3"
1702            | "esp32p4"
1703            | "esp32s31"
1704            | "atmega328p"
1705            | "atmega2560"
1706            | "atmega32u4"
1707            | "attiny85"
1708            | "rp2040"
1709            | "rp2350"
1710            | "stc89c52"
1711            | "ch32v003"
1712    )
1713}
1714
1715fn rom_name(chip: &str) -> Option<&'static str> {
1716    Some(match chip {
1717        "esp32" => "esp32_rev300_rom.elf",
1718        "esp32c3" => "esp32c3_rev3_rom.elf",
1719        "esp32c6" => "esp32c6_rev0_rom.elf",
1720        "esp32s3" => "esp32s3_rev0_rom.elf",
1721        "esp32p4" => "esp32p4_rev0_rom.elf",
1722        "esp32s31" => "esp32s31_rev0_rom.elf",
1723        _ => return None,
1724    })
1725}
1726
1727/// The radio network for this run: `--wifi` wins over `[sim.wifi]`, and a
1728/// project with neither gets no network at all.
1729///
1730/// The router's default services are HTTP on port 80 and a TCP echo on 7, so a
1731/// firmware that joins the access point has something to talk to without any
1732/// further configuration; a project that lists `[[sim.wifi.service]]` entries
1733/// replaces the defaults, and `[sim.wifi] services = false` leaves a router
1734/// that refuses every connection.
1735fn network_config(options: &Options, config: &Config) -> Result<Option<NetworkConfig>, String> {
1736    let spec = match (&options.wifi, &config.sim.wifi) {
1737        (Some(spec), _) => WifiSpec::Spec(spec.clone()),
1738        (None, Some(spec)) => spec.clone(),
1739        (None, None) => return Ok(None),
1740    };
1741
1742    let mut network = match &spec {
1743        WifiSpec::Spec(raw) => NetworkConfig {
1744            access_points: vec![access_point_from_spec(raw)?],
1745            ..NetworkConfig::default()
1746        },
1747        WifiSpec::Table(table) => {
1748            let mut network = NetworkConfig {
1749                access_points: vec![access_point(
1750                    &table.ssid,
1751                    table.psk.as_deref(),
1752                    table.channel,
1753                    table.bssid.as_deref().map(parse_bssid).transpose()?,
1754                    table.epoch,
1755                )],
1756                nearby: table
1757                    .nearby
1758                    .iter()
1759                    .map(|nearby| nearby_from_spec(nearby))
1760                    .collect::<Result<Vec<_>, String>>()?,
1761                resolve_unknown: table.resolve_unknown,
1762                ..NetworkConfig::default()
1763            };
1764            for extra in &table.extra_aps {
1765                network.access_points.push(access_point(
1766                    &extra.ssid,
1767                    extra.psk.as_deref(),
1768                    extra.channel,
1769                    extra.bssid.as_deref().map(parse_bssid).transpose()?,
1770                    extra.epoch,
1771                ));
1772            }
1773            for (name, address) in &table.names {
1774                let address: std::net::Ipv4Addr = address.parse().map_err(|_| {
1775                    format!("[sim.wifi] names.{name}: {address:?} is not an IPv4 address")
1776                })?;
1777                network.names.insert(name.clone(), address.octets());
1778            }
1779            network
1780        }
1781    };
1782
1783    match &spec {
1784        WifiSpec::Spec(_) => {
1785            network = network.with_default_services();
1786        }
1787        WifiSpec::Table(table) if table.services.is_empty() => {
1788            if table.services_default {
1789                network = network.with_default_services();
1790            }
1791        }
1792        WifiSpec::Table(table) => {
1793            for service in &table.services {
1794                let inner = if service.mqtt {
1795                    Service::mqtt(service.port)
1796                } else if service.websocket {
1797                    Service::websocket(service.port)
1798                } else if service.echo {
1799                    if service.udp {
1800                        Service::UdpEcho { port: service.port }
1801                    } else {
1802                        Service::TcpEcho { port: service.port }
1803                    }
1804                } else {
1805                    let reply = service.reply.as_ref().ok_or_else(|| {
1806                        format!(
1807                            "[sim.wifi.service] port {}: give `reply = \"...\"`, `echo = true`, \
1808                             `websocket = true` or `mqtt = true`",
1809                            service.port
1810                        )
1811                    })?;
1812                    Service::Tcp {
1813                        port: service.port,
1814                        reply: reply.as_bytes().to_vec(),
1815                        after_request: service.wait,
1816                    }
1817                };
1818                network = network.with_service(if service.tls {
1819                    Service::tls(service.port, inner)
1820                } else {
1821                    inner
1822                });
1823            }
1824        }
1825    }
1826    Ok(Some(network))
1827}
1828
1829fn access_point(
1830    ssid: &str,
1831    psk: Option<&str>,
1832    channel: Option<u8>,
1833    bssid: Option<[u8; 6]>,
1834    epoch: Option<u64>,
1835) -> AccessPoint {
1836    AccessPoint {
1837        ssid: ssid.to_string(),
1838        psk: psk.map(str::to_string),
1839        channel: channel.unwrap_or(6),
1840        bssid,
1841        epoch_s: epoch,
1842    }
1843}
1844
1845/// An access point in the short `--wifi` syntax: `ssid=NAME[,psk=PASS]
1846/// [,channel=N][,bssid=..][,epoch=S]`.
1847fn access_point_from_spec(spec: &str) -> Result<AccessPoint, String> {
1848    let mut ssid = None;
1849    let mut psk = None;
1850    let mut channel = None;
1851    let mut bssid = None;
1852    let mut epoch = None;
1853    for entry in spec.split(',').filter(|entry| !entry.is_empty()) {
1854        let (key, value) = entry
1855            .split_once('=')
1856            .ok_or_else(|| format!("invalid Wi-Fi option {entry:?}: expected key=value"))?;
1857        match key {
1858            "ssid" => ssid = Some(value.to_string()),
1859            "psk" | "password" | "pass" => psk = Some(value.to_string()),
1860            "channel" | "chan" | "ch" => {
1861                channel = Some(value.parse::<u8>().map_err(|_| {
1862                    format!("invalid Wi-Fi channel {value:?}: expected 1 through 14")
1863                })?)
1864            }
1865            "bssid" => bssid = Some(parse_bssid(value)?),
1866            "epoch" => {
1867                epoch = Some(value.parse::<u64>().map_err(|_| {
1868                    format!("invalid Wi-Fi epoch {value:?}: expected seconds since 1970")
1869                })?)
1870            }
1871            other => return Err(format!("unknown Wi-Fi option {other:?}")),
1872        }
1873    }
1874    let ssid = ssid.ok_or_else(|| format!("invalid Wi-Fi network {spec:?}: no ssid"))?;
1875    Ok(access_point(&ssid, psk.as_deref(), channel, bssid, epoch))
1876}
1877
1878fn nearby_from_spec(spec: &str) -> Result<NearbyNetwork, String> {
1879    let mut network = NearbyNetwork::new("");
1880    for entry in spec.split(',').filter(|entry| !entry.is_empty()) {
1881        let (key, value) = entry.split_once('=').ok_or_else(|| {
1882            format!("invalid nearby-network option {entry:?}: expected key=value")
1883        })?;
1884        match key {
1885            "ssid" => network.ssid = value.to_string(),
1886            "channel" | "chan" | "ch" => {
1887                network.channel = value.parse().map_err(|_| {
1888                    format!("invalid nearby-network channel {value:?}: expected 1 through 14")
1889                })?
1890            }
1891            "rssi" => {
1892                network.rssi = value.parse().map_err(|_| {
1893                    format!("invalid nearby-network rssi {value:?}: expected -128 through 127 dBm")
1894                })?
1895            }
1896            "secure" => {
1897                network.secure = match value {
1898                    "1" | "true" | "yes" => true,
1899                    "0" | "false" | "no" => false,
1900                    _ => {
1901                        return Err(format!(
1902                            "invalid nearby-network secure {value:?}: expected 0 or 1"
1903                        ));
1904                    }
1905                }
1906            }
1907            other => return Err(format!("unknown nearby-network option {other:?}")),
1908        }
1909    }
1910    if network.ssid.is_empty() {
1911        return Err(format!("invalid nearby network {spec:?}: no ssid"));
1912    }
1913    Ok(network)
1914}
1915
1916fn parse_bssid(text: &str) -> Result<[u8; 6], String> {
1917    let octets: Vec<u8> = text
1918        .split(':')
1919        .map(|octet| {
1920            u8::from_str_radix(octet, 16)
1921                .map_err(|_| format!("invalid BSSID {text:?}: expected six hex octets"))
1922        })
1923        .collect::<Result<_, _>>()?;
1924    octets
1925        .try_into()
1926        .map_err(|_| format!("invalid BSSID {text:?}: expected six hex octets"))
1927}
1928
1929/// Build the boards, load each image and start every chip. A test and a
1930/// scenario differ only in what they do once it is running.
1931///
1932/// The backend is chosen by each board's manifest: a builtin `chip` is an
1933/// adapter this build carries, a `[board.simulator]` module is a wasm
1934/// component. Everything after this point is written against [`Fleet`], so the
1935/// backends are interchangeable and a diagram may run more than one.
1936fn boot(prepared: &Prepared, options: &Options) -> Result<Booted, String> {
1937    let flat =
1938        FlatBoard::build(&prepared.circuit, &prepared.registry).map_err(|e| e.to_string())?;
1939    let parts: Vec<String> = flat.parts.iter().map(|p| p.id.clone()).collect();
1940    let mut board = Board::new(flat)
1941        .map_err(|e| e.to_string())?
1942        .with_analog(options.analog || prepared.config.sim.analog);
1943    // Probes are resolved before any time passes: a point that is not in the
1944    // diagram is a configuration error, not a channel that silently stays
1945    // empty. The project lists them, and a run may add more.
1946    for probe in &prepared.config.probes {
1947        let name = probe.name.as_deref().unwrap_or(probe.point.as_str());
1948        board.add_probe(name, &probe.point)?;
1949    }
1950    for spec in &options.probes {
1951        // `--probe sck=esp:GPIO2` names the channel and the point; a bare
1952        // point keeps its own name, as the project's probe entries do.
1953        let (name, point) = match spec.split_once('=') {
1954            Some((name, point)) => (name.trim(), point.trim()),
1955            None => (spec.as_str(), spec.as_str()),
1956        };
1957        board.add_probe(name, point)?;
1958    }
1959    // A decoder reads channels, so every name it mentions must already be a
1960    // probe. Checking here keeps a typo from producing an empty report after
1961    // a full run.
1962    for spec in prepared.config.decodes.iter().chain(options.decodes.iter()) {
1963        crate::decode::check(spec, board.probes())?;
1964    }
1965    // A `litz-wifi-router` part and a `litz-ble-beacon` part belong to the
1966    // board, so every chip on it hears the same network and the same
1967    // advertisers; `[sim.wifi]` or `--wifi` replaces the network for one run.
1968    let mut network =
1969        network_config(options, &prepared.config)?.or_else(|| board.network().cloned());
1970    let capture = if options.pcap.is_some() {
1971        let Some(config) = network.as_mut() else {
1972            return Err(
1973                "--pcap needs a simulated network: add a `litz-wifi-router` part or [sim.wifi]"
1974                    .into(),
1975            );
1976        };
1977        let capture = std::rc::Rc::new(std::cell::RefCell::new(litz_net::capture::Capture::new([
1978            10, 0, 2, 15,
1979        ])));
1980        config.capture = Some(std::rc::Rc::clone(&capture));
1981        Some(capture)
1982    } else {
1983        None
1984    };
1985    if let Some(config) = &network {
1986        board.set_network(config.clone());
1987    }
1988    let bluetooth = board.bluetooth().cloned();
1989    let shared = std::rc::Rc::new(std::cell::RefCell::new(board));
1990
1991    let mut chips = Vec::with_capacity(prepared.boards.len());
1992    for (index, plan) in prepared.boards.iter().enumerate() {
1993        let chip = build_chip(
1994            prepared,
1995            plan,
1996            std::rc::Rc::clone(&shared),
1997            index as u16,
1998            network.as_ref(),
1999            bluetooth.as_ref(),
2000        )?;
2001        chips.push(boot_chip(chip, plan)?);
2002    }
2003
2004    // The radio seams belong to the station, so they are asked of the first
2005    // board; a diagram with several Wi-Fi chips records the first one.
2006    if let Some(path) = &options.pcap_air
2007        && let Some(chip) = chips.first_mut()
2008    {
2009        chip.start_air_capture(path)?;
2010    }
2011    if let Some(path) = &options.pcap_eth
2012        && let Some(chip) = chips.first_mut()
2013    {
2014        chip.start_ethernet_capture(path)?;
2015    }
2016    if options.host_network || !options.host_forwards.is_empty() {
2017        let chip = chips
2018            .first_mut()
2019            .ok_or_else(|| "--net needs a board".to_string())?;
2020        chip.attach_host_gateway(&options.host_forwards)?;
2021    }
2022
2023    // A debugger attaches to a booted chip, so flash and symbols are already
2024    // in place when it reads memory or sets a breakpoint. A session owns its
2025    // chip's clock until the client disconnects, so one board is served; the
2026    // request says which, or names the first board that has a debug target.
2027    if let Some(request) = &options.gdb {
2028        let index = match &request.board {
2029            Some(id) => find_board(&prepared.boards, id, "--gdb")?,
2030            None => chips
2031                .iter_mut()
2032                .position(|chip| chip.debug().is_some())
2033                .ok_or_else(|| {
2034                    "--gdb needs a backend with a GDB target; a wasm MCU and the AVR core have none"
2035                        .to_string()
2036                })?,
2037        };
2038        let plan = &prepared.boards[index];
2039        let chip = &mut chips[index];
2040        let debug = chip.debug().ok_or_else(|| {
2041            format!(
2042                "--gdb: board {:?} has no GDB target; a wasm MCU and the AVR core have none",
2043                plan.id
2044            )
2045        })?;
2046        eprintln!("litz: gdb serves board {:?}", plan.id);
2047        debug.serve(request.port)?;
2048    }
2049    Ok(Booted {
2050        fleet: Fleet::new(chips),
2051        parts,
2052        board: shared,
2053        capture,
2054    })
2055}
2056
2057/// A booted circuit: the chips that run it, the part ids a report names, and
2058/// the board they all share. The board handle is what answers probe questions
2059/// once the chips own the run loop.
2060struct Booted {
2061    fleet: Fleet,
2062    parts: Vec<String>,
2063    board: std::rc::Rc<std::cell::RefCell<Board>>,
2064    /// The packet capture the run filled, when `--pcap` asked for one.
2065    capture: Option<std::rc::Rc<std::cell::RefCell<litz_net::capture::Capture>>>,
2066}
2067
2068/// The board a flag names, by its `diagram.json` instance id. The error lists
2069/// the ids that exist so a typo is answered in the same line it is reported.
2070fn find_board(boards: &[BoardPlan], id: &str, flag: &str) -> Result<usize, String> {
2071    boards.iter().position(|plan| plan.id == id).ok_or_else(|| {
2072        format!(
2073            "{flag} names board {id:?}; diagram.json has {}",
2074            boards
2075                .iter()
2076                .map(|plan| plan.id.as_str())
2077                .collect::<Vec<_>>()
2078                .join(", ")
2079        )
2080    })
2081}
2082
2083/// Which board a touch targets. Wokwi names the board in `part-id`; the older
2084/// `board` key still wins when both are present. A part id that is not a board
2085/// is ignored, so a single-board project can write either.
2086fn touch_board(
2087    prepared: &Prepared,
2088    board: &Option<String>,
2089    part: &Option<String>,
2090    flag: &str,
2091) -> Result<Option<usize>, String> {
2092    if let Some(id) = board {
2093        return find_board(&prepared.boards, id, flag).map(Some);
2094    }
2095    if let Some(part) = part
2096        && let Some(index) = prepared.boards.iter().position(|plan| plan.id == *part)
2097    {
2098        return Ok(Some(index));
2099    }
2100    Ok(None)
2101}
2102
2103/// One board's chip, attached to the shared board at its own index.
2104fn build_chip(
2105    prepared: &Prepared,
2106    plan: &BoardPlan,
2107    board: std::rc::Rc<std::cell::RefCell<Board>>,
2108    index: u16,
2109    network: Option<&NetworkConfig>,
2110    bluetooth: Option<&litz_ble::BleConfig>,
2111) -> Result<Box<dyn Chip>, String> {
2112    let info = plan
2113        .manifest
2114        .board
2115        .as_ref()
2116        .expect("prepare checked it is a board");
2117    #[cfg(not(target_family = "wasm"))]
2118    if let Some(simulator) = &info.simulator {
2119        let module = module_bytes(prepared, &plan.manifest, &simulator.module)?;
2120        return Ok(Box::new(
2121            WasmChip::from_bytes_with_abi(&module, &simulator.module, &simulator.abi)?
2122                .with_shared_board(board, index),
2123        ));
2124    }
2125    #[cfg(target_family = "wasm")]
2126    if info.simulator.is_some() {
2127        let _ = prepared;
2128        return Err(
2129            "a wasm guest chip cannot run inside the browser build; only the builtin chips \
2130             are compiled there"
2131                .into(),
2132        );
2133    }
2134    let name = info.chip.as_deref().unwrap_or("esp32c3");
2135    let mut chip = builtin_chip(
2136        name,
2137        plan.mac,
2138        plan.flash_size,
2139        board,
2140        index,
2141        Attachments {
2142            network,
2143            bluetooth,
2144            elf: plan.elf.as_deref(),
2145            ble_controller: plan.python == crate::python::PythonRuntime::CircuitPython,
2146        },
2147    )?;
2148    // A board whose manifest declares PSRAM gets the amount the chip's own
2149    // SocBus supports; the flag is the board's, the size is the chip's.
2150    if info.psram {
2151        chip.set_psram_size(4 << 20)?;
2152    }
2153    Ok(chip)
2154}
2155
2156/// Load the plan's images and start the chip.
2157fn boot_chip(mut mcu: Box<dyn Chip>, plan: &BoardPlan) -> Result<Box<dyn Chip>, String> {
2158    if !plan.rom.is_empty() {
2159        mcu.load_image(ImageKind::Rom, 0, &plan.rom)?;
2160    }
2161    if plan.firmware.is_empty() && plan.bootloader.is_none() {
2162        // A board with no image boots whatever its own simulator carries.
2163        mcu.boot()?;
2164        return Ok(mcu);
2165    }
2166    let flash = mcu.info().flash;
2167    match plan.layout {
2168        // The whole file goes in at the bootloader offset and `Chip::boot`
2169        // lets the ROM start it; the bootloader then finds the partition table
2170        // and application inside the same bytes. `flash.bootloader` is 0 on
2171        // the RISC-V parts whose official images use this layout.
2172        FirmwareLayout::Merged => {
2173            mcu.load_image(ImageKind::Bootloader, flash.bootloader, &plan.firmware)?;
2174        }
2175        FirmwareLayout::Application => match (&plan.bootloader, &plan.partition_table) {
2176            (Some(bootloader), Some(ptable)) => {
2177                mcu.load_image(ImageKind::Bootloader, flash.bootloader, bootloader)?;
2178                mcu.load_image(ImageKind::PartitionTable, flash.partition_table, ptable)?;
2179                mcu.load_image(ImageKind::Firmware, flash.app, &plan.firmware)?;
2180            }
2181            (None, None) => {
2182                mcu.load_image(ImageKind::Firmware, flash.app, &plan.firmware)?;
2183            }
2184            // A bootloader finds the application through the partition table,
2185            // so one without the other is a manifest mistake, not a fallback.
2186            _ => {
2187                return Err(format!(
2188                    "board {:?}: bootloader and partition_table go together; give both or neither",
2189                    plan.id
2190                ));
2191            }
2192        },
2193    }
2194    mcu.boot()?;
2195    Ok(mcu)
2196}
2197
2198/// The chips one diagram runs, in board order.
2199///
2200/// A single-board project is a fleet of one, so the run loop has one shape.
2201/// Board-wide questions — part state, conflicts, a pressed part — are answered
2202/// by the first chip, which sees the same board as the rest. Chip questions —
2203/// run, console, time — are asked of every chip, and their consoles are merged
2204/// in board order at each chunk boundary.
2205struct Fleet {
2206    chips: Vec<Box<dyn Chip>>,
2207    /// Each chip's console since the run began, so a MicroPython prompt can be
2208    /// found on the board that printed it.
2209    console: Vec<String>,
2210    /// How far each console has been handed out.
2211    read: Vec<usize>,
2212    /// How each chip last stopped, which is what tells a finished board from a
2213    /// slow one when the frontier is computed.
2214    stops: Vec<Stop>,
2215}
2216
2217impl Fleet {
2218    fn new(chips: Vec<Box<dyn Chip>>) -> Self {
2219        let count = chips.len();
2220        Self {
2221            chips,
2222            console: vec![String::new(); count],
2223            read: vec![0; count],
2224            stops: vec![Stop::Budget; count],
2225        }
2226    }
2227
2228    /// Advance every chip by one scheduling batch. The returned stop is the
2229    /// most significant one any chip reported, so a trap on either board ends
2230    /// the run.
2231    fn run(&mut self, steps: u64) -> litz_board::chip::RunResult {
2232        let mut cycles = 0;
2233        let mut stop = Stop::Budget;
2234        for (index, chip) in self.chips.iter_mut().enumerate() {
2235            let result = chip.run(steps);
2236            cycles = cycles.max(result.cycles);
2237            self.stops[index] = result.stop;
2238            let chunk = chip.take_console();
2239            if !chunk.is_empty() {
2240                self.console[index].push_str(&String::from_utf8_lossy(&chunk));
2241            }
2242            if stop_rank(result.stop) > stop_rank(stop) {
2243                stop = result.stop;
2244            }
2245        }
2246        litz_board::chip::RunResult { cycles, stop }
2247    }
2248
2249    /// One chip's next batch, for the paste handshake, which talks to the
2250    /// board whose REPL is ready and lets the others keep their own pace.
2251    fn run_one(&mut self, index: usize, steps: u64) {
2252        let result = self.chips[index].run(steps);
2253        self.stops[index] = result.stop;
2254        let chunk = self.chips[index].take_console();
2255        if !chunk.is_empty() {
2256            self.console[index].push_str(&String::from_utf8_lossy(&chunk));
2257        }
2258    }
2259
2260    /// Console bytes produced since the last call, merged in board order.
2261    /// Deliver a touch to one board (or the first), through its controller.
2262    fn touch(&mut self, board: Option<usize>, x: u16, y: u16, down: bool) -> Result<(), String> {
2263        let index = board.unwrap_or(0);
2264        match self.chips.get_mut(index) {
2265            Some(chip) => chip.touch(x, y, down),
2266            None => Err(format!("the diagram has no board {index}")),
2267        }
2268    }
2269
2270    /// The first chip's flash, as the run left it.
2271    fn flash_image(&self) -> Option<Vec<u8>> {
2272        self.chips.first()?.flash_image()
2273    }
2274
2275    /// Ask the first chip for the firmware's free heap.
2276    fn sample_heap(&mut self) -> Result<u32, String> {
2277        match self.chips.first_mut() {
2278            Some(chip) => chip.sample_heap(),
2279            None => Err("the diagram has no chip to sample".into()),
2280        }
2281    }
2282
2283    fn take_console(&mut self) -> Vec<u8> {
2284        let mut out = Vec::new();
2285        for (index, text) in self.console.iter().enumerate() {
2286            if self.read[index] < text.len() {
2287                out.extend_from_slice(&text.as_bytes()[self.read[index]..]);
2288                self.read[index] = text.len();
2289            }
2290        }
2291        out
2292    }
2293
2294    /// One board's console so far.
2295    fn console_text(&self, index: usize) -> &str {
2296        &self.console[index]
2297    }
2298
2299    fn write_console_to(&mut self, index: usize, bytes: &[u8]) {
2300        self.chips[index].write_console(bytes);
2301    }
2302
2303    /// The time every running chip has reached. A board that halted or
2304    /// trapped is finished and does not hold the others back.
2305    /// Whether every board has stopped for good. A halted core makes no more
2306    /// simulated time, so waiting for the timeout after this would wait for
2307    /// ever on a clock that never moves.
2308    fn finished(&self) -> bool {
2309        self.stops
2310            .iter()
2311            .all(|stop| matches!(stop, Stop::Halted | Stop::Reset | Stop::Trap))
2312    }
2313
2314    fn frontier_ns(&self) -> u64 {
2315        let mut frontier: Option<u64> = None;
2316        let mut latest = 0;
2317        for (index, chip) in self.chips.iter().enumerate() {
2318            let now = (chip.seconds() * 1e9) as u64;
2319            latest = latest.max(now);
2320            if matches!(self.stops[index], Stop::Halted | Stop::Reset | Stop::Trap) {
2321                continue;
2322            }
2323            frontier = Some(frontier.map_or(now, |front| front.min(now)));
2324        }
2325        frontier.unwrap_or(latest)
2326    }
2327
2328    fn seconds(&self) -> f64 {
2329        self.chips
2330            .iter()
2331            .map(|chip| chip.seconds())
2332            .fold(0.0, f64::max)
2333    }
2334
2335    /// Queue host actions on one board's chip. `board` is the index in
2336    /// [`Prepared::boards`], the same order the chips were built in.
2337    fn schedule(&mut self, board: usize, inputs: Vec<Input>) -> Result<(), String> {
2338        match self.chips.get_mut(board) {
2339            Some(chip) => chip.schedule(inputs),
2340            None => Err(format!("there is no board {board} to schedule input on")),
2341        }
2342    }
2343
2344    fn state(&self, part: &str) -> Option<PartState> {
2345        self.chips.iter().find_map(|chip| chip.state(part))
2346    }
2347
2348    fn press(&mut self, part: &str, pressed: bool) -> bool {
2349        self.chips.iter_mut().any(|chip| chip.press(part, pressed))
2350    }
2351
2352    fn set_control(&mut self, part: &str, value: u16) -> bool {
2353        // Part ids are unique to the circuit, so only the board that holds the
2354        // part answers; the rest report that they have no such control.
2355        self.chips
2356            .iter_mut()
2357            .any(|chip| chip.set_control(part, value))
2358    }
2359
2360    fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
2361        // A board instance is a control target of its own: `set-control` on a
2362        // board id throws that board's power switch, which is how a scenario
2363        // lets one board power another.
2364        self.chips
2365            .iter_mut()
2366            .any(|chip| chip.set_named_control(part, name, value))
2367    }
2368
2369    fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
2370        self.chips
2371            .iter()
2372            .find_map(|chip| chip.part_pin_level(part, pin))
2373    }
2374
2375    fn gpio_level(&self, board: usize, gpio: u8) -> Option<Level> {
2376        self.chips.get(board)?.gpio_level(gpio)
2377    }
2378
2379    fn conflicts(&self) -> Vec<litz_board::Conflict> {
2380        self.chips
2381            .first()
2382            .map(|chip| chip.conflicts())
2383            .unwrap_or_default()
2384    }
2385
2386    fn fault(&self) -> Option<String> {
2387        self.chips.iter().find_map(|chip| chip.fault())
2388    }
2389
2390    /// Host bytes into one board's console. Board 0 when no board was asked
2391    /// for.
2392    fn write_console_on(&mut self, board: usize, bytes: &[u8]) {
2393        if let Some(chip) = self.chips.get_mut(board) {
2394            chip.write_console(bytes);
2395        }
2396    }
2397
2398    /// Capture `board`'s display, or — when `board` is `None` — the first
2399    /// board that has one. A chip without a framebuffer says so, and the
2400    /// search moves on rather than failing a run because the first board has
2401    /// no panel.
2402    fn save_display(&mut self, board: Option<usize>, path: &Path) -> Result<(), String> {
2403        let Some(board) = board else {
2404            let mut refusal = None;
2405            for chip in &mut self.chips {
2406                match chip.save_display(path) {
2407                    Ok(()) => return Ok(()),
2408                    Err(e) => refusal.get_or_insert(e),
2409                };
2410            }
2411            return Err(refusal.unwrap_or_else(|| "the diagram has no chip to capture".into()));
2412        };
2413        match self.chips.get_mut(board) {
2414            Some(chip) => chip.save_display(path),
2415            None => Err(format!("there is no board {board} to capture")),
2416        }
2417    }
2418
2419    /// Capture one display part by id. The first chip that knows the part
2420    /// wins, which is the board the diagram wired it to.
2421    fn save_part_display(&mut self, part: &str, path: &Path) -> Result<(), String> {
2422        let mut refusal = None;
2423        for chip in &mut self.chips {
2424            match chip.save_part_display(part, path) {
2425                Ok(()) => return Ok(()),
2426                Err(error) => refusal.get_or_insert(error),
2427            };
2428        }
2429        Err(refusal.unwrap_or_else(|| format!("no part {part:?} has a framebuffer")))
2430    }
2431
2432    fn report(&mut self) -> Vec<String> {
2433        self.chips
2434            .iter_mut()
2435            .flat_map(|chip| chip.report())
2436            .collect()
2437    }
2438
2439    fn enable_coverage(&mut self) {
2440        for chip in &mut self.chips {
2441            chip.enable_coverage();
2442        }
2443    }
2444
2445    fn start_trace(&mut self) {
2446        if let Some(chip) = self.chips.first_mut() {
2447            chip.start_trace();
2448        }
2449    }
2450
2451    fn break_at(&mut self, pc: u32) {
2452        for chip in &mut self.chips {
2453            chip.break_at(pc);
2454        }
2455    }
2456
2457    fn vcd(&self) -> String {
2458        self.chips
2459            .first()
2460            .map(|chip| chip.vcd())
2461            .unwrap_or_default()
2462    }
2463}
2464
2465/// How decisive a stop is when several chips report in one batch.
2466fn stop_rank(stop: Stop) -> u8 {
2467    match stop {
2468        Stop::Trap => 5,
2469        Stop::Breakpoint(_) => 4,
2470        Stop::Reset => 3,
2471        Stop::Halted => 2,
2472        Stop::Idle => 1,
2473        Stop::Budget => 0,
2474    }
2475}
2476
2477/// The chip module a board names, from the binary for a builtin board or from
2478/// disk next to the manifest for one loaded from a directory.
2479#[cfg(not(target_family = "wasm"))]
2480fn module_bytes(
2481    prepared: &Prepared,
2482    manifest: &litz_catalog::PartManifest,
2483    module: &str,
2484) -> Result<Vec<u8>, String> {
2485    if let Some(bytes) = prepared.registry.builtin_module(&manifest.id) {
2486        return Ok(bytes.to_vec());
2487    }
2488    let base = manifest
2489        .source
2490        .as_deref()
2491        .and_then(|path| path.parent())
2492        .ok_or_else(|| {
2493            format!(
2494                "board {:?} names a module but has no directory",
2495                manifest.id
2496            )
2497        })?;
2498    let path = base.join(module);
2499    std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))
2500}
2501
2502fn run_once(
2503    prepared: &Prepared,
2504    spec: Option<&TestSpec>,
2505    _strict: bool,
2506    options: &Options,
2507) -> Result<Outcome, String> {
2508    let data = run_inner(prepared, spec, spec.is_none(), false, None, options)?;
2509    Ok(Outcome {
2510        exit_code: data.exit_code,
2511        output: data.output,
2512        sim_ms: data.sim_ms,
2513        tests: Vec::new(),
2514    })
2515}
2516
2517fn run_capture(
2518    prepared: &Prepared,
2519    timeout: Option<&str>,
2520    options: &Options,
2521) -> Result<CaptureOutcome, String> {
2522    let data = run_inner(prepared, None, false, true, timeout, options)?;
2523    Ok(CaptureOutcome {
2524        exit_code: data.exit_code,
2525        output: data.output,
2526        sim_ms: data.sim_ms,
2527        part_states: data.part_states,
2528        faults: data.faults,
2529    })
2530}
2531
2532/// Everything a run produces, before it is shaped for a terminal or a host.
2533struct RunData {
2534    exit_code: i32,
2535    output: String,
2536    sim_ms: u32,
2537    part_states: BTreeMap<String, PartState>,
2538    faults: Vec<String>,
2539}
2540
2541fn run_inner(
2542    prepared: &Prepared,
2543    spec: Option<&TestSpec>,
2544    stream: bool,
2545    capture_states: bool,
2546    timeout_override: Option<&str>,
2547    options: &Options,
2548) -> Result<RunData, String> {
2549    let Booted {
2550        fleet: mut mcu,
2551        parts,
2552        board,
2553        capture,
2554    } = boot(prepared, options)?;
2555    start_recording(&mut mcu, options, prepared);
2556    if options.coverage {
2557        mcu.enable_coverage();
2558    }
2559    // Which chip the terminal and the screenshot address is settled before any
2560    // time passes: a board name that is not in the diagram is a configuration
2561    // error, not a note at the end of a run.
2562    let console_board = match options
2563        .interactive
2564        .as_ref()
2565        .and_then(|i| i.board.as_deref())
2566    {
2567        Some(id) => find_board(&prepared.boards, id, "--interactive")?,
2568        None => 0,
2569    };
2570    let capture_board = match options
2571        .screenshot
2572        .as_ref()
2573        .and_then(|capture| capture.board.as_deref())
2574    {
2575        Some(id) => Some(find_board(&prepared.boards, id, "--screenshot")?),
2576        None => None,
2577    };
2578    // `[[test.input]] pin` is a part id when the diagram has such a part and a
2579    // pin number otherwise. Finding out before the machine exists keeps the
2580    // two meanings from colliding at run time.
2581    let presses = spec.map(|s| press_schedule(s, &parts)).unwrap_or_default();
2582
2583    let inputs = spec
2584        .map(|s| inputs_for(s, &parts, &prepared.boards))
2585        .transpose()?
2586        .unwrap_or_default();
2587    for (board, inputs) in inputs {
2588        mcu.schedule(board, inputs)?;
2589    }
2590
2591    let timeout = match timeout_override {
2592        Some(text) => parse_duration(text)?,
2593        None => spec
2594            .and_then(|s| s.timeout.as_deref())
2595            .map(parse_duration)
2596            .transpose()?
2597            .unwrap_or_else(|| parse_duration(DEFAULT_TIMEOUT).expect("default timeout")),
2598    };
2599    let expects = spec
2600        .map(|s| consoled(s.expect(), &prepared.boards))
2601        .unwrap_or_default();
2602    let fails = spec
2603        .map(|s| consoled(s.fail(), &prepared.boards))
2604        .unwrap_or_default();
2605    let mut states: Vec<Wanted> = spec
2606        .map(TestSpec::expect_state)
2607        .unwrap_or_default()
2608        .into_iter()
2609        .map(wanted)
2610        .collect::<Result<_, _>>()?;
2611    let state_at = spec
2612        .and_then(|s| s.state_at.as_deref())
2613        .map(parse_duration)
2614        .transpose()?;
2615    let state_stays = spec
2616        .and_then(|s| s.state_stays.as_deref())
2617        .map(parse_duration)
2618        .transpose()?;
2619    for want in &mut states {
2620        want.at = state_at;
2621        want.stays = state_stays;
2622        if mcu.state(&want.part).is_none() {
2623            let known: Vec<&str> = diagram_part_ids(prepared).collect();
2624            return Err(format!(
2625                "no part named {:?} in diagram.json ({}); a part inside a board is \
2626                 reached as <board>/<id>",
2627                want.part,
2628                known.join(", ")
2629            ));
2630        }
2631    }
2632
2633    let mut heap = HeapLog::from_options(
2634        options,
2635        prepared
2636            .boards
2637            .first()
2638            .map(|plan| plan.id.clone())
2639            .unwrap_or_else(|| "esp".into()),
2640    )?;
2641    // CircuitPython starts `code.py` itself; the interrupt is queued before
2642    // the first chunk so the prompt can appear.
2643    for (index, plan) in prepared.boards.iter().enumerate() {
2644        if pastes_script(plan) && !plan.python.interrupt_sequence().is_empty() {
2645            mcu.write_console_on(index, plan.python.interrupt_sequence());
2646        }
2647    }
2648    let mut serial = String::new();
2649    let mut timed_out = false;
2650    let mut due = 0;
2651    let mut saw_fail = None;
2652    // Interactive input arrives on a thread because the run loop owns the
2653    // simulated clock: blocking on a terminal read would stop time. A line is
2654    // forwarded at the next chunk boundary, which is where every other host
2655    // input lands too.
2656    let (stdin_tx, stdin_rx) = std::sync::mpsc::channel::<Vec<u8>>();
2657    if options.interactive.is_some() {
2658        std::thread::spawn(move || {
2659            use std::io::BufRead;
2660            let stdin = std::io::stdin();
2661            let mut lock = stdin.lock();
2662            let mut line = String::new();
2663            loop {
2664                line.clear();
2665                match lock.read_line(&mut line) {
2666                    Ok(0) | Err(_) => break,
2667                    Ok(_) if stdin_tx.send(line.as_bytes().to_vec()).is_err() => break,
2668                    Ok(_) => {}
2669                }
2670            }
2671        });
2672    }
2673    let mut saw_trap: Option<String> = None;
2674    // A MicroPython run is not ready for its expectations until the prompt has
2675    // appeared and the script has been pasted. `pasted` gates both the
2676    // handshake and the "expectations met" exit.
2677    let mut pasted: Vec<bool> = prepared
2678        .boards
2679        .iter()
2680        .map(|plan| !pastes_script(plan))
2681        .collect();
2682    let mut pasted_at = vec![0u64; prepared.boards.len()];
2683    // When the host last nudged a CircuitPython board: it runs `code.py` by
2684    // itself and then waits in "Press any key to enter the REPL", so the
2685    // friendly prompt only appears after a key arrives. `pasted` still gates
2686    // the handshake; this only decides when to knock.
2687    let mut nudged_at = vec![0u64; prepared.boards.len()];
2688    loop {
2689        // A fault present before the chip runs (two rails meeting on a net, a
2690        // pin tied to ground while the board is already driving) is reported
2691        // without spending a chunk of simulated time on a doomed boot.
2692        if !mcu.conflicts().is_empty() {
2693            break;
2694        }
2695        // Host input lands at chunk boundaries, so it is applied within one
2696        // million-step chunk of the time it asked for — far below the
2697        // resolution any assertion can see.
2698        let now_ns = mcu.frontier_ns();
2699        while due < presses.len() && presses[due].0 <= now_ns {
2700            let (_, part, pressed) = &presses[due];
2701            mcu.press(part, *pressed);
2702            due += 1;
2703        }
2704        while let Ok(bytes) = stdin_rx.try_recv() {
2705            mcu.write_console_on(console_board, &bytes);
2706        }
2707        let step = mcu.run(1_000_000);
2708        // A trap is a real stop, not a slow boot: without this the run would
2709        // keep spinning a dead core until the timeout and report only a
2710        // missing expectation. `fault()` carries the backend's detail when it
2711        // has one.
2712        if step.stop == Stop::Trap {
2713            saw_trap = Some(mcu.fault().unwrap_or_else(|| "the core trapped".into()));
2714            break;
2715        }
2716        let chunk = mcu.take_console();
2717        if !chunk.is_empty() {
2718            let text = String::from_utf8_lossy(&chunk);
2719            if stream {
2720                print!("{text}");
2721                let _ = std::io::stdout().flush();
2722            }
2723            serial.push_str(&text);
2724        }
2725        if !mcu.conflicts().is_empty() {
2726            break;
2727        }
2728        if let Some(log) = &mut heap {
2729            let now = mcu.frontier_ns();
2730            log.sample(&mut mcu, now);
2731            if log.failed() {
2732                break;
2733            }
2734        }
2735        if mcu.finished() {
2736            break;
2737        }
2738        if let Some(hit) = fails.iter().find(|f| seen(&mcu, &serial, f)) {
2739            saw_fail = Some(hit.clone());
2740            break;
2741        }
2742        // Each board keeps its own handshake: two boards boot at their own
2743        // pace, and the prompt belongs to the console that printed it.
2744        let now = mcu.frontier_ns();
2745        for (index, plan) in prepared.boards.iter().enumerate() {
2746            if pasted[index] {
2747                continue;
2748            }
2749            if mcu.console_text(index).contains(REPL_PROMPT) {
2750                paste_script(&mut mcu, index, &plan.scripts, plan.python);
2751                pasted[index] = true;
2752                pasted_at[index] = now;
2753            } else if plan.python == crate::python::PythonRuntime::CircuitPython
2754                && !mcu.console_text(index).is_empty()
2755                && now.saturating_sub(nudged_at[index]) >= CIRCUITPYTHON_NUDGE
2756            {
2757                // Ctrl-C: it interrupts a running code.py, and at the
2758                // "press any key" idle it is the key that opens the REPL.
2759                mcu.write_console_on(index, plan.python.interrupt_sequence());
2760                nudged_at[index] = now;
2761            } else if now >= timeout {
2762                return Err(format!(
2763                    "board {:?}: MicroPython REPL prompt never appeared within {timeout} ns of \
2764                     simulated time; check that its firmware is a MicroPython or CircuitPython build",
2765                    plan.id
2766                ));
2767            }
2768        }
2769        for want in &mut states {
2770            if let Some(actual) = mcu.state(&want.part) {
2771                observe(want, actual, now);
2772            }
2773        }
2774        let paste_settled = prepared.boards.iter().enumerate().all(|(index, plan)| {
2775            !pastes_script(plan)
2776                || (pasted[index] && now >= pasted_at[index].saturating_add(PASTE_GRACE_NS))
2777        });
2778        let satisfied = pasted.iter().all(|pasted| *pasted)
2779            && paste_settled
2780            && expects.iter().all(|e| seen(&mcu, &serial, e))
2781            && states.iter().all(|w| w.seen);
2782        if satisfied && (!expects.is_empty() || !states.is_empty()) {
2783            timed_out = false;
2784            break;
2785        }
2786        if mcu.frontier_ns() >= timeout {
2787            timed_out = true;
2788            break;
2789        }
2790    }
2791
2792    let conflicts = mcu.conflicts();
2793    let missing: Vec<&Consoled> = expects.iter().filter(|e| !seen(&mcu, &serial, e)).collect();
2794    let missing_states: Vec<&Wanted> = states.iter().filter(|w| !w.seen).collect();
2795    let passed = conflicts.is_empty()
2796        && saw_fail.is_none()
2797        && saw_trap.is_none()
2798        && missing.is_empty()
2799        && missing_states.is_empty();
2800
2801    let mut notes = Vec::new();
2802    for conflict in &conflicts {
2803        notes.push(format!(
2804            "electrical fault on net {}: {}",
2805            conflict.net, conflict.detail
2806        ));
2807    }
2808    if let Some(hit) = &saw_fail {
2809        let text = hit.text;
2810        match hit.board.and_then(|index| prepared.boards.get(index)) {
2811            Some(plan) => notes.push(format!(
2812                "found failure text {text:?} on board {:?}",
2813                plan.id
2814            )),
2815            None => notes.push(format!("found failure text {text:?}")),
2816        }
2817    }
2818    if let Some(detail) = &saw_trap {
2819        notes.push(format!("the core trapped: {detail}"));
2820    }
2821    for miss in &missing {
2822        match miss.board.and_then(|index| prepared.boards.get(index)) {
2823            Some(plan) => notes.push(format!("never saw {:?} on board {:?}", miss.text, plan.id)),
2824            None => notes.push(format!("never saw {:?}", miss.text)),
2825        }
2826    }
2827    for want in missing_states {
2828        if want.broken {
2829            let stays = want.stays.map(seconds).unwrap_or_default();
2830            notes.push(format!(
2831                "{} {} did not hold for {stays}",
2832                want.part, want.state
2833            ));
2834        } else if let Some(at) = want.at {
2835            notes.push(format!(
2836                "{} was not {} at {}",
2837                want.part,
2838                want.state,
2839                seconds(at)
2840            ));
2841        } else {
2842            notes.push(format!("never saw {} {}", want.part, want.state));
2843        }
2844    }
2845    if timed_out && spec.is_some() {
2846        notes.push(format!("timed out after {timeout} ns of simulated time"));
2847    }
2848
2849    let mut exit_code = if spec.is_none() {
2850        if !conflicts.is_empty() || saw_trap.is_some() {
2851            1
2852        } else if !timed_out && mcu.finished() {
2853            // Every core halted on its own before the clock ran out: the
2854            // program finished rather than the run being cut short.
2855            0
2856        } else {
2857            EXIT_TIMEOUT
2858        }
2859    } else if passed {
2860        0
2861    } else {
2862        1
2863    };
2864
2865    let mut part_states = BTreeMap::new();
2866    if capture_states {
2867        for part in &parts {
2868            if let Some(state) = mcu.state(part)
2869                && state != PartState::None
2870            {
2871                part_states.insert(part.clone(), state);
2872            }
2873        }
2874    }
2875    let faults: Vec<String> = conflicts
2876        .iter()
2877        .map(|conflict| format!("net {}: {}", conflict.net, conflict.detail))
2878        .collect();
2879
2880    let mut output = if stream { String::new() } else { serial };
2881    if !output.ends_with('\n') && !output.is_empty() {
2882        output.push('\n');
2883    }
2884    for note in notes {
2885        output.push_str(&format!("litz: {note}\n"));
2886    }
2887    for line in probe_report(&board) {
2888        output.push_str(&format!("litz: {line}\n"));
2889    }
2890    for line in decode_report(&board, prepared, options)? {
2891        output.push_str(&format!("litz: {line}\n"));
2892    }
2893    // Coverage is a report, not an assertion: it never changes the exit code,
2894    // so a CI step can collect it without turning a pass into a failure.
2895    for line in mcu.report() {
2896        output.push_str(&line);
2897        if !line.ends_with('\n') {
2898            output.push('\n');
2899        }
2900    }
2901    let sim_ms = (mcu.seconds() * 1000.0) as u32;
2902    finish_recording(&mcu, &board, options, capture.as_ref())?;
2903    // A failing test is the moment a picture of the display earns its keep; a
2904    // plain `run` captures unconditionally because the caller asked for it.
2905    // A capture that cannot be taken is a note, not a failure: a board with no
2906    // display should not turn a green run red.
2907    if let Some(capture) = &options.screenshot
2908        && (spec.is_none() || exit_code != 0)
2909        && let Err(e) = mcu.save_display(capture_board, &capture.path)
2910    {
2911        eprintln!("litz: {e}");
2912    }
2913    if let Some(log) = heap {
2914        let end = mcu.frontier_ns();
2915        let (lines, failure) = log.finish(&mut mcu, end);
2916        for line in lines {
2917            output.push_str(&format!("litz: {line}\n"));
2918        }
2919        if let Some(failure) = failure {
2920            exit_code = 1;
2921            output.push_str(&format!("litz: heap: {failure}\n"));
2922        }
2923    }
2924    Ok(RunData {
2925        exit_code,
2926        output,
2927        sim_ms,
2928        part_states,
2929        faults,
2930    })
2931}
2932
2933/// A file named in `litz.toml`, read relative to the project directory.
2934fn read_optional(dir: &Path, rel: Option<&str>) -> Result<Option<Vec<u8>>, String> {
2935    rel.map(|rel| {
2936        let path = dir.join(rel);
2937        std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))
2938    })
2939    .transpose()
2940}
2941
2942/// One `expect_state` entry: a part, the state it must reach, and whether it
2943/// has been seen there yet.
2944///
2945/// The wanted state stays text until it is compared, because one word can mean
2946/// the same thing for several parts — `on` is an LED being lit, a switch being
2947/// thrown and a buzzer sounding — and the part decides which reading applies.
2948struct Wanted {
2949    part: String,
2950    state: String,
2951    seen: bool,
2952    /// Sample the state at this simulated time instead of "at some point".
2953    at: Option<u64>,
2954    /// Once it matches, it must keep matching this long.
2955    stays: Option<u64>,
2956    /// The sample at `at` has been taken.
2957    sampled: bool,
2958    /// A held state started matching.
2959    started: bool,
2960    /// Simulated time the hold started.
2961    since: u64,
2962    /// The hold was broken before it completed.
2963    broken: bool,
2964}
2965
2966/// `<part>:<state>`, the inverse of what this prints in the failure note.
2967fn wanted(text: &str) -> Result<Wanted, String> {
2968    let (part, state) = text
2969        .split_once(':')
2970        .ok_or_else(|| format!("{text:?} is not <part>:<state>"))?;
2971    let known = matches!(state, "on" | "off" | "down" | "pressed" | "up" | "released")
2972        || state.parse::<u16>().is_ok()
2973        || state
2974            .strip_prefix("0x")
2975            .is_some_and(|hex| u8::from_str_radix(hex, 16).is_ok());
2976    if !known {
2977        return Err(format!(
2978            "{state:?} is not a state; write on, off, down, up, a servo angle in degrees, \
2979             or a segment mask as 0x7f"
2980        ));
2981    }
2982    Ok(Wanted {
2983        part: part.to_string(),
2984        state: state.to_string(),
2985        seen: false,
2986        at: None,
2987        stays: None,
2988        sampled: false,
2989        started: false,
2990        since: 0,
2991        broken: false,
2992    })
2993}
2994
2995/// Fold one observation of a part's state into what the test still needs.
2996///
2997/// Without modifiers this is "was ever seen". `state_at` samples instead of
2998/// accumulating, so a state that was true earlier and false at the requested
2999/// instant does not pass. `state_stays` extends a match into an interval: the
3000/// part must keep matching for the whole duration, and a single false
3001/// observation breaks it.
3002fn observe(want: &mut Wanted, actual: PartState, now: u64) {
3003    let matches = state_matches(actual, &want.state);
3004    match (want.at, want.stays) {
3005        (None, None) => {
3006            if matches {
3007                want.seen = true;
3008            }
3009        }
3010        (Some(at), None) => {
3011            if !want.sampled && now >= at {
3012                want.sampled = true;
3013                want.seen = matches;
3014            }
3015        }
3016        (None, Some(stays)) => {
3017            if want.broken || want.seen {
3018                return;
3019            }
3020            if matches {
3021                if !want.started {
3022                    want.started = true;
3023                    want.since = now;
3024                }
3025                if now.saturating_sub(want.since) >= stays {
3026                    want.seen = true;
3027                }
3028            } else if want.started {
3029                want.broken = true;
3030            }
3031        }
3032        (Some(at), Some(stays)) => {
3033            if want.broken || want.seen || now < at {
3034                return;
3035            }
3036            if !want.started {
3037                want.started = true;
3038                want.since = now;
3039            }
3040            if !matches {
3041                want.broken = true;
3042            } else if now.saturating_sub(want.since) >= stays {
3043                want.seen = true;
3044            }
3045        }
3046    }
3047}
3048
3049/// `1.5s` for a note, without trailing zeros.
3050fn seconds(ns: u64) -> String {
3051    format!("{}s", ns as f64 / 1e9)
3052}
3053
3054/// Whether a part's state is the one the test asked for.
3055fn state_matches(actual: PartState, want: &str) -> bool {
3056    match want {
3057        "on" => matches!(
3058            actual,
3059            PartState::Led { lit: true }
3060                | PartState::Switch { on: true }
3061                | PartState::Tone { sounding: true, .. }
3062        ),
3063        "off" => matches!(
3064            actual,
3065            PartState::Led { lit: false }
3066                | PartState::Switch { on: false }
3067                | PartState::Tone {
3068                    sounding: false,
3069                    ..
3070                }
3071        ),
3072        "down" | "pressed" => actual == PartState::Button { pressed: true },
3073        "up" | "released" => actual == PartState::Button { pressed: false },
3074        digits => {
3075            if let Some(hex) = digits.strip_prefix("0x") {
3076                let Ok(mask) = u8::from_str_radix(hex, 16) else {
3077                    return false;
3078                };
3079                return actual == PartState::Segments { mask };
3080            }
3081            match (digits.parse::<u16>(), actual) {
3082                (Ok(degrees), PartState::Servo { degrees: actual }) => degrees == actual,
3083                // A knob is written in percent, the unit `set-control`
3084                // and the diagram's `value` attribute use.
3085                (Ok(percent), PartState::Knob { permille }) => percent * 10 == permille,
3086                _ => false,
3087            }
3088        }
3089    }
3090}
3091
3092fn diagram_part_ids(prepared: &Prepared) -> impl Iterator<Item = &str> {
3093    prepared.circuit.parts.iter().map(|p| p.id.as_str())
3094}
3095
3096/// Presses of named parts, in the order they must happen.
3097fn press_schedule(spec: &TestSpec, parts: &[String]) -> Vec<(u64, String, bool)> {
3098    let mut presses: Vec<(u64, String, bool)> = Vec::new();
3099    for input in &spec.input {
3100        let Some(pin) = &input.pin else { continue };
3101        if !parts.iter().any(|id| id == pin) {
3102            continue;
3103        }
3104        let Ok(at) = parse_duration(&input.at) else {
3105            continue;
3106        };
3107        // A button wired to ground is pulled down while it is held, which is
3108        // the level a test writes: 0 presses, 1 releases.
3109        presses.push((at, pin.clone(), input.level.unwrap_or(1) == 0));
3110    }
3111    presses.sort_by_key(|(at, _, _)| *at);
3112    presses
3113}
3114
3115/// Test inputs as backend-independent scheduled events, grouped by board.
3116///
3117/// A part id in `pin` is pressed through the board rather than asserted onto a
3118/// chip pin, so it is left to `press_schedule`; only bare pin numbers become
3119/// GPIO events. Each group is scheduled on the chip of the board it names; the
3120/// returned order is board order, so a run queues them deterministically.
3121fn inputs_for(
3122    spec: &TestSpec,
3123    parts: &[String],
3124    boards: &[BoardPlan],
3125) -> Result<Vec<(usize, Vec<Input>)>, String> {
3126    let mut by_board: BTreeMap<usize, Vec<Input>> = BTreeMap::new();
3127    for input in &spec.input {
3128        let at_ns = parse_duration(&input.at)?;
3129        let board = input_board(spec, input, boards)?;
3130        if let Some(serial) = &input.serial {
3131            if serial.contains('\n') {
3132                return Err(format!(
3133                    "test {:?}: serial input must be one line",
3134                    spec.name
3135                ));
3136            }
3137            by_board.entry(board).or_default().push(Input::Uart {
3138                at_ns,
3139                bytes: format!("{serial}\n").into_bytes(),
3140            });
3141        }
3142        if let Some(pin) = &input.pin {
3143            if parts.iter().any(|id| id == pin) {
3144                continue;
3145            }
3146            let Ok(number) = pin.parse::<u8>() else {
3147                return Err(format!(
3148                    "test {:?}: {pin:?} is neither a part in the diagram nor a GPIO number",
3149                    spec.name
3150                ));
3151            };
3152            let level = if input.level.unwrap_or(1) == 0 {
3153                Level::Low
3154            } else {
3155                Level::High
3156            };
3157            by_board.entry(board).or_default().push(Input::Gpio {
3158                at_ns,
3159                pin: number,
3160                level,
3161            });
3162        }
3163    }
3164    let mut groups: Vec<(usize, Vec<Input>)> = by_board.into_iter().collect();
3165    for (_, inputs) in &mut groups {
3166        inputs.sort_by_key(|input| match input {
3167            Input::Gpio { at_ns, .. } | Input::Uart { at_ns, .. } => *at_ns,
3168        });
3169    }
3170    Ok(groups)
3171}
3172
3173/// The board an input lands on. One board needs no name; a diagram with more
3174/// than one cannot guess, because the same GPIO number exists on each.
3175fn input_board(
3176    spec: &TestSpec,
3177    input: &crate::config::Input,
3178    boards: &[BoardPlan],
3179) -> Result<usize, String> {
3180    match &input.board {
3181        Some(id) => boards
3182            .iter()
3183            .position(|plan| &plan.id == id)
3184            .ok_or_else(|| {
3185                format!(
3186                    "test {:?}: board {id:?} is not a development board in diagram.json ({})",
3187                    spec.name,
3188                    boards
3189                        .iter()
3190                        .map(|plan| plan.id.as_str())
3191                        .collect::<Vec<_>>()
3192                        .join(", ")
3193                )
3194            }),
3195        None if boards.len() == 1 => Ok(0),
3196        None => Err(format!(
3197            "test {:?}: the input at {} needs `board = \"...\"`; this diagram has {} boards ({})",
3198            spec.name,
3199            input.at,
3200            boards.len(),
3201            boards
3202                .iter()
3203                .map(|plan| plan.id.as_str())
3204                .collect::<Vec<_>>()
3205                .join(", ")
3206        )),
3207    }
3208}
3209
3210/// One `expect` or `fail` entry: the text, and the board whose console must
3211/// show it.
3212///
3213/// A leading `<board>@` narrows the match to that board's console. The prefix
3214/// is only read as a board when it names one, so any other text — `@`
3215/// included — is matched against the merged console of every board.
3216#[derive(Clone)]
3217struct Consoled<'a> {
3218    board: Option<usize>,
3219    text: &'a str,
3220}
3221
3222fn consoled<'a>(entries: Vec<&'a str>, boards: &[BoardPlan]) -> Vec<Consoled<'a>> {
3223    entries
3224        .into_iter()
3225        .map(|entry| match entry.split_once('@') {
3226            Some((prefix, rest)) => match boards.iter().position(|plan| plan.id == prefix) {
3227                Some(board) => Consoled {
3228                    board: Some(board),
3229                    text: rest,
3230                },
3231                None => Consoled {
3232                    board: None,
3233                    text: entry,
3234                },
3235            },
3236            None => Consoled {
3237                board: None,
3238                text: entry,
3239            },
3240        })
3241        .collect()
3242}
3243
3244/// Whether the console this entry names has shown its text. An entry without
3245/// a board reads the merged stream, exactly as a single-board project always
3246/// did.
3247fn seen(fleet: &Fleet, merged: &str, entry: &Consoled) -> bool {
3248    match entry.board {
3249        Some(index) => fleet.console_text(index).contains(entry.text),
3250        None => merged.contains(entry.text),
3251    }
3252}
3253
3254fn parse_mac(text: Option<&str>) -> [u8; 6] {
3255    let Some(text) = text else {
3256        return DEFAULT_MAC;
3257    };
3258    let bytes: Vec<u8> = text
3259        .split([':', '-'])
3260        .filter_map(|b| u8::from_str_radix(b, 16).ok())
3261        .collect();
3262    if bytes.len() == 6 {
3263        [bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]]
3264    } else {
3265        DEFAULT_MAC
3266    }
3267}
3268
3269fn blocks(diagnostics: &[Diagnostic], strict: bool) -> bool {
3270    diagnostics
3271        .iter()
3272        .any(|d| d.severity == Severity::Error || (strict && d.severity == Severity::Warning))
3273}
3274
3275fn render(diagnostics: &[Diagnostic]) -> String {
3276    diagnostics
3277        .iter()
3278        .map(|d| {
3279            format!(
3280                "{}[{}]: {}\n",
3281                if d.severity == Severity::Error {
3282                    "error"
3283                } else {
3284                    "warning"
3285                },
3286                d.code,
3287                d.message
3288            )
3289        })
3290        .collect()
3291}
3292
3293/// `--trigger CHANNEL=high|low[,pre=DURATION][,post=DURATION]`. Durations use
3294/// the same syntax as a scenario delay (`250us`, `2ms`); with no `post`, the
3295/// window runs to the end of the record.
3296pub fn parse_trigger(spec: &str) -> Result<litz_board::probe::Trigger, String> {
3297    use litz_core::Level;
3298    let (channel, rest) = spec
3299        .split_once('=')
3300        .ok_or_else(|| format!("trigger {spec:?} needs CHANNEL=high|low"))?;
3301    let mut parts = rest.split(',');
3302    let level = match parts.next().unwrap_or("").trim() {
3303        "high" | "1" => Level::High,
3304        "low" | "0" => Level::Low,
3305        other => {
3306            return Err(format!("trigger level {other:?} is not high or low"));
3307        }
3308    };
3309    let mut pre = 0;
3310    let mut post = 0;
3311    for option in parts {
3312        let (key, value) = option
3313            .split_once('=')
3314            .ok_or_else(|| format!("trigger option {option:?} needs key=value"))?;
3315        match key.trim() {
3316            "pre" => pre = crate::config::parse_duration(value.trim())?,
3317            "post" => post = crate::config::parse_duration(value.trim())?,
3318            other => {
3319                return Err(format!("trigger option {other:?} is not pre or post"));
3320            }
3321        }
3322    }
3323    let channel = channel.trim();
3324    if channel.is_empty() {
3325        return Err("trigger needs a probe name".into());
3326    }
3327    Ok(litz_board::probe::Trigger {
3328        channel: channel.to_string(),
3329        level,
3330        pre_ticks: pre,
3331        post_ticks: post,
3332    })
3333}
3334
3335#[cfg(test)]
3336mod tests {
3337    use super::*;
3338
3339    fn staged(name: &str, source: &str) -> StagedScript {
3340        StagedScript {
3341            name: name.into(),
3342            bytes: source.as_bytes().to_vec(),
3343        }
3344    }
3345
3346    #[test]
3347    fn a_multi_file_paste_writes_every_module_then_runs_the_entry() {
3348        let scripts = [
3349            staged("main.py", "import util\nprint(util.N)\n"),
3350            staged("lib/util.py", "N = 42\n"),
3351        ];
3352        let pairs: Vec<(&str, &[u8])> = scripts
3353            .iter()
3354            .map(|script| (script.name.as_str(), script.bytes.as_slice()))
3355            .collect();
3356        let text = crate::python::stage_program("main.py", &pairs);
3357        assert!(text.contains("_litz_stage('main.py', (b'import util\\nprint(util.N)\\n'))"));
3358        assert!(text.contains("_litz_stage('lib/util.py', (b'N = 42\\n'))"));
3359        assert!(text.ends_with("exec(open('main.py').read())\n"));
3360        assert!(text.contains("os.mkdir(cur)"), "directories are created");
3361    }
3362
3363    #[test]
3364    fn a_staged_path_may_not_escape_the_device_directory() {
3365        assert_eq!(staged_name("lib/util.py").unwrap(), "lib/util.py");
3366        for bad in ["/boot.py", "../main.py", "lib//x.py", "", "lib/./x.py"] {
3367            assert!(staged_name(bad).is_err(), "{bad:?} should be refused");
3368        }
3369    }
3370
3371    #[test]
3372    fn a_trigger_spec_names_a_channel_a_level_and_a_window() {
3373        let trigger = parse_trigger("sck=high,pre=250us,post=2ms").unwrap();
3374        assert_eq!(trigger.channel, "sck");
3375        assert_eq!(trigger.level, litz_core::Level::High);
3376        assert_eq!(trigger.pre_ticks, 250_000);
3377        assert_eq!(trigger.post_ticks, 2_000_000);
3378        let plain = parse_trigger("tx=low").unwrap();
3379        assert_eq!(plain.level, litz_core::Level::Low);
3380        assert_eq!((plain.pre_ticks, plain.post_ticks), (0, 0));
3381        assert!(parse_trigger("sck").is_err());
3382        assert!(parse_trigger("sck=sideways").is_err());
3383        assert!(parse_trigger("sck=high,speed=1").is_err());
3384    }
3385}