rho-coding-agent 3.12.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
//! Session marks over the socket (`rho/session/mark`), and the one the
//! daemon sets itself: a session is marked done when the last of the pull
//! requests linked to it merges, watched or not. For a session in a
//! worktree of its own, the pull request of its branch is one once a lookup
//! found it open, or merged when it opened after the worktree was added
//! (see `crate::app::pull_requests`' poller).
//!
//! A mark is saved with the session, beside its title (see
//! `crate::session`'s `mark`), so it needs no loaded session, and
//! `rho/session/list_detailed` reports it. A change tells a loaded session's
//! attached clients, as a rename does.
//!
//! Only the daemon reads a session's linked pull requests with no one
//! asking. The session is marked done at once, as the poll that read the
//! last merge ends ([`Sessions::mark_merged_done`]), which stands while
//! no turn follows; a daemon that stops between the read and the mark
//! never makes it. When the pull request was watched, a turn then tells
//! the agent of the merge, and the session is marked again as that turn
//! ends ([`turn_ended`]): its saves moved the session's `updated_at` past
//! the first mark, and clients read a session as done only while
//! `updated_at` is not after it. A prompt the person sends later moves
//! `updated_at` past the mark again, which clients read as active; the
//! mark stays, and the turn of such a prompt marks nothing, also when it
//! is the one to tell the agent news that waited. A prompt another
//! session's agent sends through session control, as a lead's "merged,
//! clean up" is, is not the person turning to the session: its turn marks
//! a finished session done again as it ends (see [`turn_ended`]).
//!
//! A merge that leaves another linked pull request unmerged, open or
//! closed, marks nothing either time: the session's work is not over, and
//! a session marked done by mistake is hidden, which is worse than one
//! left listed. The one exception is a pull request the daemon linked for
//! the session's branch that closed without merging, which the branch's
//! next pull request replaces. Neither does a pull request first read after
//! it merged, as one linked for reference, but for the pull request of the
//! branch of the session's own worktree that opened after the worktree was
//! added: the session's own work, which may open and merge while no client
//! lists the session to look its branch up. Nor does a merge while a job the session
//! started is still queued, running, or waiting for input, as a session
//! it started for a pull request not yet opened, or one it starts in the
//! turn that tells it of the merge: that work is the session's too.
//! Nothing marks the session when that job ends; it stays listed until
//! the person or a later merge settles it. Past that, [`after_merge`] is
//! the whole rule.

use rho_protocol::{self as wire, ErrorCode, RpcError};
use rho_sdk::SessionId;

use super::{
    pull_requests::worktree_of,
    reopen::{not_found, parse_session},
    store::store_blocking,
    LoadedSession, Sessions,
};
use crate::{
    app::{
        pull_requests::{unix_ms, AllMerged, PullRequestInbox, PullRequests},
        session_runtime::SessionRuntime,
    },
    session::{MarkChange, NewMark, Session as StoredSession, SessionMark},
};

impl Sessions {
    /// Saves or clears a session's mark, then tells the clients attached
    /// to it, if the daemon has it loaded.
    pub(in crate::app::daemon_host) async fn mark(
        &self,
        params: wire::SessionMarkParams,
    ) -> Result<wire::SessionMarkResponse, RpcError> {
        let id = parse_session(&params.session)?;
        let asked = params.mark.map(new_mark).transpose()?;
        let change = self
            .change_saved_mark(&id, move |_, now| asked.map(|mark| mark.at(now)))
            .await?
            .ok_or_else(|| not_found(&id))?;
        self.tell_mark(&id, change);
        Ok(wire::SessionMarkResponse::new(
            change.after.map(mark_to_wire),
        ))
    }

    /// Marks done each session whose linked pull requests have all merged,
    /// as [`after_merge`] says, until the daemon starts stopping: a merge
    /// it read before that is marked first. Not a session that started a
    /// job still in progress, which nothing marks once that job ends.
    pub(super) async fn mark_merged_done(&self) {
        let Some(mut merged) = self.pull_requests.service().take_all_merged() else {
            return;
        };
        loop {
            let AllMerged { session, at } = tokio::select! {
                biased;
                Some(merged) = merged.recv() => merged,
                () = self.stopping.cancelled() => return,
                else => return,
            };
            if self.jobs.session_started_in_progress(&session) {
                continue;
            }
            let merged_at = at / 1000;
            let change = self
                .change_saved_mark(&session, move |mark, now| after_merge(mark, merged_at, now));
            match change.await {
                Ok(Some(change)) => self.tell_mark(&session, change),
                // Deleted since, or it never saved a turn.
                Ok(None) => {}
                Err(error) => tracing::warn!(
                    %session,
                    %error,
                    "could not mark a session done for its merged pull request"
                ),
            }
        }
    }

    /// Replaces the mark of the session saved under `id`, loaded or not,
    /// with what `change` makes of the one it has and of the time now on
    /// the session store's clock; `None` when nothing is saved under `id`.
    async fn change_saved_mark(
        &self,
        id: &SessionId,
        change: impl FnOnce(Option<SessionMark>, u64) -> Option<SessionMark> + Send + 'static,
    ) -> Result<Option<MarkChange>, RpcError> {
        let (rho_home, id) = (self.rho_home.clone(), id.clone());
        store_blocking("save the session's mark", move || {
            StoredSession::change_mark_of(&rho_home, id.as_str(), change)
        })
        .await
    }

    /// Tells the clients attached to session `id`, if it is loaded, the
    /// mark `change` left, if it changed it.
    fn tell_mark(&self, id: &SessionId, change: MarkChange) {
        let loaded = self.loaded().get(id).cloned();
        if let Some(session) = loaded {
            tell_mark(&session, change);
        }
    }
}

/// Who sent a prompt, which decides whether its turn's end marks the
/// session (see [`turn_ended`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Sender {
    /// A prompt with no grant that limits it: the person's, through a
    /// client, or an outside agent's, which the daemon cannot tell apart.
    Person,
    /// Another session's agent through session control, as a lead's
    /// `sessions` tool does: a prompt whose grant limits it (see `grant`).
    SessionControl,
}

/// What started a turn, which decides whether its end marks the session
/// (see [`turn_ended`]).
#[derive(Clone, Copy, Debug)]
pub(super) enum TurnOrigin {
    /// The daemon, to tell the agent what waited for it.
    Daemon,
    /// A [`Sender::Person`] prompt sent at `at`, in unix milliseconds.
    Person { at: u64 },
    /// A prompt sent through session control to a session whose
    /// `updated_at` was `done_since` (unix seconds) as its turn began: a
    /// done mark at or after it read as finished then, or came since.
    SessionControl { done_since: u64 },
}

impl TurnOrigin {
    /// The origin of the turn of a prompt `sender` sent at `at` (unix
    /// milliseconds), as it begins on `runtime`, before the prompt saves
    /// anything. For session control, the session's `updated_at` then; when
    /// it cannot be read, which is logged, the prompt's time, so only a
    /// mark made since counts.
    pub(super) fn prompt(
        session: &LoadedSession,
        runtime: &SessionRuntime,
        sender: Sender,
        at: u64,
    ) -> Self {
        match sender {
            Sender::Person => Self::Person { at },
            Sender::SessionControl => {
                let updated_at = runtime.listed_updated_at().unwrap_or_else(|error| {
                    tracing::warn!(
                        session = %session.id,
                        error = format!("{error:#}"),
                        "could not read when a session was last active as session control prompted it"
                    );
                    None
                });
                Self::SessionControl {
                    done_since: updated_at.unwrap_or(at / 1000),
                }
            }
        }
    }

    /// How the end of this turn marks the session again, given when rho
    /// found the merge the turn `told` the agent of, if it told one (unix
    /// milliseconds); `None` for not at all. See [`turn_ended`].
    fn remark(self, told: Option<u64>) -> Option<Remark> {
        let after_merge = |merged_at: u64| Remark::AfterMerge {
            merged_at: merged_at / 1000,
        };
        match (self, told) {
            // The merge came while the prompt's turn ran.
            (Self::Person { at }, Some(merged_at)) if at <= merged_at => {
                Some(after_merge(merged_at))
            }
            (Self::Person { .. }, _) | (Self::Daemon, None) => None,
            (Self::Daemon | Self::SessionControl { .. }, Some(merged_at)) => {
                Some(after_merge(merged_at))
            }
            (Self::SessionControl { done_since }, None) => Some(Remark::StillDone { done_since }),
        }
    }
}

/// Call as `session`'s turn on `runtime`, which `origin` started, ended,
/// after its last save and before its end is told. A turn that told the
/// agent a watched pull request merged, and leaves the session with every
/// linked pull request merged, marks it done again, as [`after_merge`]
/// says: at or after the `updated_at` the turn leaves, so clients read the
/// session as done once the turn is over. Not the turn of a person's
/// prompt sent since rho found the merge, as when the news waited for one:
/// the person turned to the session again, so it stays active.
///
/// A prompt sent through session control is not the person turning to the
/// session again, as a lead telling a child its pull request merged and to
/// clean up is not: its turn keeps a session finished that read finished as
/// it began, or that was marked done while it ran. For such a session
/// alone, as its mark says now, this returns a [`StillDone`] to settle once
/// the turn's end is told. Neither marks a session that leaves a job it
/// started still in progress, as one the turn started on hearing of the
/// merge; nothing marks the session once that job ends.
pub(super) fn turn_ended(
    session: &LoadedSession,
    runtime: &SessionRuntime,
    origin: TurnOrigin,
) -> Option<StillDone> {
    let told = runtime
        .tools()
        .pull_requests()
        .and_then(PullRequestInbox::take_merge_told);
    let remark = origin.remark(told)?;
    if session.jobs.session_started_in_progress(&session.id) {
        return None;
    }
    match remark {
        Remark::AfterMerge { .. } => {
            remark_saved(session, runtime, remark);
            None
        }
        Remark::StillDone { done_since } => {
            let mark = runtime.listed_mark().unwrap_or_else(|error| {
                tracing::warn!(
                    session = %session.id,
                    error = format!("{error:#}"),
                    "could not read a session's mark as its turn ended"
                );
                None
            });
            match mark {
                Some(SessionMark::Done { at }) if at >= done_since => {
                    Some(StillDone { done_since })
                }
                _ => None,
            }
        }
    }
}

/// A session-control turn's end that found the session still finished,
/// which [`StillDone::settle`] marks done again once that end is told.
pub(super) struct StillDone {
    done_since: u64,
}

impl StillDone {
    /// Marks `session` on `runtime` done again ([`Remark::StillDone`])
    /// while its linked pull requests are all still merged
    /// ([`work_still_merged`]): a lead that gives a finished worker new work
    /// that opens a pull request leaves it active until that one merges.
    /// Call after the turn's end is told, so the lookup that takes delays
    /// no client, and before the session's next turn can start, so no
    /// prompt sent meanwhile is marked done.
    pub(super) async fn settle(
        self,
        session: &LoadedSession,
        runtime: &SessionRuntime,
        pull_requests: &PullRequests,
    ) {
        if work_still_merged(session, pull_requests).await {
            let remark = Remark::StillDone {
                done_since: self.done_since,
            };
            remark_saved(session, runtime, remark);
        }
    }
}

/// Marks the saved session again as `remark` says, telling its clients.
fn remark_saved(session: &LoadedSession, runtime: &SessionRuntime, remark: Remark) {
    match runtime.change_mark(|mark, now| remark.mark(mark, now)) {
        Ok(Some(change)) => tell_mark(session, change),
        // It keeps no file.
        Ok(None) => {}
        Err(error) => tracing::warn!(
            session = %session.id,
            error = format!("{error:#}"),
            "could not mark a session done again as its turn ended"
        ),
    }
}

/// Whether `session`'s linked pull requests, as the daemon's
/// `pull_requests` keep them, are all still merged as a session-control
/// turn ends, the condition a merge marks it done on ([`after_merge`]):
/// first, for a session in a worktree of its own, a lookup of its branch
/// now links a pull request the turn opened there, as a worker's `gh pr
/// create` does, which no client may have listed it for. Read from the
/// service, not the session's tools: a session a lead opens through session
/// control has no inbox there, as its client asked for no idle wake.
async fn work_still_merged(session: &LoadedSession, pull_requests: &PullRequests) -> bool {
    let inbox = pull_requests.inbox(&session.id, &session.workspace);
    let own = session
        .jobs
        .session_worktrees(std::slice::from_ref(&session.id))
        .pop()
        .flatten();
    let worktree = worktree_of(&session.workspace, own.as_ref());
    inbox.look_up_own_branch(worktree, unix_ms()).await;
    inbox.all_merged()
}

/// How [`turn_ended`] marks the session again; every time is unix seconds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Remark {
    /// The turn told of a merge rho found at `merged_at`: [`after_merge`].
    AfterMerge { merged_at: u64 },
    /// The turn of a session-control prompt, as [`TurnOrigin::SessionControl`]
    /// says, that left the session's linked pull requests all merged: a
    /// session still marked done at or after `done_since`, which read as
    /// finished as the turn began or was marked done since, as when rho
    /// found its merge while the turn ran, is done as of the turn's end.
    /// Any other mark stands, a pin or a restore the person made while the
    /// turn ran included.
    StillDone { done_since: u64 },
}

impl Remark {
    /// The mark a session with `mark` gets at `now`.
    fn mark(self, mark: Option<SessionMark>, now: u64) -> Option<SessionMark> {
        match (self, mark) {
            (Self::AfterMerge { merged_at }, _) => after_merge(mark, merged_at, now),
            (Self::StillDone { done_since }, Some(SessionMark::Done { at }))
                if at >= done_since =>
            {
                Some(SessionMark::Done { at: now })
            }
            (Self::StillDone { .. }, _) => mark,
        }
    }
}

/// The mark of a session whose last unmerged pull request rho found merged at
/// `merged_at`, as of `now`, both unix seconds, given the `mark` it has:
/// done as of `now`, unless the person set it apart. A pinned session
/// stays pinned, and a snoozed one snoozed until its snooze ends. One the
/// person put back on the active list since the merge stays there, so the
/// second marking, at the end of the turn that tells the agent, does not
/// undo a restore made while that turn ran.
fn after_merge(mark: Option<SessionMark>, merged_at: u64, now: u64) -> Option<SessionMark> {
    match mark {
        Some(SessionMark::Pinned { .. }) => mark,
        Some(SessionMark::Snoozed { until }) if until > now => mark,
        Some(SessionMark::Kept { at }) if at >= merged_at => mark,
        None
        | Some(SessionMark::Done { .. } | SessionMark::Snoozed { .. } | SessionMark::Kept { .. }) => {
            Some(SessionMark::Done { at: now })
        }
    }
}

/// Tells `session`'s attached clients the mark `change` left, if it
/// changed it.
fn tell_mark(session: &LoadedSession, change: MarkChange) {
    if change.before != change.after {
        session.feed.publish([wire::SessionEvent::MarkChanged {
            mark: change.after.map(mark_to_wire),
        }]);
    }
}

/// The mark `rho/session/mark` asks for, which the store stamps.
fn new_mark(mark: wire::NewSessionMark) -> Result<NewMark, RpcError> {
    match mark {
        wire::NewSessionMark::Done => Ok(NewMark::Done),
        wire::NewSessionMark::Snoozed { until } => Ok(NewMark::Snoozed { until }),
        wire::NewSessionMark::Pinned => Ok(NewMark::Pinned),
        wire::NewSessionMark::Kept => Ok(NewMark::Kept),
        // Unreachable: this build's protocol crate decoded it, so it knows
        // every kind; the enum is non-exhaustive for clients.
        _ => Err(RpcError::new(
            ErrorCode::InvalidParams,
            "this daemon does not know that kind of mark",
        )),
    }
}

/// `mark` as `rho/session/list_detailed` and `mark_changed` send it.
pub(super) fn mark_to_wire(mark: SessionMark) -> wire::SessionMark {
    match mark {
        SessionMark::Done { at } => wire::SessionMark::Done { at },
        SessionMark::Snoozed { until } => wire::SessionMark::Snoozed { until },
        SessionMark::Pinned { at } => wire::SessionMark::Pinned { at },
        SessionMark::Kept { at } => wire::SessionMark::Kept { at },
    }
}

#[cfg(test)]
#[path = "marks_tests.rs"]
mod tests;