use super::*;
use crate::compact::compile;
use crate::message::{FunctionCall, Message, ToolCall};
fn call(id: &str, name: &str, args: &str) -> ToolCall {
ToolCall {
id: id.to_string(),
kind: "function".to_string(),
function: FunctionCall {
name: name.to_string(),
arguments: args.to_string(),
},
}
}
fn numbered(mut messages: Vec<Message>) -> Vec<Message> {
for (index, message) in messages.iter_mut().enumerate() {
message.seq = Some(index as u64);
}
messages
}
fn transcript() -> Vec<Message> {
numbered(vec![
Message::user("read /etc/eclipse/config.toml and tell me why the port is wrong"),
Message::assistant_tool_calls(
Some("Looking at it now.".into()),
vec![call(
"c1",
"read_file",
r#"{"path":"/etc/eclipse/config.toml"}"#,
)],
),
Message::tool_result(
"c1",
r#"{"content":"[provider]\nbase_url = \"http://127.0.0.1:8080/v1\"\n","resolved_path":"/etc/eclipse/config.toml"}"#,
),
Message::assistant("The port is 8080 and the service expects 8787."),
Message::user("then write the corrected port into the file"),
Message::assistant_tool_calls(
None,
vec![call(
"c2",
"write_file",
r#"{"path":"/etc/eclipse/config.toml","content":"8787"}"#,
)],
),
Message::tool_result(
"c2",
r#"{"ok":true,"files_modified":["/etc/eclipse/config.toml"],"exit_code":0}"#,
),
])
}
fn log_of(handoff: &str) -> String {
let (_, sections) = split_sections(handoff);
sections
.into_iter()
.find(|(heading, _)| heading == LOG_HEADING)
.map(|(_, body)| body)
.unwrap_or_default()
}
#[test]
fn a_fresh_compile_is_byte_identical_and_the_harness_says_so() {
let rows = transcript();
let measured = verify(&rows, &rows, "s1", 6000, 2);
assert!(measured.identical, "two compiles of one transcript differ");
assert_eq!(measured.passes, 2);
assert_eq!(measured.budget_chars, 6000);
assert!(
measured.compile_micros < 1_000_000,
"a compile should not take a second"
);
assert_eq!(measured.session, "s1");
}
#[test]
fn every_log_line_is_re_read_from_the_row_it_cites() {
let rows = transcript();
let measured = verify(&rows, &rows, "s1", 6000, 1);
let f = &measured.faithfulness;
assert!(
f.lines >= rows.len(),
"the log lost rows: {} lines for {} rows: {f:?}",
f.lines,
rows.len()
);
assert!(
f.fragments >= rows.len() * 2,
"fragments were not actually looked for: {f:?}"
);
assert_eq!(f.unreferenced, 0);
assert!(f.ok(), "{:?}", f.violations);
}
#[test]
fn a_log_line_that_names_something_its_row_does_not_say_is_a_violation() {
let rows = transcript();
let handoff = compile(&rows, &Options::new("s1", 6000));
let log = log_of(&handoff);
let line = log
.lines()
.find(|line| line.contains("Looking"))
.expect("the assistant line is in the log");
let tampered = handoff.replace(line, &line.replace("Looking", "Invented"));
let f = faithfulness(&tampered, &rows);
assert!(!f.ok(), "a fabricated word was accepted");
assert!(
f.violations.iter().any(|v| v.fragment == "Invented"),
"{:?}",
f.violations
);
}
#[test]
fn a_log_line_pointing_at_the_wrong_row_is_a_violation() {
let rows = transcript();
let handoff = compile(&rows, &Options::new("s1", 6000));
let log = log_of(&handoff);
let line = log
.lines()
.find(|line| line.contains("then write the corrected port"))
.expect("the second ask is in the log");
let moved = line.replacen("[#4]", "[#0]", 1);
let tampered = handoff.replace(line, &moved);
let f = faithfulness(&tampered, &rows);
assert!(!f.ok(), "a ref pointing at the wrong row was accepted");
assert!(
f.violations
.iter()
.any(|v| v.at == 0 && v.fragment == "corrected"),
"{:?}",
f.violations
);
}
#[test]
fn a_call_line_names_the_call_that_is_really_on_its_row() {
let rows = transcript();
let handoff = compile(&rows, &Options::new("s1", 6000));
let log = log_of(&handoff);
let line = log
.lines()
.find(|line| line.contains("→ read_file"))
.expect("the call line is in the log");
let tampered = handoff.replace(line, &line.replace("read_file", "fetch_url"));
let f = faithfulness(&tampered, &rows);
assert!(
!f.ok(),
"a call line naming a tool that was never called was accepted"
);
assert!(
f.violations.iter().any(|v| v.fragment == "fetch_url"),
"{:?}",
f.violations
);
}
#[test]
fn a_result_line_whose_tool_does_not_match_the_call_it_answers_is_a_violation() {
let rows = transcript();
let handoff = compile(&rows, &Options::new("s1", 6000));
let log = log_of(&handoff);
let line = log
.lines()
.find(|line| line.contains("← read_file"))
.expect("the result line is in the log");
let tampered = handoff.replace(line, &line.replace("← read_file", "← write_file"));
let f = faithfulness(&tampered, &rows);
assert!(!f.ok(), "a result line naming the wrong tool was accepted");
assert!(
f.violations
.iter()
.any(|v| v.fragment == "write_file" && v.why.contains("answers a call to")),
"{:?}",
f.violations
);
}
#[test]
fn a_json_tool_result_is_read_through_its_encoding() {
let rows = numbered(vec![
Message::user("show me the log"),
Message::assistant_tool_calls(
None,
vec![call("c1", "shell", r#"{"command":"cat run.log"}"#)],
),
Message::tool_result(
"c1",
r#"{"exit_code":0,"output":"line one\nline two\nall good"}"#,
),
]);
let handoff = compile(&rows, &Options::new("s1", 6000));
let f = faithfulness(&handoff, &rows);
assert!(f.ok(), "{:?}", f.violations);
assert!(f.fragments > 0);
}
fn busy() -> Vec<Message> {
let mut out = Vec::new();
for index in 0..24 {
let path = format!("/etc/eclipse/conf.d/{index}.toml");
let unit = format!("unit-{index}");
out.push(Message::user(format!(
"step {index}: check {path} and tell me whether {unit} is even installed"
)));
out.push(Message::assistant_tool_calls(
None,
vec![call(
&format!("r{index}"),
"read_file",
&format!(r#"{{"path":"{path}"}}"#),
)],
));
out.push(Message::tool_result(
format!("r{index}"),
format!(r#"{{"resolved_path":"{path}","content":"[unit]\nname = \"{unit}\"\n"}}"#),
));
out.push(Message::assistant_tool_calls(
None,
vec![call(
&format!("s{index}"),
"shell",
&format!(r#"{{"command":"systemctl status {unit}"}}"#),
)],
));
out.push(Message::tool_result(
format!("s{index}"),
format!("Unit {unit}.service could not be found.\nError: no unit named {unit}\n"),
));
}
numbered(out)
}
#[test]
fn retention_counts_the_facts_a_budget_ate() {
let rows = busy();
let roomy = compare(&rows, &rows, "s1", 200_000).retention.unwrap();
assert!(roomy.files.total >= 24, "{roomy:?}");
assert!(roomy.commands.total >= 24, "{roomy:?}");
assert!(
roomy.files.all_present(),
"{} of {} files: {roomy:?}",
roomy.files.present,
roomy.files.total
);
let tight = compare(&rows, &rows, "s1", 400).retention.unwrap();
let (present, total) = tight.totals();
assert!(total >= 48, "the ledgers were not read: {tight:?}");
assert!(
present < total,
"a 400-char budget kept every one of {total} facts: {tight:?}"
);
}
#[test]
fn the_document_is_measured_against_the_transcript_it_replaces() {
let mut rows = Vec::new();
for index in 0..120 {
rows.push(Message::user(format!(
"step {index}: read the file at /etc/eclipse/conf.d/{index}.toml and tell me what it \
holds, then say whether the port in it is the one the service expects"
)));
rows.push(Message::assistant(format!(
"step {index} is done; the file exists and the port is fine"
)));
}
let rows = numbered(rows);
let measured = compare(&rows, &rows, "s1", 2000);
assert!(measured.middle_chars > 10_000, "{measured:?}");
assert!(measured.handoff_chars <= 2000, "the budget was not hard");
assert!(
measured.share() < 0.5,
"a handoff should be much smaller than the middle: {}",
measured.share()
);
assert!(measured.millis() < 100.0, "{measured:?}");
}
#[test]
fn an_empty_transcript_is_a_zero_and_not_a_division_by_zero() {
let measured = measure(&[], &[], "s1", 6000, 1, true);
assert_eq!(measured.share(), 0.0);
assert_eq!(measured.middle_chars, 0);
assert_eq!(measured.faithfulness.lines, 0);
assert!(measured.faithfulness.ok());
let retention = measured.retention.unwrap();
assert_eq!(retention.totals(), (0, 0));
assert!(retention
.ledgers()
.iter()
.all(|(_, tally)| tally.total == 0));
}
#[test]
fn a_row_with_no_stored_ref_is_counted_and_not_blamed() {
let mut rows = transcript();
for message in rows.iter_mut() {
message.seq = None;
}
let handoff = compile(&rows, &Options::new("s1", 6000));
let f = faithfulness(&handoff, &rows);
assert!(f.lines > 0);
assert_eq!(f.unreferenced, f.lines);
assert!(f.ok());
}