use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use async_trait::async_trait;
use supercode::reduce::{invert, project_messages, verify_log, ReductionKind, ReductionPolicy};
use supercode::session::Session;
use supercode::sidecar::SidecarWriter;
use supercode::store::SessionStore;
use supercode::{
Agent, ChatMessage, ChatRequest, Config, FunctionCall, Provider, Role, ToolCall, Usage,
};
fn temp_dir(tag: &str) -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!(
"supercode-tr2-guarantor-{tag}-{}-{}",
std::process::id(),
N.fetch_add(1, Ordering::SeqCst)
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
struct DupTool(String);
#[async_trait]
impl supercode::tools::Tool for DupTool {
fn name(&self) -> &str {
"dup_tool"
}
fn description(&self) -> &str {
"x"
}
fn parameters(&self) -> serde_json::Value {
serde_json::json!({"type": "object"})
}
async fn execute(
&self,
_a: serde_json::Value,
_c: &supercode::tools::ToolContext,
) -> supercode::Result<String> {
Ok(self.0.clone())
}
}
fn tool_call_msg(id: &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: "dup_tool".to_string(),
arguments: "{}".to_string(),
},
}]),
tool_call_id: None,
name: None,
metadata: Default::default(),
}
}
struct RepeatedToolThenPlain {
calls: AtomicUsize,
n_tool_calls: usize,
}
#[async_trait]
impl Provider for RepeatedToolThenPlain {
async fn complete(
&self,
_req: &ChatRequest,
_on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
) -> supercode::Result<(ChatMessage, Usage)> {
let n = self.calls.fetch_add(1, Ordering::SeqCst);
if n < self.n_tool_calls {
Ok((tool_call_msg(&format!("c{n}")), Usage::default()))
} else {
Ok((
ChatMessage::assistant(format!("done {n}")),
Usage::default(),
))
}
}
}
#[tokio::test]
async fn duplicate_output_survives_live_agent_disk_reload_offline_verify_and_invert() {
let dir = temp_dir("dev01-dev04");
let store_dir = dir.join("store");
let store = SessionStore::open(&store_dir).unwrap();
let name = "tr2-dev01";
let sidecar_path = store.sidecar_path(name);
let mut original = "D".repeat(4_000);
original.push_str("TR2-DEDUP-NEEDLE");
let pad = 5_000 - original.len();
original.push_str(&"e".repeat(pad));
assert_eq!(original.len(), 5_000);
assert!(original.len() > ReductionPolicy::default().duplicate_output_min_bytes);
assert!(original.len() < ReductionPolicy::default().tool_output_trigger_bytes);
let config = Config::builder().cwd(dir.clone()).build();
let mut reg = supercode::tools::ToolRegistry::new();
reg.register(DupTool(original.clone()));
let mut agent = Agent::with_parts(
config,
Box::new(RepeatedToolThenPlain {
calls: AtomicUsize::new(0),
n_tool_calls: 5,
}),
reg,
);
let empty_session = Session::from_claude_code_str("").unwrap();
let writer = SidecarWriter::create(&sidecar_path, &empty_session).unwrap();
agent.set_recorder(writer);
let policy1 = ReductionPolicy::default();
agent.set_reduction_policy(policy1.clone());
let reply = agent.send("investigate").await.unwrap();
assert!(reply.starts_with("done"), "unexpected reply: {reply}");
let log1 = agent.reduction_log().clone();
let dups: Vec<_> = log1
.reductions
.iter()
.filter(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. }))
.collect();
assert_eq!(
dups.len(),
1,
"exactly one of the five identical calls must be eligible to dedup \
under the default protected tail: {:?}",
log1.reductions
);
let dup_id = dups[0].id.clone();
let dup_idx = dups[0].ptr.addr.index;
let canonical_idx = match dups[0].kind {
ReductionKind::DuplicateOutput { canonical, .. } => canonical.index,
_ => unreachable!(),
};
store.save_reduction_log(name, &log1).unwrap();
{
let sidecar_jsonl = store
.load_sidecar(name)
.unwrap()
.expect("sidecar must exist on disk");
let sidecar = Session::from_sidecar_str(&sidecar_jsonl).unwrap();
let log_reloaded = store
.load_reduction_log(name)
.unwrap()
.expect("reduction log must exist on disk");
verify_log(&log_reloaded, &sidecar)
.expect("verify_log must pass clean against the reloaded-from-disk sidecar");
let (final_view, reprojected_log) =
project_messages(&sidecar.messages, &policy1, &log_reloaded);
assert_eq!(
reprojected_log, log_reloaded,
"re-projecting from the reloaded sidecar with its own log must not invent new reductions"
);
let inverted = invert(&final_view, &log_reloaded, &sidecar)
.expect("invert must pass clean against the reloaded-from-disk sidecar");
assert_eq!(inverted.len(), sidecar.messages.len());
for (a, b) in inverted.iter().zip(&sidecar.messages) {
assert_eq!(a.role, b.role);
assert_eq!(a.content, b.content);
}
assert_eq!(
inverted[dup_idx].content.as_deref(),
Some(original.as_str()),
"invert must restore the duplicate occurrence byte-exact from disk"
);
assert_eq!(
inverted[canonical_idx].content.as_deref(),
Some(original.as_str()),
"invert must restore the canonical occurrence byte-exact from disk"
);
}
let policy2 = ReductionPolicy {
tool_output_trigger_bytes: 100,
tool_output_keep_bytes: 32,
protect_last_n_tool_results: 3,
..ReductionPolicy::default()
};
agent.set_reduction_policy(policy2.clone());
let reply2 = agent.send("one more thing").await.unwrap();
assert!(reply2.starts_with("done"), "unexpected reply: {reply2}");
let log2 = agent.reduction_log().clone();
let canonical_reduction = log2
.reductions
.iter()
.find(|r| r.ptr.addr.index == canonical_idx)
.expect("the canonical must now have its own reduction");
assert!(
matches!(
canonical_reduction.kind,
ReductionKind::ToolOutputTruncated { .. }
),
"the canonical must now be independently truncated by A7: {:?}",
canonical_reduction.kind
);
let dup2 = log2
.reductions
.iter()
.find(|r| r.id == dup_id)
.expect("the duplicate reduction must survive the canonical's truncation");
assert_eq!(
dup2, dups[0],
"the duplicate reduction must reproduce verbatim (prefix stability)"
);
store.save_reduction_log(name, &log2).unwrap();
let sidecar_jsonl = store
.load_sidecar(name)
.unwrap()
.expect("sidecar must exist on disk");
let sidecar = Session::from_sidecar_str(&sidecar_jsonl).unwrap();
let log_reloaded = store
.load_reduction_log(name)
.unwrap()
.expect("reduction log must exist on disk");
verify_log(&log_reloaded, &sidecar).expect(
"verify_log must pass clean against the reloaded-from-disk sidecar \
even after the canonical's truncation",
);
let (final_view, _reprojected_log) =
project_messages(&sidecar.messages, &policy2, &log_reloaded);
let inverted = invert(&final_view, &log_reloaded, &sidecar)
.expect("invert must pass clean against the reloaded-from-disk sidecar");
assert_eq!(
inverted[dup_idx].content.as_deref(),
Some(original.as_str()),
"invert must restore the duplicate byte-exact from disk even after \
the canonical is A7-truncated"
);
assert_eq!(
inverted[canonical_idx].content.as_deref(),
Some(original.as_str()),
"invert must restore the now-truncated canonical byte-exact from disk"
);
std::fs::remove_dir_all(&dir).ok();
}