rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::sync::{
    atomic::{AtomicUsize, Ordering},
    Arc,
};

use pretty_assertions::assert_eq;
use serde_json::json;

use super::{Answer, Asked, Form, SelfQuestions};
use crate::app::{boundary_sources::BoundarySource, peer_sessions::Receipt};

fn answer(title: &str) -> Answer {
    Answer {
        title: title.into(),
        content: format!("{title}: Blue"),
    }
}

/// What the session sees of its questions: whether one is still open,
/// whether an answer waits for a turn, and how many answers a turn took.
#[derive(Debug, PartialEq)]
struct Seen {
    expecting: bool,
    waiting: bool,
    delivered: usize,
}

// Covers: a session's own question counts as open from the moment it asks,
// before its host opens it, so the turn that asked can end without the
// session settling as if nothing could wake it; an answer then waits for a
// turn, and only a boundary that commits it runs its receipt, which drops
// the saved question. A boundary dropped uncommitted puts the answer back,
// and an answer a restart found saved waits as one that just came. A miss
// settles the session with its question open, loses an answer, or drops a
// saved question no turn took.
// Owner: the answers inbox of a session's own questions.
#[test]
fn an_answer_waits_until_a_boundary_commits_it() {
    #[derive(Clone, Copy, Debug)]
    enum Step {
        Ask,
        Answer,
        Restore,
        Reserve,
        Drop,
        Commit,
    }
    use Step::{Answer as Answered, Ask, Commit, Drop, Reserve, Restore};
    let seen = |expecting, waiting, delivered| Seen {
        expecting,
        waiting,
        delivered,
    };
    let cases = [
        (vec![Ask], seen(true, false, 0)),
        (vec![Ask, Answered], seen(false, true, 0)),
        (vec![Ask, Answered, Reserve, Drop], seen(false, true, 0)),
        (vec![Ask, Answered, Reserve, Commit], seen(false, false, 1)),
        (vec![Ask, Ask, Answered], seen(true, true, 0)),
        (vec![Restore], seen(false, true, 0)),
        (vec![Restore, Reserve, Commit], seen(false, false, 1)),
    ];
    for (steps, expected) in cases {
        let name = format!("{steps:?}");
        let questions = SelfQuestions::new();
        let inbox = questions.answers().clone();
        let delivered = Arc::new(AtomicUsize::new(0));
        let receipt = || {
            let delivered = Arc::clone(&delivered);
            Receipt::new(move || {
                delivered.fetch_add(1, Ordering::Relaxed);
            })
        };
        let mut reserved = None;
        for step in steps {
            match step {
                Ask => {
                    questions
                        .ask(color_form())
                        .expect("the host takes questions");
                }
                Answered => inbox.answered(answer("Which color?"), receipt()),
                Restore => inbox.restore_answer(answer("Which color?"), receipt()),
                Reserve => reserved = Some(BoundarySource::Answers(inbox.clone()).reserve()),
                Drop => reserved = None,
                Commit => reserved.as_mut().expect("reserved").commit(),
            }
        }
        drop(reserved);

        assert_eq!(
            Seen {
                expecting: inbox.expecting(),
                waiting: inbox.has_answers(),
                delivered: delivered.load(Ordering::Relaxed),
            },
            expected,
            "{name}"
        );
    }
}

// Covers: the host takes each question a session asks, with its form and
// the id it was asked under, once; a host gone takes none, the asking tool
// hears so, and the question does not count open. A miss loses a question,
// opens it twice, or keeps a session that asked nothing from settling.
// Owner: the queue a session's own questions go to its host by.
#[test]
fn the_host_takes_each_question_once() {
    let questions = SelfQuestions::new();
    let mut asked = questions.take_asked().expect("the queue, once");
    let form = color_form();
    let id = questions
        .ask(form.clone())
        .expect("the host takes questions");
    let taken = asked.try_recv().expect("the question");
    let again = questions.take_asked().is_none();

    let gone = SelfQuestions::new();
    drop(gone.take_asked());
    let after_host = gone.ask(color_form());

    assert_eq!(
        (taken, again, after_host, gone.answers().expecting()),
        (Asked { id, form }, true, None, /*expecting*/ false)
    );
}

/// A form asking one question.
fn color_form() -> Form {
    crate::tools::questionnaire_tool::form(
        json!({"questions": [{"id": "color", "question": "Which color?", "choices": ["Red", "Blue"]}]}),
    )
    .expect("a form")
}

// Covers: a boundary takes the answers oldest first, and an answer a turn
// put back goes ahead of one that came since. A miss reorders answers or
// drops one.
// Owner: the answers inbox at the boundary.
#[test]
fn answers_put_back_go_ahead_of_newer_ones() {
    let questions = SelfQuestions::new();
    let inbox = questions.answers();
    inbox.restore_answer(answer("first"), Receipt::new(|| {}));
    let mut taken = inbox.take();
    inbox.restore_answer(answer("second"), Receipt::new(|| {}));
    inbox.restore(&mut taken);

    let taken: Vec<_> = inbox.take().answers().cloned().collect();
    assert_eq!(taken, [answer("first"), answer("second")]);
}