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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
use std::{path::PathBuf, sync::Arc, time::SystemTime};

use pretty_assertions::assert_eq;
use rho_protocol::{
    self as wire, ContentBlock, ErrorCode, IdempotencyKey, InputAnswer, InputRequestId,
    SessionPromptParams, SessionSetup, TurnId,
};
use tempfile::TempDir;
use tokio::{sync::mpsc, time::timeout};

use super::super::{
    inputs::Asker,
    job_record::SessionJobRecord,
    open::OpenWith,
    reopen::FirstTurn,
    test_events::{approval, elicitation, plan, question},
    test_sessions::{
        insert, load, load_started, opened_unadded, opened_waking, prompts_shown, seen, until,
        Load, Seen, TEST_BUDGET,
    },
    LoadedSession, Sessions,
};
use crate::{
    app::{
        daemon_host::{
            jobs::{
                JobId, JobRecord, JobRegistry, JobStore, OwedWord, StarterNotice, TurnEnd,
                TurnRecord, Word, WordChange,
            },
            wire::session_to_wire,
        },
        peer_sessions::{PeerEvent, PeerInbox, PeerNotice, PeerTurnEnd},
        pull_requests::ScriptedForge,
        session_runtime::{HangUntilCancel, SessionEvent, TurnControl},
        starter_report::{ReportKind, StarterReport},
    },
    caller_context::CallerContext,
};

/// What every prompt of these tests asks.
const PROMPT: &str = "hello";

fn prompt_params(session: &LoadedSession, key: Option<IdempotencyKey>) -> SessionPromptParams {
    SessionPromptParams {
        author: wire::PromptAuthor::Person,
        session: session_to_wire(session.id.clone()),
        content: vec![ContentBlock::Text {
            text: PROMPT.into(),
        }],
        timeout_ms: None,
        environment: std::iter::empty::<(String, String)>().collect(),
        idempotency_key: key,
        grant: None,
    }
}

/// Prompts `session` under `key`; returns once its turn began. The provider
/// never answers, so the turn runs until it is cancelled.
async fn prompt(
    sessions: &Sessions,
    session: &LoadedSession,
    key: Option<IdempotencyKey>,
) -> Result<TurnId, Option<ErrorCode>> {
    timeout(TEST_BUDGET, sessions.prompt(prompt_params(session, key)))
        .await
        .expect("the daemon answers the prompt")
        .map(|started| started.response.turn)
        .map_err(|error| error.error_code())
}

/// Prompts `session` as the `sessions` tool of the session whose inbox is
/// `caller` does: registered first, the registration gone once the daemon
/// answered.
async fn prompt_from(
    sessions: &Sessions,
    caller: &PeerInbox,
    session: &LoadedSession,
) -> Result<TurnId, Option<ErrorCode>> {
    let registration = caller.register(session.id.as_str());
    prompt(sessions, session, Some(registration.key())).await
}

/// Cancels `session`'s turn and returns once its job recorded the end.
async fn cancel(sessions: &Sessions, session: &LoadedSession) {
    session.cancel_turn();
    let ended = || {
        sessions
            .jobs
            .get(&session.job)
            .is_some_and(|job| !job.state.in_progress())
    };
    until(ended, "the cancelled turn ends").await;
}

/// The sessions the notification cards a session's clients were shown
/// refer to, in order.
fn cards(session: &LoadedSession) -> Vec<Option<String>> {
    session
        .feed
        .buffered_for_tests()
        .into_iter()
        .filter_map(|event| match event {
            wire::SessionEvent::Card {
                display: Some(card),
                ..
            } => Some(card.reference),
            _ => None,
        })
        .collect()
}

/// Each input request a session's clients were shown open, and whether it
/// was told to its starter.
fn told_starter(session: &LoadedSession) -> Vec<(u64, bool)> {
    session
        .feed
        .buffered_for_tests()
        .into_iter()
        .filter_map(|event| match event {
            wire::SessionEvent::InputRequested { request } => {
                Some((request.id.0, request.told_starter))
            }
            _ => None,
        })
        .collect()
}

/// Who holds each request open on a session, as `rho/job/list` lists it,
/// and whether it is the person's.
fn listed_holders(session: &LoadedSession) -> Vec<(Option<wire::SessionId>, bool)> {
    session
        .feed
        .live()
        .inputs
        .iter()
        .map(|request| (request.held_by.clone(), request.for_person()))
        .collect()
}

/// A session the fixture's starter started, asking it a question it is
/// told of.
async fn asking_starter(
    fixture: &Fixture,
) -> (Arc<LoadedSession>, mpsc::UnboundedReceiver<TurnControl>) {
    let child = fixture.session().await;
    prompt_from(&fixture.sessions, fixture.inbox(), &child)
        .await
        .expect("the prompt starts a turn");
    let (control, answers) = mpsc::unbounded_channel();
    child.change_inputs(|inputs| {
        inputs.note(Asker::Turn, &control, &question("pick"), SystemTime::now());
    });
    (child, answers)
}

fn ended(session: &LoadedSession) -> PeerNotice {
    PeerNotice {
        session: session.id.to_string(),
        // Untitled: named by its first message.
        name: Some(PROMPT.into()),
        event: PeerEvent::TurnEnded(PeerTurnEnd::Cancelled),
    }
}

fn asking(session: &LoadedSession, request: u64) -> PeerNotice {
    PeerNotice {
        session: session.id.to_string(),
        // Untitled: named by its first message.
        name: Some(PROMPT.into()),
        event: PeerEvent::WaitingForInput {
            request: InputRequestId(request),
            ask: "ask".into(),
            passed_up: None,
        },
    }
}

/// A daemon with a starter session whose client asked for daemon turns
/// (`idle_wake: turn`), so it has an inbox for the turns it starts.
struct Fixture {
    root: TempDir,
    _home: TempDir,
    sessions: Arc<Sessions>,
    starter: Arc<LoadedSession>,
}

impl Fixture {
    /// The starter, its idle watcher running, as the daemon adds it.
    async fn watched() -> Self {
        let fixture = Self::unwatched().await;
        fixture.sessions.watch_idle_results(&fixture.starter);
        fixture
    }

    /// The starter with no idle watcher, so nothing takes its notices but
    /// the test.
    async fn unwatched() -> Self {
        let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
        let sessions = Sessions::new(
            Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
            home.path(),
            ScriptedForge::new(),
        );
        let starter = load_starter(&sessions, &root).await;
        Self {
            root,
            _home: home,
            sessions,
            starter,
        }
    }

    /// A session the starter started, as session control's `new` opens one.
    async fn session(&self) -> Arc<LoadedSession> {
        load_started(&self.sessions, &self.root, &self.starter).await
    }

    fn inbox(&self) -> &PeerInbox {
        inbox(&self.starter)
    }

    /// Waits until the starter's clients were shown `count` notification
    /// cards, then cancels the starter's turn that showed them.
    async fn shown_then_cancelled(&self, count: usize) {
        until(
            || cards(&self.starter).len() == count,
            "the starter shows the notices",
        )
        .await;
        cancel(&self.sessions, &self.starter).await;
    }
}

/// A session that takes daemon turns, as the daemon adds it. It has history,
/// as a session that started a turn elsewhere does, so the daemon's turn has
/// something to continue.
async fn load_starter(sessions: &Sessions, root: &TempDir) -> Arc<LoadedSession> {
    let starter = load(sessions, root, Load::Waking).await;
    sessions
        .configure(wire::SessionConfigureParams {
            session: session_to_wire(starter.id.clone()),
            change: wire::SessionChange::Context {
                text: "earlier work".into(),
                display: "earlier work".into(),
            },
        })
        .await
        .expect("the starter takes context");
    starter.report_activity();
    starter
}

fn inbox(session: &LoadedSession) -> &PeerInbox {
    session
        .peer_wake
        .inbox()
        .expect("a session that takes daemon turns has an inbox")
}

// Covers: a turn the starter's call started keeps the starter active while
// it runs; once every such turn ended, the idle starter, which no client
// follows, is woken by exactly one turn that shows each notice, oldest
// first, and leaves nothing outstanding. A miss leaves the starter polling
// `sessions wait`, floods it with a turn per notice, or loops delivery
// turns.
// Owner: daemon wake for started sessions.
#[tokio::test]
async fn one_turn_wakes_an_idle_starter_for_the_turns_it_started() {
    use wire::SessionActivity::{Active, Settled};
    for count in [1, 3] {
        let fixture = Fixture::watched().await;
        let mut children = Vec::new();
        for _ in 0..count {
            let child = fixture.session().await;
            prompt_from(&fixture.sessions, fixture.inbox(), &child)
                .await
                .expect("the prompt starts a turn");
            children.push(child);
        }
        let owed_while_running = fixture.inbox().outstanding();

        // Held, so a delivery turn the first end starts takes nothing until
        // every turn ended.
        let held = fixture.starter.engine.lock().await;
        for child in &children {
            cancel(&fixture.sessions, child).await;
        }
        drop(held);
        fixture.shown_then_cancelled(count).await;

        assert_eq!(
            (
                owed_while_running,
                seen(&fixture.starter),
                cards(&fixture.starter),
                fixture.inbox().outstanding(),
            ),
            (
                true,
                vec![
                    Seen::Activity(Settled),
                    Seen::Activity(Active),
                    Seen::TurnRunning,
                    Seen::TurnEnded,
                    Seen::Activity(Settled),
                ],
                children
                    .iter()
                    .map(|child| Some(child.id.to_string()))
                    .collect::<Vec<_>>(),
                false,
            ),
            "{count} started"
        );
    }
}

/// Which key a case's prompt carries.
#[derive(Clone, Copy, Debug)]
enum Key {
    /// One the starter registered.
    Registered,
    /// None, as a person's client or a caller the daemon tells nothing
    /// sends.
    Absent,
    /// The client's own, which nobody registered.
    Unregistered,
    /// One the starter registered for another session.
    ForAnother,
}

// Covers: only the turn a prompt the starter registered starts tells the
// starter; a turn a person, or a caller with no inbox, starts tells nobody,
// and so does one whose prompt names a key nobody registered, or one the
// starter registered for another session. A miss wakes an agent for its
// user's own work.
// Owner: daemon wake for started sessions.
#[tokio::test]
async fn only_the_turn_a_registered_prompt_starts_tells_the_starter() {
    let cases = [
        (Key::Registered, true),
        (Key::Absent, false),
        (Key::Unregistered, false),
        (Key::ForAnother, false),
    ];
    for (key, tells) in cases {
        let fixture = Fixture::unwatched().await;
        let child = fixture.session().await;
        let started = match key {
            Key::Registered => prompt_from(&fixture.sessions, fixture.inbox(), &child).await,
            Key::Absent => prompt(&fixture.sessions, &child, /*key*/ None).await,
            Key::Unregistered => {
                let key = IdempotencyKey::new("the client's own");
                prompt(&fixture.sessions, &child, Some(key)).await
            }
            Key::ForAnother => {
                let elsewhere = fixture.session().await;
                let registration = fixture.inbox().register(elsewhere.id.as_str());
                prompt(&fixture.sessions, &child, Some(registration.key())).await
            }
        };
        started.expect("the prompt starts a turn");
        let owed_while_running = fixture.inbox().outstanding();
        cancel(&fixture.sessions, &child).await;
        let expected = if tells {
            vec![ended(&child)]
        } else {
            Vec::new()
        };

        assert_eq!(
            (owed_while_running, fixture.inbox().take().notices),
            (tells, expected),
            "{key:?}"
        );
    }
}

// Covers: of two callers that registered a prompt of one session, a turn
// tells only the one whose prompt started it; a second caller whose prompt
// the busy session refuses owes nothing, and a turn it starts once that one
// ended tells it alone. A miss tells a caller of a turn it never started,
// or keeps the refused caller loaded forever.
// Owner: daemon wake for started sessions.
#[tokio::test]
async fn a_turn_tells_only_the_caller_whose_prompt_started_it() {
    let fixture = Fixture::unwatched().await;
    let other = load_starter(&fixture.sessions, &fixture.root).await;
    let child = fixture.session().await;
    let (first, second) = (fixture.inbox(), inbox(&other));

    // Each turn starts while the other caller holds a registration of the
    // child too, so a claim on the session alone tells the wrong caller of
    // one of the two turns, whichever inbox the daemon looks in first.
    let second_registered = second.register(child.id.as_str());
    prompt_from(&fixture.sessions, first, &child)
        .await
        .expect("the prompt starts a turn");
    let refused = prompt(&fixture.sessions, &child, Some(second_registered.key()))
        .await
        .map(|_| ());
    let second_owed_once_refused = second.outstanding();
    cancel(&fixture.sessions, &child).await;
    let told_of_the_first = (first.take().notices, second.take().notices);
    drop(second_registered);
    let _first_registered = first.register(child.id.as_str());
    prompt_from(&fixture.sessions, second, &child)
        .await
        .expect("the prompt starts a turn");
    cancel(&fixture.sessions, &child).await;
    let told_of_the_second = (first.take().notices, second.take().notices);

    assert_eq!(
        (
            refused,
            second_owed_once_refused,
            told_of_the_first,
            told_of_the_second
        ),
        (
            Err(Some(ErrorCode::SessionBusy)),
            false,
            (vec![ended(&child)], Vec::new()),
            (Vec::new(), vec![ended(&child)]),
        )
    );
}

// Covers: a started turn tells its starter of each question once, as it
// opens, naming the request and what it asks, though it closes before a
// boundary takes the notice, and its close tells nothing; an approval, a
// plan approval or a question for the user alone, as an MCP server's
// elicitation is, tells nothing, since only a person answers it; the turn's
// end follows. A miss leaves the starter waiting on a session that waits
// on a person, or tells it of one question twice.
// Owner: daemon wake for started sessions.
#[tokio::test]
async fn a_started_turn_tells_its_starter_of_each_question_once() {
    let fixture = Fixture::unwatched().await;
    let child = fixture.session().await;
    prompt_from(&fixture.sessions, fixture.inbox(), &child)
        .await
        .expect("the prompt starts a turn");
    let (control, _answers) = mpsc::unbounded_channel();
    let ask = |event: &SessionEvent| {
        child.change_inputs(|inputs| inputs.note(Asker::Turn, &control, event, SystemTime::now()));
    };
    let answer = |request| {
        child
            .change_inputs(|inputs| inputs.answer(InputRequestId(request), InputAnswer::Decline))
            .unwrap();
    };
    let taken = || fixture.inbox().take().notices;

    ask(&approval(0));
    let approval_opened = taken();
    ask(&plan(0));
    let plan_opened = taken();
    ask(&question("pick"));
    answer(2);
    let closed_before_taken = taken();
    ask(&question("again"));
    let opened = taken();
    answer(3);
    let closed_once_taken = taken();
    ask(&elicitation("server"));
    let user_only_opened = taken();
    cancel(&fixture.sessions, &child).await;
    let turn_ended = taken();

    assert_eq!(
        [
            approval_opened,
            plan_opened,
            closed_before_taken,
            opened,
            closed_once_taken,
            user_only_opened,
            turn_ended
        ],
        [
            Vec::new(),
            Vec::new(),
            vec![asking(&child, 2)],
            vec![asking(&child, 3)],
            Vec::new(),
            Vec::new(),
            vec![ended(&child)],
        ]
    );
}

// Covers: a question the starter may answer is told to it and marked
// `told_starter`, so clients show it as asking the starter, not the user;
// a starter that prompted a session it did not start is told of no
// question and none is marked, though it still hears of the turn's end; a
// question for the user alone is never marked. A miss marks a question as
// the starter's that the starter never hears of, so it waits unseen, or
// wakes a starter for a question it would be refused on.
// Owner: daemon wake for started sessions.
#[tokio::test]
async fn only_a_starter_that_may_answer_is_told_of_a_question_and_it_is_marked() {
    for started_by_starter in [true, false] {
        let fixture = Fixture::unwatched().await;
        let child = if started_by_starter {
            fixture.session().await
        } else {
            load(&fixture.sessions, &fixture.root, Load::Saved).await
        };
        prompt_from(&fixture.sessions, fixture.inbox(), &child)
            .await
            .expect("the prompt starts a turn");
        let (control, _answers) = mpsc::unbounded_channel();
        for event in [question("pick"), elicitation("server")] {
            child.change_inputs(|inputs| {
                inputs.note(Asker::Turn, &control, &event, SystemTime::now());
            });
        }
        let asked = fixture.inbox().take().notices;
        cancel(&fixture.sessions, &child).await;
        let turn_ended = fixture.inbox().take().notices;

        let expected = if started_by_starter {
            (vec![(0, true), (1, false)], vec![asking(&child, 0)])
        } else {
            (vec![(0, false), (1, false)], Vec::new())
        };
        assert_eq!(
            (told_starter(&child), asked, turn_ended),
            (expected.0, expected.1, vec![ended(&child)]),
            "started by the starter: {started_by_starter}"
        );
    }
}

// Covers: a question told to the starter is held by it, and is the person's
// again once a turn of the starter, which reports to no session, ends
// without answering it, as `rho/job/list` lists it. A miss leaves a question
// its starter left unanswered showing as the starter's for good, which
// nobody answers when it has no fallback.
// Owner: daemon wake for started sessions.
#[tokio::test]
async fn a_starter_turn_that_ends_gives_its_unanswered_questions_back_to_the_person() {
    let fixture = Fixture::unwatched().await;
    let (child, _answers) = asking_starter(&fixture).await;
    let starter_id = session_to_wire(fixture.starter.id.clone());
    let told = listed_holders(&child);
    prompt(&fixture.sessions, &fixture.starter, /*key*/ None)
        .await
        .expect("the prompt starts a turn");
    // Once the turn took the question's notice, which it then leaves.
    fixture.shown_then_cancelled(1).await;

    assert_eq!(
        (told, listed_holders(&child)),
        (vec![(Some(starter_id), false)], vec![(None, true)])
    );
}

// Covers: a question whose notice still waits in its holder's inbox, which
// no turn of the holder took, stays with the holder as a turn of it ends;
// once a turn took the notice, the question moves on, here to the person.
// A miss passes a question on, up or to the person, before its holder ever
// saw it, as when the holder's turn ends just as the question opens.
// Owner: daemon question holders.
#[tokio::test]
async fn a_holder_keeps_a_question_until_a_turn_of_it_took_its_notice() {
    let fixture = Fixture::unwatched().await;
    let (child, _answers) = asking_starter(&fixture).await;
    let starter_id = session_to_wire(fixture.starter.id.clone());
    fixture
        .starter
        .pass_on_held(/*note*/ None, /*starter*/ None);
    let untaken = listed_holders(&child);
    fixture.inbox().take();
    fixture
        .starter
        .pass_on_held(/*note*/ None, /*starter*/ None);

    assert_eq!(
        (untaken, listed_holders(&child)),
        (vec![(Some(starter_id), false)], vec![(None, true)])
    );
}

// Covers: a question told to the starter is the person's again once the
// starter is deleted. A miss leaves it showing as asking a session that is
// gone.
// Owner: daemon wake for started sessions.
#[tokio::test]
async fn a_deleted_starter_gives_its_unanswered_questions_back_to_the_person() {
    let fixture = Fixture::unwatched().await;
    let (child, _answers) = asking_starter(&fixture).await;
    let starter_id = session_to_wire(fixture.starter.id.clone());
    let told = listed_holders(&child);
    let Fixture {
        sessions, starter, ..
    } = fixture;
    let id = session_to_wire(starter.id.clone());
    drop(starter);
    timeout(
        TEST_BUDGET,
        sessions.delete(wire::SessionDeleteParams {
            session: id,
            unless_attached: false,
            work: wire::DeleteWork::Stop,
        }),
    )
    .await
    .expect("the daemon answers the delete")
    .expect("the starter is deleted");

    assert_eq!(
        (told, listed_holders(&child)),
        (vec![(Some(starter_id), false)], vec![(None, true)])
    );
}

// Covers: a notice that arrives while the starter's own turn is under way
// is taken at that turn's boundary, and the daemon starts no turn for it
// after. A miss tells the starter twice, or starts a turn it never needed.
// Owner: daemon wake for started sessions.
#[tokio::test]
async fn a_busy_starter_takes_the_notice_at_its_boundary_and_no_turn_follows() {
    use wire::SessionActivity::{Active, Settled};
    let fixture = Fixture::watched().await;
    let child = fixture.session().await;
    prompt_from(&fixture.sessions, fixture.inbox(), &child)
        .await
        .expect("the prompt starts a turn");

    // The starter's turn starts, and waits for the runtime held here
    // until the notice waits.
    let held = fixture.starter.engine.lock().await;
    let prompted = fixture
        .sessions
        .prompt(prompt_params(&fixture.starter, /*key*/ None));
    tokio::pin!(prompted);
    let starter_running = || {
        fixture
            .sessions
            .jobs
            .get(&fixture.starter.job)
            .is_some_and(|job| job.state.in_progress())
    };
    tokio::select! {
        _ = prompted.as_mut() => panic!("the prompt answers before its turn could begin"),
        () = until(starter_running, "the starter's turn starts") => {}
    }
    cancel(&fixture.sessions, &child).await;
    let waited_for_the_boundary = fixture.inbox().has_notices();
    drop(held);
    timeout(TEST_BUDGET, prompted)
        .await
        .expect("the daemon answers the prompt")
        .expect("the prompt starts a turn");
    fixture.shown_then_cancelled(1).await;

    assert_eq!(
        (
            waited_for_the_boundary,
            seen(&fixture.starter),
            cards(&fixture.starter),
            prompts_shown(&fixture.starter),
            fixture.inbox().outstanding(),
        ),
        (
            true,
            vec![
                Seen::Activity(Settled),
                Seen::Activity(Active),
                Seen::TurnRunning,
                Seen::TurnEnded,
                Seen::Activity(Settled),
            ],
            vec![Some(child.id.to_string())],
            1,
            false,
        )
    );
}

// Covers: a started turn that ends after the starter's delivery turn took
// its notices, and before that turn ended, wakes the starter again once it
// did. A miss leaves a starter that runs several sessions untold of the
// later ones until something else starts a turn.
// Owner: daemon wake for started sessions.
#[tokio::test]
async fn a_turn_that_ends_during_the_delivery_turn_wakes_the_starter_again() {
    let fixture = Fixture::watched().await;
    let (first, second) = (fixture.session().await, fixture.session().await);
    for child in [&first, &second] {
        prompt_from(&fixture.sessions, fixture.inbox(), child)
            .await
            .expect("the prompt starts a turn");
    }

    cancel(&fixture.sessions, &first).await;
    until(
        || cards(&fixture.starter).len() == 1,
        "the starter shows the first notice",
    )
    .await;
    // The delivery turn is past the boundary that took the first notice.
    cancel(&fixture.sessions, &second).await;
    let left_behind = fixture.inbox().has_notices();
    // Not awaited to its end: the next delivery turn may be under way by
    // the time this task looks.
    fixture.starter.cancel_turn();
    fixture.shown_then_cancelled(2).await;

    assert_eq!(
        (
            left_behind,
            cards(&fixture.starter),
            fixture.inbox().outstanding(),
        ),
        (
            true,
            vec![Some(first.id.to_string()), Some(second.id.to_string())],
            false,
        )
    );
}

// Covers: a turn that owes its end to a starter not loaded as it started,
// as one that continues a turn a restart interrupted does when its own
// client attached first, still runs as the starter loads. From that load
// the turn owes the starter in memory, so its end tells the starter once,
// as it ends; a later load tells nothing more once a starter's turn took
// that notice, and tells it again if none did, as when the daemon ended
// first. A miss leaves an idle starter that stays loaded unwoken, tells it
// twice, or loses an end the daemon's end kept from it.
// Owner: daemon wake for started sessions.
#[tokio::test]
async fn a_starter_loaded_while_its_owed_turn_runs_hears_its_end_until_delivered() {
    #[derive(Debug)]
    enum Notice {
        Delivered,
        Undelivered,
    }
    for notice in [Notice::Delivered, Notice::Undelivered] {
        let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
        let sessions = Sessions::new(
            Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
            home.path(),
            ScriptedForge::new(),
        );
        let worker = load(&sessions, &root, Load::Saved).await;
        let turn = prompt(&sessions, &worker, /*key*/ None)
            .await
            .expect("the prompt starts a turn");
        let starter = opened_waking(&sessions, &root).await;
        // As `carry_starter` records it while the starter is not loaded.
        sessions.jobs.owe_starter(&worker.job, &turn, &starter.id);

        let starter = insert(&sessions, starter);
        // As the daemon's `add` does once it added the starter.
        sessions.tell_untold_ends(&starter);
        let told_while_running = inbox(&starter).take().notices;
        cancel(&sessions, &worker).await;
        let mut at_end = inbox(&starter).take();
        let told_at_end = at_end.notices.clone();
        match notice {
            Notice::Delivered => at_end.commit(),
            Notice::Undelivered => {}
        }
        sessions.tell_untold_ends(&starter);
        let told_at_next_load = inbox(&starter).take().notices;

        let again = match notice {
            Notice::Delivered => Vec::new(),
            Notice::Undelivered => vec![ended(&worker)],
        };
        assert_eq!(
            (told_while_running, told_at_end, told_at_next_load),
            (Vec::new(), vec![ended(&worker)], again),
            "{notice:?}"
        );
    }
}

// Covers: a starter that loads, as a lead does after a restart, is told
// once that a session that reports to it and is not loaded stopped without
// the report it owes, quoting its last answer, and hears nothing of it
// again once that notice was delivered; but nothing of one that pull
// request news reopens, which may still report. A miss leaves a lead
// waiting on a stopped workstream for good, tells it twice, or tells it a
// session that watches its pull request stopped.
// Owner: daemon wake for started sessions, across a restart.
#[tokio::test]
async fn a_loading_starter_hears_once_of_an_unloaded_session_that_stopped_owing_it() {
    #[derive(Debug)]
    enum Child {
        Unloaded,
        KeptForNews,
    }
    for child in [Child::Unloaded, Child::KeptForNews] {
        let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
        let sessions = Sessions::new(
            Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
            home.path(),
            ScriptedForge::new(),
        );
        let starter = load(&sessions, &root, Load::Waking).await;
        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();
        sessions.jobs.owe_word(&id, &starter.id);
        sessions
            .jobs
            .start_turn(&id, TurnRecord::starting(/*key*/ None), CallerContext::ROOT)
            .unwrap();
        let answer = WordChange::Answered {
            answer: "pushed".into(),
        };
        let notice = StarterNotice::Nothing;
        sessions
            .jobs
            .end_turn(&id, TurnEnd::Completed, None, notice, answer)
            .unwrap();
        match child {
            Child::Unloaded => {}
            Child::KeptForNews => {
                let opening = OpenWith {
                    environment: starter.environment.current(),
                    setup: SessionSetup::default(),
                    grant: CallerContext::ROOT,
                };
                sessions
                    .pull_requests
                    .keep_opening_for_tests(&session, opening);
            }
        }

        sessions.tell_untold_ends(&starter);
        let mut first = inbox(&starter).take();
        let told = first.notices.clone();
        first.commit();
        sessions.tell_untold_ends(&starter);
        let again = inbox(&starter).take().notices;

        let stopped = PeerNotice {
            session: session.to_string(),
            name: None,
            event: PeerEvent::Unreported {
                answer: "pushed".into(),
            },
        };
        let expected = match child {
            Child::Unloaded => vec![stopped],
            Child::KeptForNews => Vec::new(),
        };
        assert_eq!((told, again), (expected, Vec::new()), "{child:?}");
    }
}

// Covers: a session a prompt reopens, with notices waiting for it, as an
// orchestrator a lead re-prompts after a restart has of its workers, gives
// that prompt the turn: the daemon starts no turn of its own to deliver
// them first, which would refuse the prompt as busy. One the daemon opens
// for itself delivers them at once, the race the hold closes. A miss
// refuses the lead's re-prompt with `SessionBusy` after a restart.
// Owner: daemon session open (the reopening prompt's turn).
#[tokio::test]
async fn a_reopening_prompt_starts_its_turn_before_the_daemons_delivery() {
    for (first, expected) in [
        (FirstTurn::Daemon, Err(Some(ErrorCode::SessionBusy))),
        (FirstTurn::Prompt, Ok(())),
    ] {
        let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
        let sessions = Sessions::new(
            Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
            home.path(),
            ScriptedForge::new(),
        );
        let provider = Arc::new(HangUntilCancel);
        let (record, opened) = opened_unadded(
            &sessions,
            &root,
            Load::Waking,
            provider,
            /*parent*/ None,
        )
        .await;
        // A session it started, whose end it has yet to hear, as after a
        // restart.
        let child = JobRecord::new_session(
            JobId::generate(),
            PathBuf::from("/work"),
            rho_sdk::SessionId::new(),
        );
        let child_job = child.id.clone();
        sessions.jobs.register(child).unwrap();
        let turn = TurnRecord::starting(/*key*/ None);
        let turn_id = turn.id.clone();
        sessions
            .jobs
            .start_turn(&child_job, turn, CallerContext::ROOT)
            .unwrap();
        let starter = record.subject.session().unwrap().clone();
        sessions.jobs.owe_starter(&child_job, &turn_id, &starter);
        let notice = StarterNotice::Owed { report: None };
        sessions
            .jobs
            .end_turn(
                &child_job,
                TurnEnd::Interrupted,
                None,
                notice,
                WordChange::Keep,
            )
            .unwrap();

        let session = sessions
            .add(SessionJobRecord::Register(record), opened, first)
            .await
            .unwrap();
        // On this one-thread runtime, the idle watcher the add spawned
        // runs to its first wait here, as on a busy daemon it may before
        // the prompt's turn starts.
        tokio::task::yield_now().await;
        let prompted = prompt(&sessions, &session, /*key*/ None).await.map(|_| ());
        session.cancel_turn();

        assert_eq!(prompted, expected, "{first:?}");
    }
}

/// What [`super::PeerWake::ended`] told, comparably.
#[derive(Debug, PartialEq, Eq)]
enum Told {
    Now(PeerTurnEnd),
    Later(Option<ReportKind>),
    Nothing,
}

/// One turn of a session: what it marked, then how it ended.
struct Turn {
    mark: Option<ReportKind>,
    end: TurnEnd,
    outcome: Option<wire::TurnOutcome>,
}

fn answered_turn(mark: Option<ReportKind>, stop: wire::AnswerStop) -> Turn {
    Turn {
        mark,
        end: TurnEnd::Completed,
        outcome: Some(wire::TurnOutcome::Answered {
            text: "merged both".into(),
            stop,
        }),
    }
}

fn ended_as(end: TurnEnd, mark: Option<ReportKind>) -> Turn {
    Turn {
        mark,
        end,
        outcome: None,
    }
}

// Covers: what each turn tells the session that started its session, and
// what it does to the word the session owes it on its job. A turn of a
// session that reports to its starter tells the report it marked when it
// answered, cut off or not, which delivers what it owes, and nothing when
// it answered without one, which leaves it owing with that answer for the
// safety net, unless it reported since it was last prompted, a mark on a
// turn that did not answer delivering no report; any other end tells as it
// is, marked or not, and stops what it owes. A session that does not
// report tells every end and owes no word. A miss wakes the starter for
// progress, never for a failure, warns it of a session that already
// reported, or loses the safety net across a restart.
// Owner: daemon wake for started sessions (the reporting-turn rule).
#[test]
fn a_turn_tells_its_starter_its_report_or_any_end_but_a_silent_answer() {
    use wire::AnswerStop::{EndTurn, MaxTokens};
    use ReportKind::{Blocked, Done, NeedsDecision};
    let reported = |kind, stop| {
        Told::Now(PeerTurnEnd::Answered {
            answer: "merged both".into(),
            stop,
            report: Some(kind),
        })
    };
    let failed = || TurnEnd::Failed("provider down".into());
    let reports = true;
    // The session reports, its turns, what the last told, and what it did
    // to the word the session owes.
    let cases = vec![
        (
            reports,
            vec![answered_turn(Some(Done), EndTurn)],
            reported(Done, EndTurn),
            WordChange::Reported,
        ),
        (
            reports,
            vec![answered_turn(Some(NeedsDecision), EndTurn)],
            reported(NeedsDecision, EndTurn),
            WordChange::Reported,
        ),
        (
            reports,
            vec![answered_turn(Some(Blocked), MaxTokens)],
            reported(Blocked, MaxTokens),
            WordChange::Reported,
        ),
        (
            reports,
            vec![answered_turn(None, EndTurn)],
            Told::Nothing,
            WordChange::Answered {
                answer: "merged both".into(),
            },
        ),
        (
            reports,
            vec![
                answered_turn(Some(Done), EndTurn),
                answered_turn(None, EndTurn),
            ],
            Told::Nothing,
            WordChange::Keep,
        ),
        (
            reports,
            vec![ended_as(failed(), None)],
            Told::Now(PeerTurnEnd::Failed {
                error: "provider down".into(),
            }),
            WordChange::Told,
        ),
        (
            reports,
            vec![ended_as(TurnEnd::Cancelled, Some(Done))],
            Told::Now(PeerTurnEnd::Cancelled),
            WordChange::Told,
        ),
        (
            reports,
            vec![
                ended_as(TurnEnd::Cancelled, Some(Done)),
                answered_turn(None, EndTurn),
            ],
            Told::Nothing,
            WordChange::Answered {
                answer: "merged both".into(),
            },
        ),
        (
            reports,
            vec![ended_as(TurnEnd::Interrupted, None)],
            Told::Now(PeerTurnEnd::Interrupted),
            WordChange::Told,
        ),
        (
            !reports,
            vec![answered_turn(None, EndTurn)],
            Told::Now(PeerTurnEnd::Answered {
                answer: "merged both".into(),
                stop: EndTurn,
                report: None,
            }),
            WordChange::Keep,
        ),
    ];

    for (reporting, turns, told, change) in cases {
        let name = format!("{told:?}");
        let starter_id = rho_sdk::SessionId::new();
        let report = reporting.then(|| StarterReport::to(starter_id.clone()));
        let wake = super::PeerWake::new(&rho_sdk::SessionId::new(), None, report.clone());
        let starter = PeerInbox::default();
        // Its starter's prompt owes the word; each turn starting resets it
        // to working until a report delivers it (see `jobs`).
        let mut word = reporting.then(|| OwedWord {
            starter: starter_id.clone(),
            word: Word::Working,
        });
        let mut last = None;
        for turn in turns {
            // Every turn of a reporting session owes its starter.
            *wake.owed() = Some(super::Owed {
                notice: starter.expect("child"),
                starter: starter_id.clone(),
                session: std::sync::Weak::new(),
            });
            if let (Some(report), Some(kind)) = (&report, turn.mark) {
                report.mark(kind);
            }
            let (told, changed) = wake.ended(&turn.end, turn.outcome.as_ref(), word.as_ref());
            if changed == WordChange::Reported {
                word = None;
            }
            last = Some((
                match told {
                    super::TurnTells::Tell(_, end) => Told::Now(end),
                    super::TurnTells::Untold { report } => Told::Later(report),
                    super::TurnTells::Silent => Told::Nothing,
                },
                changed,
            ));
        }

        assert_eq!(last, Some((told, change)), "{name}");
    }
}