ftui-runtime 0.3.1

Elm-style runtime loop and subscriptions for FrankenTUI.
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
//! CI artifact contracts, replay helpers, and failure-triage reports (bd-cn65n).
//!
//! This module defines the artifact contract for the Asupersync migration CI.
//! Each test suite must emit consistent, replay-friendly artifacts. Missing or
//! malformed evidence is a hard failure. Operators can navigate from a failed
//! gate to replay instructions using the `ReplayBundle` type.
//!
//! # Artifact Contract
//!
//! Every validation suite must produce:
//! 1. A trace (ordered list of lifecycle events)
//! 2. A verdict (pass/fail with reason)
//! 3. A replay bundle (inputs + expected outputs for reproduction)
//!
//! These are validated by the tests in this file.

#![forbid(unsafe_code)]

use ftui_core::event::Event;
use ftui_render::frame::Frame;
use ftui_runtime::program::{Cmd, Model, RuntimeLane};
use ftui_runtime::simulator::ProgramSimulator;

// ============================================================================
// Artifact contract types
// ============================================================================

/// A replay bundle captures everything needed to reproduce a test result.
#[derive(Debug, Clone)]
struct ReplayBundle {
    /// Human-readable name for the scenario.
    scenario: String,
    /// Which runtime lane was tested.
    lane: RuntimeLane,
    /// Input messages (serialized as debug strings for replay).
    inputs: Vec<String>,
    /// Expected trace output.
    expected_trace: Vec<String>,
    /// Actual trace output.
    actual_trace: Vec<String>,
    /// Whether the test passed.
    passed: bool,
    /// Failure reason if any.
    failure_reason: Option<String>,
}

impl ReplayBundle {
    fn new(scenario: &str, lane: RuntimeLane) -> Self {
        Self {
            scenario: scenario.into(),
            lane,
            inputs: vec![],
            expected_trace: vec![],
            actual_trace: vec![],
            passed: true,
            failure_reason: None,
        }
    }

    fn add_input(&mut self, input: &str) {
        self.inputs.push(input.into());
    }

    fn set_expected(&mut self, trace: Vec<String>) {
        self.expected_trace = trace;
    }

    fn set_actual(&mut self, trace: Vec<String>) {
        self.actual_trace = trace;
    }

    fn verify(&mut self) {
        if self.actual_trace != self.expected_trace {
            self.passed = false;
            self.failure_reason = Some(format!(
                "Trace mismatch:\n  expected: {:?}\n  actual:   {:?}",
                self.expected_trace, self.actual_trace
            ));
        }
    }

    /// Generate triage report for operators.
    fn triage_report(&self) -> String {
        let mut report = String::new();
        report.push_str(&format!("=== Triage Report: {} ===\n", self.scenario));
        report.push_str(&format!("Lane: {}\n", self.lane));
        report.push_str(&format!(
            "Verdict: {}\n",
            if self.passed { "PASS" } else { "FAIL" }
        ));

        if let Some(ref reason) = self.failure_reason {
            report.push_str(&format!("Failure: {reason}\n"));
        }

        report.push_str("\n--- Replay Instructions ---\n");
        report.push_str("1. Create model with ArtifactModel { trace: vec![] }\n");
        report.push_str("2. Call sim.init()\n");
        for (i, input) in self.inputs.iter().enumerate() {
            report.push_str(&format!("3.{i}. sim.send({input})\n"));
        }
        report.push_str("4. Compare trace against expected\n");

        report.push_str("\n--- Expected Trace ---\n");
        for (i, entry) in self.expected_trace.iter().enumerate() {
            report.push_str(&format!("  [{i:3}] {entry}\n"));
        }

        if !self.passed {
            report.push_str("\n--- Actual Trace ---\n");
            for (i, entry) in self.actual_trace.iter().enumerate() {
                let marker = if i < self.expected_trace.len() && entry != &self.expected_trace[i] {
                    " <-- DIVERGES"
                } else if i >= self.expected_trace.len() {
                    " <-- EXTRA"
                } else {
                    ""
                };
                report.push_str(&format!("  [{i:3}] {entry}{marker}\n"));
            }
        }

        report
    }

    fn assert_passed(&self) {
        assert!(
            self.passed,
            "Artifact contract violation:\n{}",
            self.triage_report()
        );
    }
}

// ============================================================================
// Artifact model
// ============================================================================

struct ArtifactModel {
    trace: Vec<String>,
}

#[derive(Debug)]
enum AMsg {
    Step(String),
    Batch(Vec<String>),
    Task(String),
    TaskDone(String),
    Quit,
}

impl From<Event> for AMsg {
    fn from(_: Event) -> Self {
        AMsg::Step("event".into())
    }
}

impl Model for ArtifactModel {
    type Message = AMsg;

    fn init(&mut self) -> Cmd<Self::Message> {
        self.trace.push("init".into());
        Cmd::none()
    }

    fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
        match msg {
            AMsg::Step(s) => {
                self.trace.push(format!("step:{s}"));
                Cmd::none()
            }
            AMsg::Batch(items) => {
                self.trace.push(format!("batch:{}", items.len()));
                Cmd::batch(items.into_iter().map(|s| Cmd::msg(AMsg::Step(s))).collect())
            }
            AMsg::Task(l) => {
                self.trace.push(format!("task:{l}"));
                let lc = l.clone();
                Cmd::task(move || AMsg::TaskDone(lc))
            }
            AMsg::TaskDone(l) => {
                self.trace.push(format!("done:{l}"));
                Cmd::none()
            }
            AMsg::Quit => {
                self.trace.push("quit".into());
                Cmd::quit()
            }
        }
    }

    fn view(&self, _frame: &mut Frame) {}
}

fn new_sim() -> ProgramSimulator<ArtifactModel> {
    let mut sim = ProgramSimulator::new(ArtifactModel { trace: vec![] });
    sim.init();
    sim
}

// ============================================================================
// CONTRACT: ReplayBundle captures complete evidence
// ============================================================================

#[test]
fn artifact_replay_bundle_captures_pass() {
    let mut bundle = ReplayBundle::new("basic_steps", RuntimeLane::Structured);
    bundle.add_input("Step(a)");
    bundle.add_input("Step(b)");

    let mut sim = new_sim();
    sim.send(AMsg::Step("a".into()));
    sim.send(AMsg::Step("b".into()));

    let expected = vec![
        "init".to_string(),
        "step:a".to_string(),
        "step:b".to_string(),
    ];
    bundle.set_expected(expected);
    bundle.set_actual(sim.model().trace.clone());
    bundle.verify();

    assert!(bundle.passed);
    assert!(bundle.failure_reason.is_none());
    bundle.assert_passed();
}

#[test]
fn artifact_replay_bundle_detects_mismatch() {
    let mut bundle = ReplayBundle::new("intentional_mismatch", RuntimeLane::Structured);
    bundle.set_expected(vec!["init".to_string(), "step:a".to_string()]);
    bundle.set_actual(vec!["init".to_string(), "step:WRONG".to_string()]);
    bundle.verify();

    assert!(!bundle.passed);
    assert!(bundle.failure_reason.is_some());
    let reason = bundle.failure_reason.as_ref().unwrap();
    assert!(
        reason.contains("Trace mismatch"),
        "reason should mention mismatch"
    );
}

#[test]
fn artifact_triage_report_contains_replay_instructions() {
    let mut bundle = ReplayBundle::new("triage_test", RuntimeLane::Structured);
    bundle.add_input("Step(x)");
    bundle.add_input("Batch([y, z])");
    bundle.set_expected(vec!["init".into(), "step:x".into()]);
    bundle.set_actual(vec!["init".into(), "step:x".into()]);
    bundle.verify();

    let report = bundle.triage_report();
    assert!(report.contains("Triage Report: triage_test"));
    assert!(report.contains("Lane: structured"));
    assert!(report.contains("Verdict: PASS"));
    assert!(report.contains("Replay Instructions"));
    assert!(report.contains("Step(x)"));
    assert!(report.contains("Batch([y, z])"));
    assert!(report.contains("Expected Trace"));
}

#[test]
fn artifact_triage_report_marks_divergence() {
    let mut bundle = ReplayBundle::new("divergence", RuntimeLane::Legacy);
    bundle.set_expected(vec!["init".into(), "step:a".into()]);
    bundle.set_actual(vec!["init".into(), "step:WRONG".into()]);
    bundle.verify();

    let report = bundle.triage_report();
    assert!(report.contains("FAIL"));
    assert!(report.contains("DIVERGES"));
}

// ============================================================================
// CONTRACT: Validation suites produce complete artifacts
// ============================================================================

#[test]
fn artifact_happy_path_complete() {
    let mut bundle = ReplayBundle::new("happy_path", RuntimeLane::Structured);
    bundle.add_input("Step(a)");
    bundle.add_input("Batch([b, c])");
    bundle.add_input("Task(t)");

    let mut sim = new_sim();
    sim.send(AMsg::Step("a".into()));
    sim.send(AMsg::Batch(vec!["b".into(), "c".into()]));
    sim.send(AMsg::Task("t".into()));

    let expected = vec![
        "init", "step:a", "batch:2", "step:b", "step:c", "task:t", "done:t",
    ]
    .into_iter()
    .map(String::from)
    .collect();

    bundle.set_expected(expected);
    bundle.set_actual(sim.model().trace.clone());
    bundle.verify();
    bundle.assert_passed();

    // Artifact completeness checks
    assert!(!bundle.inputs.is_empty(), "inputs must be recorded");
    assert!(
        !bundle.expected_trace.is_empty(),
        "expected trace must be set"
    );
    assert!(!bundle.actual_trace.is_empty(), "actual trace must be set");
    assert_eq!(bundle.scenario, "happy_path");
    assert_eq!(bundle.lane, RuntimeLane::Structured);
}

#[test]
fn artifact_failure_path_complete() {
    let mut bundle = ReplayBundle::new("quit_path", RuntimeLane::Structured);
    bundle.add_input("Step(before)");
    bundle.add_input("Quit");
    bundle.add_input("Step(after)");

    let mut sim = new_sim();
    sim.send(AMsg::Step("before".into()));
    sim.send(AMsg::Quit);
    sim.send(AMsg::Step("after".into()));

    let expected = vec!["init", "step:before", "quit"]
        .into_iter()
        .map(String::from)
        .collect();

    bundle.set_expected(expected);
    bundle.set_actual(sim.model().trace.clone());
    bundle.verify();
    bundle.assert_passed();
    assert!(!sim.is_running());
}

#[test]
fn artifact_stress_path_complete() {
    let mut bundle = ReplayBundle::new("stress_100_batch", RuntimeLane::Structured);
    let items: Vec<String> = (0..100).map(|i| format!("{i}")).collect();
    bundle.add_input("Batch([0..99])");

    let mut sim = new_sim();
    sim.send(AMsg::Batch(items));

    let trace = sim.model().trace.clone();
    // Build expected: init, batch:100, step:0, step:1, ..., step:99
    let mut expected = vec!["init".to_string(), "batch:100".to_string()];
    for i in 0..100 {
        expected.push(format!("step:{i}"));
    }

    bundle.set_expected(expected);
    bundle.set_actual(trace);
    bundle.verify();
    bundle.assert_passed();
}

// ============================================================================
// CONTRACT: Missing evidence is a hard failure
// ============================================================================

#[test]
fn artifact_missing_expected_is_failure() {
    let mut bundle = ReplayBundle::new("missing_expected", RuntimeLane::Structured);
    // Don't set expected trace
    bundle.set_actual(vec!["init".into()]);
    bundle.verify();

    // Empty expected != non-empty actual = mismatch
    assert!(!bundle.passed, "missing expected trace must be a failure");
}

#[test]
fn artifact_missing_actual_is_failure() {
    let mut bundle = ReplayBundle::new("missing_actual", RuntimeLane::Structured);
    bundle.set_expected(vec!["init".into()]);
    // Don't set actual trace
    bundle.verify();

    // Non-empty expected != empty actual = mismatch
    assert!(!bundle.passed, "missing actual trace must be a failure");
}

// ============================================================================
// CONTRACT: Replay bundles are deterministic
// ============================================================================

#[test]
fn artifact_replay_deterministic() {
    fn run_and_bundle() -> ReplayBundle {
        let mut bundle = ReplayBundle::new("determinism", RuntimeLane::Structured);
        bundle.add_input("Step(x)");
        bundle.add_input("Batch([y, z])");
        bundle.add_input("Task(t)");

        let mut sim = new_sim();
        sim.send(AMsg::Step("x".into()));
        sim.send(AMsg::Batch(vec!["y".into(), "z".into()]));
        sim.send(AMsg::Task("t".into()));

        bundle.set_actual(sim.model().trace.clone());
        bundle.set_expected(sim.model().trace.clone()); // self-consistent
        bundle.verify();
        bundle
    }

    let b1 = run_and_bundle();
    let b2 = run_and_bundle();
    let b3 = run_and_bundle();

    assert_eq!(b1.actual_trace, b2.actual_trace);
    assert_eq!(b2.actual_trace, b3.actual_trace);
    assert!(b1.passed && b2.passed && b3.passed);
}