rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::fs;

use pretty_assertions::assert_eq;
use rho_sdk::model::Message;
use rho_tools::WorkspaceMutationObserver as _;

use super::{RewindError, RewindPreview, RewoundConversation};
use crate::{
    app::session_runtime::{test_support::idle_runtime, SessionRuntime},
    config::Config,
    permission::PermissionMode,
    session::{
        tree::NodeId,
        workspace_checkpoint::{CheckpointOutcome, RestoreClassification},
    },
};

fn leaf(runtime: &SessionRuntime) -> NodeId {
    let stored = runtime.storage.file().expect("the session is saved");
    stored
        .active_checkpoint_target()
        .unwrap()
        .expect("the session saved a node")
        .0
}

fn add(runtime: &mut SessionRuntime, text: &str) -> NodeId {
    runtime
        .append_context(
            text.into(),
            Message::user_text(text),
            /*display_key*/ None,
            [],
        )
        .unwrap();
    leaf(runtime)
}

/// What `preview` plans for each path, in path order, and the node the
/// conversation would continue from.
fn planned(preview: RewindPreview) -> (Vec<RestoreClassification>, Option<NodeId>) {
    (
        preview
            .plan
            .entries
            .iter()
            .map(|entry| entry.classification)
            .collect(),
        preview.returns_to,
    )
}

// Covers: a turn's checkpoint, opened before the turn saves anything and
// closed on its last node, lets a rewind put back the files the turn added,
// changed, and removed, and returns the conversation to before the turn's
// row, as its preview said.
// Owner: session runtime workspace rewind
#[tokio::test]
async fn a_rewind_puts_the_turns_files_and_conversation_back() {
    let home = tempfile::tempdir().unwrap();
    let config = Config::with_model("test", "model", "none");
    let mut runtime = idle_runtime(home.path(), &config).await;
    runtime.built.tools.take_checkpoints_for_tests();
    // Tools hand the tracker resolved paths.
    let workspace = fs::canonicalize(home.path()).unwrap();
    let (added, deleted, modified) = (
        workspace.join("added.txt"),
        workspace.join("deleted.txt"),
        workspace.join("modified.txt"),
    );
    fs::write(&deleted, "deleted original").unwrap();
    fs::write(&modified, "modified original").unwrap();
    let before = add(&mut runtime, "before");

    let begun = runtime.begin_workspace_checkpoint().unwrap();
    let tracker = runtime.built.tools.checkpoint_tracker().clone();
    let paths = [added.as_path(), deleted.as_path(), modified.as_path()];
    tracker.before_mutation(&paths).await.unwrap();
    fs::write(&added, "agent added").unwrap();
    fs::remove_file(&deleted).unwrap();
    fs::write(&modified, "agent modified").unwrap();
    tracker.after_mutation(&paths).await.unwrap();
    let turn = add(&mut runtime, "the turn");
    let told = runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
    let previewed = runtime.preview_rewind(&turn).unwrap();
    let promised = (previewed.returns_to.clone(), previewed.turns.clone());
    let preview = planned(previewed);

    let rewind = runtime
        .rewind_workspace(&turn, /*tip*/ None, &config)
        .await
        .unwrap();
    let read = |path: &std::path::Path| fs::read_to_string(path).ok();
    let RewoundConversation::Moved { row } = &rewind.conversation else {
        panic!("the conversation stayed: {:?}", rewind.conversation);
    };
    // The answer says what the preview promised: the row it returns to and
    // the turns it undoes.
    assert_eq!((Some(row.clone()), rewind.turns.clone()), promised);
    assert_eq!(
        (
            (begun, told),
            preview,
            (read(&added), read(&deleted), read(&modified)),
            leaf(&runtime),
        ),
        (
            (None, Vec::new()),
            (
                vec![
                    RestoreClassification::Delete,
                    RestoreClassification::Create,
                    RestoreClassification::Modify
                ],
                Some(before.clone())
            ),
            (
                None,
                Some("deleted original".to_owned()),
                Some("modified original".to_owned())
            ),
            before,
        ),
        "audit: {:?}",
        rewind.audit
    );
    runtime.shutdown().await;
}

// Covers: plan mode refuses a rewind, and its preview, before any file is
// written, and a rewind that finds a file changed since the turn leaves that
// file and the conversation where they are, as its preview said.
// Owner: session runtime workspace rewind
#[tokio::test]
async fn a_rewind_that_cannot_restore_every_file_keeps_the_conversation() {
    let home = tempfile::tempdir().unwrap();
    let config = Config::with_model("test", "model", "none");
    let mut runtime = idle_runtime(home.path(), &config).await;
    runtime.built.tools.take_checkpoints_for_tests();
    let file = fs::canonicalize(home.path()).unwrap().join("file.txt");
    fs::write(&file, "original").unwrap();
    add(&mut runtime, "before");
    runtime.begin_workspace_checkpoint().unwrap();
    let tracker = runtime.built.tools.checkpoint_tracker().clone();
    tracker.before_mutation(&[file.as_path()]).await.unwrap();
    fs::write(&file, "the turn's").unwrap();
    tracker.after_mutation(&[file.as_path()]).await.unwrap();
    let turn = add(&mut runtime, "the turn");
    runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);

    let mode = std::mem::replace(&mut runtime.permission.mode, PermissionMode::Plan);
    let planning = runtime.rewind_workspace(&turn, /*tip*/ None, &config).await;
    let previewed_planning = runtime.preview_rewind(&turn);
    let after_refusal = fs::read_to_string(&file).unwrap();
    runtime.permission.mode = mode;
    fs::write(&file, "a later edit").unwrap();
    let preview = planned(runtime.preview_rewind(&turn).unwrap());
    let conflicted = runtime
        .rewind_workspace(&turn, /*tip*/ None, &config)
        .await
        .unwrap();

    assert!(
        matches!(
            (&planning, &previewed_planning),
            (Err(RewindError::Refused(_)), Err(RewindError::Refused(_)))
        ),
        "{planning:?} {previewed_planning:?}"
    );
    assert_eq!(preview, (vec![RestoreClassification::Conflict], None));
    let RewoundConversation::Stayed = conflicted.conversation else {
        panic!("the conversation moved: {:?}", conflicted.conversation);
    };
    assert_eq!(
        (
            after_refusal.as_str(),
            fs::read_to_string(&file).unwrap().as_str(),
            leaf(&runtime)
        ),
        ("the turn's", "a later edit", turn),
        "audit: {:?}",
        conflicted.audit
    );
    runtime.shutdown().await;
}

// Covers: rewinding a turn undoes it and every later turn on the branch,
// as one plan its preview names, and returns the conversation
// to before the turn; the turns it left behind are off the branch now, so a
// rewind of one of them is refused before a file is written.
// Owner: session runtime workspace rewind
#[tokio::test]
async fn a_rewind_undoes_every_later_turn_and_refuses_another_branch() {
    let home = tempfile::tempdir().unwrap();
    let config = Config::with_model("test", "model", "none");
    let mut runtime = idle_runtime(home.path(), &config).await;
    runtime.built.tools.take_checkpoints_for_tests();
    let workspace = fs::canonicalize(home.path()).unwrap();
    let (edited, created) = (workspace.join("edited.txt"), workspace.join("created.txt"));
    fs::write(&edited, "original").unwrap();
    let before = add(&mut runtime, "before");
    // Each turn writes `paths` as `write` does, between its checkpoint's
    // open and close.
    let turn =
        async |runtime: &mut SessionRuntime, prompt: &str, write: &[(&std::path::Path, &str)]| {
            runtime.begin_workspace_checkpoint().unwrap();
            let tracker = runtime.built.tools.checkpoint_tracker().clone();
            let paths = write.iter().map(|(path, _)| *path).collect::<Vec<_>>();
            tracker.before_mutation(&paths).await.unwrap();
            for (path, text) in write {
                fs::write(path, text).unwrap();
            }
            tracker.after_mutation(&paths).await.unwrap();
            let node = add(runtime, prompt);
            runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
            node
        };
    let first = turn(&mut runtime, "first", &[(&edited, "first")]).await;
    let second = turn(
        &mut runtime,
        "second",
        &[(&edited, "second"), (&created, "new")],
    )
    .await;

    let preview = runtime.preview_rewind(&first).unwrap();
    let turns = preview.turns.clone();
    let rewind = runtime
        .rewind_workspace(&first, /*tip*/ None, &config)
        .await
        .unwrap();
    let after_rewind = (
        fs::read_to_string(&edited).ok(),
        fs::read_to_string(&created).ok(),
        leaf(&runtime),
    );
    fs::write(&edited, "a later edit").unwrap();
    let off_branch = runtime
        .rewind_workspace(&second, /*tip*/ None, &config)
        .await;

    let RewoundConversation::Moved { .. } = rewind.conversation else {
        panic!("the conversation stayed: {:?}", rewind.conversation);
    };
    assert!(
        matches!(off_branch, Err(RewindError::Refused(_))),
        "{off_branch:?}"
    );
    assert_eq!(
        (
            turns,
            planned(preview),
            after_rewind,
            fs::read_to_string(&edited).ok()
        ),
        (
            vec![first, second],
            (
                vec![RestoreClassification::Delete, RestoreClassification::Modify],
                Some(before.clone())
            ),
            (Some("original".to_owned()), None, before),
            Some("a later edit".to_owned()),
        ),
        "audit: {:?}",
        rewind.audit
    );
    runtime.shutdown().await;
}

// Covers: a later turn on the branch that took no checkpoint, as when
// capture paused, is counted in the rewind's plan, so its preview can warn
// that what the turn wrote stays; turns that took one are not.
// Owner: session runtime workspace rewind
#[tokio::test]
async fn a_rewind_counts_the_later_turns_that_took_no_checkpoint() {
    let home = tempfile::tempdir().unwrap();
    let config = Config::with_model("test", "model", "none");
    let mut runtime = idle_runtime(home.path(), &config).await;
    runtime.built.tools.take_checkpoints_for_tests();
    add(&mut runtime, "before");
    // A turn ends with a save that records how, as a run's last save does.
    let end = |runtime: &mut SessionRuntime| {
        let checkpoint = runtime.install_continuation_checkpoint().unwrap();
        runtime.persist_failed_turn(&checkpoint);
        runtime.built.session.set_checkpoint_store(None).unwrap();
    };
    runtime.begin_workspace_checkpoint().unwrap();
    add(&mut runtime, "first");
    end(&mut runtime);
    // The checkpoint names the node the turn ended on.
    let first = leaf(&runtime);
    runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
    runtime.begin_workspace_checkpoint().unwrap();
    add(&mut runtime, "second");
    end(&mut runtime);
    runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
    // Capture paused: this turn takes none.
    add(&mut runtime, "third");
    end(&mut runtime);

    let preview = runtime.preview_rewind(&first).unwrap();

    assert_eq!((preview.turns.len(), preview.plan.uncaptured_turns), (2, 1));
    runtime.shutdown().await;
}

// Covers: a rewind held to the node its preview was planned at refuses once
// the conversation moved on, as when a turn ended in between, before a file
// is written, and undoes the turns once held to the node it now is at.
// Owner: session runtime workspace rewind
#[tokio::test]
async fn a_rewind_held_to_its_previewed_tip_refuses_once_the_conversation_moved() {
    let home = tempfile::tempdir().unwrap();
    let config = Config::with_model("test", "model", "none");
    let mut runtime = idle_runtime(home.path(), &config).await;
    runtime.built.tools.take_checkpoints_for_tests();
    let file = fs::canonicalize(home.path()).unwrap().join("file.txt");
    fs::write(&file, "original").unwrap();
    add(&mut runtime, "before");
    let turn = |runtime: &mut SessionRuntime, prompt: &str| {
        runtime.begin_workspace_checkpoint().unwrap();
        let node = add(runtime, prompt);
        runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);
        node
    };
    let first = turn(&mut runtime, "first");
    let previewed = runtime.preview_rewind(&first).unwrap().tip;
    // A turn ends after the preview, writing the file.
    runtime.begin_workspace_checkpoint().unwrap();
    let tracker = runtime.built.tools.checkpoint_tracker().clone();
    tracker.before_mutation(&[file.as_path()]).await.unwrap();
    fs::write(&file, "unseen").unwrap();
    tracker.after_mutation(&[file.as_path()]).await.unwrap();
    let unseen = add(&mut runtime, "unseen");
    runtime.finalize_workspace_checkpoint(CheckpointOutcome::Completed);

    let refused = runtime
        .rewind_workspace(&first, Some(&previewed), &config)
        .await;
    let after_refusal = fs::read_to_string(&file).unwrap();
    let held = runtime
        .rewind_workspace(&first, Some(&unseen), &config)
        .await;

    let Err(RewindError::Moved { expected, now }) = refused else {
        panic!("the rewind was not held: {refused:?}");
    };
    assert!(held.is_ok(), "{held:?}");
    assert_eq!(
        (
            (expected, now),
            after_refusal,
            fs::read_to_string(&file).unwrap()
        ),
        (
            (previewed, unseen),
            "unseen".to_owned(),
            "original".to_owned()
        )
    );
    runtime.shutdown().await;
}