bynk-driver 0.434.0

The command bodies shared by the Bynk CLIs (bynkc and bynk): project rooting, check, fmt, test, and output writing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! v0.59: the `bynkc test --format json` result model, plus the parser that
//! folds the runner's NDJSON event stream into it.
//!
//! The generated `tests/main.ts` runner emits one JSON event per line when
//! `BYNK_TEST_FORMAT=ndjson` (an **internal** protocol — proposal v0.59,
//! Decision 2); `run_test` captures that stream and renders the single pinned
//! **document** below. The document is built from `#[derive(Serialize)]` structs
//! in **declaration order** — field order *is* the contract (the discipline
//! `bynk/src/report.rs` calls out); we never use `serde_json::json!`, so the
//! `preserve_order` feature some workspace crates enable can't reorder it.
//!
//! There are three terminal states, distinguished by the consumer on the
//! presence/`kind` of `error`:
//! - **normal** — `suites` present, no `error` (may have `failed > 0`);
//! - **compile** — the project never compiled: no `suites`, `error.kind ==
//!   "compile"` carrying the `bynkc` diagnostic lines;
//! - **runtime** — the runner started then died before `run-end`: the observed
//!   `suites` prefix *and* `error.kind == "runtime"` with the captured stderr.

use serde::Serialize;

/// The pinned `bynkc test --format json` document.
#[derive(Debug, PartialEq, Serialize)]
pub struct TestRun {
    pub passed: u32,
    pub failed: u32,
    /// #2138: the cases a remote run skipped (`--skip-unsupported`). Absent
    /// when zero, so every other document's layout is unchanged.
    #[serde(skip_serializing_if = "is_zero")]
    pub skipped: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suites: Option<Vec<Suite>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<TestError>,
    /// #854: the optional coverage block, present only for a `--coverage` run
    /// that produced attributable lines. Last field, so every existing
    /// document's byte layout is unchanged when it is absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coverage: Option<Coverage>,
    /// #2138: where the `system` suites ran — `"remote:<target>"` under
    /// `--against`. Absent for an in-process run. Last field, so every
    /// existing document's layout is unchanged.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transport: Option<String>,
}

fn is_zero(n: &u32) -> bool {
    *n == 0
}

/// The `coverage` block: whole-run totals plus one entry per measured `.bynk`
/// file, keyed by project-relative path. Attributed to `.bynk` source lines, not
/// emitted `.ts`/`.js` (issue #854); generated glue with no source origin is
/// out-of-scope, never counted.
#[derive(Debug, PartialEq, Serialize)]
pub struct Coverage {
    /// Covered executable lines across every measured file.
    pub covered: u32,
    /// Total executable lines across every measured file.
    pub lines: u32,
    /// Whole-run percentage (0–100), rounded.
    pub percent: u32,
    pub files: Vec<FileCoverage>,
}

/// One measured `.bynk` file's line coverage.
#[derive(Debug, PartialEq, Serialize)]
pub struct FileCoverage {
    pub path: String,
    pub covered: u32,
    pub lines: u32,
    pub percent: u32,
    /// Uncovered executable lines, 1-based and ascending.
    pub uncovered: Vec<u32>,
    /// #2104: covered executable lines, 1-based and ascending. With
    /// `uncovered`, every executable line, so an editor can mark both. Named
    /// `covered_lines` because `covered` is already the count. Additive and
    /// last, so a consumer that predates it is unaffected.
    pub covered_lines: Vec<u32>,
}

impl From<&crate::coverage::CoverageReport> for Coverage {
    fn from(r: &crate::coverage::CoverageReport) -> Self {
        Coverage {
            covered: r.total_covered(),
            lines: r.total_lines(),
            percent: r.total_percent(),
            files: r
                .files
                .iter()
                .map(|f| FileCoverage {
                    path: f.path.clone(),
                    covered: f.covered,
                    lines: f.total,
                    percent: crate::coverage::percent(f.covered, f.total),
                    uncovered: f.uncovered.clone(),
                    covered_lines: f.covered_lines.clone(),
                })
                .collect(),
        }
    }
}

#[derive(Debug, PartialEq, Serialize)]
pub struct Suite {
    pub name: String,
    pub kind: String,
    pub cases: Vec<Case>,
}

#[derive(Debug, PartialEq, Serialize)]
pub struct Case {
    pub name: String,
    /// `"pass"` / `"fail"` from a run, `"skipped"` for a case a remote run
    /// skipped (#2138), or `"discovered"` in a `--no-run`
    /// discovery document (the case was listed, not executed).
    pub outcome: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<Location>,
    /// #2138 (track §3.6): how often `--settle` retried the case's `expect`s
    /// in a remote run. Absent when it wasn't retried.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retries: Option<u32>,
    /// The case's effective tier, `"unit"`, `"integration"` or `"system"`
    /// (ADR 0153), attached from the compile's case table: the suite `kind`
    /// follows the module name and cannot say it. Appended last and omitted when
    /// absent (a property has none), so a document without it keeps its layout.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tier: Option<String>,
    /// A failed generative case: `"property"` or `"history"`. Set with `seed`,
    /// whatever the failure was, because a draw depends on the seed even when the
    /// body threw something that is not an assertion. Follows `tier`; see the ADR
    /// for appending optional `Case` fields.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// The run's root seed, as the `0x…` text `--seed` accepts. With `--case`, it
    /// reproduces the failed case's stream.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seed: Option<String>,
    /// The shrunk counterexample as the runner rendered it (`p = 73`, or the
    /// shrunk sequence of a history), when shrinking produced one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub counterexample: Option<String>,
    /// #2272: the invariant or transition a violated case named, when a violation
    /// failed it. Appended after `counterexample`; absent otherwise.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub violation: Option<Violation>,
    /// #2272: the steps of a failed history that an agent refused, each with the
    /// declaration that refused it. A refusal is data on the step, not a failure of
    /// its own, so `violation` does not say it. Appended after `violation`; absent
    /// when no step was refused.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refusals: Option<Vec<Refusal>>,
    /// #2461: where the case came from, `"doc"` for a doc-comment example marked
    /// `bynk test`. Appended after `refusals` and absent for every other case, so a
    /// document without doc examples keeps its layout; a reader treats a missing
    /// `origin` as an ordinary `case`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,
    /// How long the case ran, in milliseconds, as its module measured it (#2267
    /// stage 2). Never part of the JSON document, which stays deterministic; the
    /// `ndjson` stream's `case` event carries it, last.
    #[serde(skip)]
    pub duration_ms: Option<f64>,
}

#[derive(Debug, PartialEq, Serialize)]
pub struct Location {
    pub path: String,
    pub line: u32,
    pub col: u32,
}

/// #2272: the declaration a violated invariant or transition names. `kind` is the
/// declaration's own kind, `"invariant"` or `"transition"`, which the name alone
/// cannot say (an invariant and a transition may share one).
#[derive(Debug, PartialEq, Serialize)]
pub struct Violation {
    pub kind: String,
    pub agent: String,
    pub name: String,
    pub location: Option<Location>,
}

/// #2272: a step of a driven history that an agent refused. `index` is the step's
/// position in the shrunk sequence the case reports (from 0), `call` the handler it
/// called, and the rest names the declaration that refused it, as [`Violation`] does.
#[derive(Debug, PartialEq, Serialize)]
pub struct Refusal {
    pub index: u32,
    pub call: String,
    pub kind: String,
    pub agent: String,
    pub name: String,
    pub location: Option<Location>,
}

#[derive(Debug, PartialEq, Serialize)]
pub struct TestError {
    pub kind: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// `bynkc` diagnostic lines (`path:line:col: severity[category]: message`),
    /// for `kind == "compile"`. Empty (and omitted) otherwise.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub diagnostics: Vec<String>,
    /// Captured stderr from a crashed run, for `kind == "runtime"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stderr: Option<String>,
}

impl TestRun {
    /// A normal run with no suites (no tests, or `--no-run`).
    pub fn empty() -> Self {
        TestRun {
            passed: 0,
            failed: 0,
            skipped: 0,
            suites: Some(Vec::new()),
            error: None,
            coverage: None,
            transport: None,
        }
    }

    /// Attach a coverage block (`--coverage`, issue #854). A report with no
    /// attributed line is dropped rather than serialising an empty block, so a
    /// coverage run over a project with nothing measurable reads like a normal
    /// run.
    pub fn with_coverage(mut self, report: &crate::coverage::CoverageReport) -> Self {
        if !report.is_empty() {
            self.coverage = Some(Coverage::from(report));
        }
        self
    }

    /// v0.67: a **discovery** document (`--no-run --format json`) — the suites and
    /// cases the compile retained, listed without running. `passed`/`failed` are
    /// 0 and each case carries `outcome: "discovered"` (see [`Case`]), so the
    /// "every case has an outcome" invariant holds and no consumer mistakes a
    /// listed case for a result. Reconciles against a later run document: same
    /// suite `name`/`kind`, same case `name`s.
    pub fn discovered(suites: Vec<Suite>) -> Self {
        TestRun {
            passed: 0,
            failed: 0,
            skipped: 0,
            suites: Some(suites),
            error: None,
            coverage: None,
            transport: None,
        }
    }

    /// The document for a run that could not start or complete outside the
    /// compile step (the runner couldn't be launched, `tsc` rejected the
    /// emitted TS, or the runner died). No suites — use [`ParsedRun::into_document`]
    /// when a partial suite prefix was observed.
    pub fn runtime_error(message: impl Into<String>, stderr: Option<String>) -> Self {
        TestRun {
            passed: 0,
            failed: 0,
            skipped: 0,
            suites: None,
            error: Some(TestError {
                kind: "runtime".to_string(),
                message: Some(message.into()),
                diagnostics: Vec::new(),
                stderr: stderr.filter(|s| !s.trim().is_empty()),
            }),
            coverage: None,
            transport: None,
        }
    }

    /// The document for a project that never compiled.
    pub fn compile_error(diagnostics: Vec<String>) -> Self {
        TestRun {
            passed: 0,
            failed: 0,
            skipped: 0,
            suites: None,
            error: Some(TestError {
                kind: "compile".to_string(),
                message: None,
                diagnostics,
                stderr: None,
            }),
            coverage: None,
            transport: None,
        }
    }

    /// Attach each case's tier from the compile's case table, matched by suite
    /// and case name (the names the runner reports are the ones discovery lists).
    /// A case the table does not hold keeps whatever tier it has.
    pub fn with_tiers(mut self, discovered: &[bynk_emit::project::DiscoveredSuite]) -> Self {
        for suite in self.suites.iter_mut().flatten() {
            let Some(known) = discovered.iter().find(|d| d.name == suite.name) else {
                continue;
            };
            for case in &mut suite.cases {
                let known_case = known.cases.iter().find(|c| c.name == case.name);
                if let Some(tier) = known_case.and_then(|c| c.tier) {
                    case.tier = Some(tier.to_string());
                }
                if known_case.is_some_and(|c| c.doc) {
                    case.origin = Some("doc".to_string());
                }
            }
        }
        self
    }

    /// #2138: fold a remote run into the document — its `transport`, and each
    /// skipped case as an `outcome: "skipped"` case whose `message` is why,
    /// in its suite (a new `integration` suite when none of that name ran).
    pub fn with_remote(mut self, transport: String, skipped: &[(String, String, String)]) -> Self {
        self.transport = Some(transport);
        if skipped.is_empty() {
            return self;
        }
        self.skipped = u32::try_from(skipped.len()).unwrap_or(u32::MAX);
        let suites = self.suites.get_or_insert_with(Vec::new);
        for (suite, case, reason) in skipped {
            let case = Case {
                name: case.clone(),
                outcome: "skipped".to_string(),
                message: Some(reason.clone()),
                location: None,
                retries: None,
                // A remote run skips only `system` cases.
                tier: Some("system".to_string()),
                kind: None,
                seed: None,
                counterexample: None,
                violation: None,
                refusals: None,
                origin: None,
                duration_ms: None,
            };
            match suites.iter_mut().find(|s| &s.name == suite) {
                Some(s) => s.cases.push(case),
                None => suites.push(Suite {
                    name: suite.clone(),
                    kind: "integration".to_string(),
                    cases: vec![case],
                }),
            }
        }
        self
    }

    /// Render to a pretty JSON string (trailing newline). Serde emits struct
    /// fields in declaration order regardless of `preserve_order`.
    pub fn render(&self) -> String {
        let mut s = serde_json::to_string_pretty(self).expect("TestRun serialises");
        s.push('\n');
        s
    }
}

/// The `--suite` and `--case` values a run selected nothing for (#2273), as
/// `run-end` reports them: present only when a filter was given and a value
/// went unmatched. A filter that selects nothing is an error, not a vacuous pass.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Unmatched {
    pub suites: Vec<String>,
    pub cases: Vec<String>,
}

impl Unmatched {
    pub fn is_empty(&self) -> bool {
        self.suites.is_empty() && self.cases.is_empty()
    }

    /// One line per unmatched value, without the `<program> test:` prefix.
    pub fn messages(&self) -> Vec<String> {
        let suites = self
            .suites
            .iter()
            .map(|s| format!("no suite named --suite {s:?}"));
        let cases = self
            .cases
            .iter()
            .map(|c| format!("no case matched --case {c:?}"));
        suites.chain(cases).collect()
    }

    /// Print the error for each unmatched value to stderr, after the run's
    /// usual output, so a consumer still reads the document.
    pub fn report(&self, program: &str) {
        for message in self.messages() {
            eprintln!("{program} test: {message}");
        }
    }
}

/// The outcome of parsing the runner's NDJSON stream: the suites observed, the
/// running tallies, and whether a `run-end` event was seen (a missing `run-end`
/// means the runner died mid-stream — a crashed/incomplete run).
#[derive(Debug, Default, PartialEq)]
pub struct ParsedRun {
    pub passed: u32,
    pub failed: u32,
    pub suites: Vec<Suite>,
    pub complete: bool,
    /// What a `--suite`/`--case` filter selected nothing for (#2273).
    pub unmatched: Unmatched,
}

impl ParsedRun {
    /// Fold this parsed stream into the final document. `node_ok` is whether the
    /// runner process exited zero; `stderr` is its captured stderr (used only
    /// for a crashed run). A stream with no `run-end` — or a non-zero exit with
    /// no completion — becomes a `runtime` error carrying the observed prefix.
    pub fn into_document(self, stderr: &str) -> TestRun {
        if self.complete {
            TestRun {
                passed: self.passed,
                failed: self.failed,
                skipped: 0,
                suites: Some(self.suites),
                error: None,
                coverage: None,
                transport: None,
            }
        } else {
            let trimmed = stderr.trim();
            TestRun {
                passed: self.passed,
                failed: self.failed,
                skipped: 0,
                suites: Some(self.suites),
                error: Some(TestError {
                    kind: "runtime".to_string(),
                    message: Some("the test runner exited before completing".to_string()),
                    diagnostics: Vec::new(),
                    stderr: (!trimmed.is_empty()).then(|| trimmed.to_string()),
                }),
                coverage: None,
                transport: None,
            }
        }
    }
}

/// Parse the runner's NDJSON stdout into a [`ParsedRun`]. Unparseable or
/// unrecognised lines are skipped (the stream is an internal protocol; a
/// stray line should never abort the whole report).
pub fn parse_ndjson(stdout: &str) -> ParsedRun {
    let mut run = ParsedRun::default();
    for line in stdout.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        match value.get("type").and_then(|t| t.as_str()) {
            Some("suite-begin") => {
                run.suites.push(Suite {
                    name: str_field(&value, "name"),
                    kind: str_field(&value, "kind"),
                    cases: Vec::new(),
                });
            }
            Some("case") => {
                let case = case_from_event(&value);
                if case.outcome == "pass" {
                    run.passed += 1;
                } else {
                    run.failed += 1;
                }
                if let Some(suite) = run.suites.last_mut() {
                    suite.cases.push(case);
                }
            }
            Some("run-end") => {
                run.complete = true;
                run.unmatched = unmatched_from_event(&value);
            }
            _ => {}
        }
    }
    run
}

/// The [`Case`] a runner `case` event describes, without its tier (which comes
/// from the compile's case table). Shared by the document parser and the stream.
pub(crate) fn case_from_event(value: &serde_json::Value) -> Case {
    let message = value
        .get("message")
        .and_then(|m| m.as_str())
        .map(str::to_string);
    let location = value
        .get("location")
        .and_then(|l| l.as_str())
        .and_then(parse_location);
    let retries = value
        .get("retries")
        .and_then(serde_json::Value::as_u64)
        .filter(|n| *n > 0)
        .map(|n| u32::try_from(n).unwrap_or(u32::MAX));
    let violation = value.get("violation").map(violation_from_json);
    let refusals = refusals_from_json(value.get("refusals"));
    Case {
        name: str_field(value, "name"),
        outcome: str_field(value, "outcome"),
        message,
        location,
        retries,
        tier: None,
        kind: str_opt(value, "kind"),
        seed: str_opt(value, "seed"),
        counterexample: str_opt(value, "counterexample"),
        violation,
        refusals,
        origin: None,
        duration_ms: value.get("durationMs").and_then(serde_json::Value::as_f64),
    }
}

/// A location as the ndjson event carries it (`path:line:col`) or the JSON document
/// does (the driver serialises it from [`Location`], as an object).
fn location_from_json(value: &serde_json::Value) -> Option<Location> {
    value.get("location").and_then(|l| match l {
        serde_json::Value::String(s) => parse_location(s),
        serde_json::Value::Object(_) => Some(Location {
            path: str_field(l, "path"),
            line: l
                .get("line")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(0) as u32,
            col: l
                .get("col")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(0) as u32,
        }),
        _ => None,
    })
}

/// #2272: a runner `violation` object, as the case event and the document carry it.
pub(crate) fn violation_from_json(value: &serde_json::Value) -> Violation {
    Violation {
        kind: str_field(value, "kind"),
        agent: str_field(value, "agent"),
        name: str_field(value, "name"),
        location: location_from_json(value),
    }
}

/// #2272: a runner `refusals` array, as the case event and the document carry it. A
/// malformed entry is dropped, and an array left empty is absent.
pub(crate) fn refusals_from_json(value: Option<&serde_json::Value>) -> Option<Vec<Refusal>> {
    let refusals: Vec<Refusal> = value?
        .as_array()?
        .iter()
        .filter_map(|r| {
            Some(Refusal {
                index: u32::try_from(r.get("index")?.as_u64()?).ok()?,
                call: r.get("call")?.as_str()?.to_string(),
                kind: r.get("kind")?.as_str()?.to_string(),
                agent: r.get("agent")?.as_str()?.to_string(),
                name: r.get("name")?.as_str()?.to_string(),
                location: location_from_json(r),
            })
        })
        .collect();
    (!refusals.is_empty()).then_some(refusals)
}

/// The values a runner `run-end` event reports as selecting nothing (#2273).
pub(crate) fn unmatched_from_event(value: &serde_json::Value) -> Unmatched {
    let Some(unmatched) = value.get("unmatched") else {
        return Unmatched::default();
    };
    let strings = |key: &str| -> Vec<String> {
        unmatched
            .get(key)
            .and_then(|v| v.as_array())
            .map(|a| {
                a.iter()
                    .filter_map(|v| v.as_str())
                    .map(str::to_string)
                    .collect()
            })
            .unwrap_or_default()
    };
    Unmatched {
        suites: strings("suites"),
        cases: strings("cases"),
    }
}

fn str_opt(value: &serde_json::Value, key: &str) -> Option<String> {
    value.get(key).and_then(|v| v.as_str()).map(str::to_string)
}

fn str_field(value: &serde_json::Value, key: &str) -> String {
    value
        .get(key)
        .and_then(|v| v.as_str())
        .unwrap_or_default()
        .to_string()
}

/// Split a `path:line:col` location string into structured fields. Returns
/// `None` for anything that isn't that shape (e.g. the `"unknown"` fallback a
/// non-assertion throw carries), so such a failure keeps its message but offers
/// no click-through. Splits from the right, so a path containing `:` is safe.
fn parse_location(s: &str) -> Option<Location> {
    let (rest, col) = s.rsplit_once(':')?;
    let (path, line) = rest.rsplit_once(':')?;
    let line: u32 = line.parse().ok()?;
    let col: u32 = col.parse().ok()?;
    if path.is_empty() {
        return None;
    }
    Some(Location {
        path: path.to_string(),
        line,
        col,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn known(
        suite: &str,
        cases: &[(&str, Option<&'static str>)],
    ) -> bynk_emit::project::DiscoveredSuite {
        bynk_emit::project::DiscoveredSuite {
            name: suite.to_string(),
            kind: "unit",
            cases: cases
                .iter()
                .map(|(name, tier)| bynk_emit::project::DiscoveredCase {
                    name: (*name).to_string(),
                    location: None,
                    tier: *tier,
                    generative: None,
                    doc: false,
                })
                .collect(),
            skipped: Vec::new(),
            envs: Vec::new(),
        }
    }

    /// A case's measured duration is read from the runner's event, and is not part of
    /// the document: the JSON document stays deterministic (#2267 stage 2).
    #[test]
    fn a_cases_duration_is_read_but_never_written_to_the_document() {
        let ndjson = concat!(
            r#"{"type":"suite-begin","name":"s","kind":"unit","tests":1}"#,
            "\n",
            r#"{"type":"case","suite":"s","name":"c","outcome":"pass","durationMs":1.5}"#,
            "\n",
            r#"{"type":"suite-end","name":"s"}"#,
            "\n",
            r#"{"type":"run-end","passed":1,"failed":0}"#,
            "\n",
        );
        let parsed = parse_ndjson(ndjson);
        assert_eq!(parsed.suites[0].cases[0].duration_ms, Some(1.5));
        let rendered = parsed.into_document("").render();
        assert!(!rendered.contains("durationMs"), "{rendered}");
    }

    /// `run-end` names the `--suite`/`--case` values that selected nothing, when
    /// the runner reports any (#2273); without the field there are none.
    #[test]
    fn run_end_reports_the_values_a_filter_selected_nothing_for() {
        let ended = parse_ndjson(concat!(
            r#"{"type":"run-begin","suites":0}"#,
            "\n",
            r#"{"type":"run-end","passed":0,"failed":0,"unmatched":{"suites":["nope"],"cases":["typo","other"]}}"#,
            "\n",
        ));
        assert!(ended.complete);
        assert_eq!(ended.unmatched.suites, vec!["nope".to_string()]);
        assert_eq!(
            ended.unmatched.cases,
            vec!["typo".to_string(), "other".to_string()]
        );
        assert_eq!(
            ended.unmatched.messages(),
            vec![
                "no suite named --suite \"nope\"".to_string(),
                "no case matched --case \"typo\"".to_string(),
                "no case matched --case \"other\"".to_string(),
            ]
        );

        let plain = parse_ndjson(r#"{"type":"run-end","passed":1,"failed":0}"#);
        assert!(plain.unmatched.is_empty());
    }

    /// A run document built from the runner's NDJSON takes each case's tier from
    /// the compile's case table, by suite and case name: the runner's names are
    /// discovery's, and a case the table does not hold (or holds without a tier)
    /// keeps none.
    #[test]
    fn a_run_takes_each_cases_tier_from_the_case_table() {
        let ndjson = concat!(
            r#"{"type":"suite-begin","name":"shop","kind":"unit"}"#,
            "\n",
            r#"{"type":"case","name":"wired","outcome":"pass"}"#,
            "\n",
            r#"{"type":"case","name":"plain","outcome":"fail","message":"no"}"#,
            "\n",
            r#"{"type":"case","name":"a property","outcome":"pass"}"#,
            "\n",
            r#"{"type":"case","name":"unlisted","outcome":"pass"}"#,
            "\n",
            r#"{"type":"suite-begin","name":"other","kind":"unit"}"#,
            "\n",
            r#"{"type":"case","name":"wired","outcome":"pass"}"#,
            "\n",
            r#"{"type":"run-end"}"#,
            "\n",
        );
        let table = [
            known(
                "shop",
                &[
                    ("wired", Some("system")),
                    ("plain", Some("unit")),
                    ("a property", None),
                ],
            ),
            known("other", &[("wired", Some("integration"))]),
        ];
        let doc = parse_ndjson(ndjson).into_document("").with_tiers(&table);
        let suites = doc.suites.unwrap();
        let tiers = |i: usize| -> Vec<Option<String>> {
            suites[i].cases.iter().map(|c| c.tier.clone()).collect()
        };
        assert_eq!(
            tiers(0),
            [Some("system".into()), Some("unit".into()), None, None]
        );
        assert_eq!(
            tiers(1),
            [Some("integration".into())],
            "the same name in another suite"
        );
    }

    /// #2104: a file's coverage carries both line lists, `covered_lines` last,
    /// so the block's existing field order (the contract) is unchanged.
    #[test]
    fn file_coverage_carries_covered_and_uncovered_lines() {
        let report = crate::coverage::CoverageReport {
            files: vec![crate::coverage::FileCoverage {
                path: "src/demo/m.bynk".into(),
                covered: 2,
                total: 5,
                uncovered: vec![7, 8, 9],
                covered_lines: vec![3, 4],
            }],
        };
        assert_eq!(
            serde_json::to_string(&Coverage::from(&report)).unwrap(),
            r#"{"covered":2,"lines":5,"percent":40,"files":[{"path":"src/demo/m.bynk","covered":2,"lines":5,"percent":40,"uncovered":[7,8,9],"covered_lines":[3,4]}]}"#
        );
    }

    #[test]
    fn refusals_read_in_either_shape_and_drop_what_is_malformed() {
        let refusal = |location: &str| {
            format!(
                r#"{{"index":1,"call":"Spend","kind":"transition","agent":"Wallet","name":"never_decreases","location":{location}}}"#
            )
        };
        let as_event = refusals_from_json(
            serde_json::from_str(&format!(
                r#"[{}]"#,
                refusal(r#""src/demo/wallet.bynk:18:14""#)
            ))
            .ok()
            .as_ref(),
        )
        .unwrap();
        let as_document = refusals_from_json(
            serde_json::from_str(&format!(
                r#"[{}]"#,
                refusal(r#"{"path":"src/demo/wallet.bynk","line":18,"col":14}"#)
            ))
            .ok()
            .as_ref(),
        )
        .unwrap();
        assert_eq!(as_event, as_document);
        assert_eq!(as_event[0].index, 1);
        assert_eq!(as_event[0].kind, "transition");
        assert_eq!(as_event[0].location.as_ref().unwrap().line, 18);

        // A refusal missing a field is dropped, and an array left empty is absent.
        let malformed: serde_json::Value =
            serde_json::from_str(r#"[{"index":0,"call":"Spend","kind":"invariant"}]"#).unwrap();
        assert_eq!(refusals_from_json(Some(&malformed)), None);
        assert_eq!(refusals_from_json(Some(&serde_json::json!([]))), None);
        assert_eq!(refusals_from_json(Some(&serde_json::json!("x"))), None);
        assert_eq!(refusals_from_json(None), None);
    }

    #[test]
    fn a_violation_reads_its_location_in_either_shape() {
        // The ndjson event carries `path:line:col`; the JSON document, which `merge`
        // reads back, carries the `Location` object. Both name the same place (#2272).
        let as_event = serde_json::json!({
            "kind": "transition", "agent": "Meter", "name": "same",
            "location": "src/demo/m.bynk:28:14"
        });
        let as_document = serde_json::json!({
            "kind": "transition", "agent": "Meter", "name": "same",
            "location": { "path": "src/demo/m.bynk", "line": 28, "col": 14 }
        });
        let expected = Some(Location {
            path: "src/demo/m.bynk".to_string(),
            line: 28,
            col: 14,
        });
        assert_eq!(violation_from_json(&as_event).location, expected);
        assert_eq!(violation_from_json(&as_document).location, expected);
    }

    #[test]
    fn a_doc_example_case_is_marked_and_no_other_is() {
        let table = vec![bynk_emit::project::DiscoveredSuite {
            name: "demo.m".to_string(),
            kind: "unit",
            cases: vec![
                bynk_emit::project::DiscoveredCase {
                    name: "doc example m.bynk:4".to_string(),
                    location: None,
                    tier: Some("unit"),
                    generative: None,
                    doc: true,
                },
                bynk_emit::project::DiscoveredCase {
                    name: "real".to_string(),
                    location: None,
                    tier: Some("unit"),
                    generative: None,
                    doc: false,
                },
            ],
            skipped: Vec::new(),
            envs: Vec::new(),
        }];
        let ndjson = concat!(
            r#"{"type":"suite-begin","name":"demo.m","kind":"unit","tests":2}"#,
            "\n",
            r#"{"type":"case","suite":"demo.m","name":"doc example m.bynk:4","outcome":"pass"}"#,
            "\n",
            r#"{"type":"case","suite":"demo.m","name":"real","outcome":"pass"}"#,
            "\n",
            r#"{"type":"suite-end","name":"demo.m"}"#,
            "\n",
            r#"{"type":"run-end","passed":2,"failed":0}"#,
            "\n",
        );
        let doc = parse_ndjson(ndjson).into_document("").with_tiers(&table);
        let rendered = doc.render();
        // Appended after the other optional fields, and only on the doc case.
        assert_eq!(rendered.matches("\"origin\"").count(), 1, "{rendered}");
        assert!(rendered.contains("\"origin\": \"doc\""), "{rendered}");
        let suites = doc.suites.as_ref().unwrap();
        assert_eq!(suites[0].cases[0].origin.as_deref(), Some("doc"));
        assert_eq!(suites[0].cases[1].origin, None);
    }
}