supercode-interchange 0.4.19

Canonical, provider-neutral session interchange primitives for Supercode
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
//! Supercode's own native/sidecar session container and its residue envelopes.

use super::*;

impl Session {
    /// Serialize to the **supercode-native** lossless format: a header line
    /// recording the original source, followed by every original JSONL line
    /// verbatim. Unlike [`Self::to_jsonl`] (which targets a foreign tool's
    /// schema and is necessarily lossy), this preserves *everything* — including
    /// records with no canonical representation — so [`Self::from_native_str`]
    /// reconstructs the session with full fidelity.
    pub fn to_native_jsonl(&self) -> String {
        let source = match self.meta.source {
            SessionSource::ClaudeCode => "claude_code",
            SessionSource::Codex => "codex",
            SessionSource::Pi => "pi",
            SessionSource::OpenCode => "opencode",
            SessionSource::Grok => "grok",
            SessionSource::Gemini => "gemini",
            SessionSource::Goose => "goose",
            SessionSource::OpenClaw => "openclaw",
            SessionSource::Hermes => "hermes",
            // P5-3 safety-hardening fix: a natively-spawned session must
            // never be written to disk labeled as an imported CC session.
            SessionSource::Native => "native",
        };
        let header = serde_json::json!({
            "supercode_native": 1,
            "source": source,
            // IX-1: carries whether the ORIGINAL imported source text ended
            // with a trailing newline — `from_native_str` needs this to
            // reconstruct the exact source bytes (not just the `raw` line
            // list) when re-parsing the body with the per-source loader.
            "raw_trailing_newline": self.raw_trailing_newline,
        })
        .to_string();
        let mut out =
            String::with_capacity(self.raw.iter().map(|l| l.len() + 1).sum::<usize>() + 64);
        out.push_str(&header);
        out.push('\n');
        for line in &self.raw {
            out.push_str(line);
            out.push('\n');
        }
        out
    }

    /// Serialize to the **supercode-native v2** format: the same imported-body
    /// mechanism as [`Self::to_native_jsonl`] (a versioned header line
    /// followed by every `Session.raw` line verbatim), plus one
    /// [`crate::sidecar::NativeTurn`] record per message in `appended` — turns
    /// produced after import, which have no backing `raw` line of their own.
    /// `NativeTurn` carries `metadata` in full (unlike `ChatMessage`'s wire
    /// serde), so nothing the live agent loop records is lost to disk.
    ///
    /// `appended` is caller-supplied rather than inferred from
    /// `self.messages`: A1 doesn't track which of `self.messages` came from
    /// import vs. the live loop — that bookkeeping belongs to the live writer
    /// built on top of this (A2/A3).
    pub fn to_native_jsonl_v2(&self, appended: &[ChatMessage]) -> String {
        self.to_native_jsonl_v2_with_timestamp(appended, None)
    }

    pub(crate) fn to_native_jsonl_v2_with_timestamp(
        &self,
        appended: &[ChatMessage],
        fixed_timestamp: Option<&str>,
    ) -> String {
        let source = match self.meta.source {
            SessionSource::ClaudeCode => "claude_code",
            SessionSource::Codex => "codex",
            SessionSource::Pi => "pi",
            SessionSource::OpenCode => "opencode",
            SessionSource::Grok => "grok",
            SessionSource::Gemini => "gemini",
            SessionSource::Goose => "goose",
            SessionSource::OpenClaw => "openclaw",
            SessionSource::Hermes => "hermes",
            // P5-3 safety-hardening fix: a natively-spawned session must
            // never be written to disk labeled as an imported CC session.
            SessionSource::Native => "native",
        };
        // P5-3 (§2 module 9, §5.2 P5 row 3 "native write side — store
        // already parses CC sidechains + CX lineage on import"): a
        // natively-spawned subagent's own `Session` carries its lineage on
        // `SessionMeta` (`agent_id`/`parent_tool_use_id`/`lineage`) — before
        // this, `to_native_jsonl_v2` never wrote any of the three to disk at
        // all, so a native-spawned child's lineage was lost the instant it
        // round-tripped through a sidecar. Emitted only when non-empty/`Some`
        // (`skip_serializing_if`-equivalent via manual omission below) so a
        // plain top-level session's header is byte-identical to before this
        // change.
        let mut header_obj = serde_json::json!({
            "supercode_native": 2,
            "source": source,
            "session_id": self.meta.session_id,
            "created": fixed_timestamp
                .map(ToOwned::to_owned)
                .unwrap_or_else(crate::sidecar::now_rfc3339),
            // IX-1: see `to_native_jsonl`'s header field of the same name.
            "raw_trailing_newline": self.raw_trailing_newline,
        });
        if let Some(obj) = header_obj.as_object_mut() {
            if let Some(agent_id) = &self.meta.agent_id {
                obj.insert("agent_id".to_string(), Value::String(agent_id.clone()));
            }
            if let Some(parent_tool_use_id) = &self.meta.parent_tool_use_id {
                obj.insert(
                    "parent_tool_use_id".to_string(),
                    Value::String(parent_tool_use_id.clone()),
                );
            }
            if !self.meta.lineage.is_empty() {
                obj.insert(
                    "lineage".to_string(),
                    serde_json::to_value(&self.meta.lineage).unwrap_or(Value::Null),
                );
            }
        }
        let header = header_obj.to_string();
        let mut out =
            String::with_capacity(self.raw.iter().map(|l| l.len() + 1).sum::<usize>() + 64);
        out.push_str(&header);
        out.push('\n');
        for line in &self.raw {
            out.push_str(line);
            out.push('\n');
        }
        for (turn_index, msg) in appended.iter().enumerate() {
            let turn = match fixed_timestamp {
                Some(timestamp) => crate::sidecar::NativeTurn::from_with_timestamp_and_index(
                    msg,
                    timestamp.to_string(),
                    turn_index as u64,
                ),
                None => crate::sidecar::NativeTurn::from_with_timestamp_and_index(
                    msg,
                    crate::sidecar::now_rfc3339(),
                    turn_index as u64,
                ),
            };
            out.push_str(&serde_json::to_string(&turn).unwrap_or_default());
            out.push('\n');
        }
        out
    }

    /// Parse the supercode-native format produced by [`Self::to_native_jsonl`]
    /// / [`Self::to_native_jsonl_v2`]. A v1 file (no appended turns) parses
    /// exactly as before. A v2 file's appended `NativeTurn` records —
    /// discriminated by the `supercode_turn` key, which never appears in a v1
    /// body — are split out before the imported body is handed to the
    /// per-source loader, then reattached in file order: to `messages` (via
    /// [`crate::sidecar::NativeTurn::into_message`]) and to `raw` (verbatim),
    /// so a v2 file round-trips byte-for-byte through
    /// [`Self::to_native_jsonl_v2`] again.
    pub fn from_native_str(jsonl: &str) -> Result<Session> {
        // IX-1: the native WRAPPER's own lines are split verbatim (not via
        // the blank-skipping `non_empty_lines`) so that any `raw` line it
        // carries — which can itself be blank, CRLF-terminated, or
        // whitespace-padded, now that raw-capture is strict-verbatim —
        // survives being embedded in (and re-extracted from) this wrapper
        // bit-for-bit. The wrapper we ourselves emit never has a blank line
        // of its own (`to_native_jsonl(_v2)` always writes one well-formed
        // record per line), so this is a behavior-preserving switch for any
        // native text this crate produced; it also makes a hand-fed/legacy
        // native string tolerated exactly as `non_empty_lines` used to.
        let (all_lines, _wrapper_trailing_newline) = split_lines_verbatim(jsonl);
        let mut lines = all_lines.into_iter();
        let header = lines.next().unwrap_or("");
        let hv: Value = serde_json::from_str(header).unwrap_or(Value::Null);
        let source = hv.get("source").and_then(Value::as_str);
        // IX-1: whether the ORIGINAL imported source (before it was wrapped
        // in this native format) ended with a trailing newline — a property
        // of the pre-wrap source, not of this wrapper (which always
        // LF-terminates every line it writes, regardless). Missing on a
        // native file written before IX-1 (or a hand-built header in an
        // older test/sidecar) — default `true`, the historical
        // always-newline-terminated assumption.
        let raw_trailing_newline = hv
            .get("raw_trailing_newline")
            .and_then(Value::as_bool)
            .unwrap_or(true);

        // Split appended NativeTurn records (v2) out of the imported body. A
        // v1 body never carries a `supercode_turn` key, so this is a no-op
        // there — one code path serves both versions.
        let mut body_lines: Vec<String> = Vec::new();
        let mut turn_lines: Vec<&str> = Vec::new();
        for line in lines {
            let is_turn = serde_json::from_str::<Value>(line)
                .ok()
                .is_some_and(|v| v.get("supercode_turn").is_some());
            if is_turn {
                turn_lines.push(line);
            } else {
                body_lines.push(line.to_string());
            }
        }
        // IX-1: reconstruct the ORIGINAL imported source bytes exactly —
        // `body_lines.join("\n")` alone would silently gain a trailing
        // newline the original source never had (or lose one it did have).
        let body = join_lines_verbatim(&body_lines, raw_trailing_newline);

        // The remaining lines are the original log; re-parse with the right loader.
        let mut session = match source {
            Some("codex") => Self::from_codex_str(&body)?,
            Some("claude_code") => Self::from_claude_code_str(&body)?,
            Some("pi") => Self::from_pi_str(&body)?,
            Some("opencode") => Self::from_opencode_str(&body)?,
            Some("grok") => Self::from_grok_str(&body)?,
            Some("gemini") => Self::from_gemini_str(&body)?,
            Some("goose") => Self::from_goose_str(&body)?,
            Some("openclaw") => Self::from_openclaw_str(&body)?,
            // P5-3 safety-hardening fix: a natively-spawned session's body
            // is always empty (it never had any foreign-tool prefix to
            // begin with — see `SessionSource::Native`'s doc comment), so
            // any loader would parse it identically; `from_claude_code_str`
            // is reused purely as a blank-skeleton builder (empty
            // `raw`/`messages`), then its `meta.source` is corrected to
            // `Native` — never left mislabeled as `ClaudeCode`.
            Some("native") => {
                let mut s = Self::from_claude_code_str(&body)?;
                s.meta.source = SessionSource::Native;
                s
            }
            // No/unknown header — auto-detect the body.
            _ => match detect_source(&body) {
                Some(SessionSource::Codex) => Self::from_codex_str(&body)?,
                Some(SessionSource::Pi) => Self::from_pi_str(&body)?,
                Some(SessionSource::OpenClaw) => Self::from_openclaw_str(&body)?,
                Some(SessionSource::OpenCode) => Self::from_opencode_str(&body)?,
                Some(SessionSource::Grok) => Self::from_grok_str(&body)?,
                Some(SessionSource::Gemini) => Self::from_gemini_str(&body)?,
                Some(SessionSource::Goose) => Self::from_goose_str(&body)?,
                _ => Self::from_claude_code_str(&body)?,
            },
        };

        for line in turn_lines {
            match serde_json::from_str::<crate::sidecar::NativeTurn>(line) {
                Ok(turn) => {
                    session.raw.push(line.to_string());
                    session.messages.push(turn.into_message());
                }
                Err(_) => {
                    // A valid JSON object carrying the native-turn
                    // discriminator belongs to this wrapper, not to the
                    // imported body. If its required fields are malformed,
                    // count it as parse loss so every fail-loud caller can
                    // refuse continuation instead of silently dropping a
                    // native history record. Keep the rejected source line
                    // in `raw` as well: diagnostics must count it in their
                    // denominator, and even corrupt input must not disappear
                    // merely because it reached the parser.
                    session.raw.push(line.to_string());
                    session.parse_error_lines += 1;
                }
            }
        }

        // P5-3 (native write side, see `Self::to_native_jsonl_v2`'s matching
        // header block): recover a natively-spawned subagent's own lineage
        // from the v2 header, when present. Overlays (rather than merges
        // into) whatever the per-source body loader may have already set on
        // `session.meta` — these three keys are ONLY ever written by
        // `to_native_jsonl_v2` itself (never by a CC/CX/OC/Pi body), so a
        // header that carries them is authoritative for a file this crate
        // produced.
        if let Some(agent_id) = hv.get("agent_id").and_then(Value::as_str) {
            session.meta.agent_id = Some(agent_id.to_string());
        }
        if let Some(parent_tool_use_id) = hv.get("parent_tool_use_id").and_then(Value::as_str) {
            session.meta.parent_tool_use_id = Some(parent_tool_use_id.to_string());
        }
        if let Some(lineage) = hv.get("lineage").and_then(Value::as_object) {
            for (k, v) in lineage {
                if let Some(s) = v.as_str() {
                    session.meta.lineage.insert(k.clone(), s.to_string());
                }
            }
        }

        Ok(session)
    }

    /// The full-fidelity [`Session`] a sidecar denotes.
    ///
    /// The sidecar (native-v2 format, D1) is the imported body plus every
    /// appended [`crate::sidecar::NativeTurn`]. Unlike the deliberately
    /// tolerant lower-level native parser, this persisted-store entry point
    /// validates its framing header before loading anything: a missing,
    /// malformed, or unsupported header must never become a zero-message
    /// session that callers could continue as if it were complete.
    pub fn from_sidecar_str(s: &str) -> Result<Session> {
        let header = s.lines().next().ok_or_else(|| {
            Error::InvalidSession("sidecar header is missing from an empty artifact".to_string())
        })?;
        let value: Value = serde_json::from_str(header).map_err(|error| {
            Error::InvalidSession(format!("sidecar header is not valid JSON: {error}"))
        })?;
        let version = value.get("supercode_native").and_then(Value::as_u64);
        if !matches!(version, Some(1 | 2)) {
            return Err(Error::InvalidSession(
                "sidecar header must declare supported `supercode_native` version 1 or 2"
                    .to_string(),
            ));
        }
        let source = value.get("source").and_then(Value::as_str);
        if !matches!(
            source,
            Some(
                "native"
                    | "claude_code"
                    | "codex"
                    | "gemini"
                    | "goose"
                    | "opencode"
                    | "pi"
                    | "grok"
            )
        ) {
            return Err(Error::InvalidSession(
                "sidecar header must declare a supported `source`".to_string(),
            ));
        }
        Self::from_native_str(s)
    }
}

pub(super) fn native_display_human_line(line: &str, source: Option<SessionSource>) -> bool {
    if !line
        .as_bytes()
        .windows(6)
        .any(|window| window == b"\"user\"")
    {
        return false;
    }
    let Ok(value) = serde_json::from_str::<Value>(line) else {
        return false;
    };
    match source {
        Some(SessionSource::Codex) => {
            value.get("type").and_then(Value::as_str) == Some("response_item")
                && value
                    .get("payload")
                    .and_then(|payload| payload.get("type"))
                    .and_then(Value::as_str)
                    == Some("message")
                && value
                    .get("payload")
                    .and_then(|payload| payload.get("role"))
                    .and_then(Value::as_str)
                    == Some("user")
        }
        Some(SessionSource::ClaudeCode) => {
            value.get("type").and_then(Value::as_str) == Some("user")
                && value
                    .get("message")
                    .and_then(|message| message.get("content"))
                    .is_some_and(|content| match content {
                        Value::String(text) => !text.trim().is_empty(),
                        Value::Array(parts) => parts.iter().any(|part| {
                            part.get("type").and_then(Value::as_str) == Some("text")
                                && part
                                    .get("text")
                                    .and_then(Value::as_str)
                                    .is_some_and(|text| !text.trim().is_empty())
                        }),
                        _ => false,
                    })
        }
        Some(SessionSource::Gemini) => {
            value.get("type").and_then(Value::as_str) == Some("user")
                && value.get("content").is_some_and(|content| match content {
                    Value::String(text) => !text.trim().is_empty(),
                    Value::Array(parts) => parts.iter().any(|part| {
                        part.get("text")
                            .and_then(Value::as_str)
                            .is_some_and(|text| !text.trim().is_empty())
                    }),
                    _ => false,
                })
        }
        _ => false,
    }
}

pub(super) fn capture_native_residue(
    meta: &mut SessionMeta,
    source: &str,
    record_index: usize,
    raw_line: &str,
    record: &Value,
    kind: &str,
) {
    // A record that IS a restored envelope carrier never re-captures itself.
    if record.get(SUPERCODE_NATIVE_RESIDUE_KEY).is_some()
        || record.get(SUPERCODE_NATIVE_RESIDUE_SUMMARY_KEY).is_some()
        || record.get(SUPERCODE_CODEX_PROVENANCE_KEY).is_some()
    {
        return;
    }
    // A transcript that RESTORED a foreign envelope holds residue in transit
    // back to its own source; local capture never clobbers it (the local
    // records still survive this format's own raw diagonal).
    if meta
        .native_residue_source
        .as_deref()
        .is_some_and(|existing| existing != source)
    {
        return;
    }
    meta.native_residue.push(serde_json::json!({
        "record_index": record_index,
        "kind": kind,
        "raw": raw_line,
    }));
    meta.native_residue_source = Some(source.to_string());
}

/// PARITY-23: the GENERALIZED portable residue key (envelope v2). One key
/// for every source format; `_supercode_codex_provenance` (v1) stays
/// readable forever for artifacts written before the generalization.
pub(super) const SUPERCODE_NATIVE_RESIDUE_KEY: &str = "_supercode_native_residue";

/// PARITY-23 dev/05: the residue TOMBSTONE — a tiny always-embedded summary
/// (`{version, source, kinds, records, records_sha256}`) that survives when
/// a caller deliberately strips the heavy records key to shed weight. A
/// summary without its records makes the deletion DETECTABLE: load succeeds
/// and reports exactly which source-native metadata can no longer be
/// restored, instead of the loss being silent.
pub(super) const SUPERCODE_NATIVE_RESIDUE_SUMMARY_KEY: &str = "_supercode_native_residue_summary";

pub(super) fn native_residue_summary(envelope: &Value) -> Value {
    let records = envelope
        .get("records")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    let mut kinds: Vec<String> = records
        .iter()
        .filter_map(|entry| entry.get("kind").and_then(Value::as_str))
        .map(str::to_string)
        .collect();
    kinds.sort();
    kinds.dedup();
    serde_json::json!({
        "version": 2,
        "source": envelope.get("source").cloned().unwrap_or(Value::Null),
        "kinds": kinds,
        "records": records.len(),
        "records_sha256": envelope.get("records_sha256").cloned().unwrap_or(Value::Null),
    })
}

/// Canonical-JSON digest over the residue records — the tamper/corruption
/// binding (PARITY-23 dev/04). Uses the same canonical ordering rules as the
/// audit's `canonicalJson` so the digest is stable across serializers.
fn residue_records_sha256(records: &[Value]) -> String {
    fn canonical(value: &Value, out: &mut String) {
        match value {
            Value::Array(items) => {
                out.push('[');
                for (index, item) in items.iter().enumerate() {
                    if index > 0 {
                        out.push(',');
                    }
                    canonical(item, out);
                }
                out.push(']');
            }
            Value::Object(map) => {
                out.push('{');
                let mut keys: Vec<&String> = map.keys().collect();
                keys.sort();
                for (index, key) in keys.iter().enumerate() {
                    if index > 0 {
                        out.push(',');
                    }
                    out.push_str(&serde_json::to_string(key).unwrap_or_default());
                    out.push(':');
                    canonical(&map[*key], out);
                }
                out.push('}');
            }
            other => out.push_str(&other.to_string()),
        }
    }
    let mut text = String::from("[");
    for (index, record) in records.iter().enumerate() {
        if index > 0 {
            text.push(',');
        }
        canonical(record, &mut text);
    }
    text.push(']');
    let mut hasher = blake3::Hasher::new();
    hasher.update(text.as_bytes());
    hasher.finalize().to_hex().to_string()
}

/// Envelope v2 for the session's native residue. Today the only capture
/// store is `meta.codex_provenance` (source `codex`); per-format inventories
/// land incrementally per the PARITY-23 design doc.
pub(super) fn native_residue_envelope(meta: &SessionMeta) -> Option<Value> {
    if !meta.codex_provenance.is_empty() {
        return Some(serde_json::json!({
            "version": 2,
            "source": "codex",
            "records": &meta.codex_provenance,
            "records_sha256": residue_records_sha256(&meta.codex_provenance),
        }));
    }
    let source = meta.native_residue_source.as_deref()?;
    (!meta.native_residue.is_empty()).then(|| {
        serde_json::json!({
            "version": 2,
            "source": source,
            "records": &meta.native_residue,
            "records_sha256": residue_records_sha256(&meta.native_residue),
        })
    })
}

/// Restore a v2 residue envelope, digest-verified (PARITY-23 dev/04):
/// version/source/digest problems FAIL CLOSED with a diagnostic naming what
/// cannot be restored — never silent fabrication. v1 envelopes delegate to
/// the original codex restore path unchanged.
pub(super) fn restore_native_residue(extension: &Value, meta: &mut SessionMeta) -> Result<bool> {
    match extension.get("version").and_then(Value::as_u64) {
        Some(2) => {}
        other => {
            return Err(Error::InvalidSession(format!(
                "invalid portable native residue: expected version 2, found {other:?} —                  source-native records cannot be restored from this envelope"
            )));
        }
    }
    let source = extension.get("source").and_then(Value::as_str);
    if !matches!(source, Some("codex") | Some("claude_code") | Some("grok")) {
        return Err(Error::InvalidSession(format!(
            "invalid portable native residue: unsupported source {source:?} —              this build restores codex, claude_code and grok residue; the records are preserved raw but not replayed"
        )));
    }
    let Some(records) = extension.get("records").and_then(Value::as_array) else {
        return Err(Error::InvalidSession(
            "invalid portable native residue: `records` must be an array".to_string(),
        ));
    };
    let Some(claimed) = extension.get("records_sha256").and_then(Value::as_str) else {
        return Err(Error::InvalidSession(
            "invalid portable native residue: `records_sha256` digest is missing —              cannot verify the residue was not tampered with; refusing to restore"
                .to_string(),
        ));
    };
    let actual = residue_records_sha256(records);
    if claimed != actual {
        return Err(Error::InvalidSession(
            "invalid portable native residue: records digest mismatch — the residue was              modified or corrupted after export; refusing to restore source-native records"
                .to_string(),
        ));
    }
    if let Some(source) = source.filter(|source| *source != "codex") {
        // Digest verified: validate each record kind against the raw line
        // (the same fail-loud rule the codex path applies).
        let mut restored = Vec::with_capacity(records.len());
        for entry in records {
            let (Some(_), Some(kind), Some(raw)) = (
                entry.get("record_index").and_then(Value::as_u64),
                entry.get("kind").and_then(Value::as_str),
                entry.get("raw").and_then(Value::as_str),
            ) else {
                return Err(Error::InvalidSession(
                    "invalid portable native residue: each record needs record_index/kind/raw"
                        .to_string(),
                ));
            };
            let Ok(record) = serde_json::from_str::<Value>(raw) else {
                return Err(Error::InvalidSession(
                    "invalid portable native residue: raw is not valid JSON".to_string(),
                ));
            };
            let matches = match source {
                "claude_code" => claude_residue_kind(&record) == Some(kind),
                "grok" => grok_residue_kind(&record).as_deref() == Some(kind),
                _ => unreachable!("source whitelist checked above"),
            };
            if !matches {
                return Err(Error::InvalidSession(format!(
                    "invalid portable native residue: kind `{kind}` does not match raw record"
                )));
            }
            restored.push(entry.clone());
        }
        if restored.is_empty() {
            return Err(Error::InvalidSession(
                "invalid portable native residue: `records` must not be empty".to_string(),
            ));
        }
        meta.native_residue = restored;
        meta.native_residue_source = Some(source.to_string());
        return Ok(true);
    }
    // Digest verified: the inner record validation and meta rebuild are the
    // v1 rules exactly.
    restore_codex_provenance(&serde_json::json!({"version": 1, "records": records}), meta)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn malformed_discriminated_native_turn_is_counted_as_parse_loss() {
        let base = Session::from_native_messages(Vec::new());
        let mut native = base.to_native_jsonl_v2(&[]);
        native.push_str("{\"supercode_turn\":1}\n");

        let parsed = Session::from_native_str(&native).unwrap();
        assert_eq!(parsed.parse_error_lines, 1);
        assert!(parsed.messages.is_empty());
        assert_eq!(
            parsed.raw.last().map(String::as_str),
            Some("{\"supercode_turn\":1}")
        );
    }

    #[test]
    fn spliced_export_refuses_a_native_wrapper_with_parse_loss() {
        let imported = Session::from_claude_code_str(
            r#"{"type":"user","sessionId":"s","cwd":"/tmp","message":{"role":"user","content":"hi"}}"#,
        )
        .unwrap();
        let mut native = imported.to_native_jsonl_v2(&[ChatMessage::assistant("continued")]);
        native.push_str("{\"supercode_turn\":1}\n");

        let parsed = Session::from_native_str(&native).unwrap();
        let error = parsed
            .to_jsonl_spliced(SessionFormat::ClaudeCode, None)
            .unwrap_err();
        assert!(error.to_string().contains("parse loss"), "{error}");
    }

    #[test]
    fn sidecar_loader_requires_a_supported_native_header() {
        for malformed in [
            "",
            "not-json\n",
            "{}\n",
            "{\"supercode_native\":2}\n",
            "{\"supercode_native\":99,\"source\":\"native\"}\n",
        ] {
            let error = Session::from_sidecar_str(malformed).unwrap_err();
            assert!(error.to_string().contains("sidecar header"), "{error}");
        }
    }
}