rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use std::{path::PathBuf, sync::Arc, time::Duration};

use pretty_assertions::assert_eq;
use rho_protocol::{self as wire, ContentBlock as WireBlock, PromptAuthor, SessionPromptParams};
use rho_sdk::{
    model::{ContentBlock, ModelIdentity, ModelResponse},
    provider::{ScriptedProvider, ScriptedTurn},
};
use tempfile::TempDir;
use tokio::time::timeout;

use super::{
    super::{
        pull_request_wake::{watch_for_tests, TEST_PULL_REQUEST},
        test_sessions::{git, load_on, Load},
        LoadedSession, Sessions,
    },
    after_merge,
};
use crate::{
    app::{
        daemon_host::{
            jobs::{JobEvent, JobRecord, JobRegistry, JobStore, TurnEnd},
            wire::session_to_wire,
        },
        pull_requests::{PullRequestInbox, ScriptedForge},
    },
    session::{Session as StoredSession, SessionListing, SessionMark, SessionSummary},
};

/// Bounds each wait on the daemon's own tasks; never the way a test syncs.
const TEST_BUDGET: Duration = Duration::from_secs(10);

// Covers: a merged pull request marks its session done as of now, also
// one done or kept before the merge, or whose snooze has ended; a pinned
// session stays pinned, a snoozed one snoozed until its snooze ends, and
// one the person put back since the merge stays put back, so the marking
// at the end of the turn that told the agent undoes no restore made while
// it ran. Owner: daemon session marks.
#[test]
fn a_merge_marks_a_session_done_unless_the_person_set_it_apart() {
    use SessionMark::{Done, Kept, Pinned, Snoozed};
    const MERGED_AT: u64 = 1_000;
    const NOW: u64 = 1_060;
    let done = Some(Done { at: NOW });
    let cases = [
        (None, done),
        (Some(Done { at: 900 }), done),
        (Some(Kept { at: MERGED_AT - 1 }), done),
        (Some(Snoozed { until: NOW }), done),
        (Some(Pinned { at: 900 }), Some(Pinned { at: 900 })),
        (
            Some(Snoozed { until: NOW + 1 }),
            Some(Snoozed { until: NOW + 1 }),
        ),
        (Some(Kept { at: MERGED_AT }), Some(Kept { at: MERGED_AT })),
    ];
    let marked: Vec<_> = cases
        .iter()
        .map(|(mark, _)| after_merge(*mark, MERGED_AT, NOW))
        .collect();
    assert_eq!(marked, cases.map(|(_, after)| after));
}

/// What the agent answers the turn that tells it of the merge.
const NOTED: &str = "noted";

/// What a session's clients heard of its mark and its turns, in order.
#[derive(Debug, PartialEq)]
enum Heard {
    TurnRunning,
    Mark(Option<wire::SessionMark>),
    /// The turn ended with this answer.
    Answered(String),
    /// The turn ended some other way.
    Unanswered(wire::TurnOutcome),
}

/// Which turn tells a session's agent news that waits for it.
enum Told {
    /// One the daemon starts as the news comes, the session idle.
    ByTheDaemon,
    /// The next the person prompts: the daemon starts none.
    AtTheNextPrompt,
}

/// A session loaded in its own daemon and saved under that daemon's Rho
/// home, its first prompt answered, whose agent watches a pull request
/// `forge` scripts and answers one turn more with [`NOTED`].
struct Fixture {
    /// The home's `sessions` directory, also the session's workspace.
    root: TempDir,
    _home: TempDir,
    forge: Arc<ScriptedForge>,
    sessions: Arc<Sessions>,
    session: Arc<LoadedSession>,
    /// How many events the session's feed held once it watched.
    told_before: usize,
}

impl Fixture {
    async fn watching(told: Told) -> Self {
        let mut fixture = Self::prompted(told, Load::Waking).await;
        watch_for_tests(&fixture.forge, &fixture.inbox()).await;
        fixture.told_before = fixture.session.feed.buffered_for_tests().len();
        fixture
    }

    /// As [`Self::watching`], loaded as `load` says, with no watch: its
    /// agent answers one turn more with [`NOTED`].
    async fn prompted(told: Told, load: Load) -> Self {
        let home = TempDir::new().unwrap();
        let root = tempfile::Builder::new()
            .prefix("sessions")
            .rand_bytes(0)
            .tempdir_in(home.path())
            .unwrap();
        let forge = ScriptedForge::new();
        let sessions = Sessions::new(
            Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
            home.path(),
            forge.clone(),
        );
        let answers = ["hello", NOTED].map(|text| {
            ScriptedTurn::completed(ModelResponse::Assistant(vec![ContentBlock::Text(
                text.into(),
            )]))
        });
        let provider = ScriptedProvider::new(ModelIdentity::new("test", "test", "model"), answers);
        let session = load_on(&sessions, &root, load, Arc::new(provider)).await;
        // As the session is added.
        session.report_activity();
        match told {
            Told::ByTheDaemon => sessions.watch_idle_results(&session),
            Told::AtTheNextPrompt => {}
        }
        let fixture = Self {
            root,
            _home: home,
            forge,
            sessions,
            session,
            told_before: 0,
        };
        // A turn that tells of news continues a conversation: give it one.
        fixture.prompt().await;
        fixture
    }

    fn inbox(&self) -> PullRequestInbox {
        let (id, root) = (&self.session.id, self.root.path());
        self.sessions.pull_requests.inbox(id, root)
    }

    /// The person prompts the session, and the turn runs to its end.
    async fn prompt(&self) {
        let prompted = self.sessions.prompt(SessionPromptParams {
            author: PromptAuthor::Person,
            session: session_to_wire(self.session.id.clone()),
            content: vec![WireBlock::Text {
                text: "hello".into(),
            }],
            timeout_ms: None,
            environment: std::iter::empty::<(String, String)>().collect(),
            idempotency_key: None,
            grant: None,
        });
        timeout(TEST_BUDGET, prompted)
            .await
            .expect("the turn saves its prompt")
            .unwrap();
        // The turn holds the runtime until its end is recorded.
        let ended = timeout(TEST_BUDGET, self.session.engine.lock());
        drop(ended.await.expect("the turn ends"));
    }

    /// The poll reads the watched pull request merged.
    async fn merge(&self) {
        let wake = &self.sessions.pull_requests;
        wake.merge_for_tests(&self.forge, /*minutes*/ 1).await;
    }

    /// The watched pull request merges, and the delivery turn its news
    /// starts on the idle session runs to its end.
    async fn merge_and_deliver(&self) {
        self.merge().await;
        let jobs = &self.sessions.jobs;
        let started = async {
            loop {
                // Enabled before the look, so a start after it wakes this.
                let changed = jobs.changed();
                tokio::pin!(changed);
                changed.as_mut().enable();
                if self.heard().contains(&Heard::TurnRunning) {
                    return;
                }
                changed.await;
            }
        };
        timeout(TEST_BUDGET, started)
            .await
            .expect("the daemon starts a delivery turn");
        // The turn holds the runtime until its end is recorded.
        let ended = timeout(TEST_BUDGET, self.session.engine.lock());
        drop(ended.await.expect("the delivery turn ends"));
    }

    /// What the session's feed told of its mark and its turns since the
    /// session began to watch.
    fn heard(&self) -> Vec<Heard> {
        self.session
            .feed
            .buffered_for_tests()
            .into_iter()
            .skip(self.told_before)
            .filter_map(|event| match event {
                wire::SessionEvent::State {
                    state: wire::JobState::Running,
                    ..
                } => Some(Heard::TurnRunning),
                wire::SessionEvent::MarkChanged { mark } => Some(Heard::Mark(mark)),
                wire::SessionEvent::TurnEnded {
                    outcome: wire::TurnOutcome::Answered { text, .. },
                    ..
                } => Some(Heard::Answered(text)),
                wire::SessionEvent::TurnEnded { outcome, .. } => Some(Heard::Unanswered(outcome)),
                _ => None,
            })
            .collect()
    }

    /// The session as a list reports it.
    fn listed(&self) -> SessionSummary {
        let root = self.root.path();
        let sessions =
            StoredSession::list_in_root_for_test(root, root, SessionListing::Everything).unwrap();
        let [session] = <[_; 1]>::try_from(sessions).expect("one session is saved");
        session
    }
}

// Covers: the turn that tells a session's agent its watched pull request
// merged leaves the session marked done, at a time not before the
// `updated_at` that turn's saves left, so a client reading
// `updated_at <= at` shows it finished once the turn is over, and tells
// the session's clients the mark before it tells them the turn ended. A
// daemon that marks the session only as it reads the merge leaves a mark
// the turn's saves outdate, and tells none here.
// Owner: daemon session marks.
#[tokio::test]
async fn the_turn_that_tells_of_a_merge_leaves_the_session_marked_done() {
    let fixture = Fixture::watching(Told::ByTheDaemon).await;

    fixture.merge_and_deliver().await;

    let listed = fixture.listed();
    let Some(SessionMark::Done { at }) = listed.mark else {
        panic!("the session is marked done, not {:?}", listed.mark);
    };
    assert_eq!(
        (at >= listed.updated_at, fixture.heard()),
        (
            true,
            vec![
                Heard::TurnRunning,
                Heard::Mark(Some(wire::SessionMark::Done { at })),
                Heard::Answered(NOTED.into()),
            ]
        )
    );
}

// Covers: a merge no turn tells the session's agent of, as while its
// client takes no daemon turns or after a daemon restart, still marks the
// session done as the daemon reads it, as of then rather than of the poll,
// and tells its clients. A daemon that marks only at the end of the
// telling turn leaves such a session unmarked. Owner: daemon session marks.
#[tokio::test]
async fn a_merge_no_turn_tells_of_marks_the_session_done_at_once() {
    let fixture = Fixture::watching(Told::AtTheNextPrompt).await;
    fixture.merge().await;

    // The daemon marks the merges it read before it stops.
    fixture.sessions.stopping.cancel();
    timeout(TEST_BUDGET, fixture.sessions.mark_merged_done())
        .await
        .expect("the daemon marks what it read, then stops");

    let listed = fixture.listed();
    let Some(SessionMark::Done { at }) = listed.mark else {
        panic!("the session is marked done, not {:?}", listed.mark);
    };
    assert_eq!(
        (at >= listed.updated_at, fixture.heard()),
        (
            true,
            vec![Heard::Mark(Some(wire::SessionMark::Done { at }))]
        )
    );
}

/// Where a job the session started is when its pull request merges.
enum Started {
    /// Queued for capacity, as a subagent run is before it runs.
    InProgress,
    /// Queued, and recorded as writing the session itself: the job the
    /// registry finds writing the session is then this one, not the job
    /// that started it.
    InProgressWritingIt,
    /// It ran, and completed.
    Ended,
}

// Covers: a merge marks nothing while a job the session started is still
// in progress, neither as the daemon reads the merge nor as the turn that
// tells the agent of it ends, so a session whose started sessions or
// subagents work on is not hidden; one whose started job ended is marked.
// A daemon that marks on the merges alone hides the first three; one that
// holds back for any job the session ever started leaves the last listed;
// one that asks only the job it finds writing the session hides the third.
// Owner: daemon session marks.
#[tokio::test]
async fn a_merge_marks_nothing_while_a_job_the_session_started_is_in_progress() {
    let cases = [
        (Told::AtTheNextPrompt, Started::InProgress, false),
        (Told::ByTheDaemon, Started::InProgress, false),
        (Told::AtTheNextPrompt, Started::InProgressWritingIt, false),
        (Told::AtTheNextPrompt, Started::Ended, true),
    ];
    let (mut marked, mut expected) = (Vec::new(), Vec::new());
    for (told, started, done) in cases {
        let by_the_daemon = matches!(told, Told::ByTheDaemon);
        let fixture = Fixture::watching(told).await;
        let jobs = &fixture.sessions.jobs;
        let writes = match started {
            Started::InProgress | Started::Ended => None,
            Started::InProgressWritingIt => Some(fixture.session.id.clone()),
        };
        let run = JobRecord::new_subagent(
            fixture.session.job.clone(),
            PathBuf::from("/work"),
            writes,
            "run".into(),
            /*worktree*/ None,
        );
        let run_id = run.id.clone();
        jobs.register(run).unwrap();
        match started {
            Started::InProgress | Started::InProgressWritingIt => {}
            Started::Ended => {
                jobs.record(&run_id, JobEvent::TurnEnded(TurnEnd::Completed))
                    .unwrap();
            }
        }

        if by_the_daemon {
            fixture.merge_and_deliver().await;
        } else {
            fixture.merge().await;
            fixture.sessions.stopping.cancel();
            timeout(TEST_BUDGET, fixture.sessions.mark_merged_done())
                .await
                .expect("the daemon marks what it read, then stops");
        }

        let listed_done = matches!(fixture.listed().mark, Some(SessionMark::Done { .. }));
        let told_mark = fixture
            .heard()
            .iter()
            .any(|heard| matches!(heard, Heard::Mark(_)));
        marked.push((listed_done, told_mark));
        expected.push((done, done));
    }
    assert_eq!(marked, expected);
}

// Covers: a merge whose news waited for the person's next prompt, as after
// a daemon restart, marks nothing as that prompt's turn tells the agent:
// the person turned to the session again, so it is not marked done under
// them. Owner: daemon session marks.
#[tokio::test]
async fn a_prompt_that_tells_of_an_earlier_merge_marks_nothing() {
    let fixture = Fixture::watching(Told::AtTheNextPrompt).await;
    fixture.merge().await;
    let waited = fixture.inbox().has_news();

    fixture.prompt().await;

    assert_eq!(
        (
            (waited, fixture.inbox().has_news()),
            fixture.listed().mark,
            fixture.heard()
        ),
        (
            (true, false),
            None,
            vec![Heard::TurnRunning, Heard::Answered(NOTED.into())]
        )
    );
}

// Covers: the pull request a session's own worktree's branch has, found
// open while a client lists the session, marks the session done when it
// merges, though nothing linked it and the worktree is gone by the time the
// merge is read; a pinned session stays pinned; a session in a checkout it
// may share, as a clone a person switches branches in, gets no link, so
// that branch's merge leaves it listed. A daemon that counts only what
// something linked leaves the first unmarked; one that ignores the
// person's mark unpins the second; one that links any checkout's pull
// request hides the third. Owner: daemon session marks.
#[tokio::test]
async fn the_merge_of_its_own_branch_pull_request_marks_a_session_done() {
    use wire::PullRequestLinkOrigin::Branch;
    const LISTED_AT: u64 = 1_700_000_000_000;
    // Past the list's 5-minute cadence, so the next list reads the link.
    const RELISTED_AT: u64 = LISTED_AT + 6 * 60 * 1000;
    let done = Some(std::mem::discriminant(&SessionMark::Done { at: 0 }));
    let pinned = Some(std::mem::discriminant(&SessionMark::Pinned { at: 0 }));
    let cases = [
        (Load::WakingInOwnWorktree, None, (vec![Branch], done)),
        (
            Load::WakingInOwnWorktree,
            Some(wire::NewSessionMark::Pinned),
            (vec![Branch], pinned),
        ),
        (Load::Waking, None, (Vec::new(), None)),
    ];
    let (mut settled, mut expected) = (Vec::new(), Vec::new());
    for (load, asked, outcome) in cases {
        let fixture = Fixture::prompted(Told::AtTheNextPrompt, load).await;
        let (sessions, root) = (&fixture.sessions, fixture.root.path());
        git(root, &["init", "--quiet", "--initial-branch=feature"]);
        let origin = "git@github.com:acme/widgets.git";
        git(root, &["remote", "add", "origin", origin]);
        fixture.forge.set_open(TEST_PULL_REQUEST, &[], &[]);
        fixture.forge.set_branch(TEST_PULL_REQUEST, "feature");
        let id = session_to_wire(fixture.session.id.clone());
        if asked.is_some() {
            let params = wire::SessionMarkParams::new(id.clone(), asked);
            sessions.mark(params).await.unwrap();
        }
        let list_and_poll = async |now: u64| {
            let params = wire::SessionPullRequestListParams::new(vec![id.clone()]);
            sessions.pull_request_list(params, now).await.unwrap();
            sessions.pull_requests.service().tick(now).await;
        };

        list_and_poll(LISTED_AT).await;
        // The worktree goes, as cleanup removes a merged one: the session's
        // checkout no longer names the branch.
        std::fs::remove_dir_all(root.join(".git")).unwrap();
        fixture.forge.set_merged(TEST_PULL_REQUEST);
        list_and_poll(RELISTED_AT).await;
        sessions.stopping.cancel();
        timeout(TEST_BUDGET, sessions.mark_merged_done())
            .await
            .expect("the daemon marks what it read, then stops");

        let view = sessions
            .pull_requests
            .service()
            .view(&fixture.session.id, RELISTED_AT);
        let origins: Vec<_> = view.linked.iter().map(|linked| linked.origin).collect();
        let mark = fixture.listed().mark.as_ref().map(std::mem::discriminant);
        settled.push((view.branch.map(|branch| branch.lookup), (origins, mark)));
        expected.push((Some(wire::BranchLookup::NotGit), outcome));
    }
    assert_eq!(settled, expected);
}