supercode-harness 0.4.4

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
//! Acceptance tests for TR-10 (`ReductionKind::ToolInputElided`): the
//! assistant-side twin of A7 (tool RESULTS)/A8 (stale file READS) — eliding
//! the disk-persisted payload argument of an already-executed, SUCCESSFUL
//! tool_use call, leaving every other argument (e.g. `path`) verbatim.
//!
//! Mirrors `reduce_projection.rs`'s idiom throughout: hand-built
//! `ChatMessage` vectors run through the REAL `project_messages`/`invert`/
//! `export_session` pipeline (never a re-implementation of the reduction
//! logic), with `session_of(msgs)` wrapping a message vector in a bare
//! `Session` to serve as the `sidecar_session` `invert` needs (the sidecar
//! IS the unreduced message list — SPEC.md A6).

use std::path::PathBuf;

use supercode_harness::reduce::{
    invert, is_tool_error, mark_tool_error, probe_tool_input_fresh, project_messages, reduction_id,
    tool_input_escalation_action, EscalationAction, ReductionKind, ReductionLog, ReductionPolicy,
    REDUCTION_SENTINEL,
};
use supercode_harness::{ChatMessage, FunctionCall, Role, Session, ToolCall};

// ---- shared helpers ---------------------------------------------------------

/// An empty (Claude-Code-origin) `Session` whose `messages` is then
/// overwritten — the same idiom `reduce_projection.rs::session_of` uses, so
/// a hand-built message vector can serve as `invert`'s `sidecar_session`.
fn session_of(msgs: Vec<ChatMessage>) -> Session {
    let mut session = Session::from_claude_code_str("").unwrap();
    session.messages = msgs;
    session
}

/// Build an assistant message issuing one `write_file(path, content)` tool
/// call with the given call id — every other field left at its default (no
/// leading text, one tool call).
fn write_call(id: &str, path: &str, content: &str) -> ChatMessage {
    ChatMessage {
        role: Role::Assistant,
        content: None,
        content_parts: None,
        tool_calls: Some(vec![ToolCall {
            id: id.to_string(),
            kind: "function".to_string(),
            function: FunctionCall {
                name: "write_file".to_string(),
                arguments: serde_json::json!({ "path": path, "content": content }).to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    }
}

/// A successful `write_file` result message paired to `id`.
fn write_ok_result(id: &str, path: &str, bytes: usize) -> ChatMessage {
    ChatMessage::tool_result(id, "write_file", format!("Wrote {bytes} bytes to {path}"))
}

/// An ERRORED `write_file` result message paired to `id` — the TR-10/TR-6
/// boundary case: marked via [`mark_tool_error`], the only way `ChatMessage`
/// carries "this call failed" (see `reduce.rs::TOOL_ERROR_METADATA_KEY`'s
/// doc comment for why there's no other structural slot).
fn write_err_result(id: &str) -> ChatMessage {
    let mut m = ChatMessage::tool_result(id, "write_file", "Error: disk full");
    mark_tool_error(&mut m);
    m
}

/// A deterministic all-ASCII filler string of exactly `len` bytes.
fn filler(len: usize) -> String {
    (0..len).map(|i| (b'a' + (i % 26) as u8) as char).collect()
}

/// The tool_call's raw `arguments` string at `msg_index`'s first tool call.
fn args_of(msgs: &[ChatMessage], msg_index: usize) -> String {
    msgs[msg_index].tool_calls()[0].function.arguments.clone()
}

fn parsed_args(msgs: &[ChatMessage], msg_index: usize) -> serde_json::Value {
    serde_json::from_str(&args_of(msgs, msg_index)).unwrap()
}

// ---- dev/01: successful large Write elided, invert byte-exact --------------

#[test]
fn dev01_large_successful_write_is_elided_stub_visible_and_inverts_byte_exact() {
    let big = filler(20_000);
    let msgs = vec![
        ChatMessage::user("please write the report"),
        write_call("w1", "reports/out.txt", &big),
        write_ok_result("w1", "reports/out.txt", big.len()),
        ChatMessage::assistant("done"),
    ];
    let asst_idx = 1;

    let (view, log) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());

    assert_eq!(log.reductions.len(), 1, "exactly one reduction expected");
    let r = &log.reductions[0];
    let (original_bytes, path, content_hash, call_id, field) = match &r.kind {
        ReductionKind::ToolInputElided {
            original_bytes,
            path,
            content_hash,
            call_id,
            field,
        } => (
            *original_bytes,
            path.clone(),
            content_hash.clone(),
            call_id.clone(),
            field.clone(),
        ),
        other => panic!("expected ToolInputElided, got {other:?}"),
    };
    assert_eq!(original_bytes, big.len());
    assert_eq!(path, Some(PathBuf::from("reports/out.txt")));
    assert_eq!(
        content_hash,
        supercode_harness::reduce::content_hash(big.as_bytes())
    );
    assert_eq!(call_id, "w1");
    assert_eq!(field, "content");
    assert_eq!(r.ptr.span, None, "whole-field elision carries no byte span");
    assert_eq!(r.ptr.addr.index, asst_idx);
    assert_eq!(r.ptr.addr.role, Role::Assistant);

    // The stub is visible in the view's tool_call arguments (not `content` —
    // this kind's slot is the assistant's tool_use arguments).
    let reduced = parsed_args(&view, asst_idx);
    let content_val = reduced.get("content").unwrap().as_str().unwrap();
    assert!(content_val.contains(REDUCTION_SENTINEL), "{content_val}");
    assert!(content_val.contains("tool-input"), "{content_val}");
    assert!(content_val.contains(&r.id), "{content_val}");
    assert!(content_val.contains("write_file"), "{content_val}");
    assert!(content_val.contains("20,000"), "{content_val}");
    assert!(
        content_val.contains("reports/out.txt"),
        "path should be named in the summary: {content_val}"
    );

    // Non-payload argument (`path`) stays verbatim.
    assert_eq!(
        reduced.get("path").unwrap().as_str().unwrap(),
        "reports/out.txt"
    );

    // The message carries the reduction id (metadata never hits the wire).
    assert_eq!(reduction_id(&view[asst_idx]), Some(r.id.as_str()));

    // `invert` restores the EXACT original arguments string, byte for byte.
    let sidecar = session_of(msgs.clone());
    let inverted = invert(&view, &log, &sidecar).unwrap();
    assert_eq!(
        args_of(&inverted, asst_idx),
        args_of(&msgs, asst_idx),
        "invert must restore the original tool_call arguments byte-for-byte"
    );
    assert_eq!(reduction_id(&inverted[asst_idx]), None);

    // Every other message is untouched.
    for i in [0usize, 2, 3] {
        assert_eq!(
            inverted[i].content, msgs[i].content,
            "message {i} must be untouched"
        );
    }

    // Determinism + prefix stability: re-projecting from the same prior log
    // reproduces the SAME id and byte-identical stub.
    let (view2, log2) = project_messages(&msgs, &ReductionPolicy::default(), &log);
    assert_eq!(log2.reductions, log.reductions);
    assert_eq!(args_of(&view2, asst_idx), args_of(&view, asst_idx));
}

// ---- dev/02: errored / pending calls are never input-elided -----------------

#[test]
fn dev02_errored_write_call_is_never_input_elided() {
    let big = filler(20_000);
    let msgs = vec![write_call("w1", "out.txt", &big), write_err_result("w1")];
    assert!(is_tool_error(&msgs[1]));

    let (view, log) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
    assert!(
        log.reductions.is_empty(),
        "an errored call's oversized input must never be elided: {:?}",
        log.reductions
    );
    assert_eq!(args_of(&view, 0), args_of(&msgs, 0));
}

#[test]
fn dev02_still_pending_write_call_is_never_input_elided() {
    let big = filler(20_000);
    // No paired tool result at all — the call hasn't finished (or the
    // transcript is mid-turn).
    let msgs = vec![
        ChatMessage::user("write it"),
        write_call("w1", "out.txt", &big),
    ];

    let (view, log) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
    assert!(
        log.reductions.is_empty(),
        "a still-pending call's oversized input must never be elided: {:?}",
        log.reductions
    );
    assert_eq!(args_of(&view, 1), args_of(&msgs, 1));
}

// ---- dev/03: threshold + field-level selectivity ----------------------------

#[test]
fn dev03_args_below_threshold_are_untouched() {
    let small = filler(100); // well under the default 8192-byte trigger
    let msgs = vec![
        write_call("w1", "out.txt", &small),
        write_ok_result("w1", "out.txt", 100),
    ];

    let (view, log) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
    assert!(
        log.reductions.is_empty(),
        "a small payload must not be elided"
    );
    assert_eq!(args_of(&view, 0), args_of(&msgs, 0));
}

#[test]
fn dev03_non_payload_field_is_never_elided_even_when_oversized() {
    // `path` is (unrealistically) huge here too — only `content` is ever the
    // designated payload field for `write_file`, so `path` must survive
    // untouched regardless of its own size.
    let big_content = filler(20_000);
    let big_path = format!("dir/{}.txt", filler(9_000));
    let msg = ChatMessage {
        role: Role::Assistant,
        content: None,
        content_parts: None,
        tool_calls: Some(vec![ToolCall {
            id: "w1".to_string(),
            kind: "function".to_string(),
            function: FunctionCall {
                name: "write_file".to_string(),
                arguments: serde_json::json!({ "path": big_path, "content": big_content })
                    .to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    };
    let msgs = vec![msg, write_ok_result("w1", "dir/x.txt", big_content.len())];

    let (view, log) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
    assert_eq!(
        log.reductions.len(),
        1,
        "exactly the `content` field is elided"
    );
    match &log.reductions[0].kind {
        ReductionKind::ToolInputElided { field, .. } => assert_eq!(field, "content"),
        other => panic!("expected ToolInputElided, got {other:?}"),
    }
    let reduced = parsed_args(&view, 0);
    assert_eq!(
        reduced.get("path").unwrap().as_str().unwrap(),
        big_path,
        "the oversized non-payload `path` field must remain verbatim, never elided"
    );
    assert!(reduced
        .get("content")
        .unwrap()
        .as_str()
        .unwrap()
        .contains(REDUCTION_SENTINEL));
}

// ---- dev/04: freshness matrix (à la A8) -------------------------------------

fn a8_style_temp_dir(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "supercode-tr10-{tag}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

#[test]
fn dev04_freshness_matrix_fresh_keeps_stub_stale_rehydrates_from_sidecar() {
    let dir = a8_style_temp_dir("freshness");
    let file_path = dir.join("f.txt");
    let content = filler(20_000);
    std::fs::write(&file_path, &content).unwrap();

    let msgs = vec![
        write_call("w1", file_path.to_str().unwrap(), &content),
        write_ok_result("w1", file_path.to_str().unwrap(), content.len()),
    ];
    let (view, log) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
    assert_eq!(log.reductions.len(), 1);
    let r = &log.reductions[0];
    let content_hash = match &r.kind {
        ReductionKind::ToolInputElided { content_hash, .. } => content_hash.clone(),
        other => panic!("expected ToolInputElided, got {other:?}"),
    };

    // ---- (i) disk still matches -> KeepStub. ----
    assert!(probe_tool_input_fresh(&file_path, &content_hash));
    assert_eq!(
        tool_input_escalation_action(probe_tool_input_fresh(&file_path, &content_hash)),
        EscalationAction::KeepStub
    );
    // The stub is still exactly what a "keep" decision leaves in place.
    assert_eq!(args_of(&view, 0), args_of(&view, 0));

    // ---- (ii) disk changes since -> RehydrateFromSidecar, and rehydrating
    // (invert) really does restore the original from the sidecar. ----
    std::fs::write(&file_path, format!("{content}-modified-on-disk")).unwrap();
    assert!(!probe_tool_input_fresh(&file_path, &content_hash));
    assert_eq!(
        tool_input_escalation_action(probe_tool_input_fresh(&file_path, &content_hash)),
        EscalationAction::RehydrateFromSidecar
    );
    let sidecar = session_of(msgs.clone());
    let inverted = invert(&view, &log, &sidecar).unwrap();
    assert_eq!(
        args_of(&inverted, 0),
        args_of(&msgs, 0),
        "rehydrating from the sidecar must restore the exact original write, \
         independent of what disk looks like now"
    );

    // ---- (iii) file deleted -> never fresh either (fails closed). ----
    std::fs::remove_file(&file_path).unwrap();
    assert!(!probe_tool_input_fresh(&file_path, &content_hash));

    std::fs::remove_dir_all(&dir).ok();
}

// ---- dev/05: export purity (A11 leak guard) ---------------------------------

#[test]
fn dev05_export_never_leaks_the_stub_original_args_present() {
    let big = filler(20_000);
    let msgs = vec![
        ChatMessage::user("write it"),
        write_call("w1", "out.txt", &big),
        write_ok_result("w1", "out.txt", big.len()),
    ];
    // Sanity: this really does mint a ToolInputElided reduction (otherwise
    // the "no sentinel" assertion below would be vacuously true).
    let (_, log) = project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
    assert_eq!(log.reductions.len(), 1);

    // Export ALWAYS reads the sidecar (the unreduced messages), never the
    // reduced view or the log — build the sidecar JSONL the same way
    // `export_sidecar.rs`/`rehydrate.rs` do: an empty imported prefix plus
    // every message as an APPENDED `NativeTurn` record (`to_native_jsonl_v2`
    // — unlike `to_native_jsonl`, which serializes `raw`, not `messages`).
    let empty = Session::from_claude_code_str("").unwrap();
    let native = empty.to_native_jsonl_v2(&msgs);

    let exported =
        supercode_harness::reduce::export_session(&native, supercode_harness::SessionFormat::Codex)
            .expect("export must succeed on a genuinely unreduced sidecar");
    assert_eq!(
        exported.matches(REDUCTION_SENTINEL).count(),
        0,
        "exported transcript must contain zero stubs"
    );
    assert!(
        exported.contains(&big),
        "exported transcript must contain the ORIGINAL full write content"
    );

    let exported_spliced = supercode_harness::reduce::export_session_spliced(
        &native,
        supercode_harness::SessionFormat::Codex,
        None,
    )
    .expect("spliced export must succeed on a genuinely unreduced sidecar");
    assert_eq!(exported_spliced.matches(REDUCTION_SENTINEL).count(), 0);
    assert!(exported_spliced.contains(&big));
}

// ---- MCP per-tool opt-in -----------------------------------------------------

#[test]
fn mcp_tool_only_elided_when_opted_in_via_policy() {
    let big = filler(20_000);
    let mcp_call = ChatMessage {
        role: Role::Assistant,
        content: None,
        content_parts: None,
        tool_calls: Some(vec![ToolCall {
            id: "m1".to_string(),
            kind: "function".to_string(),
            function: FunctionCall {
                name: "mcp__blobstore__put".to_string(),
                arguments: serde_json::json!({ "key": "asset/1", "data": big }).to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    };
    let msgs = vec![
        mcp_call,
        ChatMessage::tool_result("m1", "mcp__blobstore__put", "ok"),
    ];

    // Not opted in: default policy never touches it.
    let (_, log_default) =
        project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
    assert!(
        log_default.reductions.is_empty(),
        "an MCP tool must never be elided without an explicit opt-in"
    );

    // Opted in: the same call is now a candidate.
    let mut policy = ReductionPolicy::default();
    policy
        .tool_input_elidable_fields
        .insert("mcp__blobstore__put".to_string(), "data".to_string());
    let (view, log) = project_messages(&msgs, &policy, &ReductionLog::default());
    assert_eq!(log.reductions.len(), 1);
    let reduced = parsed_args(&view, 0);
    assert!(reduced
        .get("data")
        .unwrap()
        .as_str()
        .unwrap()
        .contains(REDUCTION_SENTINEL));
    assert_eq!(reduced.get("key").unwrap().as_str().unwrap(), "asset/1");
}