use super::*;
use crate::llm::{FunctionCall, ToolCall};
fn sample_call(id: &str, name: &str) -> ToolCall {
ToolCall {
id: id.into(),
kind: "function".into(),
function: FunctionCall {
name: name.into(),
arguments: "{}".into(),
},
}
}
#[test]
fn seed_has_two_messages() {
let t = Transcript::seed("you are helpful", "do the thing");
assert_eq!(t.messages().len(), 2);
assert_eq!(t.messages()[0].role, "system");
assert_eq!(t.messages()[1].role, "user");
}
#[test]
fn push_assistant_records_text() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(Some("hello".into()), &[]);
assert_eq!(t.assistant_text(), "hello");
assert_eq!(t.messages().last().expect("msg").role, "assistant");
}
#[test]
fn push_assistant_skips_empty_text() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(Some(String::new()), &[sample_call("c1", "echo")]);
assert_eq!(t.assistant_text(), "");
}
#[test]
fn push_tool_result_sets_call_id() {
let mut t = Transcript::seed("s", "u");
t.push_tool_result("call_1", "echo", "echoed");
let messages = t.messages();
let last = messages.last().expect("msg");
assert_eq!(last.role, "tool");
assert_eq!(last.tool_call_id.as_deref(), Some("call_1"));
assert_eq!(last.name.as_deref(), Some("echo"));
}
#[test]
fn messages_reflects_appends() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(None, &[sample_call("c1", "echo")]);
t.push_tool_result("c1", "echo", "ok");
assert_eq!(t.messages().len(), 4);
}
#[test]
fn assistant_text_joins_turns() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(Some("first".into()), &[]);
t.push_assistant(Some("second".into()), &[]);
assert_eq!(t.assistant_text(), "first\n\nsecond");
}
#[test]
fn to_messages_is_passthrough_before_compaction() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(Some("hi".into()), &[]);
assert_eq!(t.to_messages(), t.messages());
}
#[test]
fn maybe_compact_is_noop_below_threshold() {
let mut t = Transcript::seed("s", "u");
t.push_assistant(Some("hi".into()), &[]);
let cfg = CompactionConfig {
token_threshold: 10_000,
keep_last_messages: 1,
};
assert!(!t.maybe_compact(&cfg));
assert_eq!(t.compacted_count(), 0);
}
#[test]
fn maybe_compact_never_touches_system_or_user() {
let mut t = Transcript::seed("s", &"long task ".repeat(50));
for i in 0..10 {
t.push_assistant(Some(format!("assistant turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
assert!(t.compacted_count() > 0);
let raw = t.messages();
assert_eq!(raw[0].role, "system");
assert_eq!(raw[1].role, "user");
assert_eq!(raw.len(), 2 + 20);
}
#[test]
fn maybe_compact_estimate_drops_after_compaction_fires() {
use super::super::compaction::estimate_total_tokens;
let mut t = Transcript::seed("s", "task");
for i in 0..10 {
t.push_assistant(
Some(format!("assistant turn {i}: {}", "x".repeat(200))),
&[],
);
t.push_tool_result(&format!("c{i}"), "bash", &"output ".repeat(50));
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
let pre_fire_estimate = estimate_total_tokens(&t.to_messages());
assert!(t.maybe_compact(&cfg));
let post_fire_estimate = estimate_total_tokens(&t.to_messages());
assert!(
post_fire_estimate < pre_fire_estimate,
"expected estimate to drop after compaction: pre={pre_fire_estimate} post={post_fire_estimate}"
);
}
fn assert_view_pairing_intact(view: &[ChatMessage]) {
let mut introduced: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut answered: std::collections::HashSet<String> = std::collections::HashSet::new();
for msg in view {
if let Some(calls) = &msg.tool_calls {
for call in calls {
introduced.insert(call.id.clone());
}
}
if msg.role == "tool" {
let id = msg.tool_call_id.clone().unwrap_or_default();
assert!(
introduced.contains(&id),
"tool entry for {id:?} has no preceding assistant tool_calls entry in this view: {view:?}"
);
answered.insert(id);
}
}
for id in &introduced {
assert!(
answered.contains(id),
"assistant tool_calls id {id:?} has no answering tool entry in this view: {view:?}"
);
}
}
#[test]
fn maybe_compact_pulls_whole_multi_tool_call_group_forward() {
let mut t = Transcript::seed("s", "the task");
for i in 0..5 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
t.push_assistant(
None,
&[
sample_call("multi_1", "get_weather"),
sample_call("multi_2", "get_time"),
],
);
t.push_tool_result("multi_1", "get_weather", "72F");
t.push_tool_result("multi_2", "get_time", "12:00 UTC");
assert_eq!(t.messages().len(), 15);
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
assert_eq!(t.compacted_count(), 10);
let view = t.to_messages();
assert_view_pairing_intact(&view);
assert!(
view.iter()
.any(|m| m.tool_calls.as_ref().is_some_and(|c| c.len() == 2)),
"the multi-tool-call assistant entry must survive uncompacted: {view:?}"
);
}
#[test]
fn maybe_compact_never_compacts_pinned_skill_output() {
let mut t = Transcript::seed("s", "task");
t.push_tool_result(
"call_skill",
USE_SKILL_TOOL_NAME,
"full skill body: do the distinctive thing",
);
for i in 0..10 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
let compacted_view = t.to_messages();
assert!(
compacted_view
.iter()
.any(|m| m.content.as_deref() == Some("full skill body: do the distinctive thing")),
"pinned skill output must survive verbatim in the compacted view: {compacted_view:?}"
);
}
#[test]
fn maybe_compact_still_compacts_non_skill_tool_results() {
let mut t = Transcript::seed("s", "task");
for i in 0..10 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
let compacted_view = t.to_messages();
assert!(compacted_view.len() < t.messages().len());
assert!(
compacted_view
.iter()
.any(|m| m.content.as_deref().unwrap_or("").contains("[compacted")),
"expected non-skill tool results to still collapse into a summary: {compacted_view:?}"
);
}
#[test]
fn to_messages_collapses_compacted_span() {
let mut t = Transcript::seed("s", "task");
for i in 0..10 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
let compacted_view = t.to_messages();
assert!(compacted_view.len() < t.messages().len());
let has_summary = compacted_view
.iter()
.any(|m| m.content.as_deref().unwrap_or("").contains("[compacted"));
assert!(
has_summary,
"expected a summary message in {compacted_view:?}"
);
}
#[test]
fn to_messages_replays_last_user_message_after_compaction() {
let mut t = Transcript::seed("s", "the original task");
for i in 0..10 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
let compacted_view = t.to_messages();
let last = compacted_view.last().expect("non-empty view");
assert_eq!(last.role, "user");
assert_eq!(last.content.as_deref(), Some("the original task"));
}
#[test]
fn to_messages_does_not_replay_on_every_subsequent_turn() {
let mut t = Transcript::seed("s", "the original task");
for i in 0..10 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
let compaction_turn_view = t.to_messages();
let last = compaction_turn_view.last().expect("non-empty view");
assert_eq!(last.role, "user");
assert_eq!(last.content.as_deref(), Some("the original task"));
for i in 10..15 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let later_view = t.to_messages();
let task_occurrences = later_view
.iter()
.filter(|m| m.content.as_deref() == Some("the original task"))
.count();
assert_eq!(
task_occurrences, 1,
"the original task must appear exactly once (its seeded position), not replayed on every later turn: {later_view:?}"
);
let last = later_view.last().expect("non-empty view");
assert_ne!(
last.content.as_deref(),
Some("the original task"),
"later turns must not re-anchor the model on the original task: {later_view:?}"
);
}
#[test]
fn maybe_compact_is_noop_on_seed_only_transcript() {
let mut t = Transcript::seed("s", "u");
let cfg = CompactionConfig {
token_threshold: 0,
keep_last_messages: 100,
};
assert!(!t.maybe_compact(&cfg));
assert_eq!(t.compacted_count(), 0);
assert_eq!(t.to_messages(), t.messages());
}
#[test]
fn compacted_entries_remain_in_raw_history() {
let mut t = Transcript::seed("s", "task");
t.push_assistant(Some("distinctive-early-turn-text".into()), &[]);
for i in 0..10 {
t.push_assistant(Some(format!("turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(t.maybe_compact(&cfg));
assert!(t.compacted_count() > 0);
let raw = t.messages();
assert!(
raw.iter()
.any(|m| m.content.as_deref() == Some("distinctive-early-turn-text")),
"compacted entry's original content must survive in the raw history"
);
}
#[test]
fn push_user_appends_without_reseeding_system() {
let mut t = Transcript::seed("s", "first task");
t.push_user("second task");
let messages = t.messages();
assert_eq!(messages.len(), 3);
assert_eq!(messages[0].role, "system");
assert_eq!(messages[1].role, "user");
assert_eq!(messages[1].content.as_deref(), Some("first task"));
assert_eq!(messages[2].role, "user");
assert_eq!(messages[2].content.as_deref(), Some("second task"));
assert_eq!(
messages.iter().filter(|m| m.role == "system").count(),
1,
"push_user must never add a second system message"
);
}
#[test]
fn assistant_text_since_scopes_to_new_turns_only() {
let mut t = Transcript::seed("s", "task");
assert_eq!(t.assistant_text_mark(), 0);
t.push_assistant(Some("run one's answer".into()), &[]);
let mark_after_run_one = t.assistant_text_mark();
assert_eq!(mark_after_run_one, 1);
assert_eq!(t.assistant_text_since(0), "run one's answer");
t.push_user("second task");
t.push_assistant(Some("run two's answer".into()), &[]);
assert_eq!(
t.assistant_text_since(mark_after_run_one),
"run two's answer"
);
assert_eq!(
t.assistant_text(),
"run one's answer\n\nrun two's answer",
"the raw joined view must still contain both runs' text"
);
}
#[test]
fn assistant_text_since_out_of_range_mark_is_empty_not_panicking() {
let t = Transcript::seed("s", "task");
assert_eq!(t.assistant_text_since(100), "");
}
#[test]
fn to_messages_omits_goals_message_when_all_empty() {
let t = Transcript::seed("s", "u");
let msgs = t.to_messages();
assert_eq!(msgs.len(), 2, "no goals message should be injected");
assert_eq!(msgs[0].role, "system");
assert_eq!(msgs[1].role, "user");
}
#[test]
fn to_messages_injects_goals_at_position_one() {
let t = Transcript::seed("you are helpful", "u");
let before = t.to_messages();
let system_before = before[0].content.clone();
t.goals_handle()
.lock()
.expect("lock")
.set(1, "ship the feature", crate::agent_loop::GoalSource::Model)
.expect("valid slot");
let after = t.to_messages();
assert_eq!(
after[0].content, system_before,
"the real system message bytes must be unaffected by a goal update"
);
assert_eq!(after[0].role, "system");
assert_eq!(
after[1].role, "system",
"goals block is injected as system-role"
);
assert!(
after[1]
.content
.as_deref()
.unwrap_or("")
.contains("1. ship the feature")
);
assert_eq!(
after.len(),
before.len() + 1,
"exactly one extra message (the goals block) is injected"
);
}
#[test]
fn goals_handle_mutation_visible_in_to_messages() {
let t = Transcript::seed("s", "u");
let handle = t.goals_handle();
assert!(
t.to_messages()
.iter()
.all(|m| m.role != "system" || m.content.as_deref() != Some(""))
);
handle
.lock()
.expect("lock")
.set(
5,
"goal via shared handle",
crate::agent_loop::GoalSource::Operator,
)
.expect("valid slot");
let msgs = t.to_messages();
assert!(
msgs.iter().any(|m| m
.content
.as_deref()
.unwrap_or("")
.contains("goal via shared handle")),
"mutation through the cloned handle must be visible to the original transcript"
);
}
#[test]
fn to_messages_goals_survive_aggressive_compaction() {
let mut t = Transcript::seed("s", &"long task ".repeat(50));
t.goals_handle()
.lock()
.expect("lock")
.set(1, "never forget this", crate::agent_loop::GoalSource::Model)
.expect("valid slot");
for i in 0..10 {
t.push_assistant(Some(format!("assistant turn {i}")), &[]);
t.push_tool_result(&format!("c{i}"), "bash", "output");
}
let cfg = CompactionConfig {
token_threshold: 1,
keep_last_messages: 2,
};
assert!(
t.maybe_compact(&cfg),
"aggressive config must trigger compaction"
);
assert!(t.compacted_count() > 0);
let msgs = t.to_messages();
assert_eq!(msgs[0].role, "system");
assert_eq!(msgs[1].role, "system");
assert!(
msgs[1]
.content
.as_deref()
.unwrap_or("")
.contains("never forget this"),
"goals block must survive compaction unmodified, got: {:?}",
msgs[1].content
);
}
fn text_response(content: serde_json::Value) -> crate::llm::ChatResponse {
serde_json::from_value(serde_json::json!({
"id": "gen-1",
"choices": [{
"message": { "role": "assistant", "content": content, "tool_calls": [] },
"finish_reason": "stop"
}],
"usage": { "prompt_tokens": 1, "completion_tokens": 0, "total_tokens": 1 }
}))
.expect("valid ChatResponse fixture")
}
#[test]
fn push_response_drops_a_turn_with_no_text_and_no_calls() {
let mut t = Transcript::seed("s", "task");
t.push_response(&text_response(serde_json::json!("")));
t.push_response(&text_response(serde_json::json!(null)));
t.push_response(&text_response(serde_json::json!(" \n ")));
let messages = t.messages();
assert_eq!(
messages.len(),
2,
"a turn with nothing in it must leave no entry: {messages:?}"
);
}
#[test]
fn push_response_appends_a_turn_that_says_something() {
let mut t = Transcript::seed("s", "task");
t.push_response(&text_response(serde_json::json!("here is the answer")));
let messages = t.messages();
assert_eq!(messages.len(), 3);
assert_eq!(messages[2].role, "assistant");
assert_eq!(messages[2].content.as_deref(), Some("here is the answer"));
}
fn tool_call_response() -> crate::llm::ChatResponse {
serde_json::from_value(serde_json::json!({
"id": "gen-2",
"choices": [{
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call-1",
"type": "function",
"function": { "name": "echo", "arguments": "{}" }
}]
},
"finish_reason": "tool_calls"
}],
"usage": { "prompt_tokens": 1, "completion_tokens": 0, "total_tokens": 1 }
}))
.expect("valid ChatResponse fixture")
}
#[test]
fn push_response_keeps_a_tool_call_turn_with_no_text() {
let mut t = Transcript::seed("s", "task");
t.push_response(&tool_call_response());
let messages = t.messages();
assert_eq!(
messages.len(),
3,
"the guard must drop only turns with no calls AND no text: {messages:?}"
);
assert_eq!(messages[2].role, "assistant");
let calls = messages[2]
.tool_calls
.as_ref()
.expect("the tool call must survive the round trip");
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].function.name, "echo");
}