eclipse-core 0.13.4

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! The harness's own tests: a document that is stable, a ref that resolves, and a violation that
//! is actually caught. The last one is the reason this file exists — a faithfulness check that
//! cannot fail is a claim with no test behind it.

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(),
        },
    }
}

/// Row numbers as a stored session gives them, starting at 0.
fn numbered(mut messages: Vec<Message>) -> Vec<Message> {
    for (index, message) in messages.iter_mut().enumerate() {
        message.seq = Some(index as u64);
    }
    messages
}

/// A small conversation with all four row kinds: an ask, a call, a JSON result, prose.
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}"#,
        ),
    ])
}

/// The Session Log section on its own, so a test can tamper with one line and nothing else.
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;
    // A row with both prose and a call gets two lines, so the count is a floor, not an equality.
    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));
    // A word that appears in no row: exactly what a compiler regression that paraphrased would
    // produce, and exactly what this check has to refuse.
    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));
    // The second ask is row 4. Point its line at row 0 and the line now claims something row 0
    // does not contain — the failure mode that makes a handoff's own instructions useless.
    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");
    // The result row itself never names `read_file` — the name lives on the call row, so the
    // check has to follow the id rather than trust the line.
    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() {
    // The renderer quotes a string it decoded out of the result JSON. An escaped newline must not
    // turn that quotation into a fabrication, or every JSON-shaped tool result would fail.
    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);
}

/// A conversation with more facts than any small budget can hold: 24 distinct paths, 24 shell
/// commands, and a failure in each step.
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
    );

    // A budget that cannot hold the ledgers must lose whole facts, and the tally has to say how
    // many rather than round to 100%.
    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() {
    // An in-memory transcript has `[tN]` refs, which name a position and no row. That is worth
    // reporting, but it is not a lie in the document.
    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());
}