wvq-runtime 0.1.0-alpha.2

Bounded test-runner adapters and evidence normalization for Weavatrix Quality
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
//! Typed `TestProgram` IR. Canonical tests are programs, not Playwright source.

use std::collections::BTreeMap;
use std::path::Path;

use serde::{Deserialize, Serialize};
use thiserror::Error;
use wvq_domain::{ObligationId, ProgramId};

/// Why a program or target was rejected.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ProgramError {
    /// `schema_v` is not `1`.
    #[error("unknown test_program schema_v {0}")]
    UnknownSchema(u32),
    /// Action/target/field is not in the IR.
    #[error("{0}")]
    Invalid(String),
    /// JSON could not be decoded, including unknown fields.
    #[error("malformed TestProgram: {0}")]
    Malformed(String),
}

/// When a binary/text artifact may be captured.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CaptureWhen {
    /// Never capture.
    Never,
    /// Capture only after a failed assertion.
    OnFailure,
    /// Capture on every step.
    Always,
}

/// Evidence collection for one program. Screenshot follows this policy only.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EvidencePolicy {
    /// Screenshot capture.
    #[serde(default = "never")]
    pub screenshot: CaptureWhen,
    /// Playwright trace.
    #[serde(default = "never")]
    pub trace: CaptureWhen,
    /// Network metadata (not bodies).
    #[serde(default = "always")]
    pub network: CaptureWhen,
    /// Console messages.
    #[serde(default = "always")]
    pub console: CaptureWhen,
    /// Web storage keys.
    #[serde(default = "on_failure")]
    pub storage: CaptureWhen,
}

fn never() -> CaptureWhen {
    CaptureWhen::Never
}
fn always() -> CaptureWhen {
    CaptureWhen::Always
}
fn on_failure() -> CaptureWhen {
    CaptureWhen::OnFailure
}

impl Default for EvidencePolicy {
    fn default() -> Self {
        Self {
            screenshot: CaptureWhen::Never,
            trace: CaptureWhen::Never,
            network: CaptureWhen::Always,
            console: CaptureWhen::Always,
            storage: CaptureWhen::OnFailure,
        }
    }
}

impl EvidencePolicy {
    /// Whether a screenshot handle may appear on this observation.
    #[must_use]
    pub fn allow_screenshot(&self, failed: bool) -> bool {
        match self.screenshot {
            CaptureWhen::Always => true,
            CaptureWhen::OnFailure => failed,
            CaptureWhen::Never => false,
        }
    }
}

/// How the program was produced.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProgramSource {
    /// Hand-authored against sealed obligations.
    Authored,
    /// Generated by an agent/model and validated against an existing seal.
    Generated,
    /// Promoted from a recorded session.
    Recorded,
    /// Recovered candidate. Cannot seal by itself.
    Recovered,
}

/// Semantic UI target. `XPath` is not a field and unknown keys fail closed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct Target {
    /// ARIA role.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    /// Accessible name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accessible_name: Option<String>,
    /// Associated label.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// Project-stable test id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub test_id: Option<String>,
    /// Component name hint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub component_hint: Option<String>,
    /// Optional semantic scope resolved before this target.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scope: Option<Box<Target>>,
    /// Last-resort CSS. Never `XPath`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fallback_css: Option<String>,
}

impl Target {
    fn validate(&self) -> Result<(), ProgramError> {
        let identities = [
            self.role.as_deref(),
            self.accessible_name.as_deref(),
            self.label.as_deref(),
            self.test_id.as_deref(),
            self.component_hint.as_deref(),
            self.fallback_css.as_deref(),
        ];
        let empty = identities
            .iter()
            .flatten()
            .all(|value| value.trim().is_empty());
        if empty {
            return Err(ProgramError::Invalid(
                "target needs a semantic identity (test_id, role, name, label, or CSS fallback)"
                    .into(),
            ));
        }
        if identities.iter().flatten().any(|value| {
            let value = value.trim().to_ascii_lowercase();
            value.contains("xpath") || value.starts_with("//")
        }) {
            return Err(ProgramError::Invalid(
                "XPath is not a TestProgram identity".into(),
            ));
        }
        if let Some(scope) = &self.scope {
            scope.validate()?;
        }
        Ok(())
    }
}

/// Deterministic browser fault registered by a program.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum FaultSpec {
    /// Abort matching requests.
    Abort {
        /// URL substring.
        url_contains: String,
    },
    /// Fulfil matching requests with a fixed response.
    HttpResponse {
        /// URL substring.
        url_contains: String,
        /// HTTP status.
        status: u16,
        /// Optional deterministic body.
        #[serde(default)]
        body: String,
        /// Fixed response headers.
        #[serde(default)]
        headers: BTreeMap<String, String>,
    },
    /// Delay matching requests before continuing.
    Delay {
        /// URL substring.
        url_contains: String,
        /// Bounded delay.
        delay_ms: u32,
    },
}

impl FaultSpec {
    fn validate(&self) -> Result<(), ProgramError> {
        let (url, status, delay) = match self {
            Self::Abort { url_contains } => (url_contains, None, None),
            Self::HttpResponse {
                url_contains,
                status,
                ..
            } => (url_contains, Some(*status), None),
            Self::Delay {
                url_contains,
                delay_ms,
            } => (url_contains, None, Some(*delay_ms)),
        };
        if url.trim().is_empty() {
            return Err(ProgramError::Invalid(
                "fault URL fragment must be non-empty".into(),
            ));
        }
        if status.is_some_and(|status| !(100..=599).contains(&status)) {
            return Err(ProgramError::Invalid(
                "fault HTTP status must be between 100 and 599".into(),
            ));
        }
        if delay.is_some_and(|delay| delay == 0 || delay > 30_000) {
            return Err(ProgramError::Invalid(
                "fault delay_ms must be between 1 and 30000".into(),
            ));
        }
        Ok(())
    }
}

/// Registered direct API operation. URLs stay relative to the configured app.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ApiOperation {
    /// HTTP method.
    pub method: String,
    /// Root-relative application path.
    pub path: String,
    /// Fixed request headers.
    #[serde(default)]
    pub headers: BTreeMap<String, String>,
}

impl ApiOperation {
    fn validate(&self) -> Result<(), ProgramError> {
        if !matches!(
            self.method.as_str(),
            "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"
        ) {
            return Err(ProgramError::Invalid(format!(
                "unsupported API method `{}`",
                self.method
            )));
        }
        if !self.path.starts_with('/') || self.path.starts_with("//") {
            return Err(ProgramError::Invalid(
                "API operation path must be root-relative".into(),
            ));
        }
        Ok(())
    }
}

/// Wait predicate. Timeouts are explicit; no implicit sleeps in the IR.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum WaitCondition {
    /// Target is visible.
    Visible {
        /// Target.
        target: Target,
    },
    /// URL matches a prefix/path.
    Url {
        /// Route prefix or path.
        route: String,
    },
}

/// Typed action. Unknown `action` tags fail closed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum TestAction {
    /// Open a route.
    Navigate {
        /// Application route.
        route: String,
    },
    /// Click / press a control.
    Activate {
        /// Semantic target.
        target: Target,
    },
    /// Fill an input.
    Fill {
        /// Semantic target.
        target: Target,
        /// Fixture value (not a locator).
        value: String,
    },
    /// Choose an option.
    Select {
        /// Semantic target.
        target: Target,
        /// Option value.
        value: String,
    },
    /// Keyboard key.
    Press {
        /// Optional focused target.
        #[serde(default)]
        target: Option<Target>,
        /// Key token (`Enter`).
        key: String,
    },
    /// Deterministic wait.
    Wait {
        /// Condition.
        condition: WaitCondition,
    },
    /// Feature flag.
    SetFeatureFlag {
        /// Flag key.
        key: String,
        /// Flag value.
        value: String,
    },
    /// Inject a named fault.
    InjectFault {
        /// Fault identity.
        fault: String,
    },
    /// Direct API operation.
    ApiCall {
        /// Operation id.
        operation: String,
        /// Input fixture name.
        input: String,
    },
    /// Pointer hover. Does not activate.
    Hover {
        /// Semantic target.
        target: Target,
    },
    /// Bring a target into view. Does not activate.
    Scroll {
        /// Semantic target.
        target: Target,
    },
    /// Drag `target` onto `to`. Both identities are semantic.
    Drag {
        /// Source.
        target: Target,
        /// Drop target.
        to: Target,
    },
    /// Set files on a file input from a named program fixture. Not a filesystem path.
    Upload {
        /// Semantic file-input target.
        target: Target,
        /// Name in `TestProgram.data`.
        fixture: String,
    },
    /// Activate a control and wait for a download. Bytes stay out of observations.
    Download {
        /// Semantic target that starts the download.
        target: Target,
    },
    /// Activate a control and switch to the opened popup or tab.
    Popup {
        /// Semantic target that opens the window.
        target: Target,
    },
    /// Switch the driver to an already-open page whose route matches a prefix.
    SwitchTab {
        /// Route prefix or path.
        route: String,
    },
    /// Assert a sealed obligation.
    Assert {
        /// Obligation id.
        obligation: ObligationId,
    },
}

impl TestAction {
    pub(crate) fn validate(&self) -> Result<(), ProgramError> {
        match self {
            Self::Navigate { route } if route.is_empty() => Err(ProgramError::Invalid(
                "navigate route must be non-empty".into(),
            )),
            Self::Activate { target }
            | Self::Fill { target, .. }
            | Self::Select { target, .. }
            | Self::Hover { target }
            | Self::Scroll { target }
            | Self::Download { target }
            | Self::Popup { target }
            | Self::Wait {
                condition: WaitCondition::Visible { target },
            } => target.validate(),
            Self::Drag { target, to } => {
                target.validate()?;
                to.validate()
            }
            Self::Upload { target, fixture } => {
                target.validate()?;
                validate_registered_name("upload fixture", fixture)
            }
            Self::SwitchTab { route } if route.is_empty() => Err(ProgramError::Invalid(
                "switch_tab route must be non-empty".into(),
            )),
            Self::Press { target, key } => {
                if key.is_empty() {
                    return Err(ProgramError::Invalid("press key must be non-empty".into()));
                }
                target.as_ref().map_or(Ok(()), Target::validate)
            }
            Self::Wait {
                condition: WaitCondition::Url { route },
            } if route.is_empty() => {
                Err(ProgramError::Invalid("wait url must be non-empty".into()))
            }
            Self::SetFeatureFlag { key, .. } if key.is_empty() => Err(ProgramError::Invalid(
                "feature flag key must be non-empty".into(),
            )),
            Self::InjectFault { fault } if fault.is_empty() => {
                Err(ProgramError::Invalid("fault id must be non-empty".into()))
            }
            Self::ApiCall { operation, .. } if operation.is_empty() => Err(ProgramError::Invalid(
                "api operation must be non-empty".into(),
            )),
            _ => Ok(()),
        }
    }

    /// Wire tag used by the diagnostic failure reel.
    #[must_use]
    pub fn kind(&self) -> &'static str {
        match self {
            Self::Navigate { .. } => "navigate",
            Self::Activate { .. } => "activate",
            Self::Fill { .. } => "fill",
            Self::Select { .. } => "select",
            Self::Press { .. } => "press",
            Self::Wait { .. } => "wait",
            Self::SetFeatureFlag { .. } => "set_feature_flag",
            Self::InjectFault { .. } => "inject_fault",
            Self::ApiCall { .. } => "api_call",
            Self::Hover { .. } => "hover",
            Self::Scroll { .. } => "scroll",
            Self::Drag { .. } => "drag",
            Self::Upload { .. } => "upload",
            Self::Download { .. } => "download",
            Self::Popup { .. } => "popup",
            Self::SwitchTab { .. } => "switch_tab",
            Self::Assert { .. } => "assert",
        }
    }

    /// Semantic target the action names, if any. Navigate and assert have none.
    #[must_use]
    pub fn semantic_target(&self) -> Option<&Target> {
        match self {
            Self::Activate { target }
            | Self::Fill { target, .. }
            | Self::Select { target, .. }
            | Self::Hover { target }
            | Self::Scroll { target }
            | Self::Drag { target, .. }
            | Self::Upload { target, .. }
            | Self::Download { target }
            | Self::Popup { target }
            | Self::Wait {
                condition: WaitCondition::Visible { target },
            } => Some(target),
            Self::Press { target, .. } => target.as_ref(),
            _ => None,
        }
    }
}

/// Ceiling on named upload fixture text. Larger payloads fail closed.
const MAX_UPLOAD_TEXT_BYTES: usize = 64 * 1024;

fn validate_registered_name(label: &str, name: &str) -> Result<(), ProgramError> {
    if name.is_empty() {
        return Err(ProgramError::Invalid(format!("{label} must be non-empty")));
    }
    if name.contains('/') || name.contains('\\') || name.contains("..") {
        return Err(ProgramError::Invalid(format!(
            "{label} must be a registered name, not a path"
        )));
    }
    Ok(())
}

fn validate_upload_filename(name: &str) -> Result<(), ProgramError> {
    if name.is_empty() || name == "." || name == ".." {
        return Err(ProgramError::Invalid(
            "upload filename must be a basename".into(),
        ));
    }
    let path = Path::new(name);
    if path.components().count() != 1 || path.file_name() != Some(std::ffi::OsStr::new(name)) {
        return Err(ProgramError::Invalid(
            "upload filename must be a basename".into(),
        ));
    }
    Ok(())
}

fn validate_upload_fixture(
    fixture: &str,
    data: &BTreeMap<String, serde_json::Value>,
) -> Result<(), ProgramError> {
    validate_registered_name("upload fixture", fixture)?;
    let Some(value) = data.get(fixture) else {
        return Err(ProgramError::Invalid(format!(
            "upload names unknown data `{fixture}`"
        )));
    };
    let Some(object) = value.as_object() else {
        return Err(ProgramError::Invalid(
            "upload fixture must be an object with filename and text".into(),
        ));
    };
    if object.keys().any(|key| key != "filename" && key != "text") {
        return Err(ProgramError::Invalid(
            "upload fixture has unknown fields".into(),
        ));
    }
    let Some(filename) = object.get("filename").and_then(serde_json::Value::as_str) else {
        return Err(ProgramError::Invalid(
            "upload fixture needs a filename".into(),
        ));
    };
    let Some(text) = object.get("text").and_then(serde_json::Value::as_str) else {
        return Err(ProgramError::Invalid("upload fixture needs text".into()));
    };
    validate_upload_filename(filename)?;
    if text.len() > MAX_UPLOAD_TEXT_BYTES {
        return Err(ProgramError::Invalid(
            "upload fixture text exceeds 64KiB".into(),
        ));
    }
    Ok(())
}

/// Canonical browser/API program.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TestProgram {
    /// Schema version. Only `1`.
    pub schema_v: u32,
    /// Program identity.
    pub id: ProgramId,
    /// Provenance.
    pub source: ProgramSource,
    /// Sealed obligations this program may prove.
    pub obligations: Vec<ObligationId>,
    /// Setup actions executed before the measured steps.
    #[serde(default)]
    pub preconditions: Vec<TestAction>,
    /// Ordered steps.
    pub steps: Vec<TestAction>,
    /// Named deterministic data fixtures used by API operations and uploads.
    #[serde(default)]
    pub data: BTreeMap<String, serde_json::Value>,
    /// Named network faults. `InjectFault` can only select one of these.
    #[serde(default)]
    pub faults: BTreeMap<String, FaultSpec>,
    /// Named, root-relative API operations.
    #[serde(default)]
    pub api_operations: BTreeMap<String, ApiOperation>,
    /// Capture policy.
    #[serde(default)]
    pub evidence_policy: EvidencePolicy,
    /// Deterministic seed for fixtures/faults.
    #[serde(default)]
    pub deterministic_seed: Option<u64>,
}

impl TestProgram {
    /// Decode and validate a program document.
    ///
    /// # Errors
    ///
    /// Unknown schema, unknown fields/actions, empty/XPath-like targets, or
    /// missing obligations/steps.
    pub fn from_json(raw: &str) -> Result<Self, ProgramError> {
        if raw.contains("\"xpath\"") {
            return Err(ProgramError::Invalid(
                "XPath is not a TestProgram identity".into(),
            ));
        }
        let program: Self =
            serde_json::from_str(raw).map_err(|err| ProgramError::Malformed(err.to_string()))?;
        program.validate()?;
        Ok(program)
    }

    /// Structural validation.
    ///
    /// # Errors
    ///
    /// Returns [`ProgramError`] when the program cannot be executed.
    pub fn validate(&self) -> Result<(), ProgramError> {
        if self.schema_v != 1 {
            return Err(ProgramError::UnknownSchema(self.schema_v));
        }
        if self.obligations.is_empty() {
            return Err(ProgramError::Invalid(
                "TestProgram needs at least one obligation".into(),
            ));
        }
        if self.steps.is_empty() {
            return Err(ProgramError::Invalid(
                "TestProgram needs at least one step".into(),
            ));
        }
        for fault in self.faults.values() {
            fault.validate()?;
        }
        for operation in self.api_operations.values() {
            operation.validate()?;
        }
        if self
            .preconditions
            .iter()
            .any(|action| matches!(action, TestAction::Assert { .. }))
        {
            return Err(ProgramError::Invalid(
                "preconditions cannot assert an obligation".into(),
            ));
        }
        let mut asserted = std::collections::BTreeSet::new();
        for step in self.preconditions.iter().chain(&self.steps) {
            step.validate()?;
            match step {
                TestAction::Assert { obligation } if !self.obligations.contains(obligation) => {
                    return Err(ProgramError::Invalid(format!(
                        "assert names undeclared obligation `{obligation}`"
                    )));
                }
                TestAction::Assert { obligation } => {
                    asserted.insert(obligation.clone());
                }
                TestAction::InjectFault { fault } if !self.faults.contains_key(fault) => {
                    return Err(ProgramError::Invalid(format!(
                        "inject_fault names unknown fault `{fault}`"
                    )));
                }
                TestAction::ApiCall { operation, input }
                    if !self.api_operations.contains_key(operation)
                        || !self.data.contains_key(input) =>
                {
                    return Err(ProgramError::Invalid(format!(
                        "api_call requires registered operation `{operation}` and data `{input}`"
                    )));
                }
                TestAction::Upload { fixture, .. } => {
                    validate_upload_fixture(fixture, &self.data)?;
                }
                _ => {}
            }
        }
        if let Some(missing) = self
            .obligations
            .iter()
            .find(|obligation| !asserted.contains(*obligation))
        {
            return Err(ProgramError::Invalid(format!(
                "declared obligation `{missing}` is never asserted"
            )));
        }
        Ok(())
    }
}

/// One ordered browser request. Bodies and header values are never captured.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NetworkRequestObservation {
    /// Monotonic identity within one browser program run.
    pub sequence: u64,
    /// Uppercase HTTP method.
    pub method: String,
    /// Request URL. Repository redaction policy may replace sensitive parts.
    pub url: String,
    /// Response status when it was observed before this snapshot.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<u16>,
    /// Playwright resource class (`fetch`, `xhr`, `document`, …), when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource_type: Option<String>,
    /// Lowercase request media type, without parameters.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    /// Canonical JSON or raw SHA-256 of the request body. Never the body.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body_digest: Option<String>,
    /// GraphQL operation name when the request was GraphQL-shaped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub graphql_operation: Option<String>,
    /// SHA-256 of the whitespace-normalised GraphQL query.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub graphql_query_digest: Option<String>,
    /// SHA-256 of canonical GraphQL variables.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub graphql_variables_digest: Option<String>,
}

impl NetworkRequestObservation {
    /// Privacy-safe comparison token. Falls back to method + path for v1 journals.
    #[must_use]
    pub fn identity_key(&self) -> String {
        let mut identity = crate::identify_request(
            &self.method,
            &self.url,
            self.content_type.as_deref().unwrap_or(""),
            None,
        );
        if let Some(content_type) = &self.content_type {
            identity.content_type.clone_from(content_type);
        }
        identity.body_digest.clone_from(&self.body_digest);
        if self.graphql_query_digest.is_some() || self.graphql_variables_digest.is_some() {
            identity.graphql = Some(crate::GraphqlIdentity {
                operation_name: self.graphql_operation.clone(),
                query_digest: self.graphql_query_digest.clone().unwrap_or_default(),
                variables_digest: self.graphql_variables_digest.clone().unwrap_or_default(),
            });
            identity.body_digest = None;
        }
        identity.key()
    }
}

/// Structured observation. Binary screenshots stay handles.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct Observation {
    /// Current route.
    #[serde(default)]
    pub route: Option<String>,
    /// Accessibility / DOM digest.
    #[serde(default)]
    pub a11y_digest: Option<String>,
    /// Network metadata (method + URL), not bodies.
    #[serde(default)]
    pub network: Vec<String>,
    /// Ordered request identities used for exact per-action evidence.
    #[serde(default)]
    pub network_requests: Vec<NetworkRequestObservation>,
    /// True when the bounded request journal omitted later requests.
    #[serde(default)]
    pub network_requests_truncated: bool,
    /// Console lines.
    #[serde(default)]
    pub console: Vec<String>,
    /// Storage keys.
    #[serde(default)]
    pub storage: BTreeMap<String, String>,
    /// Whether storage was instrumented for the current document.
    #[serde(default)]
    pub storage_available: bool,
    /// Viewport `WxH`.
    #[serde(default)]
    pub viewport: Option<String>,
    /// CAS handle. Absent unless the evidence policy allows it.
    #[serde(default)]
    pub screenshot_handle: Option<String>,
    /// SHA-256 of the captured visual surface. Never a perceptual score.
    #[serde(default)]
    pub visual_digest: Option<String>,
    /// Which bytes `visual_digest` covers. Currently `screenshot_png`.
    #[serde(default)]
    pub visual_surface: Option<String>,
}

/// Apply [`EvidencePolicy`] to a raw observation.
#[must_use]
pub fn filter_observation(
    mut observation: Observation,
    policy: &EvidencePolicy,
    failed: bool,
) -> Observation {
    if !policy.allow_screenshot(failed) {
        observation.screenshot_handle = None;
        observation.visual_digest = None;
        observation.visual_surface = None;
    }
    if matches!(policy.network, CaptureWhen::Never)
        || (matches!(policy.network, CaptureWhen::OnFailure) && !failed)
    {
        observation.network.clear();
        observation.network_requests.clear();
        observation.network_requests_truncated = false;
    }
    if matches!(policy.console, CaptureWhen::Never)
        || (matches!(policy.console, CaptureWhen::OnFailure) && !failed)
    {
        observation.console.clear();
    }
    if matches!(policy.storage, CaptureWhen::Never)
        || (matches!(policy.storage, CaptureWhen::OnFailure) && !failed)
    {
        observation.storage.clear();
    }
    observation
}