rho-coding-agent 3.13.0

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

use pretty_assertions::assert_eq;
use rho_protocol as wire;
use rho_sdk::{
    model::{ContentBlock, ModelResponse},
    provider::ScriptedTurn,
};

use super::{
    super::super::{engine::Engine, pull_request_wake::TEST_PULL_REQUEST, test_sessions::Load},
    Fixture, Told,
};
use crate::{
    app::{daemon_host::jobs::JobRecord, pull_requests::LinkOrigin, starter_report::ReportKind},
    session::SessionMark,
};

/// Who sends one of a reporting session's prompts.
#[derive(Clone, Copy)]
enum Prompter {
    /// The person, through a client.
    Person,
    /// Its starter's agent, through session control.
    Lead,
}

/// What stands before a reporting session's turns.
#[derive(Clone, Copy)]
enum Before {
    Nothing,
    /// A pull request linked to it is open.
    OpenPullRequest,
    /// A subagent run it started is still in progress.
    StartedInProgress,
    /// It was marked done ahead of every save.
    MarkedDone,
}

/// What a reporting session's mark reads as once its turns ended.
#[derive(Debug, PartialEq)]
enum Reads {
    /// Marked done anew, at or after its last save: finished.
    Done,
    /// Not marked: active.
    Active,
}

// Covers: a session that reports to its starter, as an orchestrator that
// links no pull request of its own, is marked done when it reports `done`,
// at or after its last save, also while a job it started is still in
// progress, but not while a pull request linked to it is left open; a
// report of another kind leaves it active, and so does one that follows a
// `done` report, which clears the done mark, though a lead sent the
// prompt. A lead's prompt whose turn reports nothing keeps a finished
// session finished, marked anew. A daemon that settles only on merged pull
// requests leaves the first and the last active; one that holds a report
// back for a started job leaves the second active, as an orchestrator
// whose worker's turn still runs would stay for good; one that ignores the
// links hides the third; one that leaves the mark to `updated_at` keeps
// the fifth done when both turns end in one second.
// Owner: daemon session marks (a reporting session's).
#[tokio::test]
async fn a_reporting_session_is_done_when_it_reports_done() {
    use ReportKind::{Done, NeedsDecision};
    const LINKED_AT: u64 = 1_700_000_000_000;
    let lead = wire::SessionGrant {
        depth: 1,
        access: wire::GrantAccess::Write,
        workspaces: wire::GrantWorkspaces::Any,
    };
    let cases = [
        (
            "done",
            Before::Nothing,
            vec![(Prompter::Person, Some(Done))],
        ),
        (
            "done, a job it started in progress",
            Before::StartedInProgress,
            vec![(Prompter::Person, Some(Done))],
        ),
        (
            "done, a pull request open",
            Before::OpenPullRequest,
            vec![(Prompter::Person, Some(Done))],
        ),
        (
            "needs a decision",
            Before::Nothing,
            vec![(Prompter::Person, Some(NeedsDecision))],
        ),
        (
            "done, then needs a decision",
            Before::Nothing,
            vec![
                (Prompter::Person, Some(Done)),
                (Prompter::Lead, Some(NeedsDecision)),
            ],
        ),
        (
            "finished, then a lead's silent turn",
            Before::MarkedDone,
            vec![(Prompter::Lead, None)],
        ),
    ];
    let mut seen = Vec::new();
    for (name, before, turns) in cases {
        let answers = turns.iter().map(|_| {
            ScriptedTurn::completed(ModelResponse::Assistant(vec![ContentBlock::Text(
                "the answer".into(),
            )]))
        });
        let fixture = Fixture::answering(Told::AtTheNextPrompt, Load::Reporting, answers).await;
        // Ahead of every save, so a mark made again differs from it.
        let ahead = fixture.listed().updated_at + 3600;
        match before {
            Before::Nothing => {}
            Before::OpenPullRequest => {
                fixture.forge.set_open(TEST_PULL_REQUEST, &[], &[]);
                fixture
                    .inbox()
                    .link(TEST_PULL_REQUEST, LinkOrigin::Agent, LINKED_AT)
                    .await
                    .unwrap();
            }
            Before::StartedInProgress => {
                let run = JobRecord::new_subagent(
                    fixture.session.job.clone(),
                    PathBuf::from("/work"),
                    /*session*/ None,
                    "run".into(),
                    /*worktree*/ None,
                );
                fixture.sessions.jobs.register(run).unwrap();
            }
            Before::MarkedDone => {
                let done = Some(SessionMark::Done { at: ahead });
                fixture
                    .sessions
                    .change_saved_mark(&fixture.session.id, move |_, _| done)
                    .await
                    .unwrap();
            }
        }

        for (from, report) in &turns {
            let grant = match from {
                Prompter::Person => None,
                Prompter::Lead => Some(lead.clone()),
            };
            // As its `report_to_starter` call marks it in the turn: the
            // turn starts with it, and its end takes it. The tool itself
            // runs in the daemon end-to-end test.
            if let Some(kind) = report {
                let engine = fixture.session.engine.lock().await;
                let Some(Engine::Rho(runtime)) = &*engine else {
                    panic!("a Rho session");
                };
                runtime.starter_report().expect("it reports").mark(*kind);
            }
            fixture.prompt_with(grant).await;
        }

        let listed = fixture.listed();
        let reads = match listed.mark {
            Some(SessionMark::Done { at }) if at >= listed.updated_at && at != ahead => Reads::Done,
            None => Reads::Active,
            mark => panic!("{name}: marked {mark:?}, updated at {}", listed.updated_at),
        };
        seen.push((name, reads));
    }
    assert_eq!(
        seen,
        [
            ("done", Reads::Done),
            ("done, a job it started in progress", Reads::Done),
            ("done, a pull request open", Reads::Active),
            ("needs a decision", Reads::Active),
            ("done, then needs a decision", Reads::Active),
            ("finished, then a lead's silent turn", Reads::Done),
        ]
    );
}