omena-testkit 0.3.0

Shared Rust fixture and scenario substrate for the Omena CSS test stack
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
use serde::Serialize;
use std::collections::BTreeSet;

/// One reusable fixture seed consumed by the testkit boundary report.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OmenaTestkitFixtureSeedV0 {
    /// Stable fixture label.
    pub label: &'static str,
    /// Fixture lane such as `sass-language` or `cascade-proof`.
    pub lane: &'static str,
    /// Raw `omena-fixture-v0` text.
    pub raw: &'static str,
    /// Product surfaces expected to consume this fixture.
    pub expected_products: &'static [&'static str],
    /// Promotion target for M4.
    pub promotion_target: &'static str,
}

/// Parsed reusable fixture.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OmenaFixtureV0 {
    /// Fixture grammar version.
    pub schema_version: &'static str,
    /// Parsed files.
    pub files: Vec<OmenaFixtureFileV0>,
    /// Parsed expectations.
    pub expectations: Vec<OmenaFixtureExpectationV0>,
}

/// One file section in a reusable fixture.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OmenaFixtureFileV0 {
    /// Workspace-relative file path.
    pub path: String,
    /// File-header metadata such as dialect or layer.
    pub metadata: Vec<OmenaFixtureFileMetadataV0>,
    /// Markers removed from the source while preserving clean-source offsets.
    /// Hex-encoded files are raw UTF-8 transports and never interpret markers.
    pub markers: Vec<OmenaFixtureMarkerV0>,
    /// File text.
    pub source: String,
}

/// One metadata key/value pair from a fixture file header.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OmenaFixtureFileMetadataV0 {
    /// Metadata key.
    pub key: String,
    /// Metadata value.
    pub value: String,
}

/// One marker extracted from fixture source text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OmenaFixtureMarkerV0 {
    /// Marker kind such as `cursor`, `namedPoint`, or `rangeStart`.
    pub kind: &'static str,
    /// Optional marker payload.
    pub name: Option<String>,
    /// Byte offset in the cleaned source.
    pub byte_start: usize,
    /// Byte end in the cleaned source.
    pub byte_end: usize,
}

/// One expectation section in a reusable fixture.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OmenaFixtureExpectationV0 {
    /// Expectation key.
    pub key: String,
    /// Expectation text.
    pub value: String,
}

/// Known `omena-fixture-v0` expectation families.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum OmenaFixtureExpectationKindV0 {
    /// Product-surface expectation.
    Product,
    /// Free-form assertion text.
    Assertion,
    /// Expected diagnostic with code/range/message details in the body.
    Diagnostic,
    /// A diagnostic code or code pattern that must not appear.
    NoDiagnostic,
    /// Expected diagnostic count, usually `<code>:<n>`.
    Count,
    /// Expected cascade winner declaration id.
    CascadeOutcome,
    /// Expected declaration participating in a cascade witness.
    CascadeWitness,
    /// Expected external-reference boundary state.
    BoundaryState,
    /// Unknown or product-owned expectation family.
    Unknown,
}

impl OmenaFixtureExpectationV0 {
    /// Classify the expectation family without interpreting product-owned
    /// expectation payloads.
    pub fn kind(&self) -> OmenaFixtureExpectationKindV0 {
        omena_fixture_expectation_kind_from_key(&self.key)
    }
}

/// Classify a raw expectation key by its leading keyword.
pub fn omena_fixture_expectation_kind_from_key(key: &str) -> OmenaFixtureExpectationKindV0 {
    match key.split_whitespace().next().unwrap_or_default() {
        "product" => OmenaFixtureExpectationKindV0::Product,
        "assertion" => OmenaFixtureExpectationKindV0::Assertion,
        "diagnostic" => OmenaFixtureExpectationKindV0::Diagnostic,
        "no-diagnostic" => OmenaFixtureExpectationKindV0::NoDiagnostic,
        "count" => OmenaFixtureExpectationKindV0::Count,
        "cascade-outcome" => OmenaFixtureExpectationKindV0::CascadeOutcome,
        "cascade-witness" => OmenaFixtureExpectationKindV0::CascadeWitness,
        "boundary-state" => OmenaFixtureExpectationKindV0::BoundaryState,
        _ => OmenaFixtureExpectationKindV0::Unknown,
    }
}

/// Parsed fixture seed evidence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OmenaTestkitFixtureSeedReportV0 {
    /// Stable fixture label.
    pub label: &'static str,
    /// Fixture lane.
    pub lane: &'static str,
    /// Whether the fixture parses with `omena-fixture-v0`.
    pub parses: bool,
    /// Parse error when present.
    pub parse_error: Option<String>,
    /// Parsed file count.
    pub file_count: usize,
    /// Parsed expectation count.
    pub expectation_count: usize,
    /// Parsed file-header metadata count.
    pub metadata_count: usize,
    /// Parsed marker count.
    pub marker_count: usize,
    /// Expected product surfaces.
    pub expected_products: Vec<&'static str>,
    /// Promotion target for M4.
    pub promotion_target: &'static str,
    /// Per-expectation evaluation outcomes.
    ///
    /// Evaluated against an empty engine output here (the seed corpus is a
    /// parse-only substrate with no engine wired): `no-diagnostic` and
    /// `count <code>:0` families pass, while `diagnostic`/`boundary-state`/
    /// `cascade-outcome`/`cascade-witness` families fail as absent. An
    /// engine-backed consumer supplies real diagnostics, boundary states, and
    /// cascade projections via
    /// [`crate::fixture_eval::evaluate_omena_fixture_v0`].
    pub expectation_outcomes: Vec<crate::fixture_eval::OmenaFixtureExpectationOutcomeV0>,
}

/// Fixture seed corpus summary.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OmenaTestkitFixtureSeedCorpusReportV0 {
    /// Schema version.
    pub schema_version: &'static str,
    /// Product surface name.
    pub product: &'static str,
    /// Fixture grammar.
    pub fixture_grammar: &'static str,
    /// Fixture count.
    pub fixture_count: usize,
    /// Covered lane count.
    pub lane_count: usize,
    /// Parsed metadata count across all seed files.
    pub metadata_count: usize,
    /// Parsed marker count across all seed files.
    pub marker_count: usize,
    /// Whether every seed parses with the shared fixture grammar.
    pub all_seeds_parse: bool,
    /// Seed reports.
    pub reports: Vec<OmenaTestkitFixtureSeedReportV0>,
}

/// Summarize any `omena-fixture-v0` fixture seed corpus.
pub fn summarize_omena_testkit_fixture_seed_corpus(
    seeds: &[OmenaTestkitFixtureSeedV0],
) -> OmenaTestkitFixtureSeedCorpusReportV0 {
    let reports = seeds
        .iter()
        .copied()
        .map(report_fixture_seed)
        .collect::<Vec<_>>();
    let all_seeds_parse = reports.iter().all(|report| report.parses);
    let lane_count = reports
        .iter()
        .map(|report| report.lane)
        .collect::<BTreeSet<_>>()
        .len();
    let metadata_count = reports.iter().map(|report| report.metadata_count).sum();
    let marker_count = reports.iter().map(|report| report.marker_count).sum();

    OmenaTestkitFixtureSeedCorpusReportV0 {
        schema_version: "0",
        product: "omena-testkit.fixture-seed-corpus",
        fixture_grammar: "omena-fixture-v0",
        fixture_count: reports.len(),
        lane_count,
        metadata_count,
        marker_count,
        all_seeds_parse,
        reports,
    }
}

/// Parse a `omena-fixture-v0` workspace fixture.
pub fn parse_omena_fixture_v0(raw: &str) -> Result<OmenaFixtureV0, String> {
    let mut files = Vec::new();
    let mut expectations = Vec::new();
    let mut current_file: Option<OmenaFixtureFileV0> = None;
    let mut current_expectation: Option<OmenaFixtureExpectationV0> = None;

    for line in raw.lines() {
        if let Some(header) = line
            .strip_prefix("--- file:")
            .or_else(|| line.strip_prefix("//-"))
        {
            finish_fixture_section(&mut files, current_file.take());
            finish_fixture_section(&mut expectations, current_expectation.take());
            let (path, metadata) = parse_omena_fixture_file_header(header.trim())?;
            current_file = Some(OmenaFixtureFileV0 {
                path,
                metadata,
                markers: Vec::new(),
                source: String::new(),
            });
            continue;
        }

        if let Some(key) = line.strip_prefix("--- expect:") {
            finish_fixture_section(&mut files, current_file.take());
            finish_fixture_section(&mut expectations, current_expectation.take());
            current_expectation = Some(OmenaFixtureExpectationV0 {
                key: key.trim().to_string(),
                value: String::new(),
            });
            continue;
        }

        if let Some(file) = current_file.as_mut() {
            push_fixture_line(&mut file.source, line);
        } else if let Some(expectation) = current_expectation.as_mut() {
            push_fixture_line(&mut expectation.value, line);
        } else if !line.trim().is_empty() {
            return Err("fixture content must start with a file or expect marker".to_string());
        }
    }

    finish_fixture_section(&mut files, current_file.take());
    finish_fixture_section(&mut expectations, current_expectation.take());

    for file in &mut files {
        let hex_encoded = file
            .metadata
            .iter()
            .any(|metadata| metadata.key == "encoding" && metadata.value == "hex");
        if hex_encoded {
            file.source = decode_hex_omena_fixture_file(file.source.as_str())?;
            continue;
        }
        let (cleaned_source, markers) = extract_omena_fixture_markers(&file.source)?;
        file.source = cleaned_source;
        file.markers = markers;
    }

    if files.is_empty() {
        return Err("fixture must contain at least one file section".to_string());
    }
    if expectations.is_empty() {
        return Err("fixture must contain at least one expectation section".to_string());
    }

    Ok(OmenaFixtureV0 {
        schema_version: "0",
        files,
        expectations,
    })
}

fn report_fixture_seed(seed: OmenaTestkitFixtureSeedV0) -> OmenaTestkitFixtureSeedReportV0 {
    match parse_omena_fixture_v0(seed.raw) {
        Ok(fixture) => {
            let metadata_count = fixture.files.iter().map(|file| file.metadata.len()).sum();
            let marker_count = fixture.files.iter().map(|file| file.markers.len()).sum();
            // The seed corpus has no engine wired, so evaluate against empty
            // engine output: this still exercises the evaluator at the hook
            // point so the assertions are run, not merely parsed.
            let expectation_outcomes =
                crate::fixture_eval::evaluate_omena_fixture_v0(&fixture, &[], &[], &[]);
            OmenaTestkitFixtureSeedReportV0 {
                label: seed.label,
                lane: seed.lane,
                parses: true,
                parse_error: None,
                file_count: fixture.files.len(),
                expectation_count: fixture.expectations.len(),
                metadata_count,
                marker_count,
                expected_products: seed.expected_products.to_vec(),
                promotion_target: seed.promotion_target,
                expectation_outcomes,
            }
        }
        Err(error) => OmenaTestkitFixtureSeedReportV0 {
            label: seed.label,
            lane: seed.lane,
            parses: false,
            parse_error: Some(error),
            file_count: 0,
            expectation_count: 0,
            metadata_count: 0,
            marker_count: 0,
            expected_products: seed.expected_products.to_vec(),
            promotion_target: seed.promotion_target,
            expectation_outcomes: Vec::new(),
        },
    }
}

fn finish_fixture_section<T>(sections: &mut Vec<T>, current: Option<T>) {
    if let Some(section) = current {
        sections.push(section);
    }
}

fn push_fixture_line(buffer: &mut String, line: &str) {
    if !buffer.is_empty() {
        buffer.push('\n');
    }
    buffer.push_str(line);
}

fn parse_omena_fixture_file_header(
    header: &str,
) -> Result<(String, Vec<OmenaFixtureFileMetadataV0>), String> {
    let mut parts = header.split_whitespace();
    let path = parts
        .next()
        .ok_or_else(|| "fixture file header must include a path".to_string())?;
    if path.contains(':') {
        return Err("fixture file header path must precede metadata".to_string());
    }

    let mut metadata = Vec::new();
    for part in parts {
        let Some((key, value)) = part.split_once(':') else {
            return Err(format!("fixture metadata `{part}` must use key:value"));
        };
        validate_omena_fixture_metadata(key, value)?;
        metadata.push(OmenaFixtureFileMetadataV0 {
            key: key.to_string(),
            value: value.to_string(),
        });
    }

    Ok((path.to_string(), metadata))
}

fn validate_omena_fixture_metadata(key: &str, value: &str) -> Result<(), String> {
    if value.is_empty() {
        return Err(format!("fixture metadata `{key}` must have a value"));
    }
    match key {
        "dialect" => match value {
            "css" | "scss" | "less" => Ok(()),
            _ => Err("fixture dialect metadata must be css, scss, or less".to_string()),
        },
        "encoding" => match value {
            "hex" => Ok(()),
            _ => Err("fixture encoding metadata must be hex".to_string()),
        },
        "layer" | "composes-from" | "consumer-of" => Ok(()),
        _ => Err(format!("fixture metadata key `{key}` is not supported")),
    }
}

fn decode_hex_omena_fixture_file(source: &str) -> Result<String, String> {
    let encoded = source.trim();
    if !encoded.len().is_multiple_of(2) {
        return Err("hex-encoded fixture file source must have even length".to_string());
    }
    let mut bytes = Vec::with_capacity(encoded.len() / 2);
    for pair in encoded.as_bytes().chunks_exact(2) {
        let high = hex_nibble(pair[0]).ok_or_else(|| {
            "hex-encoded fixture file source must contain only hex digits".to_string()
        })?;
        let low = hex_nibble(pair[1]).ok_or_else(|| {
            "hex-encoded fixture file source must contain only hex digits".to_string()
        })?;
        bytes.push((high << 4) | low);
    }
    String::from_utf8(bytes)
        .map_err(|_| "hex-encoded fixture file source must decode to UTF-8".to_string())
}

fn hex_nibble(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

fn extract_omena_fixture_markers(
    source: &str,
) -> Result<(String, Vec<OmenaFixtureMarkerV0>), String> {
    let mut cleaned = String::new();
    let mut markers = Vec::new();
    let mut cursor = 0;

    while let Some(relative_start) = source[cursor..].find("/*") {
        let start = cursor + relative_start;
        cleaned.push_str(&source[cursor..start]);
        let Some(relative_end) = source[start + 2..].find("*/") else {
            return Err("fixture marker comment is unterminated".to_string());
        };
        let end = start + 2 + relative_end + 2;
        let body = &source[start + 2..end - 2];
        if let Some(marker) = parse_omena_fixture_marker(body, cleaned.len())? {
            markers.push(marker);
        } else {
            cleaned.push_str(&source[start..end]);
        }
        cursor = end;
    }

    cleaned.push_str(&source[cursor..]);
    Ok((cleaned, markers))
}

fn parse_omena_fixture_marker(
    body: &str,
    byte_offset: usize,
) -> Result<Option<OmenaFixtureMarkerV0>, String> {
    if body == "|" {
        return Ok(Some(omena_fixture_marker("cursor", None, byte_offset)));
    }
    if let Some(name) = body.strip_prefix("at:") {
        return Ok(Some(omena_fixture_marker(
            "namedPoint",
            Some(validate_omena_fixture_marker_payload("at", name)?),
            byte_offset,
        )));
    }
    if let Some(name) = body
        .strip_prefix("</")
        .and_then(|name| name.strip_suffix('>'))
    {
        return Ok(Some(omena_fixture_marker(
            "rangeEnd",
            Some(validate_omena_fixture_marker_payload("range end", name)?),
            byte_offset,
        )));
    }
    if let Some(name) = body
        .strip_prefix('<')
        .and_then(|name| name.strip_suffix('>'))
    {
        return Ok(Some(omena_fixture_marker(
            "rangeStart",
            Some(validate_omena_fixture_marker_payload("range start", name)?),
            byte_offset,
        )));
    }
    if let Some(name) = body.strip_prefix("name:") {
        return Ok(Some(omena_fixture_marker(
            "nameAnchor",
            Some(validate_omena_fixture_marker_payload("name", name)?),
            byte_offset,
        )));
    }
    if let Some(target) = body.strip_prefix("from:") {
        return Ok(Some(omena_fixture_marker(
            "linkEnd",
            Some(validate_omena_fixture_marker_payload("from", target)?),
            byte_offset,
        )));
    }
    Ok(None)
}

fn omena_fixture_marker(
    kind: &'static str,
    name: Option<String>,
    byte_offset: usize,
) -> OmenaFixtureMarkerV0 {
    OmenaFixtureMarkerV0 {
        kind,
        name,
        byte_start: byte_offset,
        byte_end: byte_offset,
    }
}

fn validate_omena_fixture_marker_payload(kind: &str, value: &str) -> Result<String, String> {
    if value.is_empty() {
        return Err(format!("fixture marker `{kind}` must have a value"));
    }
    Ok(value.to_string())
}

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

    const CROSS_LANGUAGE_FIXTURE: &str = r#"--- file: src/App.tsx
import styles from "./Button.module.scss";
styles.button;
--- file: src/Button.module.scss
.button { color: red; }
--- expect: product
omena-query.source-syntax-index
--- expect: assertion
shared fixture parser keeps source and style files in the same workspace fixture
"#;

    #[test]
    fn parses_reusable_omena_fixture_v0_sections() -> Result<(), String> {
        let fixture = parse_omena_fixture_v0(
            r#"--- file: src/proof.css
.a { color: red; }
--- expect: product
omena-transform-passes.cascade-proof-obligations
--- expect: assertion
proof obligations remain product-visible
"#,
        )?;

        assert_eq!(fixture.schema_version, "0");
        assert_eq!(fixture.files.len(), 1);
        assert_eq!(fixture.files[0].path, "src/proof.css");
        assert!(fixture.files[0].source.contains(".a"));
        assert_eq!(fixture.expectations.len(), 2);
        assert_eq!(fixture.expectations[0].key, "product");
        assert_eq!(
            fixture.expectations[0].value,
            "omena-transform-passes.cascade-proof-obligations"
        );

        Ok(())
    }

    #[test]
    fn keeps_source_and_style_files_in_one_workspace_fixture() -> Result<(), String> {
        let fixture = parse_omena_fixture_v0(CROSS_LANGUAGE_FIXTURE)?;

        assert_eq!(fixture.files.len(), 2);
        assert_eq!(fixture.files[0].path, "src/App.tsx");
        assert_eq!(fixture.files[1].path, "src/Button.module.scss");
        assert!(
            fixture
                .expectations
                .iter()
                .any(|expectation| expectation.value == "omena-query.source-syntax-index")
        );

        Ok(())
    }

    #[test]
    fn parses_omena_fixture_v0_metadata_and_markers() -> Result<(), String> {
        let fixture = parse_omena_fixture_v0(
            r#"//- src/Card.module.scss dialect:scss layer:style
.card { color: /*|*/red; }
.card/*at:selector*/ { color: blue; }
.card { color: /*<colorRange>*/green/*</colorRange>*/; }
.card { composes: item/*from:src/Base.module.scss#item*/; }
--- expect: product
omena-testkit.fixture-markers
"#,
        )?;

        assert_eq!(fixture.files.len(), 1);
        assert_eq!(fixture.files[0].path, "src/Card.module.scss");
        assert_eq!(
            fixture.files[0]
                .metadata
                .iter()
                .map(|metadata| (metadata.key.as_str(), metadata.value.as_str()))
                .collect::<Vec<_>>(),
            vec![("dialect", "scss"), ("layer", "style")]
        );
        assert_eq!(
            fixture.files[0]
                .markers
                .iter()
                .map(|marker| (marker.kind, marker.name.as_deref()))
                .collect::<Vec<_>>(),
            vec![
                ("cursor", None),
                ("namedPoint", Some("selector")),
                ("rangeStart", Some("colorRange")),
                ("rangeEnd", Some("colorRange")),
                ("linkEnd", Some("src/Base.module.scss#item"))
            ]
        );
        assert!(fixture.files[0].source.contains(".card { color: red; }"));
        assert!(!fixture.files[0].source.contains("/*|*/"));
        assert_eq!(
            fixture.files[0].markers[0].byte_start,
            ".card { color: ".len()
        );

        Ok(())
    }

    #[test]
    fn keeps_non_fixture_comments_in_source() -> Result<(), String> {
        let fixture = parse_omena_fixture_v0(
            r#"//- src/Card.module.css dialect:css
.card { /* regular comment */ color: red; }
--- expect: product
omena-testkit.fixture-markers
"#,
        )?;

        assert!(fixture.files[0].source.contains("/* regular comment */"));
        assert!(fixture.files[0].markers.is_empty());

        Ok(())
    }

    #[test]
    fn hex_encoded_file_source_is_marker_inert_and_byte_preserving() -> Result<(), String> {
        let source = concat!(
            ".card {\n",
            "  //---- divider comment\n",
            "  content: \"--- file: nope /*|*/ /*at:point*/ /*<range>*/ /*</range>*/\";\n",
            "}\n",
            "/*"
        );
        let raw = format!(
            "--- file: src/Card.module.scss encoding:hex\n{}\n--- expect: product\nomena-testkit.fixture-encoding\n",
            hex_encode_for_test(source)
        );
        let fixture = parse_omena_fixture_v0(raw.as_str())?;

        assert_eq!(fixture.files.len(), 1);
        assert_eq!(fixture.files[0].path, "src/Card.module.scss");
        assert_eq!(fixture.files[0].source, source);
        assert!(fixture.files[0].markers.is_empty());

        Ok(())
    }

    #[test]
    fn hex_encoded_file_source_rejects_non_utf8_bytes() {
        let result = parse_omena_fixture_v0(
            "--- file: src/raw.css encoding:hex\nff\n--- expect: product\nomena-testkit.fixture-encoding\n",
        );
        assert_eq!(
            result.err().as_deref(),
            Some("hex-encoded fixture file source must decode to UTF-8")
        );
    }

    #[test]
    fn classifies_m7_diagnostic_cascade_and_boundary_expectations() -> Result<(), String> {
        let fixture = parse_omena_fixture_v0(
            r#"//- src/Nested.module.scss dialect:scss
.article {
  &.box { &.fill { padding: 1px; } }
}
--- expect: diagnostic
code: unreachableDeclaration
range: colorRange
--- expect: no-diagnostic unspecifiedCascadeTie
--- expect: count unreachableDeclaration:0
--- expect: cascade-outcome decl-1
--- expect: cascade-witness decl-2
--- expect: boundary-state ext-1 Resolved
--- expect: boundary-state ext-2 Partial
--- expect: boundary-state ext-3 Stale
--- expect: boundary-state ext-4 Missing
--- expect: boundary-state ext-5 Unresolved
"#,
        )?;

        assert_eq!(
            fixture
                .expectations
                .iter()
                .map(OmenaFixtureExpectationV0::kind)
                .collect::<Vec<_>>(),
            vec![
                OmenaFixtureExpectationKindV0::Diagnostic,
                OmenaFixtureExpectationKindV0::NoDiagnostic,
                OmenaFixtureExpectationKindV0::Count,
                OmenaFixtureExpectationKindV0::CascadeOutcome,
                OmenaFixtureExpectationKindV0::CascadeWitness,
                OmenaFixtureExpectationKindV0::BoundaryState,
                OmenaFixtureExpectationKindV0::BoundaryState,
                OmenaFixtureExpectationKindV0::BoundaryState,
                OmenaFixtureExpectationKindV0::BoundaryState,
                OmenaFixtureExpectationKindV0::BoundaryState,
            ]
        );
        assert_eq!(
            fixture.expectations[1].key,
            "no-diagnostic unspecifiedCascadeTie"
        );
        assert_eq!(
            fixture.expectations[2].key,
            "count unreachableDeclaration:0"
        );
        Ok(())
    }

    #[test]
    fn rejects_unknown_fixture_metadata() {
        let error = parse_omena_fixture_v0(
            r#"//- src/Card.module.css unknown:value
.card { color: red; }
--- expect: product
omena-testkit.fixture-markers
"#,
        )
        .err();

        assert_eq!(
            error.as_deref(),
            Some("fixture metadata key `unknown` is not supported")
        );
    }

    #[test]
    fn rejects_fixture_without_sections() {
        let error = parse_omena_fixture_v0("plain text").err();

        assert_eq!(
            error.as_deref(),
            Some("fixture content must start with a file or expect marker")
        );
    }

    #[test]
    fn rejects_fixture_without_expectations() {
        let error = parse_omena_fixture_v0(
            r#"--- file: src/Button.module.scss
.button { color: red; }
"#,
        )
        .err();

        assert_eq!(
            error.as_deref(),
            Some("fixture must contain at least one expectation section")
        );
    }

    #[test]
    fn summarizes_external_fixture_seed_corpus() {
        let seeds = [OmenaTestkitFixtureSeedV0 {
            label: "external",
            lane: "consumer",
            raw: r#"--- file: src/input.css
.x { color: red; }
--- expect: product
consumer.product
"#,
            expected_products: &["consumer.product"],
            promotion_target: "omena-testkit/consumer",
        }];

        let report = summarize_omena_testkit_fixture_seed_corpus(&seeds);

        assert_eq!(report.product, "omena-testkit.fixture-seed-corpus");
        assert_eq!(report.fixture_count, 1);
        assert_eq!(report.lane_count, 1);
        assert!(report.all_seeds_parse);
        assert_eq!(report.reports[0].file_count, 1);
        assert_eq!(report.reports[0].expectation_count, 1);
    }

    fn hex_encode_for_test(source: &str) -> String {
        source
            .as_bytes()
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect()
    }
}