supercode-harness 0.4.6

The optional native Supercode agent and tool harness
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
//! CI-runnable regression guard for the session serializers.
//!
//! Unlike `session_saving.rs`'s corpus-gated tests (which need a maintainer's
//! real `~/.claude`/`~/.codex` logs and are `#[ignore]`d), everything here runs
//! under a plain `cargo test` against the two committed fixtures. It exists to
//! catch a silent regression in `Session::to_claude_code_jsonl` /
//! `Session::to_codex_jsonl` — the product's central resumability promise —
//! without requiring `SUPERCODE_CORPUS` or real session logs in CI.
//!
//! No test in this file reads an env var, is `#[ignore]`d, or is `cfg`-gated:
//! every assertion below runs and must pass on every `cargo test` invocation.

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

use supercode_harness::session::{Session, SessionFormat};
use supercode_harness::{ChatMessage, FunctionCall, Role, ToolCall};

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

/// Compare two messages for semantic (not byte) equality: role, text content,
/// tool-result linkage, and tool calls (name, id, and *parsed* arguments).
///
/// Deliberately duplicated from `session_saving.rs::msg_eq` rather than shared
/// — each integration test binary is compiled standalone, and this file must
/// stand on its own so it can't be weakened by editing another test file.
fn msg_eq(a: &ChatMessage, b: &ChatMessage) -> bool {
    if a.role != b.role || a.content != b.content || a.tool_call_id != b.tool_call_id {
        return false;
    }
    let (ca, cb) = (a.tool_calls(), b.tool_calls());
    if ca.len() != cb.len() {
        return false;
    }
    ca.iter().zip(cb).all(|(x, y)| {
        x.id == y.id
            && x.function.name == y.function.name
            && x.function.parsed_arguments().ok() == y.function.parsed_arguments().ok()
    })
}

fn assert_messages_eq(label: &str, a: &[ChatMessage], b: &[ChatMessage]) {
    assert_eq!(
        a.len(),
        b.len(),
        "{label}: message count changed\n  before: {a:#?}\n  after:  {b:#?}"
    );
    for (i, (x, y)) in a.iter().zip(b).enumerate() {
        assert!(
            msg_eq(x, y),
            "{label}: message {i} differs:\n  before: {x:?}\n  after:  {y:?}"
        );
    }
}

fn non_system(messages: &[ChatMessage]) -> Vec<ChatMessage> {
    messages
        .iter()
        .filter(|m| m.role != Role::System)
        .cloned()
        .collect()
}

/// PARITY-11: a genuinely reasoning-only turn (Claude `thinking`/
/// `redacted_thinking` metadata, no text/tool_use/image/tool_calls at all —
/// `push_claude_assistant`'s fix for the real corpus's ~21% standalone
/// `thinking`-only assistant records, which used to vanish silently on
/// LOAD) is provider-private and has no Codex wire slot for a standalone
/// occurrence — deliberately not written on that hop (see
/// `write_codex_records`'s PARITY-11 comment). Filter it for the SAME
/// reason `non_system` filters `Role::System` — no cross-format slot, not a
/// regression.
fn non_reasoning_only(messages: &[ChatMessage]) -> Vec<ChatMessage> {
    messages
        .iter()
        .filter(|m| {
            !(m.role == Role::Assistant
                && m.content.is_none()
                && m.content_parts.is_none()
                && m.tool_calls().is_empty()
                && (m.metadata.contains_key("thinking")
                    || m.metadata.contains_key("redacted_thinking")))
        })
        .cloned()
        .collect()
}

// ---- 1. Fixture non-vacuity floors -----------------------------------------
//
// These run *before* trusting any round-trip assertion below: if a future
// fixture edit (or a loader regression that silently drops messages) hollows
// out the fixtures, this test fails loudly instead of letting the round-trip
// tests pass vacuously on an empty/degenerate conversation.

#[test]
fn fixtures_exercise_the_hard_shapes() {
    let cc = Session::from_claude_code(fixture("claude_code_session.jsonl")).unwrap();
    // Measured against the committed fixture: 1 user turn, 1 assistant turn
    // that issues a tool call (Task/Agent), the paired tool result, and a
    // final assistant text turn == 4 canonical messages. The floor is set at
    // the current value (not padded above it) so a loader regression that
    // drops even one of these canonical messages is caught.
    assert!(
        cc.messages.len() >= 4,
        "claude fixture hollowed out: only {} messages (expected >= 4)",
        cc.messages.len()
    );
    assert!(
        cc.messages.iter().any(|m| m.role == Role::User),
        "claude fixture must contain at least one User message"
    );
    assert!(
        cc.messages
            .iter()
            .any(|m| m.role == Role::Assistant && !m.tool_calls().is_empty()),
        "claude fixture must contain at least one Assistant message with a tool call"
    );
    assert!(
        cc.messages
            .iter()
            .any(|m| m.role == Role::Tool
                && m.tool_call_id.as_deref().is_some_and(|s| !s.is_empty())),
        "claude fixture must contain at least one Tool message with a non-empty tool_call_id"
    );

    let cx = Session::from_codex(fixture("codex_session.jsonl")).unwrap();
    assert!(
        cx.messages.len() >= 6,
        "codex fixture hollowed out: only {} messages (expected >= 6)",
        cx.messages.len()
    );
    let assistant_tool_calls = cx
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant && !m.tool_calls().is_empty())
        .count();
    assert!(
        assistant_tool_calls >= 2,
        "codex fixture must contain >= 2 assistant tool calls, found {assistant_tool_calls}"
    );
    let tool_results = cx.messages.iter().filter(|m| m.role == Role::Tool).count();
    assert!(
        tool_results >= 2,
        "codex fixture must contain >= 2 tool-result messages, found {tool_results}"
    );
    assert!(
        cx.meta.system_prompt.is_some(),
        "codex fixture must carry a base-instructions system prompt"
    );
    assert!(
        cx.meta.session_id.is_some(),
        "codex fixture must carry a session id"
    );
}

// ---- 2. Same-format semantic round-trip, both formats ----------------------

#[test]
fn claude_load_save_load_semantic_roundtrip() {
    let original = Session::from_claude_code(fixture("claude_code_session.jsonl")).unwrap();
    let jsonl = original.to_jsonl(SessionFormat::ClaudeCode).unwrap();
    let reloaded = Session::from_claude_code_str(&jsonl).unwrap();

    assert_messages_eq("claude round-trip", &original.messages, &reloaded.messages);
    assert_eq!(original.meta.session_id, reloaded.meta.session_id);
    assert_eq!(original.meta.model, reloaded.meta.model);
    assert_eq!(original.meta.cwd, reloaded.meta.cwd);
}

#[test]
fn codex_load_save_load_semantic_roundtrip() {
    let original = Session::from_codex(fixture("codex_session.jsonl")).unwrap();
    let jsonl = original.to_jsonl(SessionFormat::Codex).unwrap();
    let reloaded = Session::from_codex_str(&jsonl).unwrap();

    assert_messages_eq("codex round-trip", &original.messages, &reloaded.messages);
    assert_eq!(original.meta.session_id, reloaded.meta.session_id);
    assert_eq!(original.meta.model, reloaded.meta.model);
    assert_eq!(original.meta.cwd, reloaded.meta.cwd);
    // Codex carries the base instructions; they must survive the round-trip.
    assert_eq!(original.meta.system_prompt, reloaded.meta.system_prompt);
}

// ---- 3. Cross-format export, BOTH directions -------------------------------

#[test]
fn claude_to_codex_reload_preserves_conversation() {
    // NEW coverage (not exercised by any un-gated test today): a Claude-loaded
    // session has empty `meta.codex_headers`, so this exercises
    // `write_synthesized_codex_header` plus the Codex serializer's
    // function_call/function_call_output emission, then reloads with the
    // Codex parser and compares.
    let claude = Session::from_claude_code(fixture("claude_code_session.jsonl")).unwrap();
    let as_codex = claude.to_jsonl(SessionFormat::Codex).unwrap();
    let reloaded = Session::from_codex_str(&as_codex).unwrap();

    // PARITY-11: Codex has no wire slot for the fixture's standalone
    // `thinking`-only assistant record — filtered here for the same reason
    // `non_system` filters `Role::System` (see `non_reasoning_only`'s doc
    // comment); the rest of the conversation is still compared in full.
    let before = non_reasoning_only(&non_system(&claude.messages));
    let after = non_reasoning_only(&non_system(&reloaded.messages));
    assert_messages_eq("claude->codex cross-format", &before, &after);
}

/// PARITY-6/7 (real-corpus-confirmed, provenance P006/P007): a real Claude
/// Code transcript commonly carries two ADJACENT but genuinely SEPARATE
/// assistant records with no user turn between them — e.g. a text-only
/// narration line immediately followed by a bare tool-call line (Claude
/// itself writes these as two distinct JSONL records even though they read
/// as "one turn"). Exporting to Codex synthesizes an assistant `message`
/// response_item for the first and a bare `function_call` response_item for
/// the second, immediately adjacent with nothing between them — exactly the
/// shape Codex's own IX-6 "combined text+tool_use turn" merge heuristic
/// (`push_codex_item`) is designed to re-fold into ONE `ChatMessage`. Before
/// the PARITY-6/7 fix, the heuristic had no way to tell that shape apart from
/// a GENUINELY single Claude record (text+tool_use in the same `content`
/// array), so it wrongly merged these two unrelated messages into one,
/// silently shrinking the message count on every real-world Claude -> Codex
/// hop (confirmed via `inspect` on 10 real large Claude sessions: every one
/// lost hundreds of messages this way). The fix stamps a synthetic
/// `metadata.turn_id` per originating `ChatMessage` (`write_codex_records`)
/// so the merge only fires when it's actually the same source record.
#[test]
fn claude_to_codex_does_not_merge_two_adjacent_but_separate_assistant_turns() {
    let claude_jsonl = r#"{"type":"user","uuid":"u1","parentUuid":null,"sessionId":"demo","message":{"role":"user","content":"look into it"}}
{"type":"assistant","uuid":"a1","parentUuid":"u1","sessionId":"demo","message":{"role":"assistant","content":[{"type":"text","text":"Let me check that file."}]}}
{"type":"assistant","uuid":"a2","parentUuid":"a1","sessionId":"demo","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{"file_path":"/tmp/x.txt"}}]}}
{"type":"user","uuid":"u2","parentUuid":"a2","sessionId":"demo","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"file contents"}]}}"#;

    let claude = Session::from_claude_code_str(claude_jsonl).unwrap();
    // Sanity: the source really does load as TWO separate assistant messages
    // (a text-only one, then a bare tool-call one) — if a future loader
    // change combined them at import time, this test would no longer be
    // exercising the adjacency shape it's named for.
    let source_assistants: Vec<_> = claude
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .collect();
    assert_eq!(
        source_assistants.len(),
        2,
        "fixture must load as two separate assistant messages: {:#?}",
        claude.messages
    );
    assert_eq!(
        source_assistants[0].content.as_deref(),
        Some("Let me check that file.")
    );
    assert!(source_assistants[0].tool_calls().is_empty());
    assert!(source_assistants[1].content.is_none());
    assert_eq!(source_assistants[1].tool_calls().len(), 1);

    let as_codex = claude.to_jsonl(SessionFormat::Codex).unwrap();
    let reloaded = Session::from_codex_str(&as_codex).unwrap();
    let reloaded_assistants: Vec<_> = reloaded
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .collect();
    assert_eq!(
        reloaded_assistants.len(),
        2,
        "two originally-separate assistant turns must NOT merge into one \
         across a Claude -> Codex -> reload hop: {:#?}",
        reloaded.messages
    );
    assert_eq!(
        reloaded_assistants[0].content.as_deref(),
        Some("Let me check that file.")
    );
    assert!(
        reloaded_assistants[0].tool_calls().is_empty(),
        "the tool call belongs to the SECOND original message, not the first: {:#?}",
        reloaded_assistants[0]
    );
    assert!(reloaded_assistants[1].content.is_none());
    assert_eq!(reloaded_assistants[1].tool_calls().len(), 1);
    assert_eq!(reloaded_assistants[1].tool_calls()[0].function.name, "Read");

    // Message count is fully preserved end to end (the PARITY-6/7 headline
    // symptom): 1 user + 2 assistant + 1 tool-result in, same 4 out.
    assert_eq!(claude.messages.len(), 4);
    assert_eq!(reloaded.messages.len(), 4);
}

/// N2 (Fable-5 review, turn_id-collision hardening, scenario b): a native
/// Codex transcript can carry a `message(turn-7)` whose `__codex_open_turn`
/// merge marker later gets stripped by a truncation/clear boundary (here: a
/// `compacted` record, which strips the marker off its replayed tail — see
/// the `Some("compacted")` arm's IX-6 comment in `push_codex_item`) while
/// STILL keeping the real `turn_id` value `turn-7`. A subsequent
/// `function_call(turn-7)` then loads as a genuinely SEPARATE `ChatMessage`
/// (the stripped marker correctly refuses the merge on load) that neverthe-
/// less carries the SAME real `turn_id` string. Before the N2 fix,
/// full-synthesis re-export naively reused `turn-7` verbatim for BOTH
/// messages (each loop iteration in `write_codex_records` independently
/// reuses its own `real_turn_id`) and emitted them adjacent — nothing
/// distinguishes that from a single message's own multi-call turn, so
/// reimport wrongly recombines the two into one (2 -> 1), the exact
/// bug-class PARITY-6/7 fixed for the *fabricated*-id case, reopened here
/// for the *real*-id-reuse case. Fails against 27607794504d26ae, whose
/// `write_codex_records` did `Some(real.to_string())` unconditionally with
/// no collision tracking.
#[test]
fn codex_native_turn_id_reuse_across_a_stripped_merge_boundary_does_not_recombine() {
    let codex_jsonl = r#"{"timestamp":"2024-01-01T00:00:00Z","type":"compacted","payload":{"replacement_history":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Working on it."}],"metadata":{"turn_id":"turn-7"}}]}}
{"timestamp":"2024-01-01T00:00:01Z","type":"response_item","payload":{"type":"function_call","name":"Read","arguments":"{}","call_id":"call_1","metadata":{"turn_id":"turn-7"}}}
{"timestamp":"2024-01-01T00:00:02Z","type":"response_item","payload":{"type":"function_call_output","call_id":"call_1","output":"file contents"}}"#;

    let codex = Session::from_codex_str(codex_jsonl).unwrap();
    // Sanity: this really does load as TWO separate assistant `ChatMessage`s
    // sharing the same real `turn_id`, not merged by the initial load itself
    // — the marker-strip on the compaction boundary must have done its job,
    // or this test isn't exercising the shape it's named for.
    let source_assistants: Vec<_> = codex
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .collect();
    assert_eq!(
        source_assistants.len(),
        2,
        "fixture must load as two separate assistant messages sharing turn_id \
         `turn-7`: {:#?}",
        codex.messages
    );
    assert_eq!(
        source_assistants[0]
            .metadata
            .get("turn_id")
            .map(String::as_str),
        Some("turn-7")
    );
    assert_eq!(
        source_assistants[1]
            .metadata
            .get("turn_id")
            .map(String::as_str),
        Some("turn-7"),
        "both original messages must carry the SAME real turn_id for this to \
         be the scenario under test"
    );

    let as_codex = codex.to_jsonl(SessionFormat::Codex).unwrap();
    let reloaded = Session::from_codex_str(&as_codex).unwrap();
    let reloaded_assistants: Vec<_> = reloaded
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .collect();
    assert_eq!(
        reloaded_assistants.len(),
        2,
        "two originally-separate assistant turns that merely SHARE a real \
         turn_id (across a stripped merge boundary) must NOT recombine into \
         one on a Codex -> Codex full-synthesis round-trip: {:#?}",
        reloaded.messages
    );
    assert_eq!(
        reloaded_assistants[0].content.as_deref(),
        Some("Working on it.")
    );
    assert!(
        reloaded_assistants[0].tool_calls().is_empty(),
        "the tool call belongs to the SECOND original message, not the first: {:#?}",
        reloaded_assistants[0]
    );
    assert!(reloaded_assistants[1].content.is_none());
    assert_eq!(reloaded_assistants[1].tool_calls().len(), 1);
    assert_eq!(reloaded_assistants[1].tool_calls()[0].function.name, "Read");
}

/// N2, scenario (a): a Claude -> Codex export fabricates `sc-grp-0` as msg
/// A's disambiguation id; reloading makes A carry that value as a REAL
/// `turn_id`. If a later, unrelated bare tool-call message B (no `turn_id`
/// of its own — e.g. freshly appended, not loaded from this same Codex
/// export) is exported in the SAME pass, the OLD fabrication counter
/// (`next_group_id` always restarting at 0) collides with A's now-real
/// `sc-grp-0` — both end up tagged `sc-grp-0`. Emitted adjacent (nothing
/// else appended after A in this constructed case), reimport merges B's
/// call into A even though they're unrelated `ChatMessage`s. Fails against
/// 27607794504d26ae, whose fabrication counter had no collision awareness.
#[test]
fn fabricated_group_id_does_not_collide_with_a_reused_real_one() {
    // Simulate the reload state directly: msg A already carries a REAL
    // turn_id of "sc-grp-0" (as if it came back from a prior Claude->Codex
    // export + reload), and msg B is a fresh bare tool-call message with NO
    // turn_id of its own — the fabrication path is what assigns B's id.
    let mut a = ChatMessage::assistant("Let me check that file.".to_string());
    a.metadata
        .insert("turn_id".to_string(), "sc-grp-0".to_string());

    let mut b = ChatMessage::assistant(String::new());
    b.content = None;
    b.tool_calls = Some(vec![ToolCall {
        id: "call_b".to_string(),
        kind: "function".to_string(),
        function: FunctionCall {
            name: "Read".to_string(),
            arguments: "{}".to_string(),
        },
    }]);

    // Mirrors the `session_of` idiom used across the reduce/* test suites
    // (e.g. `reduce_dedup.rs`) for hand-building a `Session` around an
    // explicit message list, rather than parsing it from text.
    let mut session = Session::from_claude_code_str("").unwrap();
    session.messages = vec![a, b];
    let as_codex = session.to_jsonl(SessionFormat::Codex).unwrap();
    let reloaded = Session::from_codex_str(&as_codex).unwrap();
    let reloaded_assistants: Vec<_> = reloaded
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .collect();
    assert_eq!(
        reloaded_assistants.len(),
        2,
        "msg A's reused real turn_id and msg B's freshly-fabricated one must \
         not collide and recombine the two: {:#?}",
        reloaded.messages
    );
    assert!(reloaded_assistants[0].tool_calls().is_empty());
    assert_eq!(reloaded_assistants[1].tool_calls().len(), 1);
    assert_eq!(reloaded_assistants[1].tool_calls()[0].function.name, "Read");
}

/// N2 follow-up (Fable-5 review, MEDIUM): scenarios (a)/(b) above only cover
/// `to_jsonl`'s FULL-SYNTHESIS Codex export, whose `used_group_ids` tracking
/// set is genuinely empty at the start (every group id in `out` is one this
/// same call is about to assign). A12's SPLICED export
/// (`to_jsonl_spliced`/`to_codex_jsonl_spliced`, the dominant hop-back /
/// rate-limit-rescue path — SPEC.md A12) is different: it replays a RAW
/// VERBATIM prefix (already containing real/fabricated group ids from a
/// PRIOR export) and then calls the SAME `write_codex_records` for only the
/// appended tail. Before this fix, that tail's tracking set still started
/// empty — blind to the ids the prefix it's being appended after already
/// used — so an appended output-less `function_call` could fabricate a group
/// id that collides with one still "open" (no closing `function_call_output`
/// or intervening turn) at the end of the prefix, and reimport's merge check
/// (`can_merge`, `push_codex_item`) would wrongly splice the unrelated
/// appended call into the historical prefix message (2 -> 1).
///
/// Concretely: a Claude -> Codex export of a short *interrupted* session
/// ends with `message(sc-grp-0)` + an output-less `function_call(sc-grp-0)`
/// (no `function_call_output` — the call never completed). Loading that
/// (rescue flow) and appending a bare (content-`None`) tool-call assistant
/// message, then exporting via the splice path, used to restart fabrication
/// at `sc-grp-0` for the appended call too — colliding with the still-open
/// prefix call and merging on reimport. Fails against `parity/claude-
/// fidelity-v3` @ 8969105 (the same commit scenarios a/b above pin), whose
/// `to_codex_jsonl_spliced` called `write_codex_records(&mut out,
/// &self.messages[message_prefix_len..])` with no seed of the just-replayed
/// prefix's group ids.
#[test]
fn spliced_export_tail_group_id_does_not_collide_with_replayed_prefix() {
    // The RAW prefix: exactly the shape a Claude -> Codex export of an
    // interrupted session produces — an assistant `message` and its own
    // (output-less) `function_call`, both stamped with the SAME group id
    // `sc-grp-0`, and nothing that closes the turn (no
    // `function_call_output`, no following record).
    let codex_jsonl = r#"{"timestamp":"2024-01-01T00:00:00Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Let me check that file."}],"metadata":{"turn_id":"sc-grp-0"}}}
{"timestamp":"2024-01-01T00:00:01Z","type":"response_item","payload":{"type":"function_call","name":"Read","arguments":"{}","call_id":"call_a","metadata":{"turn_id":"sc-grp-0"}}}"#;

    let codex = Session::from_codex_str(codex_jsonl).unwrap();
    // Sanity: the message + its own adjacent, matching-turn_id, output-less
    // function_call load-side MERGE into ONE assistant `ChatMessage` (the
    // ordinary D1/PARITY-6/7 combined-turn shape) carrying real turn_id
    // `sc-grp-0` — this is the exact shape under test. The loader's
    // `ensure_tool_results_paired` additionally synthesizes a loud
    // "[no tool result recorded — turn interrupted]" placeholder `Tool`
    // message for `call_a`'s missing output (unrelated to the group-id
    // collision this test targets — that placeholder lives only in
    // `messages`, never in `raw`, so it's invisible to the spliced export's
    // verbatim-prefix replay below). If this sanity check fails, the fixture
    // isn't exercising the scenario the rest of the test assumes.
    assert_eq!(
        codex.messages.len(),
        2,
        "fixture must load as ONE merged (message+call) assistant turn plus \
         the synthesized interrupted-tool-result placeholder: {:#?}",
        codex.messages
    );
    assert_eq!(codex.messages[0].role, Role::Assistant);
    assert_eq!(codex.messages[0].tool_calls().len(), 1);
    assert_eq!(
        codex.messages[0]
            .metadata
            .get("turn_id")
            .map(String::as_str),
        Some("sc-grp-0")
    );
    assert_eq!(codex.messages[1].role, Role::Tool);

    // Append a bare (content-None) tool-call assistant message — e.g. a
    // thinking-only turn's tool call — via the same NativeTurn sidecar
    // mechanism the live agent loop uses (`to_native_jsonl_v2`/
    // `from_native_str`), so `raw`/`messages`/`imported_message_count` stay
    // in the lockstep `to_jsonl_spliced` requires.
    let mut appended = ChatMessage::assistant(String::new());
    appended.content = None;
    appended.tool_calls = Some(vec![ToolCall {
        id: "call_b".to_string(),
        kind: "function".to_string(),
        function: FunctionCall {
            name: "Read".to_string(),
            arguments: "{}".to_string(),
        },
    }]);
    let native = codex.to_native_jsonl_v2(std::slice::from_ref(&appended));
    let spliced_session = Session::from_native_str(&native).unwrap();
    assert_eq!(
        spliced_session.messages.len(),
        3,
        "sanity: prefix's merged message + its interrupted-tool placeholder \
         + the freshly appended tail message"
    );

    // Export via the SPLICED path (A12 — the dominant hop-back / rate-limit-
    // rescue export `export_session_spliced`/the CLI's `--reduced` resume
    // ultimately calls), not `to_jsonl` (full synthesis, already covered by
    // the scenario (a)/(b) tests above).
    let exported = spliced_session
        .to_jsonl_spliced(SessionFormat::Codex, None)
        .unwrap();
    let reloaded = Session::from_codex_str(&exported).unwrap();
    let reloaded_assistants: Vec<_> = reloaded
        .messages
        .iter()
        .filter(|m| m.role == Role::Assistant)
        .collect();
    assert_eq!(
        reloaded_assistants.len(),
        2,
        "the appended tail call must get a group id that does NOT collide \
         with the still-open prefix call's `sc-grp-0` — a collision here \
         would wrongly splice the unrelated appended message into the \
         historical prefix message on reimport (2 -> 1): {:#?}",
        reloaded.messages
    );
    assert_eq!(reloaded_assistants[0].tool_calls().len(), 1);
    assert_eq!(reloaded_assistants[0].tool_calls()[0].id, "call_a");
    assert_eq!(reloaded_assistants[1].tool_calls().len(), 1);
    assert_eq!(reloaded_assistants[1].tool_calls()[0].id, "call_b");
}

#[test]
fn codex_to_claude_reload_preserves_conversation() {
    // Since PARITY-6 dev/02, `to_claude_code_jsonl`'s `Role::System` arm
    // re-materializes a content-bearing System message as a real Claude
    // `type: "system"` record instead of omitting it, so the content itself
    // does survive this hop. This test still filters `Role::System` on both
    // sides (same allowance session_saving.rs's cross-format test makes) for
    // a narrower reason: this fixture's developer/system turn is native
    // Codex framing with no Claude-origin `systemSubtype` metadata to carry
    // over, so the re-materialized record's `subtype` is only a best-effort
    // guess (`local_command` fallback) — comparing it message-for-message
    // against the original would fail on that guessed label even though no
    // content was lost. Not a weakening of this test's teeth: the
    // user/assistant/tool conversation, including tool linkage, is still
    // compared in full.
    let codex = Session::from_codex(fixture("codex_session.jsonl")).unwrap();
    let as_cc = codex.to_jsonl(SessionFormat::ClaudeCode).unwrap();
    let reloaded = Session::from_claude_code_str(&as_cc).unwrap();

    let before = non_system(&codex.messages);
    let after = non_system(&reloaded.messages);
    assert_messages_eq("codex->claude cross-format", &before, &after);
}

// ---- 4. Output well-formedness under export --------------------------------

#[test]
fn exported_jsonl_is_parseable_line_by_line() {
    let claude = Session::from_claude_code(fixture("claude_code_session.jsonl")).unwrap();
    let codex = Session::from_codex(fixture("codex_session.jsonl")).unwrap();

    let cases: [(&str, &Session, SessionFormat); 4] = [
        (
            "claude fixture as ClaudeCode",
            &claude,
            SessionFormat::ClaudeCode,
        ),
        ("claude fixture as Codex", &claude, SessionFormat::Codex),
        (
            "codex fixture as ClaudeCode",
            &codex,
            SessionFormat::ClaudeCode,
        ),
        ("codex fixture as Codex", &codex, SessionFormat::Codex),
    ];

    for (label, session, format) in cases {
        let jsonl = session.to_jsonl(format).unwrap();
        let mut lines_seen = 0usize;
        for line in jsonl.lines().filter(|l| !l.trim().is_empty()) {
            lines_seen += 1;
            let v: serde_json::Value = serde_json::from_str(line)
                .unwrap_or_else(|e| panic!("{label}: line is not valid JSON ({e}): {line}"));
            match format {
                SessionFormat::ClaudeCode => {
                    assert!(
                        v.get("type").is_some(),
                        "{label}: Claude Code line missing top-level `type`: {line}"
                    );
                    assert!(
                        v.get("payload").is_none(),
                        "{label}: Claude Code line must not carry a `payload` envelope: {line}"
                    );
                }
                SessionFormat::Codex => {
                    assert!(
                        v.get("payload").is_some(),
                        "{label}: Codex line missing `payload` envelope: {line}"
                    );
                }
                // Not exercised here — Pi has its own well-formedness
                // assertions in `pi_interop.rs`; OpenCode is wave B.
                SessionFormat::Gemini
                | SessionFormat::Grok
                | SessionFormat::Goose
                | SessionFormat::OpenCode
                | SessionFormat::Pi => {}
            }
        }
        assert!(lines_seen > 0, "{label}: export produced no lines at all");
    }
}

/// R1 (Skeptic B, spliced-export uuid-collision hardening — the Claude Code
/// counterpart of the Codex N2 follow-up test above, mirroring the same
/// bug-class fix — `next_claude_uuid` in `session.rs` is the Claude-side
/// twin of `write_codex_records`'s `used_group_ids` collision guard).
///
/// A12's SPLICED export (`to_jsonl_spliced`/`to_claude_code_jsonl_spliced`)
/// replays a RAW VERBATIM prefix, then synthesizes `uuid`s only for the
/// appended tail via `write_claude_code_records`, whose `synth_uuid` counter
/// used to always restart at 1 — blind to any uuid the just-replayed prefix
/// already carries. A CHAIN of export -> reimport -> append -> export again
/// therefore used to fabricate the SAME tail uuid twice: the second
/// synthesized tail collides with the first synthesized tail, which is now
/// sitting in the reimported raw prefix. A uuid-keyed consumer (Claude
/// Code's fork/tree lineage, `parentUuid` links) can mis-link across such a
/// collision even though the message CONTENT itself survives (loaders read
/// file order, not uuid identity). Fails against `parity/integrated-v3` @
/// e7b15fd, whose `to_claude_code_jsonl_spliced` called
/// `write_claude_code_records(&mut out, &self.messages[message_prefix_len..],
/// &sid, &cwd, parent, 1)` with no seed of the just-replayed prefix's uuids.
#[test]
fn spliced_export_tail_uuid_does_not_collide_across_an_export_reimport_append_chain() {
    // A minimal, real-shaped Claude Code raw prefix: one user turn, one
    // assistant turn, each carrying its own real `uuid`/`sessionId` — the
    // ground truth `to_claude_code_jsonl_spliced` replays verbatim ahead of
    // whatever tail it synthesizes.
    let claude_jsonl = r#"{"parentUuid":null,"type":"user","message":{"role":"user","content":"hello"},"uuid":"11111111-1111-4111-8111-111111111111","sessionId":"sess-1","timestamp":"2024-01-01T00:00:00Z"}
{"parentUuid":"11111111-1111-4111-8111-111111111111","type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"hi there"}]},"uuid":"22222222-2222-4222-8222-222222222222","sessionId":"sess-1","timestamp":"2024-01-01T00:00:01Z"}"#;
    let base = Session::from_claude_code_str(claude_jsonl).unwrap();

    // First append + splice (mirrors the live agent loop's NativeTurn
    // sidecar mechanism — `to_native_jsonl_v2`/`from_native_str`, the same
    // idiom the Codex N2 follow-up test above uses). This produces the
    // FIRST synthesized tail: exactly one assistant message, minted as
    // `synth_uuid(1)`.
    let appended_1 = ChatMessage::assistant("first appended reply".to_string());
    let native_1 = base.to_native_jsonl_v2(std::slice::from_ref(&appended_1));
    let spliced_1 = Session::from_native_str(&native_1).unwrap();
    let exported_1 = spliced_1
        .to_jsonl_spliced(SessionFormat::ClaudeCode, None)
        .unwrap();

    // Reimport the first export — its prefix now includes the real prefix
    // PLUS the first tail's synthesized uuid — then append a SECOND tail and
    // splice-export again. Pre-fix, this second tail's counter restarts at 1
    // exactly like the first tail's did, so it fabricates the identical
    // `synth_uuid(1)` value the first tail already used (now sitting in the
    // reimported prefix): a collision.
    let reloaded_1 = Session::from_claude_code_str(&exported_1).unwrap();
    let appended_2a = ChatMessage::assistant("second appended reply, part 1".to_string());
    let appended_2b = ChatMessage::assistant("second appended reply, part 2".to_string());
    let native_2 = reloaded_1.to_native_jsonl_v2(&[appended_2a, appended_2b]);
    let spliced_2 = Session::from_native_str(&native_2).unwrap();
    let exported_2 = spliced_2
        .to_jsonl_spliced(SessionFormat::ClaudeCode, None)
        .unwrap();

    // Collect every `uuid` across the FINAL export's lines (original prefix
    // + first synthesized tail, now both replayed verbatim, + the second
    // synthesized tail) and assert none repeats.
    let mut seen = std::collections::HashMap::<String, usize>::new();
    let mut ordered_uuids = Vec::new();
    for line in exported_2.lines().filter(|l| !l.trim().is_empty()) {
        let v: serde_json::Value = serde_json::from_str(line).unwrap();
        if let Some(uuid) = v.get("uuid").and_then(|u| u.as_str()) {
            *seen.entry(uuid.to_string()).or_insert(0) += 1;
            ordered_uuids.push((uuid.to_string(), v.get("parentUuid").cloned()));
        }
    }
    let dupes: Vec<_> = seen.iter().filter(|(_, &n)| n > 1).collect();
    assert!(
        dupes.is_empty(),
        "every uuid across the prefix + both synthesized tails must be \
         distinct — a chain of export -> reimport -> append -> export again \
         must not re-fabricate a uuid the prior export's tail already used: \
         duplicates = {dupes:?}, full export = {exported_2}"
    );

    // Intra-tail linkage sanity: the SECOND tail has two messages
    // (`appended_2a` -> `appended_2b`); `appended_2b`'s own record's
    // `parentUuid` must equal `appended_2a`'s own (possibly counter-skipped,
    // now-non-colliding) `uuid` — the collision fix must not desync the
    // chain it's threading through.
    assert_eq!(
        ordered_uuids.len(),
        5,
        "expected exactly 5 uuid-carrying records: original user+assistant \
         prefix (2), first tail (1 message), second tail (2 messages): {ordered_uuids:?}"
    );
    let (second_tail_first_uuid, _) = &ordered_uuids[3];
    let (_, second_tail_second_parent) = &ordered_uuids[4];
    assert_eq!(
        second_tail_second_parent
            .as_ref()
            .and_then(|p| p.as_str())
            .map(str::to_string),
        Some(second_tail_first_uuid.clone()),
        "the second tail's own two messages must still chain to each other \
         via parentUuid, using the actual (possibly skipped) minted uuid: \
         {ordered_uuids:?}"
    );
}