rho-coding-agent 3.13.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
use pretty_assertions::assert_eq;
use rho_protocol::{
    display::{
        NotificationCard, NotificationItem, NotificationOutcome, NotificationSubject,
        NotificationTone, NotificationUrgency,
    },
    AnswerStop, InputRequestId, SessionId,
};

use super::{PassedUp, PeerBatch, PeerEvent, PeerInbox, PeerNotice, PeerTurnEnd, Receipt};
use crate::{
    app::{
        boundary_results::BoundaryResults, boundary_sources::Reserved, starter_report::ReportKind,
    },
    display_transcript::{DisplayRow, DisplayTranscript},
};

/// The model input and transcript rows a boundary that took `batch`, and
/// nothing else, renders.
fn rendered(batch: &PeerBatch) -> Option<(String, DisplayTranscript)> {
    BoundaryResults {
        notices: &[],
        reserved: &[Reserved::Peers(PeerInbox::default(), batch.clone())],
    }
    .render(/*manager*/ None)
    .finish()
}

fn answered(stop: AnswerStop) -> PeerTurnEnd {
    PeerTurnEnd::Answered {
        answer: "all green".into(),
        stop,
        report: None,
    }
}

// Covers: one boundary that takes notices of two sessions renders them
// once, in the order they arrived: one model input naming both sessions,
// and one transcript card per notice. A miss drops a session's news or
// shows it twice.
// Owner: started-session notices at the boundary.
#[test]
fn a_boundary_renders_one_card_per_notice_in_order() {
    let inbox = PeerInbox::default();
    inbox.expect_for_tests("child-a").tell_ended(
        Some("Fix the build".into()),
        answered(AnswerStop::EndTurn),
        Receipt::new(|| {}),
    );
    let child_b = inbox.expect_for_tests("child-b");
    child_b.tell_waiting(
        /*title*/ None,
        InputRequestId(3),
        "Pick a database".into(),
    );
    let batch = inbox.take();
    let cards: Vec<NotificationCard> = batch.rows().into_iter().map(|row| row.card).collect();

    let (model, transcript) = rendered(&batch).expect("the notices render");
    let named = |session: &str| model.find(session).expect("the session is named");
    let senders: Vec<String> = cards.iter().map(|card| card.sender.clone()).collect();
    let shown: Vec<NotificationCard> = transcript
        .0
        .into_iter()
        .map(|row| match row {
            DisplayRow::Notification(row) => row.card,
            other => panic!("a notice renders as a card, not {other:?}"),
        })
        .collect();

    assert_eq!(
        (named("child-a") < named("child-b"), senders, shown),
        (
            true,
            vec!["child-a".to_owned(), "child-b".to_owned()],
            cards
        )
    );
}

/// Each excerpt `prompt` quotes: the session it is labelled with, and its
/// one-line text.
fn quoted(prompt: &str) -> Vec<(String, String)> {
    let lines: Vec<&str> = prompt.lines().collect();
    lines
        .iter()
        .enumerate()
        .filter_map(|(at, line)| {
            let session = line.strip_prefix("session ")?.strip_suffix(':')?;
            Some((session.to_owned(), (*lines.get(at + 2)?).to_owned()))
        })
        .collect()
}

// Covers: a question passed up quotes the note of the session that passed
// it, labelled with that session rather than the one asking, while its
// line still names the one asking; a question its asker told, or one
// passed up with nothing said, quotes nothing. A miss shows the lead the
// orchestrator's reading of the question as the worker's own words, or
// drops it.
// Owner: started-session notices.
#[test]
fn a_question_passed_up_quotes_the_note_of_the_session_that_passed_it() {
    let note = "the brand is the user's call";
    let cases = [
        (None, Vec::new()),
        (Some(""), Vec::new()),
        (
            Some(note),
            vec![("orchestrator".to_owned(), note.to_owned())],
        ),
    ];
    for (passed_note, expected) in cases {
        let inbox = PeerInbox::default();
        let (request, ask) = (InputRequestId(0), "Which color?".to_owned());
        match passed_note {
            None => inbox
                .expect_for_tests("worker")
                .tell_waiting(/*title*/ None, request, ask),
            Some(note) => inbox.tell_held(
                "worker",
                /*name*/ None,
                request,
                ask,
                Some(PassedUp {
                    by: "orchestrator".into(),
                    note: Some(note.into()),
                }),
            ),
        }
        let prompt = inbox.take().prompt();
        let asking = prompt
            .lines()
            .filter(|line| line.starts_with("session worker: waiting_for_input"))
            .count();

        assert_eq!((asking, quoted(&prompt)), (1, expected), "{passed_note:?}");
    }
}

// Covers: an answer the model cut off or refused does not read as a
// success, and a question needs the reader while a finished answer is only
// notable. A report reads as its kind: only done as a success, and a session
// that stopped without a report as a warning. A miss tells the starter that
// a refused or blocked turn did its work, or files a question among routine
// cards.
// Owner: started-session notices.
#[test]
fn a_notice_reads_as_what_its_session_did() {
    use NotificationOutcome as Outcome;
    use NotificationUrgency as Urgency;
    let ask = || PeerEvent::WaitingForInput {
        request: InputRequestId(3),
        ask: "Pick a database".into(),
        passed_up: None,
    };
    let ended = |stop| PeerEvent::TurnEnded(answered(stop));
    let reported = |stop, kind| {
        PeerEvent::TurnEnded(PeerTurnEnd::Answered {
            answer: "merged both".into(),
            stop,
            report: Some(kind),
        })
    };
    let cases = [
        (
            ended(AnswerStop::EndTurn),
            NotificationTone::Success,
            Outcome::Completed,
            Urgency::Notable,
        ),
        (
            ended(AnswerStop::MaxTokens),
            NotificationTone::Warning,
            Outcome::CutOff,
            Urgency::Notable,
        ),
        (
            ended(AnswerStop::Refusal),
            NotificationTone::Warning,
            Outcome::Refused,
            Urgency::Notable,
        ),
        (
            ask(),
            NotificationTone::Warning,
            Outcome::Question,
            Urgency::NeedsYou,
        ),
        (
            reported(AnswerStop::EndTurn, ReportKind::Done),
            NotificationTone::Success,
            Outcome::Reported,
            Urgency::Notable,
        ),
        (
            reported(AnswerStop::EndTurn, ReportKind::NeedsDecision),
            NotificationTone::Warning,
            Outcome::Reported,
            Urgency::Notable,
        ),
        (
            reported(AnswerStop::EndTurn, ReportKind::Blocked),
            NotificationTone::Error,
            Outcome::Reported,
            Urgency::Notable,
        ),
        (
            reported(AnswerStop::MaxTokens, ReportKind::Done),
            NotificationTone::Warning,
            Outcome::CutOff,
            Urgency::Notable,
        ),
        (
            reported(AnswerStop::Refusal, ReportKind::Done),
            NotificationTone::Warning,
            Outcome::Refused,
            Urgency::Notable,
        ),
        (
            PeerEvent::Unreported {
                answer: "waiting on CI".into(),
            },
            NotificationTone::Warning,
            Outcome::Unreported,
            Urgency::Notable,
        ),
        (
            PeerEvent::StoppedAsking {
                ask: "Pick a database".into(),
            },
            NotificationTone::Warning,
            Outcome::Unreported,
            Urgency::Notable,
        ),
        (
            PeerEvent::Restarted {
                pull_requests: vec!["https://github.com/acme/widgets/pull/12".into()],
            },
            NotificationTone::Warning,
            Outcome::Interrupted,
            Urgency::Notable,
        ),
    ];
    for (event, tone, outcome, urgency) in cases {
        let name = format!("{event:?}");
        let notice = PeerNotice {
            session: "child".into(),
            name: None,
            event,
        };
        let row = notice.row();
        let info = row.info.expect("a notice is typed");
        let session = NotificationSubject::Session {
            id: SessionId::new("child"),
        };
        assert_eq!(
            (row.card.tone, info.urgency, &info.subject, &info.items[..]),
            (
                tone,
                urgency,
                &session,
                &[NotificationItem::new(
                    outcome,
                    urgency,
                    tone,
                    session.clone(),
                    row.card.title.clone()
                )][..]
            ),
            "{name}"
        );
    }
}

/// What one step does to the inbox.
#[derive(Debug)]
enum Step {
    /// Session `0` asks question `1`.
    Ask(&'static str, u64),
    /// Session `0`'s turn ends.
    End(&'static str),
    /// A boundary takes the notices; the next [`Step::Restore`] puts them
    /// back.
    Take,
    Restore,
}

fn asking(session: &str, request: u64) -> PeerNotice {
    PeerNotice {
        session: session.into(),
        name: None,
        event: PeerEvent::WaitingForInput {
            request: InputRequestId(request),
            ask: "input".into(),
            passed_up: None,
        },
    }
}

fn ended(session: &str) -> PeerNotice {
    PeerNotice {
        session: session.into(),
        name: None,
        event: PeerEvent::TurnEnded(PeerTurnEnd::Cancelled),
    }
}

// Covers: the inbox keeps each started session's latest notice, oldest
// session first, so a session that asked and then ended tells only of its
// end; a boundary that puts back what it took never hides a newer notice
// of the same session. A miss tells the starter twice, or tells it stale
// news.
// Owner: started-session notices.
#[test]
fn the_inbox_keeps_each_sessions_latest_notice() {
    let cases: [(&str, Vec<Step>, Vec<PeerNotice>); 3] = [
        (
            "an end replaces the question",
            vec![Step::Ask("a", 0), Step::End("b"), Step::End("a")],
            vec![ended("b"), ended("a")],
        ),
        (
            "a question that came after the take",
            vec![
                Step::Ask("a", 0),
                Step::Take,
                Step::Ask("a", 1),
                Step::Restore,
            ],
            vec![asking("a", 1)],
        ),
        (
            "a take put back goes first",
            vec![
                Step::Ask("a", 0),
                Step::Take,
                Step::Ask("b", 1),
                Step::Restore,
            ],
            vec![asking("a", 0), asking("b", 1)],
        ),
    ];
    for (name, steps, expected) in cases {
        let inbox = PeerInbox::default();
        let mut a = Some(inbox.expect_for_tests("a"));
        let mut b = Some(inbox.expect_for_tests("b"));
        let mut taken = PeerBatch::default();
        for step in steps {
            match step {
                Step::Ask(session, request) => {
                    let owed = if session == "a" { &a } else { &b };
                    owed.as_ref().unwrap().tell_waiting(
                        /*title*/ None,
                        InputRequestId(request),
                        "input".into(),
                    );
                }
                Step::End(session) => {
                    let owed = if session == "a" { &mut a } else { &mut b };
                    owed.take().unwrap().tell_ended(
                        /*title*/ None,
                        PeerTurnEnd::Cancelled,
                        Receipt::new(|| {}),
                    );
                }
                Step::Take => taken = inbox.take(),
                Step::Restore => inbox.restore(&taken),
            }
        }
        assert_eq!(inbox.take().notices, expected, "{name}");
    }
}

// Covers: a turn owes a notice once its prompt's registration is claimed,
// until it ends or its expectation goes unsent, as when the started session
// goes first; a later turn's expectation outlives the earlier one's; a
// registration that goes unclaimed, as for a refused prompt, owes nothing
// and cannot be claimed after. A leak keeps the starter loaded and active
// forever.
// Owner: started-session notices.
#[test]
fn a_turn_owes_a_notice_until_it_ends_or_goes() {
    let inbox = PeerInbox::default();
    let expecting = || (inbox.expecting(), inbox.outstanding());

    let refused = inbox.register("a");
    let key = refused.key();
    let while_registered = expecting();
    drop(refused);
    let claimed_after_refusal = inbox.claim("a", &key).is_some();
    let owed = inbox.expect_for_tests("a");
    let while_owed = expecting();
    owed.tell_ended(
        /*title*/ None,
        PeerTurnEnd::Interrupted,
        Receipt::new(|| {}),
    );
    let once_told = expecting();
    inbox.take();
    let once_taken = expecting();
    let earlier = inbox.expect_for_tests("a");
    let later = inbox.expect_for_tests("a");
    drop(earlier);
    let with_a_later_turn = expecting();
    drop(later);
    let once_gone = expecting();

    assert_eq!(
        (
            while_registered,
            claimed_after_refusal,
            [
                while_owed,
                once_told,
                once_taken,
                with_a_later_turn,
                once_gone
            ]
        ),
        (
            (false, false),
            false,
            [
                (true, true),
                (false, true),
                (false, false),
                (true, true),
                (false, false),
            ]
        )
    );
}

// Covers: a notice's receipt runs only once a turn's boundary delivered
// the batch that holds it, as `boundary_sources::Reserved::commit` does,
// and stays with notices a turn put back; a notice a newer one of its
// session replaced runs its receipt with the newer one. A miss forgets an
// end or stop the daemon must tell again after a restart, or tells one
// twice.
// Owner: peer inbox delivery receipts.
#[test]
fn a_receipt_runs_once_its_notice_is_delivered() {
    use std::sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    };
    #[derive(Clone, Copy, Debug)]
    enum Delivery {
        Take,
        Restore,
        Commit,
    }
    use Delivery::{Commit, Restore, Take};
    // How many notices of the session are told, the steps, and how many
    // receipts ran.
    let cases = [
        (1, vec![Take], 0),
        (1, vec![Take, Commit], 1),
        (1, vec![Take, Restore], 0),
        (1, vec![Take, Restore, Take, Commit], 1),
        (2, vec![Take, Commit], 2),
    ];
    for (told, steps, expected) in cases {
        let name = format!("{told} told, {steps:?}");
        let ran = Arc::new(AtomicUsize::new(0));
        let inbox = PeerInbox::default();
        for _ in 0..told {
            let ran = Arc::clone(&ran);
            let receipt = Receipt::new(move || {
                ran.fetch_add(1, Ordering::Relaxed);
            });
            inbox.tell_ended("a", /*name*/ None, PeerTurnEnd::Cancelled, receipt);
        }
        let mut batch = PeerBatch::default();
        for step in steps {
            match step {
                Take => batch = inbox.take(),
                Restore => inbox.restore(&batch),
                Commit => batch.commit(),
            }
        }

        assert_eq!(ran.load(Ordering::Relaxed), expected, "{name}");
    }
}