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};
fn session_of(msgs: Vec<ChatMessage>) -> Session {
let mut session = Session::from_claude_code_str("").unwrap();
session.messages = msgs;
session
}
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(),
}
}
fn write_ok_result(id: &str, path: &str, bytes: usize) -> ChatMessage {
ChatMessage::tool_result(id, "write_file", format!("Wrote {bytes} bytes to {path}"))
}
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
}
fn filler(len: usize) -> String {
(0..len).map(|i| (b'a' + (i % 26) as u8) as char).collect()
}
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()
}
#[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);
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}"
);
assert_eq!(
reduced.get("path").unwrap().as_str().unwrap(),
"reports/out.txt"
);
assert_eq!(reduction_id(&view[asst_idx]), Some(r.id.as_str()));
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);
for i in [0usize, 2, 3] {
assert_eq!(
inverted[i].content, msgs[i].content,
"message {i} must be untouched"
);
}
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));
}
#[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);
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));
}
#[test]
fn dev03_args_below_threshold_are_untouched() {
let small = filler(100); 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() {
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));
}
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:?}"),
};
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
);
assert_eq!(args_of(&view, 0), args_of(&view, 0));
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"
);
std::fs::remove_file(&file_path).unwrap();
assert!(!probe_tool_input_fresh(&file_path, &content_hash));
std::fs::remove_dir_all(&dir).ok();
}
#[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()),
];
let (_, log) = project_messages(&msgs, &ReductionPolicy::default(), &ReductionLog::default());
assert_eq!(log.reductions.len(), 1);
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));
}
#[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"),
];
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"
);
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");
}