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
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,
    },
    finished, Remark, Said, TurnClose, TurnOrigin,
};
use crate::{
    app::{
        daemon_host::{
            jobs::{JobEvent, JobRecord, JobRegistry, JobStore, TurnEnd},
            wire::session_to_wire,
        },
        pull_requests::{unix_ms, LinkOrigin, 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, _)| finished(*mark, MERGED_AT, NOW))
        .collect();
    assert_eq!(marked, cases.map(|(_, after)| after));
}

// Covers: which turn ends mark a session done again, and how. A turn that
// told of a merge does, as `finished` says, unless the person prompted it
// after the merge; so does a session-control prompt's turn that told of
// one. A session-control prompt's turn that told of none keeps a session
// done that read as finished as it began, or was marked done since, and
// leaves any other mark as it is. A person's turn or the daemon's that told
// of none marks nothing.
// For a session that reports to its starter, what the turn told the
// starter comes first: `done` marks it done, as `finished` says, whoever
// started the turn and whatever merge it told of; anything else told, a
// report of another kind or a failure, clears a done mark and leaves any
// other; a turn that told nothing keeps a finished session finished, as a
// session-control prompt's does, also when the daemon started it, but not
// when the person prompted it; a daemon turn of any other session can't.
// What the turn told is its report if it answered; any other end of a
// turn that began, but the daemon's stop, is told as it is; a turn that
// never began told nothing. Owner: daemon session marks.
#[test]
fn a_turn_ends_by_marking_again_as_its_origin_and_news_say() {
    use crate::app::starter_report::ReportKind;
    use SessionMark::{Done, Kept, Pinned, Snoozed};
    const MERGED_MS: u64 = 2_000_000;
    let after_merge = Some(Remark::AfterMerge { merged_at: 2_000 });
    let still_done = Some(Remark::StillDone { done_since: 500 });
    let lead = TurnOrigin::SessionControl { done_since: 500 };
    let daemon = TurnOrigin::Daemon {
        done_since: Some(500),
    };
    // Of a session that does not report to its starter.
    let daemon_plain = TurnOrigin::Daemon { done_since: None };
    let person = TurnOrigin::Person { at: 0 };
    let done = Some(Said::Done { at: 2_100 });
    let reported_done = Some(Remark::ReportedDone { at: 2_100 });
    let remarks = [
        (
            TurnOrigin::Person { at: MERGED_MS },
            Some(MERGED_MS),
            None,
            after_merge,
        ),
        (
            TurnOrigin::Person { at: MERGED_MS + 1 },
            Some(MERGED_MS),
            None,
            None,
        ),
        (person, None, None, None),
        (daemon_plain, Some(MERGED_MS), None, after_merge),
        (daemon_plain, None, None, None),
        (lead, Some(MERGED_MS), None, after_merge),
        (lead, None, None, still_done),
        // A session that reports to its starter.
        (person, None, done, reported_done),
        (daemon, Some(MERGED_MS), done, reported_done),
        (lead, None, Some(Said::Other), Some(Remark::Reopened)),
        (
            daemon,
            Some(MERGED_MS),
            Some(Said::Other),
            Some(Remark::Reopened),
        ),
        (daemon, None, Some(Said::Nothing), still_done),
        (lead, None, Some(Said::Nothing), still_done),
        (daemon, Some(MERGED_MS), Some(Said::Nothing), after_merge),
        (person, None, Some(Said::Nothing), None),
    ];
    let got: Vec<_> = remarks
        .iter()
        .map(|(origin, told, said, _)| origin.remark(*told, *said))
        .collect();
    assert_eq!(got, remarks.map(|(_, _, _, remark)| remark));

    const NOW: u64 = 2_200;
    let still_done = Remark::StillDone { done_since: 500 };
    let reported_done = Remark::ReportedDone { at: 2_100 };
    let marks = [
        (still_done, Some(Done { at: 500 }), Some(Done { at: NOW })),
        (still_done, Some(Done { at: 499 }), Some(Done { at: 499 })),
        (still_done, Some(Kept { at: 600 }), Some(Kept { at: 600 })),
        (
            still_done,
            Some(Pinned { at: 600 }),
            Some(Pinned { at: 600 }),
        ),
        (still_done, None, None),
        (reported_done, None, Some(Done { at: NOW })),
        (Remark::Reopened, Some(Done { at: 2_000 }), None),
        (
            Remark::Reopened,
            Some(Pinned { at: 600 }),
            Some(Pinned { at: 600 }),
        ),
        (
            Remark::Reopened,
            Some(Snoozed { until: NOW + 1 }),
            Some(Snoozed { until: NOW + 1 }),
        ),
        (Remark::Reopened, None, None),
    ];
    let marked: Vec<_> = marks
        .iter()
        .map(|(remark, mark, _)| remark.mark(*mark, NOW))
        .collect();
    assert_eq!(marked, marks.map(|(_, _, after)| after));

    let answered = wire::TurnOutcome::Answered {
        text: "the report".into(),
        stop: wire::AnswerStop::EndTurn,
    };
    let cancelled = wire::TurnOutcome::Cancelled;
    let (done_report, other) = (Some(ReportKind::Done), Some(Said::Other));
    let said = [
        (TurnEnd::Completed, Some(&answered), done_report, true, done),
        (
            TurnEnd::Completed,
            Some(&answered),
            None,
            true,
            Some(Said::Nothing),
        ),
        (
            TurnEnd::Completed,
            Some(&answered),
            Some(ReportKind::NeedsDecision),
            true,
            other,
        ),
        (
            TurnEnd::Failed("boom".into()),
            None,
            done_report,
            true,
            other,
        ),
        (TurnEnd::Cancelled, Some(&cancelled), None, true, other),
        (
            TurnEnd::Cancelled,
            Some(&cancelled),
            None,
            false,
            Some(Said::Nothing),
        ),
        (
            TurnEnd::Interrupted,
            None,
            done_report,
            true,
            Some(Said::Nothing),
        ),
    ];
    let got: Vec<_> = said
        .iter()
        .map(|(end, outcome, report, began, _)| {
            let close = TurnClose {
                end,
                outcome: *outcome,
                began: *began,
            };
            Some(Said::of(&close, *report, 2_100))
        })
        .collect();
    assert_eq!(got, said.map(|(_, _, _, _, said)| said));
}

/// 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 answers = [NOTED].map(|text| {
            ScriptedTurn::completed(ModelResponse::Assistant(vec![ContentBlock::Text(
                text.into(),
            )]))
        });
        Self::answering(told, load, answers).await
    }

    /// As [`Self::prompted`], its agent answering the requests after its
    /// first prompt's with `answers`.
    async fn answering(
        told: Told,
        load: Load,
        answers: impl IntoIterator<Item = ScriptedTurn>,
    ) -> 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 hello = ScriptedTurn::completed(ModelResponse::Assistant(vec![ContentBlock::Text(
            "hello".into(),
        )]));
        let answers: Vec<ScriptedTurn> = std::iter::once(hello).chain(answers).collect();
        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) {
        self.prompt_with(/*grant*/ None).await;
    }

    /// The session is prompted with `grant`, as session control names one
    /// and a person's client does not, and the turn runs to its end.
    async fn prompt_with(&self, grant: Option<wire::SessionGrant>) {
        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,
        });
        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: through the daemon, a finished session, as one marked done when
// its pull request merged, stays finished through the turn of a prompt
// another session's agent sends through session control, as a lead's
// "merged, clean up" is: once its end is told, the daemon marks the session
// done again, at or after the `updated_at` its saves left, and tells its
// clients, also after a lookup of its own worktree's branch finds only the
// merged pull request. A person's prompt is the person turning to it again:
// its turn leaves the mark as it was, which its saves outdate. Nor does
// session control mark again a session whose mark a later save outdated, as
// one the person turned back to, or a worker the lead gave new work that
// opened a pull request on its branch: that lookup links it, and the worker
// stays active until it merges, which settles it though no tick read it
// open. An active worker's lead turn, which no end could mark again, asks
// the forge nothing. The worker rows open as a lead's `sessions new` does,
// with no idle wake, so their tools hold no inbox. A daemon that reads every
// prompt as the person's leaves the first active; one that marks again
// whatever the session read as hides the third; one that marks again
// without the lookup hides the fifth, and one that keeps what the lookup
// read unread leaves it active once its pull request merged; one that reads
// the links through the session's tools leaves the fourth active; one that
// looks the branch up on every lead turn reads the forge for the last.
// Owner: daemon session marks.
#[tokio::test]
async fn a_session_control_prompt_keeps_a_finished_session_finished() {
    /// What the turn's end did to the session's done mark.
    #[derive(Debug, PartialEq)]
    enum Mark {
        /// Marked done again, after the turn's saves, and told after its
        /// end.
        Again,
        /// Left as it was, and nothing told.
        Left,
    }
    /// What the branch of the session's own worktree has as the turn ends.
    enum Worktree {
        /// It works in a checkout of no branch.
        None,
        /// Its branch has the merged pull request.
        Merged,
        /// Its branch has a new pull request, open.
        Retasked,
    }
    const LINKED_AT: u64 = 1_700_000_000_000;
    const NEW_PULL_REQUEST: &str = "acme/widgets#13";
    let lead = wire::SessionGrant {
        depth: 1,
        access: wire::GrantAccess::Write,
        workspaces: wire::GrantWorkspaces::Any,
    };
    // A mark stamped ahead of every save reads finished, and one made again
    // as the turn ends differs from it; one a second before the last save
    // reads active.
    let (finished, active) = (3600, -1);
    let cases = [
        (
            "session control, finished",
            Some(lead.clone()),
            finished,
            Worktree::None,
        ),
        ("person, finished", None, finished, Worktree::None),
        (
            "session control, active",
            Some(lead.clone()),
            active,
            Worktree::None,
        ),
        (
            "session control, own worktree",
            Some(lead.clone()),
            finished,
            Worktree::Merged,
        ),
        (
            "session control, re-tasked",
            Some(lead.clone()),
            finished,
            Worktree::Retasked,
        ),
        (
            "session control, active worker",
            Some(lead),
            active,
            Worktree::Retasked,
        ),
    ];
    let mut seen = Vec::new();
    for (name, grant, offset, worktree) in cases {
        let load = match worktree {
            Worktree::None => Load::Waking,
            Worktree::Merged | Worktree::Retasked => Load::InOwnWorktree,
        };
        let mut fixture = Fixture::prompted(Told::AtTheNextPrompt, load).await;
        // Its pull request merged, as the poll read it.
        fixture.forge.set_open(TEST_PULL_REQUEST, &[], &[]);
        fixture
            .inbox()
            .link(TEST_PULL_REQUEST, LinkOrigin::Agent, LINKED_AT)
            .await
            .unwrap();
        fixture.forge.set_merged(TEST_PULL_REQUEST);
        let service = fixture.sessions.pull_requests.service();
        service.tick(LINKED_AT + 60_000).await;
        match worktree {
            Worktree::None => {}
            Worktree::Merged | Worktree::Retasked => {
                let root = fixture.root.path();
                git(root, &["init", "--quiet", "--initial-branch=feature"]);
                git(
                    root,
                    &["remote", "add", "origin", "git@github.com:acme/widgets.git"],
                );
                fixture.forge.set_branch(TEST_PULL_REQUEST, "feature");
            }
        }
        if let Worktree::Retasked = worktree {
            fixture.forge.set_open(NEW_PULL_REQUEST, &["ci"], &[]);
            fixture.forge.set_branch(NEW_PULL_REQUEST, "feature");
        }
        let done_at = fixture.listed().updated_at.saturating_add_signed(offset);
        let done = Some(SessionMark::Done { at: done_at });
        fixture
            .sessions
            .change_saved_mark(&fixture.session.id, move |_, _| done)
            .await
            .unwrap();
        fixture.told_before = fixture.session.feed.buffered_for_tests().len();
        fixture.forge.take_asked();

        fixture.prompt_with(grant).await;

        let looked_up = (fixture.forge.take_asked().iter()).any(|plan| !plan.branches.is_empty());

        let listed = fixture.listed();
        let heard = fixture.heard();
        let position = |find: fn(&Heard) -> bool| heard.iter().position(find);
        let told =
            position(|heard| matches!(heard, Heard::Mark(Some(wire::SessionMark::Done { .. }))));
        let ended = position(|heard| matches!(heard, Heard::Answered(_) | Heard::Unanswered(_)));
        let told_after_end = told.zip(ended).is_some_and(|(told, ended)| told > ended);
        let told = told.is_some();
        let mark = match listed.mark {
            Some(SessionMark::Done { at })
                if at != done_at && at >= listed.updated_at && told_after_end =>
            {
                Some(Mark::Again)
            }
            mark if mark == done && !told => Some(Mark::Left),
            _ => None,
        };
        let linked: Vec<u32> = fixture
            .inbox()
            .list(LINKED_AT)
            .into_iter()
            .map(|listed| listed.pr.number)
            .collect();
        // The re-tasked worker's new pull request merges, as a tick reads.
        let settled_later = match worktree {
            Worktree::Retasked if offset == finished => {
                fixture.forge.set_merged(NEW_PULL_REQUEST);
                // Past the linked cadence since the turn's end read it.
                service.tick(unix_ms() + 6 * 60 * 1000).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 = fixture.listed();
                // Marked anew, not the mark it was left with.
                let marked = |at: u64| at != done_at && at >= listed.updated_at;
                Some(matches!(listed.mark, Some(SessionMark::Done { at }) if marked(at)))
            }
            Worktree::None | Worktree::Merged | Worktree::Retasked => None,
        };
        seen.push((name, mark, looked_up, linked, settled_later));
    }
    assert_eq!(
        seen,
        [
            (
                "session control, finished",
                Some(Mark::Again),
                false,
                vec![12],
                None
            ),
            ("person, finished", Some(Mark::Left), false, vec![12], None),
            (
                "session control, active",
                Some(Mark::Left),
                false,
                vec![12],
                None
            ),
            (
                "session control, own worktree",
                Some(Mark::Again),
                true,
                vec![12],
                None
            ),
            (
                "session control, re-tasked",
                Some(Mark::Left),
                true,
                vec![12, 13],
                Some(true)
            ),
            (
                "session control, active worker",
                Some(Mark::Left),
                false,
                vec![12],
                None
            ),
        ]
    );
}

// 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);
}

#[path = "marks_reports_tests.rs"]
mod reports;