wvq-runtime 0.1.0-alpha.3

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
//! Normalized `BehaviorGraph`: hashed states, recorded traces, replay, promotion.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use wvq_domain::{ContentHash, ObligationId, ProgramId};

use crate::program::{ProgramError, ProgramSource, Target, TestAction, TestProgram};

/// Semantically normalized runtime state. Screenshots are not part of identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct BehaviorState {
    /// Application route.
    pub route: String,
    /// Actor / auth role.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub actor: Option<String>,
    /// Visible component.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub component: Option<String>,
    /// Modal identity, or `closed`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub modal: Option<String>,
    /// Network phase (`idle`, `loading`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network_phase: Option<String>,
    /// Data class (`above_visual_limit`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data_class: Option<String>,
    /// Feature flags, sorted.
    #[serde(default)]
    pub feature_flags: BTreeMap<String, String>,
    /// Accessibility / DOM digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub a11y_digest: Option<String>,
    /// Viewport `WxH`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub viewport: Option<String>,
}

impl BehaviorState {
    /// Build the persistent semantic state used by browser runs and passive recordings.
    #[must_use]
    pub fn from_observation(observation: &crate::Observation) -> Option<Self> {
        let route = observation
            .route
            .as_deref()
            .map(str::trim)
            .filter(|route| !route.is_empty())?;
        Some(Self {
            route: route.to_owned(),
            a11y_digest: observation.a11y_digest.clone(),
            viewport: observation.viewport.clone(),
            ..Self::default()
        })
    }

    /// Canonical JSON bytes used by both state identity and CAS persistence.
    ///
    /// # Errors
    ///
    /// Returns [`ProgramError::Malformed`] when serialization fails.
    pub fn canonical_json(&self) -> Result<Vec<u8>, ProgramError> {
        serde_json::to_vec(&canonical_value(self))
            .map_err(|err| ProgramError::Malformed(err.to_string()))
    }

    /// SHA-256 of the canonical JSON. Flag insertion order does not matter.
    ///
    /// # Errors
    ///
    /// Returns [`ProgramError::Malformed`] if the digest cannot be formed.
    pub fn digest(&self) -> Result<ContentHash, ProgramError> {
        let bytes = self.canonical_json()?;
        let hex = Sha256::digest(bytes)
            .iter()
            .fold(String::new(), |mut out, byte| {
                let _ = write!(out, "{byte:02x}");
                out
            });
        ContentHash::new(hex).map_err(|err| ProgramError::Malformed(err.to_string()))
    }
}

fn canonical_value(state: &BehaviorState) -> serde_json::Value {
    let mut map = serde_json::Map::new();
    insert_opt(&mut map, "a11y_digest", state.a11y_digest.as_ref());
    insert_opt(&mut map, "actor", state.actor.as_ref());
    insert_opt(&mut map, "component", state.component.as_ref());
    insert_opt(&mut map, "data_class", state.data_class.as_ref());
    map.insert(
        "feature_flags".into(),
        serde_json::to_value(&state.feature_flags).unwrap_or(serde_json::Value::Null),
    );
    insert_opt(&mut map, "modal", state.modal.as_ref());
    insert_opt(&mut map, "network_phase", state.network_phase.as_ref());
    map.insert(
        "route".into(),
        serde_json::Value::String(state.route.clone()),
    );
    insert_opt(&mut map, "viewport", state.viewport.as_ref());
    serde_json::Value::Object(map)
}

fn insert_opt(
    map: &mut serde_json::Map<String, serde_json::Value>,
    key: &str,
    value: Option<&String>,
) {
    if let Some(text) = value.filter(|item| !item.is_empty()) {
        map.insert(key.to_owned(), serde_json::Value::String(text.clone()));
    }
}

/// One recorded transition: `before --action--> after`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BehaviorEdge {
    /// Source state digest.
    pub src: ContentHash,
    /// Semantic action.
    pub action: TestAction,
    /// Destination state digest.
    pub dst: ContentHash,
}

impl BehaviorEdge {
    /// Stable edge identity shared by novelty scoring and persistence.
    ///
    /// # Errors
    ///
    /// Returns [`ProgramError::Malformed`] when the action cannot be serialized.
    pub fn identity(&self) -> Result<ContentHash, ProgramError> {
        let action = serde_json::to_string(&self.action)
            .map_err(|err| ProgramError::Malformed(err.to_string()))?;
        let bytes = format!("{}|{action}|{}", self.src, self.dst);
        let hex = Sha256::digest(bytes.as_bytes())
            .iter()
            .fold(String::new(), |mut out, byte| {
                let _ = write!(out, "{byte:02x}");
                out
            });
        ContentHash::new(hex).map_err(|err| ProgramError::Malformed(err.to_string()))
    }
}

/// One recorded event in a manual session.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RecordedEvent {
    /// User/runtime action.
    pub action: TestAction,
    /// State after the action.
    pub after: BehaviorState,
}

/// Finished manual session. Valuable QA must not disappear after one run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BehaviorTrace {
    /// Session identity.
    pub session_id: String,
    /// Fixture name (`admin-above-limit`).
    pub fixture: Option<String>,
    /// Deterministic seed used while recording.
    pub seed: Option<u64>,
    /// Named safe fixtures referenced by recorded form actions.
    #[serde(default)]
    pub data: BTreeMap<String, serde_json::Value>,
    /// Linked sealed obligations.
    pub obligations: Vec<ObligationId>,
    /// Linked API operations.
    pub api_operations: Vec<String>,
    /// Linked code-coverage node / file ids.
    pub coverage: Vec<String>,
    /// Initial state.
    pub initial: BehaviorState,
    /// Ordered events.
    pub events: Vec<RecordedEvent>,
}

impl BehaviorTrace {
    /// Unique state digests in visit order.
    ///
    /// # Errors
    ///
    /// Hash failure.
    pub fn state_digests(&self) -> Result<Vec<ContentHash>, ProgramError> {
        let mut out = vec![self.initial.digest()?];
        for event in &self.events {
            out.push(event.after.digest()?);
        }
        Ok(out)
    }

    /// Graph edges for persistence.
    ///
    /// # Errors
    ///
    /// Hash failure.
    pub fn edges(&self) -> Result<Vec<BehaviorEdge>, ProgramError> {
        let mut edges = Vec::new();
        let mut src = self.initial.digest()?;
        for event in &self.events {
            let dst = event.after.digest()?;
            edges.push(BehaviorEdge {
                src,
                action: event.action.clone(),
                dst: dst.clone(),
            });
            src = dst;
        }
        Ok(edges)
    }
}

/// Semantic manual recorder. Targets must be semantic; `XPath` fails closed.
#[derive(Debug, Clone)]
pub struct Recorder {
    session_id: String,
    fixture: Option<String>,
    seed: Option<u64>,
    initial: Option<BehaviorState>,
    current: Option<BehaviorState>,
    events: Vec<RecordedEvent>,
    obligations: BTreeSet<ObligationId>,
    api_operations: BTreeSet<String>,
    coverage: BTreeSet<String>,
    data: BTreeMap<String, serde_json::Value>,
}

impl Recorder {
    /// Start a session. Same seed/fixture must be reused on replay.
    #[must_use]
    pub fn new(session_id: impl Into<String>, fixture: Option<String>, seed: Option<u64>) -> Self {
        Self {
            session_id: session_id.into(),
            fixture,
            seed,
            initial: None,
            current: None,
            events: Vec::new(),
            obligations: BTreeSet::new(),
            api_operations: BTreeSet::new(),
            coverage: BTreeSet::new(),
            data: BTreeMap::new(),
        }
    }

    /// Observe the starting state before any action.
    pub fn start(&mut self, initial: BehaviorState) {
        self.initial = Some(initial.clone());
        self.current = Some(initial);
    }

    /// Record a semantic transition.
    ///
    /// # Errors
    ///
    /// Unknown/empty action or missing initial state.
    pub fn step(&mut self, action: TestAction, after: BehaviorState) -> Result<(), ProgramError> {
        action.validate()?;
        if self.initial.is_none() {
            return Err(ProgramError::Invalid(
                "recorder requires start() before step()".into(),
            ));
        }
        self.current = Some(after.clone());
        self.events.push(RecordedEvent { action, after });
        Ok(())
    }

    /// Link a sealed obligation covered by this session.
    pub fn link_obligation(&mut self, id: ObligationId) {
        self.obligations.insert(id);
    }

    /// Link an API operation observed during the session.
    pub fn link_api(&mut self, operation: impl Into<String>) {
        self.api_operations.insert(operation.into());
    }

    /// Link a measured coverage node/file.
    pub fn link_coverage(&mut self, node: impl Into<String>) {
        self.coverage.insert(node.into());
    }

    /// Register one explicit replay fixture. The recorder never invents values.
    pub fn link_fixture(&mut self, name: impl Into<String>, value: serde_json::Value) {
        self.data.insert(name.into(), value);
    }

    /// Finish the session.
    ///
    /// # Errors
    ///
    /// Missing initial state.
    pub fn finish(self) -> Result<BehaviorTrace, ProgramError> {
        let Some(initial) = self.initial else {
            return Err(ProgramError::Invalid(
                "recorder has no initial state".into(),
            ));
        };
        Ok(BehaviorTrace {
            session_id: self.session_id,
            fixture: self.fixture,
            seed: self.seed,
            data: self.data,
            obligations: self.obligations.into_iter().collect(),
            api_operations: self.api_operations.into_iter().collect(),
            coverage: self.coverage.into_iter().collect(),
            initial,
            events: self.events,
        })
    }
}

/// Known graph used to compute a session's contribution.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GraphMemory {
    /// Digests already in the `BehaviorGraph`.
    pub known_states: BTreeSet<String>,
    /// Edge identities already in the `BehaviorGraph`.
    pub known_edges: BTreeSet<String>,
    /// Obligations already proven or linked.
    pub known_obligations: BTreeSet<String>,
    /// API operations already seen.
    pub known_apis: BTreeSet<String>,
    /// Coverage nodes already measured.
    pub known_coverage: BTreeSet<String>,
}

/// What a session added: existing vs new, plus redundant steps.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CoverageContribution {
    /// Obligations already known.
    pub existing_obligations: Vec<String>,
    /// Obligations first seen here.
    pub new_obligations: Vec<String>,
    /// New hashed behavior states.
    pub new_behavior_states: u64,
    /// New non-loop behavior transitions.
    pub new_behavior_edges: u64,
    /// New API operations.
    pub new_api_operations: Vec<String>,
    /// New coverage nodes.
    pub new_code_coverage: Vec<String>,
    /// Steps that did not change the state digest.
    pub redundant_steps: u64,
}

/// Score a trace against graph memory.
///
/// # Errors
///
/// Hash failure.
pub fn coverage_contribution(
    trace: &BehaviorTrace,
    memory: &GraphMemory,
) -> Result<CoverageContribution, ProgramError> {
    let mut seen_states = BTreeSet::new();
    let mut new_behavior_states = 0_u64;
    for digest in trace.state_digests()? {
        if seen_states.insert(digest.as_str().to_owned())
            && !memory.known_states.contains(digest.as_str())
        {
            new_behavior_states = new_behavior_states.saturating_add(1);
        }
    }
    let (existing_obligations, new_obligations) =
        split_known(&trace.obligations, &memory.known_obligations);
    let mut seen_edges = BTreeSet::new();
    let mut new_behavior_edges = 0_u64;
    for edge in trace
        .edges()?
        .into_iter()
        .filter(|edge| edge.src != edge.dst)
    {
        let identity = edge.identity()?;
        if seen_edges.insert(identity.to_string())
            && !memory.known_edges.contains(identity.as_str())
        {
            new_behavior_edges = new_behavior_edges.saturating_add(1);
        }
    }
    let (_, new_api_operations) = split_known_str(&trace.api_operations, &memory.known_apis);
    let (_, new_code_coverage) = split_known_str(&trace.coverage, &memory.known_coverage);
    Ok(CoverageContribution {
        existing_obligations,
        new_obligations,
        new_behavior_states,
        new_behavior_edges,
        new_api_operations,
        new_code_coverage,
        redundant_steps: count_redundant(trace)?,
    })
}

fn split_known(ids: &[ObligationId], known: &BTreeSet<String>) -> (Vec<String>, Vec<String>) {
    let mut existing = Vec::new();
    let mut new = Vec::new();
    for id in ids {
        if known.contains(id.as_str()) {
            existing.push(id.to_string());
        } else {
            new.push(id.to_string());
        }
    }
    (existing, new)
}

fn split_known_str(ids: &[String], known: &BTreeSet<String>) -> (Vec<String>, Vec<String>) {
    let mut existing = Vec::new();
    let mut new = Vec::new();
    for id in ids {
        if known.contains(id) {
            existing.push(id.clone());
        } else {
            new.push(id.clone());
        }
    }
    (existing, new)
}

fn count_redundant(trace: &BehaviorTrace) -> Result<u64, ProgramError> {
    let mut prev = trace.initial.digest()?;
    let mut redundant = 0_u64;
    for event in &trace.events {
        let next = event.after.digest()?;
        if next == prev {
            redundant = redundant.saturating_add(1);
        }
        prev = next;
    }
    Ok(redundant)
}

/// Promote a useful path into a versioned `TestProgram`.
///
/// Redundant steps are dropped and the recording seed is copied through.
///
/// Every obligation the trace claims gets an exact [`TestAction::Assert`]. A
/// program that declares several obligations but only asserts the first one
/// would report proof it never measured, so the missing assertions are appended
/// in declaration order. Assertions the recording already contains are kept
/// where they are and never duplicated.
///
/// # Errors
///
/// No remaining steps, invalid identity, an assertion naming an obligation the
/// trace does not declare, or a program that still fails
/// [`TestProgram::validate`].
pub fn promote(trace: &BehaviorTrace, program_id: ProgramId) -> Result<TestProgram, ProgramError> {
    let declared = trace
        .obligations
        .iter()
        .map(|obligation| obligation.as_str().to_owned())
        .collect::<BTreeSet<_>>();
    let mut steps = Vec::new();
    let mut asserted = BTreeSet::new();
    let mut measured = 0_usize;
    let mut prev = trace.initial.digest()?;
    for event in &trace.events {
        let next = event.after.digest()?;
        // A recorded assertion carries no state change of its own, so it must
        // survive the redundancy filter that drops no-op interactions.
        let assertion = match &event.action {
            TestAction::Assert { obligation } => Some(obligation.as_str().to_owned()),
            _ => None,
        };
        if let Some(obligation) = assertion {
            if !declared.contains(&obligation) {
                return Err(ProgramError::Invalid(format!(
                    "recorded assertion names undeclared obligation `{obligation}`"
                )));
            }
            // Deduplicate: the same obligation asserted twice stays asserted once.
            if asserted.insert(obligation) {
                steps.push(event.action.clone());
            }
        } else if next != prev {
            steps.push(event.action.clone());
            measured += 1;
        }
        prev = next;
    }
    if measured == 0 {
        return Err(ProgramError::Invalid(
            "promotion candidate has no non-redundant steps".into(),
        ));
    }
    // Deterministic order: declaration order, appended after the measured steps.
    for obligation in &trace.obligations {
        if asserted.insert(obligation.as_str().to_owned()) {
            steps.push(TestAction::Assert {
                obligation: obligation.clone(),
            });
        }
    }
    let program = TestProgram {
        schema_v: 1,
        id: program_id,
        source: ProgramSource::Recorded,
        obligations: trace.obligations.clone(),
        preconditions: Vec::new(),
        steps,
        data: trace.data.clone(),
        faults: BTreeMap::new(),
        api_operations: BTreeMap::new(),
        evidence_policy: crate::program::EvidencePolicy::default(),
        deterministic_seed: trace.seed,
    };
    program.validate()?;
    Ok(program)
}

/// Host that applies a typed action and returns the resulting state.
pub trait ReplayHost {
    /// Apply one IR action.
    ///
    /// # Errors
    ///
    /// Host/runtime failure.
    fn apply(&mut self, action: &TestAction) -> Result<BehaviorState, ProgramError>;
}

/// Replay a promoted program with the same seed/fixture contract.
///
/// # Errors
///
/// Seed mismatch, empty program, or host failure.
pub fn replay_program(
    program: &TestProgram,
    seed: Option<u64>,
    host: &mut dyn ReplayHost,
) -> Result<Vec<BehaviorState>, ProgramError> {
    program.validate()?;
    check_seed(program.deterministic_seed, seed)?;
    let mut states = Vec::new();
    for step in &program.steps {
        states.push(host.apply(step)?);
    }
    Ok(states)
}

/// Replay a recorded session with the same fixture and seed.
///
/// # Errors
///
/// Fixture/seed mismatch or host failure.
pub fn replay_trace(
    trace: &BehaviorTrace,
    fixture: Option<&str>,
    seed: Option<u64>,
    host: &mut dyn ReplayHost,
) -> Result<Vec<BehaviorState>, ProgramError> {
    check_seed(trace.seed, seed)?;
    match (&trace.fixture, fixture) {
        (Some(recorded), Some(wanted)) if recorded != wanted => {
            return Err(ProgramError::Invalid(
                "replay fixture does not match the recorded session".into(),
            ));
        }
        _ => {}
    }
    let mut states = Vec::new();
    for event in &trace.events {
        let after = host.apply(&event.action)?;
        if after.digest()? != event.after.digest()? {
            return Err(ProgramError::Invalid(
                "replay diverged from the recorded BehaviorGraph".into(),
            ));
        }
        states.push(after);
    }
    Ok(states)
}

fn check_seed(recorded: Option<u64>, requested: Option<u64>) -> Result<(), ProgramError> {
    match (recorded, requested) {
        (Some(left), Some(right)) if left != right => Err(ProgramError::Invalid(
            "replay seed does not match the recorded session".into(),
        )),
        _ => Ok(()),
    }
}

/// Helper for tests: a tiny semantic activate target.
#[must_use]
pub fn semantic_target(role: &str, name: &str) -> Target {
    Target {
        role: Some(role.to_owned()),
        accessible_name: Some(name.to_owned()),
        ..Target::default()
    }
}