eclipse-cli 0.13.4

Command-line interface for eclipse
//! `#173`: the terminal half of `/loop` — the words, and one tick.
//!
//! [`eclipse_core::loops`] decides everything that can be decided without a clock or a model:
//! what a typed line asked for, when the next tick is due, and what a record says. This module is
//! the part that needs a person at a keyboard — the sentence each verb answers with, the busy
//! probe, and one tick run end to end — so the plain REPL and the full-screen interface cannot
//! answer `/loop` differently.
//!
//! A tick runs through the *front's own* run entry: the closure passed to [`tick`] is the same
//! call the composer makes, so the second tick's request carries the first tick's history for the
//! same reason a typed turn does — same session id, same store. What this module adds around it
//! is the rule that a tick landing on a busy session is dropped rather than queued.

pub use eclipse_core::loops::manage;
use eclipse_core::loops::{self, Request, State};
use eclipse_core::Agent;
use std::path::Path;

/// The last thing the model said in `session`, read back from the store.
///
/// A front that already has the text in hand (the interface's transcript) does not need this;
/// the plain REPL streams its replies straight to the terminal, so the store is where the reply
/// still exists after the turn has finished. A transcript that cannot be read answers `None`,
/// which the check treats as "the turn produced no text" rather than as a no.
pub fn last_reply(agent: &Agent, session: &str) -> Option<String> {
    let records = agent.store().load_records(session).ok()?;
    records.iter().rev().find_map(|record| {
        let text = record.message.content.clone().unwrap_or_default();
        (record.message.role == eclipse_core::message::Role::Assistant && !text.trim().is_empty())
            .then_some(text)
    })
}

/// Whether this line starts a loop: the one verb that needs a session to exist before it runs.
pub fn starts(arg: &str) -> bool {
    matches!(loops::parse(arg), Ok(Request::Start(_)))
}

/// The loop that is asking to fire now, if there is one.
///
/// The caller keeps no copy of the record in memory: it re-reads the file on each look, so a
/// `/loop pause` typed into another process is obeyed by this one on the next tick.
pub fn due(root: &Path, session: &str, now_ms: i64) -> Option<State> {
    let state = loops::load(root, session).ok().flatten()?;
    state.due(now_ms).then_some(state)
}

#[cfg(test)]
mod tests {
    use super::*;
    use eclipse_core::loops::{Outcome, Owner, Status};

    fn dir() -> tempfile::TempDir {
        tempfile::tempdir().unwrap()
    }

    #[test]
    fn starting_a_loop_writes_the_record_and_names_what_will_not_survive() {
        let d = dir();
        let said = manage(d.path(), "s1", "2m check the build", Owner::Cli, 0).unwrap();
        assert!(said.contains("loop started"), "{said}");
        assert!(said.contains("first tick in 2m"), "{said}");
        assert!(said.contains("stops when this process exits"), "{said}");
        assert!(said.contains("/cron"), "{said}");
        let state = loops::load(d.path(), "s1").unwrap().expect("saved");
        assert_eq!(state.prompt, "check the build");
        assert_eq!(state.fired, 0);
    }

    #[test]
    fn one_loop_per_session_and_the_second_start_is_told_where_it_is() {
        let d = dir();
        manage(d.path(), "s1", "2m a", Owner::Cli, 0).unwrap();
        let why = format!(
            "{:#}",
            manage(d.path(), "s1", "5m b", Owner::Cli, 0).unwrap_err()
        );
        assert!(why.contains("already has a loop running"), "{why}");
        assert!(why.contains("/loop stop"), "{why}");
    }

    #[test]
    fn a_paused_loop_is_resumed_rather_than_replaced() {
        let d = dir();
        manage(d.path(), "s1", "2m a", Owner::Cli, 0).unwrap();
        manage(d.path(), "s1", "pause", Owner::Cli, 10_000).unwrap();
        let why = format!(
            "{:#}",
            manage(d.path(), "s1", "5m b", Owner::Cli, 10_000).unwrap_err()
        );
        assert!(why.contains("paused"), "{why}");
        let said = manage(d.path(), "s1", "resume", Owner::Cli, 10_000).unwrap();
        assert!(said.contains("next tick in 2m"), "{said}");
        let state = loops::load(d.path(), "s1").unwrap().unwrap();
        assert_eq!(state.status, Status::Running);
        assert_eq!(state.next_due_ms, 10_000 + 120_000);
    }

    #[test]
    fn an_ended_loop_can_be_started_again() {
        let d = dir();
        manage(d.path(), "s1", "2m a --times 1", Owner::Cli, 0).unwrap();
        let mut state = loops::load(d.path(), "s1").unwrap().unwrap();
        state.record(120_000, Outcome::Ran);
        loops::save(d.path(), &state).unwrap();
        assert!(manage(d.path(), "s1", "status", Owner::Cli, 130_000)
            .unwrap()
            .contains("loop ended"));
        // An ended loop is not resumed: it is started again, and the refusal says which.
        let why = format!(
            "{:#}",
            manage(d.path(), "s1", "resume", Owner::Cli, 130_000).unwrap_err()
        );
        assert!(why.contains("has ended"), "{why}");
        let said = manage(d.path(), "s1", "2m b", Owner::Cli, 130_000).unwrap();
        assert!(said.contains("loop started"), "{said}");
        assert_eq!(
            loops::load(d.path(), "s1").unwrap().unwrap().prompt,
            "b",
            "the new loop replaced the ended one"
        );
    }

    #[test]
    fn stop_says_how_many_ticks_it_actually_ran() {
        let d = dir();
        manage(d.path(), "s1", "2m a", Owner::Cli, 0).unwrap();
        let mut state = loops::load(d.path(), "s1").unwrap().unwrap();
        state.record(120_000, Outcome::Ran);
        state.record(240_000, Outcome::Ran);
        loops::save(d.path(), &state).unwrap();
        assert!(manage(d.path(), "s1", "stop", Owner::Cli, 250_000)
            .unwrap()
            .contains("2 tick(s)"));
        // Pausing what has already ended is answered with the record rather than refused: the
        // person asked a reasonable question and the answer is that there is nothing to pause.
        assert!(manage(d.path(), "s1", "pause", Owner::Cli, 250_000)
            .unwrap()
            .contains("loop ended"));
        assert!(manage(d.path(), "s1", "resume", Owner::Cli, 250_000).is_err());
    }

    #[test]
    fn a_session_with_no_loop_answers_every_verb_without_inventing_one() {
        let d = dir();
        assert!(manage(d.path(), "s1", "", Owner::Cli, 0)
            .unwrap()
            .contains("no loop in this session"));
        assert!(manage(d.path(), "s1", "pause", Owner::Cli, 0).is_err());
        assert!(manage(d.path(), "s1", "resume", Owner::Cli, 0).is_err());
        assert!(manage(d.path(), "s1", "stop", Owner::Cli, 0).is_ok());
        assert!(loops::load(d.path(), "s1").unwrap().is_none());
    }

    #[test]
    fn a_tick_is_due_only_through_the_file_not_through_a_remembered_copy() {
        let d = dir();
        manage(d.path(), "s1", "2m a", Owner::Cli, 1_000).unwrap();
        assert!(due(d.path(), "s1", 120_999).is_none());
        // Another process pausing it is obeyed by the next look, because the look is a read.
        manage(d.path(), "s1", "pause", Owner::Cli, 121_000).unwrap();
        assert!(due(d.path(), "s1", 121_000).is_none());
        manage(d.path(), "s1", "resume", Owner::Cli, 121_000).unwrap();
        let state = due(d.path(), "s1", 241_000).expect("due");
        assert_eq!(state.session, "s1");
        assert!(due(d.path(), "nobody", 121_000).is_none());
    }

    #[test]
    fn the_start_line_names_both_bounds_when_both_were_given() {
        let d = dir();
        let said = manage(
            d.path(),
            "s1",
            "2m a --times 3 --until the build is green",
            Owner::Cli,
            0,
        )
        .unwrap();
        assert!(
            said.contains("at most 3 or until the build is green"),
            "{said}"
        );
    }
}