supercode-harness 0.4.11

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
//! A11 acceptance tests (SPEC.md §6): export always reads the sidecar, never
//! the reduced view; the placeholder-leak guard fails closed; the B6
//! `tool_search` call/result pair exports to Codex as the paired
//! `tool_search_call`/`tool_search_output` records (the exact inverse of the
//! importer's normalization, `session.rs:1246-1272`).
//!
//! No test here reads an env var or is `#[ignore]`d — every assertion runs on
//! a plain `cargo test`, matching `roundtrip_regression.rs`'s convention.

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

use supercode_harness::reduce::{export_session, REDUCTION_SENTINEL};
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 `roundtrip_regression.rs::msg_eq` (which in
/// turn duplicates `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:?}"
        );
    }
}

/// Codex has no Claude-Code-style system/developer transcript slot to
/// round-trip through the Claude Code writer, and `to_claude_code_jsonl`
/// documentedly omits `Role::System` — filter it on both sides, matching
/// `roundtrip_regression.rs::non_system`. Applied uniformly (not just for
/// Codex-origin sessions) so the same comparison works for both export
/// targets in the same loop.
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: emitting one would get
/// silently misattributed to an unrelated later turn instead, which is
/// worse). Filter it here for the SAME reason `non_system` filters
/// `Role::System` — it has 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()
}

/// Mirrors `roundtrip_regression.rs::exported_jsonl_is_parseable_line_by_line`'s
/// per-line well-formedness assertions: every line parses as JSON and carries
/// the format's required top-level keys.
fn assert_well_formed(label: &str, jsonl: &str, format: SessionFormat) {
    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 by this file's fixtures (wave A scope: Claude/Codex
            // export regression only — see `pi_interop.rs` for Pi's own
            // well-formedness assertions; 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");
}

fn plain_message(role: Role, content: &str) -> ChatMessage {
    ChatMessage {
        role,
        content: Some(content.to_string()),
        content_parts: None,
        tool_calls: None,
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    }
}

fn two_synthetic_turns() -> Vec<ChatMessage> {
    vec![
        plain_message(Role::User, "Appended turn: what is 2+2?"),
        plain_message(Role::Assistant, "4."),
    ]
}

// ---- 1. Positive: export reads the sidecar, leaks nothing ------------------

#[test]
fn export_ignores_reduction_and_leaks_nothing() {
    let original = Session::from_claude_code(fixture("claude_code_session.jsonl")).unwrap();
    let appended = two_synthetic_turns();
    let sidecar = original.to_native_jsonl_v2(&appended);

    // The full-fidelity session this sidecar denotes: the imported prefix
    // plus the 2 appended turns — exactly what `export_session` must produce,
    // regardless of any reduced view that might exist alongside it (there is
    // none here; A11 does not need a real reduction to prove the contract:
    // `export_session` never even takes a view/log as input).
    let mut full_messages = original.messages.clone();
    full_messages.extend(appended.iter().cloned());

    for format in [SessionFormat::ClaudeCode, SessionFormat::Codex] {
        let exported = export_session(&sidecar, format)
            .unwrap_or_else(|e| panic!("export_session({format:?}) failed: {e}"));

        // (i) neither output contains the reduction sentinel.
        assert!(
            !exported.contains(REDUCTION_SENTINEL),
            "export_session({format:?}) leaked the reduction sentinel:\n{exported}"
        );

        // (ii) reloading yields messages ≡ the full unreduced session.
        let reloaded = Session::load_str(&exported, format)
            .unwrap_or_else(|e| panic!("reloading export_session({format:?}) output failed: {e}"));
        // Codex has no wire slot for a standalone reasoning-only turn (see
        // `non_reasoning_only`'s doc comment) — filter only on that leg, so
        // the Claude Code leg stays maximally strict (it DOES preserve them).
        let (expected, actual) = match format {
            SessionFormat::Codex => (
                non_reasoning_only(&non_system(&full_messages)),
                non_reasoning_only(&non_system(&reloaded.messages)),
            ),
            _ => (non_system(&full_messages), non_system(&reloaded.messages)),
        };
        assert_messages_eq(
            &format!("export_session({format:?}) round-trip"),
            &expected,
            &actual,
        );

        // (iii) line-by-line well-formedness.
        assert_well_formed(
            &format!("export_session({format:?}) output"),
            &exported,
            format,
        );
    }
}

// ---- 2. Grammar-aware leak guard --------------------------------------------

#[test]
fn export_session_allows_sentinel_mentions_but_rejects_exact_stubs() {
    let original = Session::from_claude_code(fixture("claude_code_session.jsonl")).unwrap();
    let genuine_but_sentinel_shaped = plain_message(
        Role::User,
        "please literally output [sc-reduced tool-output r0001-aaaa: not a real reduction]",
    );
    let sidecar = original.to_native_jsonl_v2(&[genuine_but_sentinel_shaped]);

    for format in [SessionFormat::ClaudeCode, SessionFormat::Codex] {
        let exported = export_session(&sidecar, format)
            .unwrap_or_else(|e| panic!("sentinel mention must remain exportable: {e}"));
        assert!(exported.contains("please literally output [sc-reduced"));
    }

    let exact_stub = plain_message(
        Role::Tool,
        "[sc-reduced tool-output r0001-aaaa: full output in session sidecar]",
    );
    let poisoned = original.to_native_jsonl_v2(&[exact_stub]);
    for format in [SessionFormat::ClaudeCode, SessionFormat::Codex] {
        let result = export_session(&poisoned, format);
        assert!(result.is_err(), "an exact reduction stub must fail closed");
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains(REDUCTION_SENTINEL),
            "error message should name the sentinel it found: {msg:?}"
        );
    }

    let truncated_stub = plain_message(
        Role::Tool,
        "visible output prefix\n\n[sc-reduced tool-output r0003-cccc: full output in session sidecar]",
    );
    let poisoned_truncated = original.to_native_jsonl_v2(&[truncated_stub]);
    assert!(
        export_session(&poisoned_truncated, SessionFormat::Codex).is_err(),
        "a reduction stub after a retained output prefix must fail closed"
    );

    let tool_input_stub = ChatMessage {
        role: Role::Assistant,
        content: None,
        content_parts: None,
        tool_calls: Some(vec![ToolCall {
            id: "call-stub".to_string(),
            kind: "function".to_string(),
            function: FunctionCall {
                name: "write_file".to_string(),
                arguments: serde_json::json!({
                    "path": "out.txt",
                    "content": "[sc-reduced tool-input r0002-bbbb: original field in session sidecar]"
                })
                .to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    };
    let poisoned_args = original.to_native_jsonl_v2(&[tool_input_stub]);
    assert!(
        export_session(&poisoned_args, SessionFormat::Codex).is_err(),
        "a grammar-valid reduction stub nested in tool arguments must fail closed"
    );
}

// ---- 3. B6 export mapping: tool_search round-trips to Codex ----------------

fn tool_search_pair() -> Vec<ChatMessage> {
    let call = ToolCall {
        id: "call_search_1".to_string(),
        kind: "function".to_string(),
        function: FunctionCall {
            name: "tool_search".to_string(),
            arguments: serde_json::json!({"query": "patch", "max_results": 5}).to_string(),
        },
    };
    let assistant = ChatMessage {
        role: Role::Assistant,
        content: None,
        content_parts: None,
        tool_calls: Some(vec![call]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    };
    let result = ChatMessage {
        role: Role::Tool,
        content: Some(serde_json::json!(["apply_patch"]).to_string()),
        content_parts: None,
        tool_calls: None,
        tool_call_id: Some("call_search_1".to_string()),
        name: None,
        metadata: Default::default(),
    };
    vec![assistant, result]
}

#[test]
fn tool_search_pair_roundtrips_to_codex() {
    let original = Session::from_claude_code(fixture("claude_code_session.jsonl")).unwrap();
    let appended = tool_search_pair();
    let sidecar = original.to_native_jsonl_v2(&appended);

    let exported = export_session(&sidecar, SessionFormat::Codex).unwrap();
    assert!(
        exported.contains("\"tool_search_call\""),
        "Codex export must contain a tool_search_call record:\n{exported}"
    );
    assert!(
        exported.contains("\"tool_search_output\""),
        "Codex export must contain a tool_search_output record:\n{exported}"
    );
    // The exporter emits the exact inverse of the importer's normalization
    // (`session.rs:1246-1272`), so a generic `function_call`/`function_call_output`
    // pair named `tool_search` must NOT appear alongside it.
    assert!(
        !exported.contains("\"function_call\",\"name\":\"tool_search\"")
            && !exported.contains("\"name\":\"tool_search\",\"arguments\""),
        "tool_search must not ALSO be emitted as a generic function_call:\n{exported}"
    );

    // import(export(s)) preserves the pair as a single tool_search call/result.
    let reloaded = Session::from_codex_str(&exported).unwrap();
    let call_msg = reloaded
        .messages
        .iter()
        .find(|m| {
            m.tool_calls()
                .iter()
                .any(|c| c.function.name == "tool_search")
        })
        .expect("reloaded Codex session must contain a tool_search ToolCall");
    let call = call_msg
        .tool_calls()
        .iter()
        .find(|c| c.function.name == "tool_search")
        .unwrap()
        .clone();
    let result_msg = reloaded
        .messages
        .iter()
        .find(|m| m.tool_call_id.as_deref() == Some(call.id.as_str()))
        .expect("reloaded Codex session must contain the matching tool result");
    assert_eq!(result_msg.role, Role::Tool);
    let arr: Vec<String> = serde_json::from_str(result_msg.content.as_deref().unwrap_or(""))
        .expect("tool_search result content should parse as a JSON array");
    assert_eq!(arr, vec!["apply_patch".to_string()]);

    // Claude Code gets an ordinary tool_use/tool_result pair (no special
    // tool_search framing — it's just another named tool call there).
    let cc_exported = export_session(&sidecar, SessionFormat::ClaudeCode).unwrap();
    assert!(
        !cc_exported.contains(REDUCTION_SENTINEL),
        "Claude Code export must not leak the sentinel either"
    );
    let cc_reloaded = Session::from_claude_code_str(&cc_exported).unwrap();
    let cc_call = cc_reloaded
        .messages
        .iter()
        .find_map(|m| {
            m.tool_calls()
                .iter()
                .find(|c| c.function.name == "tool_search")
                .cloned()
        })
        .expect("Claude Code reload must still carry the tool_search ToolCall");
    let cc_result = cc_reloaded
        .messages
        .iter()
        .find(|m| m.tool_call_id.as_deref() == Some(cc_call.id.as_str()))
        .expect("Claude Code reload must carry the matching tool_result");
    assert_eq!(cc_result.role, Role::Tool);
}

// ---- 4. D1: tool_search_call turn_id merge (PARITY-6/7's bug-class left ----
// ---- half-done for tool_search_call) ---------------------------------------

/// D1 (Fable-5 review, confirmed): `write_codex_records` stamps the SAME
/// synthetic `metadata.turn_id` onto a `tool_search_call` record that it
/// stamps onto a `function_call` record for the same originating
/// `ChatMessage` (see the PARITY-6/7 comment on `write_codex_records`), but
/// until this fix `push_codex_item`'s `tool_search_call` reader arm never
/// looked at that stamp — it unconditionally started a brand-new
/// `ChatMessage` every time. That silently inflated the message count on
/// reload: a single Claude assistant record containing text + one
/// `tool_search` block round-tripped through Codex as TWO messages instead
/// of one. Fails against the pre-fix reader (which had no merge check in
/// this arm at all).
#[test]
fn tool_search_call_merges_with_preceding_text_on_codex_reload() {
    let call = ToolCall {
        id: "call_ts_1".to_string(),
        kind: "function".to_string(),
        function: FunctionCall {
            name: "tool_search".to_string(),
            arguments: serde_json::json!({"query": "patch"}).to_string(),
        },
    };
    let assistant = ChatMessage {
        role: Role::Assistant,
        content: Some("Let me look for the right tool.".to_string()),
        content_parts: None,
        tool_calls: Some(vec![call]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    };

    let original = Session::from_claude_code(fixture("claude_code_session.jsonl")).unwrap();
    let sidecar = original.to_native_jsonl_v2(&[assistant]);
    let exported = export_session(&sidecar, SessionFormat::Codex).unwrap();
    let reloaded = Session::from_codex_str(&exported).unwrap();

    let merged: Vec<_> = reloaded
        .messages
        .iter()
        .filter(|m| {
            m.role == Role::Assistant
                && m.content.as_deref() == Some("Let me look for the right tool.")
        })
        .collect();
    assert_eq!(
        merged.len(),
        1,
        "text+tool_search must reload as exactly ONE assistant message, not split: {:#?}",
        reloaded.messages
    );
    assert_eq!(
        merged[0].tool_calls().len(),
        1,
        "the tool_search call must be merged INTO the text message, not orphaned: {:#?}",
        merged[0]
    );
    assert_eq!(merged[0].tool_calls()[0].function.name, "tool_search");
}

/// D1, second shape: TWO `tool_search` blocks (no text at all) from the same
/// original `ChatMessage`. Before the fix each `tool_search_call` record
/// started its own message unconditionally, so this round-tripped as 2
/// messages instead of 1 (a 1 -> 2 inflation with no text message involved
/// at all — the pre-fix code had no path that could ever merge two
/// `tool_search_call`s together).
#[test]
fn two_tool_search_calls_merge_to_one_message_on_codex_reload() {
    let calls = vec![
        ToolCall {
            id: "call_ts_a".to_string(),
            kind: "function".to_string(),
            function: FunctionCall {
                name: "tool_search".to_string(),
                arguments: serde_json::json!({"query": "a"}).to_string(),
            },
        },
        ToolCall {
            id: "call_ts_b".to_string(),
            kind: "function".to_string(),
            function: FunctionCall {
                name: "tool_search".to_string(),
                arguments: serde_json::json!({"query": "b"}).to_string(),
            },
        },
    ];
    let assistant = ChatMessage {
        role: Role::Assistant,
        content: None,
        content_parts: None,
        tool_calls: Some(calls),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    };

    let original = Session::from_claude_code(fixture("claude_code_session.jsonl")).unwrap();
    let sidecar = original.to_native_jsonl_v2(&[assistant]);
    let exported = export_session(&sidecar, SessionFormat::Codex).unwrap();
    let reloaded = Session::from_codex_str(&exported).unwrap();

    let merged: Vec<_> = reloaded
        .messages
        .iter()
        .filter(|m| {
            m.tool_calls()
                .iter()
                .any(|c| c.function.name == "tool_search")
        })
        .collect();
    assert_eq!(
        merged.len(),
        1,
        "two tool_search blocks from the SAME original message must reload \
         as ONE ChatMessage, not two: {:#?}",
        reloaded.messages
    );
    assert_eq!(
        merged[0].tool_calls().len(),
        2,
        "both tool_search calls must land on the same merged message: {:#?}",
        merged[0]
    );
}