supercode-core 0.2.1

A lightweight, fully-customizable AI coding agent SDK in Rust. Talks to any model via OpenRouter or any OpenAI-compatible endpoint.
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
//! §4.2 — EMULATE-TO-CONTINUE: per harness X in {claude, codex, opencode,
//! pi, grok}, load the real fixture, push a synthetic continuation turn, splice-
//! export back to X's own format, and assert (1) the imported prefix is
//! replayed verbatim/value-equal, (2) the appended turn reloads, and (3) a
//! frozen, format-specific offline invariant checker accepts the output
//! (`docs/interop/opencode-pi-spec.md` §4.2).
//!
//! The offline checker (assertion 3) is explicitly a self-authored contract
//! restatement, not independent evidence. Real stock-CLI continuation is owned
//! by `scripts/stock-resume-matrix-probe.mjs`, whose content-free dated receipt
//! is validated by `scripts/vision-audit.mjs`. The always-run table below prints
//! `live_resume = n/a` for every row so a green offline row is never mistaken
//! for external confirmation.

mod interop_common;

use std::path::{Path, PathBuf};

use async_trait::async_trait;
use serde_json::Value;
use supercode::reduce::export_session_spliced;
use supercode::session::{Session, SessionFormat};
use supercode::sidecar::SidecarWriter;
use supercode::{
    Agent, ChatMessage, ChatRequest, Config, FrontendRuntime, Provider, Role, RpcEngine, Usage,
};

fn fixture(name: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures")
        .join(name)
}

fn fixture_file_for(f: SessionFormat) -> &'static str {
    match f {
        SessionFormat::ClaudeCode => "claude_code_session.jsonl",
        SessionFormat::Codex => "codex_session.jsonl",
        SessionFormat::OpenCode => "opencode_session.jsonl",
        SessionFormat::Pi => "pi_session.jsonl",
        SessionFormat::Grok => "grok_session/chat_history.jsonl",
    }
}

fn fname(f: SessionFormat) -> &'static str {
    match f {
        SessionFormat::ClaudeCode => "claude",
        SessionFormat::Codex => "codex",
        SessionFormat::OpenCode => "opencode",
        SessionFormat::Pi => "pi",
        SessionFormat::Grok => "grok",
    }
}

fn load_fixture(f: SessionFormat) -> Session {
    let path = fixture(fixture_file_for(f));
    match f {
        SessionFormat::ClaudeCode => Session::from_claude_code(path).unwrap(),
        SessionFormat::Codex => Session::from_codex(path).unwrap(),
        SessionFormat::OpenCode => Session::from_opencode(path).unwrap(),
        SessionFormat::Pi => Session::from_pi(path).unwrap(),
        SessionFormat::Grok => Session::from_grok(path).unwrap(),
    }
}

fn continuation_turns() -> Vec<ChatMessage> {
    vec![
        ChatMessage::user("one more thing (emulate-continue synthetic turn)"),
        ChatMessage::assistant("sure thing (emulate-continue synthetic reply)"),
    ]
}

const FRONTEND_PROMPT: &str = "continue this imported harness through the SDK frontend";
const FRONTEND_REPLY: &str = "frontend continuation preserved the native session";

struct FixedContinuationProvider;

#[async_trait]
impl Provider for FixedContinuationProvider {
    async fn complete(
        &self,
        _request: &ChatRequest,
        on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode::Result<(ChatMessage, Usage)> {
        on_delta(FRONTEND_REPLY);
        Ok((ChatMessage::assistant(FRONTEND_REPLY), Usage::default()))
    }
}

fn messages_semantically_equal(a: &ChatMessage, b: &ChatMessage) -> bool {
    if a.role != b.role
        || a.content != b.content
        || a.content_parts != b.content_parts
        || a.tool_call_id != b.tool_call_id
        || a.name != b.name
    {
        return false;
    }
    let (left, right) = (a.tool_calls(), b.tool_calls());
    left.len() == right.len()
        && left.iter().zip(right).all(|(left, right)| {
            left.id == right.id
                && left.function.name == right.function.name
                && left.function.parsed_arguments().ok() == right.function.parsed_arguments().ok()
        })
}

fn assert_message_prefix(label: &str, expected: &[ChatMessage], actual: &[ChatMessage]) {
    assert!(
        actual.len() >= expected.len(),
        "{label}: expected at least {} messages, got {}",
        expected.len(),
        actual.len()
    );
    for (index, (expected, actual)) in expected.iter().zip(actual).enumerate() {
        assert!(
            messages_semantically_equal(expected, actual),
            "{label}: imported message {index} changed:\nexpected={expected:#?}\nactual={actual:#?}"
        );
    }
}

/// One row of the §4.2 metric table.
struct Row {
    harness: &'static str,
    prefix_verbatim: bool,
    turn_present: bool,
    invariants_ok: bool,
    live_resume: &'static str,
}

impl Row {
    fn print(&self) {
        println!(
            "  {:<10} | prefix_verbatim={:<5} | turn_present={:<5} | invariants_ok={:<5} | live_resume={}",
            self.harness, self.prefix_verbatim, self.turn_present, self.invariants_ok, self.live_resume
        );
    }
}

// ---------------------------------------------------------------------------
// Build one splice for `format`: load the fixture, append the synthetic
// continuation turns through the native-v2 sidecar mechanism (keeps
// raw/messages growing in lockstep, mirrors pi_interop.rs/opencode_interop.rs),
// then `to_jsonl_spliced(format, None)`.
// ---------------------------------------------------------------------------

struct Spliced {
    original: Session,
    out: String,
}

fn build_splice(format: SessionFormat) -> Spliced {
    let original = load_fixture(format);
    let appended = continuation_turns();
    let sidecar = original.to_native_jsonl_v2(&appended);
    let reconstructed = Session::from_sidecar_str(&sidecar).unwrap();
    let out = reconstructed
        .to_jsonl_spliced(format, None)
        .unwrap_or_else(|e| panic!("{format:?}: to_jsonl_spliced failed: {e}"));
    Spliced { original, out }
}

fn non_empty_lines(s: &str) -> Vec<&str> {
    s.lines().map(str::trim).filter(|l| !l.is_empty()).collect()
}

// ---------------------------------------------------------------------------
// Per-format checks
// ---------------------------------------------------------------------------

/// ClaudeCode/Codex/Pi: line-oriented JSONL, `session_id=None` — the raw
/// prefix must appear byte-for-byte unchanged at the head of `out`.
fn prefix_verbatim_line_oriented(sp: &Spliced) -> bool {
    let out_lines = non_empty_lines(&sp.out);
    if out_lines.len() < sp.original.raw.len() {
        return false;
    }
    out_lines
        .iter()
        .zip(&sp.original.raw)
        .all(|(got, want)| *got == want)
}

/// OpenCode: `out` is a single export DOCUMENT — every imported raw
/// envelope's `value` must appear value-equal at its position in the doc's
/// `messages[]`/`parts[]` (S5's restated phrasing).
fn prefix_value_equal_opencode(sp: &Spliced) -> bool {
    let (expected_messages, expected_parts) = raw_envelope_maps(&sp.original.raw);
    let doc: Value = match serde_json::from_str(&sp.out) {
        Ok(v) => v,
        Err(_) => return false,
    };
    let Some(messages) = doc.get("messages").and_then(Value::as_array) else {
        return false;
    };
    // The imported prefix occupies the FIRST `expected_messages.len()` slots,
    // in the same order raw was captured (session-info -> message by
    // (time.created,id) -> that message's parts by id, §1.2).
    if messages.len() < expected_messages.len() {
        return false;
    }
    // `raw_envelope_maps` loses insertion order (it's a HashMap); recover the
    // envelope order directly from `raw` itself instead of the map's keys.
    let mut order: Vec<String> = Vec::new();
    for line in &sp.original.raw {
        let Ok(env) = serde_json::from_str::<Value>(line) else {
            continue;
        };
        let Some(key) = env.get("key").and_then(Value::as_array) else {
            continue;
        };
        if key.first().and_then(Value::as_str) == Some("message") {
            if let Some(id) = env
                .get("value")
                .and_then(|v| v.get("id"))
                .and_then(Value::as_str)
            {
                if !order.iter().any(|o| o == id) {
                    order.push(id.to_string());
                }
            }
        }
    }

    for (i, expected_id) in order.iter().enumerate() {
        let Some(entry) = messages.get(i) else {
            return false;
        };
        let info = &entry["info"];
        if info.get("id").and_then(Value::as_str) != Some(expected_id.as_str()) {
            return false;
        }
        if info != &expected_messages[expected_id.as_str()] {
            return false;
        }
        let Some(parts) = entry["parts"].as_array() else {
            return false;
        };
        for part in parts {
            let Some(part_id) = part.get("id").and_then(Value::as_str) else {
                return false;
            };
            if Some(part) != expected_parts.get(part_id) {
                return false;
            }
        }
    }
    true
}

/// Duplicated test-side re-derivation (interop_common convention): `(message
/// id -> value, part id -> value)` from a session's raw envelope lines.
fn raw_envelope_maps(
    raw: &[String],
) -> (
    std::collections::HashMap<String, Value>,
    std::collections::HashMap<String, Value>,
) {
    let mut messages = std::collections::HashMap::new();
    let mut parts = std::collections::HashMap::new();
    for line in raw {
        let Ok(env) = serde_json::from_str::<Value>(line) else {
            continue;
        };
        let Some(key) = env.get("key").and_then(Value::as_array) else {
            continue;
        };
        let value = env.get("value").cloned().unwrap_or(Value::Null);
        match key.first().and_then(Value::as_str) {
            Some("message") => {
                if let Some(id) = value.get("id").and_then(Value::as_str) {
                    messages.insert(id.to_string(), value);
                }
            }
            Some("part") => {
                if let Some(id) = value.get("id").and_then(Value::as_str) {
                    parts.insert(id.to_string(), value);
                }
            }
            _ => {}
        }
    }
    (messages, parts)
}

/// Appended-turn-present: reload `out` with `format`'s own loader and check
/// both continuation messages reload.
fn turn_present(sp: &Spliced, format: SessionFormat) -> bool {
    let reloaded = match Session::load_str(&sp.out, format) {
        Ok(s) => s,
        Err(_) => return false,
    };
    let has_user = reloaded
        .messages
        .iter()
        .any(|m| m.content.as_deref() == Some("one more thing (emulate-continue synthetic turn)"));
    let has_assistant = reloaded
        .messages
        .iter()
        .any(|m| m.content.as_deref() == Some("sure thing (emulate-continue synthetic reply)"));
    has_user && has_assistant
}

fn grok_invariants_ok(sp: &Spliced) -> bool {
    sp.out
        .lines()
        .filter(|line| !line.trim().is_empty())
        .all(|line| serde_json::from_str::<Value>(line).is_ok())
        && Session::from_grok_str(&sp.out).is_ok()
}

// ---- Pi resume-invariant checker (§4.2.3, S10) -----------------------------

fn pi_invariants_ok(sp: &Spliced) -> bool {
    let mut lines = sp.out.lines().filter(|l| !l.trim().is_empty());
    let Some(header_line) = lines.next() else {
        return false;
    };
    if header_line.len() > 512 {
        eprintln!(
            "pi invariant FAIL: header line {} bytes > 512",
            header_line.len()
        );
        return false;
    }
    let Ok(header) = serde_json::from_str::<Value>(header_line) else {
        return false;
    };
    if header.get("type").and_then(Value::as_str) != Some("session") {
        return false;
    }
    if header.get("version").and_then(Value::as_i64) != Some(3) {
        return false;
    }
    if header.get("id").and_then(Value::as_str).is_none() {
        return false;
    }

    let mut seen_ids: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut last_tool_call_ids: std::collections::HashSet<String> =
        std::collections::HashSet::new();
    let appended_start = sp.original.raw.len();
    for (i, line) in sp.out.lines().filter(|l| !l.trim().is_empty()).enumerate() {
        if i == 0 {
            continue;
        }
        let Ok(v) = serde_json::from_str::<Value>(line) else {
            return false;
        };
        if v.get("type").is_none() || v.get("id").is_none() || v.get("timestamp").is_none() {
            eprintln!("pi invariant FAIL: entry {i} missing type/id/timestamp: {line}");
            return false;
        }
        if v.as_object().is_some_and(|o| !o.contains_key("parentId")) {
            eprintln!("pi invariant FAIL: entry {i} missing parentId: {line}");
            return false;
        }
        let id = v
            .get("id")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        if i >= appended_start {
            // Fresh, 8-hex, collision-free.
            let is_8hex = id.len() == 8 && id.chars().all(|c| c.is_ascii_hexdigit());
            if !is_8hex {
                eprintln!("pi invariant FAIL: appended entry {i} id {id:?} is not 8-hex");
                return false;
            }
            if seen_ids.contains(&id) {
                eprintln!("pi invariant FAIL: appended entry {i} id {id:?} collides");
                return false;
            }
        }
        seen_ids.insert(id.clone());

        // toolResult must follow its toolCall.
        if let Some(msg) = v.get("message") {
            if msg.get("role").and_then(Value::as_str) == Some("toolResult") {
                let Some(call_id) = msg.get("toolCallId").and_then(Value::as_str) else {
                    return false;
                };
                if !last_tool_call_ids.contains(call_id) {
                    eprintln!("pi invariant FAIL: toolResult {call_id} has no preceding toolCall");
                    return false;
                }
            }
            if let Some(content) = msg.get("content").and_then(Value::as_array) {
                for block in content {
                    if block.get("type").and_then(Value::as_str) == Some("toolCall") {
                        if let Some(tc_id) = block.get("id").and_then(Value::as_str) {
                            last_tool_call_ids.insert(tc_id.to_string());
                        }
                    }
                }
            }
        }
    }

    // Filename convention shape check (S10): `<iso>_<id>.jsonl` under the
    // cwd-encoded `--<enc-cwd>--` directory. Offline shape check only — this
    // does not touch the filesystem.
    let ts = header
        .get("timestamp")
        .and_then(Value::as_str)
        .unwrap_or("");
    let id = header.get("id").and_then(Value::as_str).unwrap_or("");
    let filename = format!("{ts}_{id}.jsonl");
    let plausible_iso = ts.len() >= 19 && ts.as_bytes().get(4) == Some(&b'-') && ts.contains('T');
    if !plausible_iso || !filename.ends_with(".jsonl") || !filename.contains(id) {
        eprintln!("pi invariant FAIL: filename shape implausible: {filename:?}");
        return false;
    }

    true
}

// ---- Codex/Claude resume-invariant checker (existing to_jsonl_spliced) ----

fn claude_invariants_ok(sp: &Spliced) -> bool {
    let lines = non_empty_lines(&sp.out);
    if lines.len() <= sp.original.raw.len() {
        return false;
    }
    for line in &lines[sp.original.raw.len()..] {
        let Ok(v) = serde_json::from_str::<Value>(line) else {
            return false;
        };
        if v.get("type").and_then(Value::as_str).is_none() {
            return false;
        }
        if v.get("uuid").is_none() || v.get("parentUuid").is_none() {
            return false;
        }
    }
    true
}

fn codex_invariants_ok(sp: &Spliced) -> bool {
    let lines = non_empty_lines(&sp.out);
    if lines.len() <= sp.original.raw.len() {
        return false;
    }
    for line in &lines[sp.original.raw.len()..] {
        let Ok(v) = serde_json::from_str::<Value>(line) else {
            return false;
        };
        if v.get("type").and_then(Value::as_str) != Some("response_item") {
            return false;
        }
    }
    true
}

/// OpenCode: `out` decodes against `{info, messages:[{info,parts}]}`, ids
/// preserved, no placeholder leak — PLUS the excess keys / part timestamps /
/// side-records `opencode import` cannot ingest (S5) must be recoverable
/// from the accompanying raw native sidecar, not only from the export doc.
fn opencode_invariants_ok(sp: &Spliced, original: &Session) -> bool {
    opencode_invariants_ok_with_text(
        sp,
        original,
        "one more thing (emulate-continue synthetic turn)",
    )
}

fn opencode_invariants_ok_with_text(
    sp: &Spliced,
    original: &Session,
    expected_user_text: &str,
) -> bool {
    let Ok(doc) = serde_json::from_str::<Value>(&sp.out) else {
        return false;
    };
    if doc.get("info").is_none() {
        return false;
    }
    let Some(messages) = doc.get("messages").and_then(Value::as_array) else {
        return false;
    };
    for m in messages {
        if m.get("info").is_none() || m.get("parts").and_then(Value::as_array).is_none() {
            return false;
        }
    }
    // No placeholder leak into freshly-appended content: the synthetic
    // continuation text must appear verbatim, never masked.
    let has_appended_text = messages.iter().any(|m| {
        m["parts"].as_array().is_some_and(|parts| {
            parts
                .iter()
                .any(|p| p.get("text").and_then(Value::as_str) == Some(expected_user_text))
        })
    });
    if !has_appended_text {
        return false;
    }

    // S5: excess keys / part timestamps / side-records are NOT restored via
    // the export doc / `opencode import` — the direct-write native sidecar is
    // their only fidelity path. Prove they're there.
    let tmp = std::env::temp_dir().join(format!(
        "sc-emulate-continue-oc-sidecar-{}",
        std::process::id()
    ));
    std::fs::remove_dir_all(&tmp).ok();
    let session_dir = match original.to_opencode_direct_write(&tmp) {
        Ok(d) => d,
        Err(_) => return false,
    };
    let info_ok = std::fs::read_to_string(session_dir.join("ses_main0001.json"))
        .ok()
        .and_then(|t| serde_json::from_str::<Value>(&t).ok())
        .is_some_and(|info| info.get("experimentalFeatureFlag") == Some(&Value::Bool(true)));
    let diff_ok =
        std::fs::read_to_string(tmp.join("storage/session_diff/ses_main0001.json")).is_ok();
    std::fs::remove_dir_all(&tmp).ok();
    info_ok && diff_ok
}

// ---------------------------------------------------------------------------
// The per-harness metric test
// ---------------------------------------------------------------------------

#[test]
fn emulate_continue_harness_table() {
    let mut rows = Vec::new();

    for &format in &[
        SessionFormat::ClaudeCode,
        SessionFormat::Codex,
        SessionFormat::OpenCode,
        SessionFormat::Pi,
        SessionFormat::Grok,
    ] {
        let sp = build_splice(format);
        assert_eq!(sp.original.meta.source, format.source());

        let (prefix_ok, invariants_ok) = match format {
            SessionFormat::ClaudeCode => (
                prefix_verbatim_line_oriented(&sp),
                claude_invariants_ok(&sp),
            ),
            SessionFormat::Codex => (prefix_verbatim_line_oriented(&sp), codex_invariants_ok(&sp)),
            SessionFormat::Pi => (prefix_verbatim_line_oriented(&sp), pi_invariants_ok(&sp)),
            SessionFormat::OpenCode => (
                prefix_value_equal_opencode(&sp),
                opencode_invariants_ok(&sp, &sp.original),
            ),
            SessionFormat::Grok => (prefix_verbatim_line_oriented(&sp), grok_invariants_ok(&sp)),
        };
        let present = turn_present(&sp, format);

        assert!(
            prefix_ok,
            "{format:?}: imported prefix not replayed verbatim/value-equal"
        );
        assert!(
            present,
            "{format:?}: appended continuation turn did not reload"
        );
        assert!(invariants_ok, "{format:?}: resume-invariant checker failed");

        rows.push(Row {
            harness: fname(format),
            prefix_verbatim: prefix_ok,
            turn_present: present,
            invariants_ok,
            live_resume: "n/a",
        });
    }

    println!("\n=== §4.2 EMULATE-TO-CONTINUE (5-row table) ===");
    for row in &rows {
        row.print();
    }
    println!(
        "(live_resume is offline-`n/a` for every row above — run\n \
         scripts/stock-resume-matrix-probe.mjs for independent stock-CLI evidence)"
    );
}

#[tokio::test]
async fn every_native_format_continues_through_frontend_and_exports_back_without_residue() {
    for &format in &[
        SessionFormat::ClaudeCode,
        SessionFormat::Codex,
        SessionFormat::OpenCode,
        SessionFormat::Pi,
        SessionFormat::Grok,
    ] {
        let source_path = fixture(fixture_file_for(format));
        let source_before = std::fs::read(&source_path).unwrap();
        let original = load_fixture(format);
        let root = std::env::temp_dir().join(format!(
            "sc-frontend-emulate-continue-{}-{}",
            fname(format),
            std::process::id()
        ));
        std::fs::remove_dir_all(&root).ok();
        std::fs::create_dir_all(&root).unwrap();
        let sidecar_path = root.join("continued.native.jsonl");

        let mut agent = Agent::with_provider(
            Config::builder()
                .cwd(&root)
                .system_prompt("SUP-46 frontend continuation proof")
                .build(),
            Box::new(FixedContinuationProvider),
        );
        agent.load_session(original.clone());
        agent.set_recorder(SidecarWriter::create(&sidecar_path, &original).unwrap());
        let runtime =
            RpcEngine::new_named(agent, format!("sup46-{}-frontend", fname(format)), None);

        let mut observer = FrontendRuntime::attach(runtime.as_ref(), 1_000)
            .await
            .unwrap();
        assert_eq!(
            observer
                .history
                .first()
                .map(|message| (&message.role, message.content.as_deref())),
            Some((&Role::System, Some("SUP-46 frontend continuation proof"))),
            "{format:?}: runtime system envelope changed"
        );
        assert_message_prefix(
            &format!("{format:?} frontend replay"),
            &original.messages,
            &observer.history[1..],
        );
        assert_eq!(
            FrontendRuntime::submit(runtime.as_ref(), FRONTEND_PROMPT.into())
                .await
                .unwrap(),
            FRONTEND_REPLY,
            "{format:?}: frontend submit changed the provider reply"
        );

        let mut event_kinds = Vec::new();
        loop {
            let event =
                tokio::time::timeout(std::time::Duration::from_secs(5), observer.next_event())
                    .await
                    .unwrap()
                    .unwrap();
            let terminal = event.kind == "turn_succeeded";
            event_kinds.push(event.kind);
            if terminal {
                break;
            }
        }
        assert_eq!(
            event_kinds,
            [
                "user_message",
                "turn_started",
                "text_delta",
                "usage",
                "turn_completed",
                "turn_succeeded",
            ],
            "{format:?}: frontend event contract drifted"
        );

        let sidecar = std::fs::read_to_string(&sidecar_path).unwrap();
        let continued = Session::from_sidecar_str(&sidecar).unwrap();
        assert_eq!(
            continued.messages.len(),
            original.messages.len() + 2,
            "{format:?}: sidecar did not record exactly one continued turn"
        );
        assert_message_prefix(
            &format!("{format:?} durable sidecar"),
            &original.messages,
            &continued.messages,
        );
        let tail = &continued.messages[original.messages.len()..];
        assert_eq!(tail[0].role, Role::User, "{format:?}");
        assert_eq!(tail[0].content.as_deref(), Some(FRONTEND_PROMPT));
        assert_eq!(tail[1].role, Role::Assistant, "{format:?}");
        assert_eq!(tail[1].content.as_deref(), Some(FRONTEND_REPLY));
        for message in tail {
            for key in message.metadata.keys() {
                assert!(
                    matches!(
                        key.as_str(),
                        "timestamp" | "supercode_native_uuid" | "model"
                    ),
                    "{format:?}: UI metadata `{key}` leaked"
                );
            }
            assert!(
                !message
                    .content
                    .as_deref()
                    .unwrap_or_default()
                    .contains('\u{1b}'),
                "{format:?}: terminal control bytes leaked"
            );
        }

        let exported = export_session_spliced(&sidecar, format, None).unwrap();
        assert!(
            !exported.contains("[sc-reduced"),
            "{format:?}: reduction placeholder leaked into native export"
        );
        let reloaded = Session::load_str(&exported, format).unwrap();
        assert_eq!(
            reloaded.messages.len(),
            continued.messages.len(),
            "{format:?}: native reload changed message count"
        );
        assert_message_prefix(
            &format!("{format:?} native export"),
            &continued.messages,
            &reloaded.messages,
        );

        let spliced = Spliced {
            original: original.clone(),
            out: exported,
        };
        let (prefix_ok, invariants_ok) = match format {
            SessionFormat::ClaudeCode => (
                prefix_verbatim_line_oriented(&spliced),
                claude_invariants_ok(&spliced),
            ),
            SessionFormat::Codex => (
                prefix_verbatim_line_oriented(&spliced),
                codex_invariants_ok(&spliced),
            ),
            SessionFormat::OpenCode => (
                prefix_value_equal_opencode(&spliced),
                opencode_invariants_ok_with_text(&spliced, &original, FRONTEND_PROMPT),
            ),
            SessionFormat::Pi => (
                prefix_verbatim_line_oriented(&spliced),
                pi_invariants_ok(&spliced),
            ),
            SessionFormat::Grok => (
                prefix_verbatim_line_oriented(&spliced),
                grok_invariants_ok(&spliced),
            ),
        };
        assert!(
            prefix_ok,
            "{format:?}: native/unknown prefix residue was lost"
        );
        assert!(invariants_ok, "{format:?}: stock-resume invariants failed");
        assert_eq!(
            std::fs::read(&source_path).unwrap(),
            source_before,
            "{format:?}: frontend continuation mutated its source fixture"
        );

        runtime.shutdown().await;
        std::fs::remove_dir_all(root).ok();
    }
}