rho-coding-agent 3.13.0

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

use pretty_assertions::assert_eq;
use rho_protocol::SessionSetup;
use tempfile::TempDir;

use super::super::{
    open::OpenWith,
    pull_request_wake::{watch_for_tests, TEST_PULL_REQUEST},
    test_sessions::{load, Load},
    Sessions,
};
use crate::{
    app::{
        daemon_host::jobs::{
            JobId, JobRecord, JobRegistry, JobStore, StarterNotice, TurnEnd, TurnRecord, WordChange,
        },
        peer_sessions::{PeerEvent, PeerNotice},
        pull_requests::ScriptedForge,
    },
    caller_context::CallerContext,
};

/// How the session that reports to the starter stands as the daemon starts.
#[derive(Debug)]
enum Child {
    /// It reported and waits, unloaded, on the open pull request it watches.
    Waiting,
    /// As [`Self::Waiting`], but the starter's first load never delivered
    /// the notice, as when it unloaded first.
    WaitingUndelivered,
    /// Pull request news reopens it: the idle unload kept its opening.
    KeptForNews,
    /// A client has it loaded, so its pull request news reaches it.
    Loaded,
    /// Its pull request merged.
    Merged,
    /// It stopped watching its pull request, which stays linked.
    Unwatched,
    /// Its last turn was cancelled, which its starter was told.
    Cancelled,
    /// It owes its starter word, its last turn having answered without a
    /// report.
    OwesWord,
}

// Covers: a starter loads after the daemon started, as a lead does after a
// restart. It hears once of a session that reports to it, completed its
// last turn, and waits unloaded on an open pull request it watches, naming
// that pull request, and never again once a turn took the notice; until
// then each load tells it again. It hears nothing of one pull request news
// reopens, one that is loaded, one whose pull request merged or that no
// longer watches it, or one whose last turn was cancelled; of one that owes
// it word it hears only the stop. A miss leaves a lead's pull request
// stalled with nobody told, tells it twice, or tells it of a session that
// wakes on its own or never would have.
// Owner: daemon wake for started sessions, across a restart.
#[tokio::test]
async fn a_loading_starter_hears_once_of_a_reported_session_waiting_on_its_pull_request() {
    use Child::{
        Cancelled, KeptForNews, Loaded, Merged, OwesWord, Unwatched, Waiting, WaitingUndelivered,
    };
    for child in [
        Waiting,
        WaitingUndelivered,
        KeptForNews,
        Loaded,
        Merged,
        Unwatched,
        Cancelled,
        OwesWord,
    ] {
        let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
        let forge = ScriptedForge::new();
        let sessions = Sessions::new(
            Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
            home.path(),
            forge.clone(),
        );
        let starter = load(&sessions, &root, Load::Waking).await;
        let (session, id) = match child {
            Loaded => {
                let loaded = load(&sessions, &root, Load::Waking).await;
                (loaded.id.clone(), loaded.job.clone())
            }
            _ => {
                let session = rho_sdk::SessionId::new();
                let job = JobRecord::new_session(
                    JobId::generate(),
                    PathBuf::from("/work"),
                    session.clone(),
                );
                let id = job.id.clone();
                sessions.jobs.register(job).unwrap();
                (session, id)
            }
        };
        sessions.jobs.set_title(&id, "worker");
        sessions.jobs.set_reports_to(&id, Some(&starter.id));
        let pull_requests = sessions.pull_requests.inbox(&session, root.path());
        watch_for_tests(&forge, &pull_requests).await;
        let (end, change) = match child {
            Cancelled => (TurnEnd::Cancelled, WordChange::Keep),
            OwesWord => {
                sessions.jobs.owe_word(&id, &starter.id);
                let answer = WordChange::Answered {
                    answer: "pushed".into(),
                };
                (TurnEnd::Completed, answer)
            }
            _ => (TurnEnd::Completed, WordChange::Keep),
        };
        let turn = TurnRecord::starting(/*key*/ None);
        sessions
            .jobs
            .start_turn(&id, turn, CallerContext::ROOT)
            .unwrap();
        sessions
            .jobs
            .end_turn(&id, end, None, StarterNotice::Nothing, change)
            .unwrap();
        match child {
            KeptForNews => {
                let opening = OpenWith {
                    environment: starter.environment.current(),
                    setup: SessionSetup::default(),
                    grant: CallerContext::ROOT,
                };
                sessions
                    .pull_requests
                    .keep_opening_for_tests(&session, opening);
            }
            Merged => sessions.pull_requests.merge_for_tests(&forge, 1).await,
            Unwatched => {
                pull_requests.unwatch(TEST_PULL_REQUEST).await.unwrap();
            }
            Waiting | WaitingUndelivered | Loaded | Cancelled | OwesWord => {}
        }

        // As the daemon starts, then as its `add` does once the starter
        // loaded, twice.
        sessions.note_restart_notices();
        let inbox = starter.peer_wake.inbox().expect("the starter hears");
        sessions.tell_untold_ends(&starter);
        let mut first = inbox.take();
        let told = first.notices.clone();
        if !matches!(child, WaitingUndelivered) {
            first.commit();
        }
        sessions.tell_untold_ends(&starter);
        let again = inbox.take().notices;

        let notice = |event| PeerNotice {
            session: session.to_string(),
            name: Some("worker".into()),
            event,
        };
        let restarted = notice(PeerEvent::Restarted {
            pull_requests: vec!["https://github.com/acme/widgets/pull/12".into()],
        });
        let stopped = notice(PeerEvent::Unreported {
            answer: "pushed".into(),
        });
        let expected = match child {
            Waiting => (vec![restarted], Vec::new()),
            WaitingUndelivered => (vec![restarted.clone()], vec![restarted]),
            KeptForNews | Loaded | Merged | Unwatched | Cancelled => (Vec::new(), Vec::new()),
            OwesWord => (vec![stopped], Vec::new()),
        };
        assert_eq!((told, again), expected, "{child:?}");
    }
}