eclipse-cli 0.13.4

Command-line interface for eclipse
//! `eclipse compact verify | compare`: the harness that measures a compiled handoff.
//!
//! Both commands resolve the session the same way a run would — the same planner, the same
//! tool-definition charge, the same handoff budget — so the numbers describe the document the
//! loop would actually inject, not a document built by the harness for the occasion. The only
//! knob is `--chars`, which pins the budget so a measurement can be repeated against a fixed
//! ceiling while everything else varies.

use anyhow::{bail, Result};
use eclipse_core::compact::verify::{self as harness, Measurement, Tally};
use eclipse_core::config::{process_env, Config};
use eclipse_core::context_files;
use eclipse_core::message::Message;
use eclipse_core::plugins;
use eclipse_core::runtime::Agent;
use serde_json::json;
use std::ops::Range;

/// What a request for a session would drop, and the budget the loop would compile to.
pub struct Window {
    pub rows: Vec<Message>,
    pub dropped: Range<usize>,
    /// False when nothing is over the rail: `dropped` then covers the whole transcript,
    /// because "what would a handoff say" is still answerable for a short session — but a
    /// compaction would not have happened, and a report that said it had would be a lie.
    pub drops: bool,
    pub budget: usize,
}

/// The middle window of a stored session, planned exactly as `eclipse context handoff` plans it
/// — which is exactly as the loop plans it, one turn before it needs to.
pub fn window(cfg: &Config, session: &str, chars: Option<usize>) -> Result<Window> {
    let store = eclipse_core::session::SessionStore::new(cfg.sessions_dir(&process_env)?);
    if !store.exists(session) {
        bail!("no such session {session:?}");
    }
    let rows: Vec<Message> = store.load(session)?;
    let agent = Agent::from_config(cfg)?;
    let loaded = plugins::load(&cfg.plugins_dirs(&process_env), &cfg.plugins.enabled);
    let ctx = context_files::for_config(cfg, &process_env, &loaded);
    let prompt = context_files::assemble(&cfg.agent.system_prompt, &ctx, &[]);
    let system = Message::system(&prompt);
    let windows = eclipse_core::context::plan_windows(
        &system,
        &rows,
        agent.context_budget(),
        agent.tool_spec_tokens(),
        cfg.context.protect_last_n.max(1),
    );
    let budget = chars.unwrap_or_else(|| agent.handoff_budget());
    // With nothing over the rail the whole transcript is what a compaction would be given,
    // which is the honest answer to "what would this document look like" for a short session.
    let drops = windows.drops_anything();
    let dropped = if drops {
        windows.dropped()
    } else {
        0..rows.len()
    };
    Ok(Window {
        rows,
        dropped,
        drops,
        budget,
    })
}

/// `eclipse compact verify -s <id>` — the same transcript twice, and every `[#N]` re-read.
pub fn verify(
    cfg: &Config,
    session: &str,
    chars: Option<usize>,
    determinism: bool,
    as_json: bool,
) -> Result<()> {
    let window = window(cfg, session, chars)?;
    let passes = if determinism { 2 } else { 1 };
    let measured = harness::verify(
        &window.rows,
        &window.rows[window.dropped.clone()],
        session,
        window.budget,
        passes,
    );

    if as_json {
        println!("{}", serde_json::to_string_pretty(&describe(&measured))?);
    } else {
        println!(
            "# session {session} — {} of {} message(s) compiled to {} chars of {} budget in {:.2} ms",
            measured.messages,
            window.rows.len(),
            measured.handoff_chars,
            measured.budget_chars,
            measured.millis()
        );
        if !window.drops {
            println!(
                "# nothing is over the rail: this session would not be compacted; the document \
                 below is what one would say"
            );
        }
        if measured.passes > 1 {
            println!(
                "# {} passes: {}",
                measured.passes,
                if measured.identical {
                    "byte-identical"
                } else {
                    "THE SAME INPUT PRODUCED DIFFERENT BYTES"
                }
            );
        }
        print_faithfulness(&measured, "#");
    }

    let mut problems: Vec<String> = Vec::new();
    if !measured.identical {
        problems.push("two compiles of one transcript differ".to_string());
    }
    if !measured.faithfulness.ok() {
        problems.push(format!(
            "{} log line(s) cite a row that does not contain them",
            measured.faithfulness.violations.len()
        ));
    }
    if !problems.is_empty() {
        bail!("{}", problems.join("; "));
    }
    Ok(())
}

/// `eclipse compact compare -s <id>` — what compaction cost, and what of the transcript it kept.
pub fn compare(cfg: &Config, session: &str, chars: Option<usize>, as_json: bool) -> Result<()> {
    let window = window(cfg, session, chars)?;
    let measured = harness::compare(
        &window.rows,
        &window.rows[window.dropped.clone()],
        session,
        window.budget,
    );

    if as_json {
        println!("{}", serde_json::to_string_pretty(&describe(&measured))?);
    } else {
        println!(
            "# session {session} — middle of {} message(s), {} chars → {} chars ({:.0}% of the \
             middle) in {:.2} ms, budget {}",
            measured.messages,
            measured.middle_chars,
            measured.handoff_chars,
            measured.share() * 100.0,
            measured.millis(),
            measured.budget_chars
        );
        if let Some(retention) = &measured.retention {
            for (name, tally) in retention.ledgers() {
                println!("{name:<9} {}", line_for(tally));
                for missing in &tally.missing {
                    println!("  not named: {missing}");
                }
            }
            let (present, total) = retention.totals();
            println!("# retained {present}/{total} fact(s)");
        }
        print_faithfulness(&measured, "#");
    }

    // Retention below 100% is a budget decision and the reason this command exists, so it is
    // reported and not failed on. A log line that does not survive its own ref is a defect.
    if !measured.faithfulness.ok() {
        bail!(
            "{} log line(s) cite a row that does not contain them",
            measured.faithfulness.violations.len()
        );
    }
    Ok(())
}

fn line_for(tally: &Tally) -> String {
    format!("{}/{}", tally.present, tally.total)
}

fn print_faithfulness(measured: &Measurement, prefix: &str) {
    let f = &measured.faithfulness;
    println!(
        "{prefix} session log: {} line(s), {} fragment(s) re-read from their row, {} violation(s)",
        f.lines,
        f.fragments,
        f.violations.len()
    );
    if f.unreferenced > 0 {
        println!(
            "{prefix}   {} line(s) carry no row ref ([tN]): nothing to read back",
            f.unreferenced
        );
    }
    for violation in f.violations.iter().take(10) {
        println!(
            "{prefix}   [#{}] `{}` — {}",
            violation.at, violation.fragment, violation.why
        );
    }
}

/// The measurement as JSON: the struct's own numbers plus the two derived ratios, so a script
/// does not have to divide.
fn describe(measured: &Measurement) -> serde_json::Value {
    let mut value = json!({
        "session": measured.session,
        "messages": measured.messages,
        "middle_chars": measured.middle_chars,
        "handoff_chars": measured.handoff_chars,
        "share_of_middle": measured.share(),
        "budget_chars": measured.budget_chars,
        "compile_micros": measured.compile_micros,
        "passes": measured.passes,
        "identical": measured.identical,
        "log_lines": measured.faithfulness.lines,
        "log_fragments": measured.faithfulness.fragments,
        "unreferenced_lines": measured.faithfulness.unreferenced,
        "violations": measured
            .faithfulness
            .violations
            .iter()
            .map(|v| json!({"at": v.at, "fragment": v.fragment, "why": v.why}))
            .collect::<Vec<_>>(),
    });
    if let Some(retention) = &measured.retention {
        let mut ledgers = serde_json::Map::new();
        for (name, tally) in retention.ledgers() {
            ledgers.insert(
                name.to_string(),
                json!({"total": tally.total, "present": tally.present, "missing": tally.missing}),
            );
        }
        let (present, total) = retention.totals();
        value["retention"] = json!({"present": present, "total": total, "ledgers": ledgers});
    }
    value
}