marver 0.0.20

A TUI workspace for AI agent sessions: tmux orchestration, git worktree management, and repo control in one place.
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
//! Desktop notifications for state changes worth interrupting someone over.
//!
//! Two halves, deliberately separate: [`for_transition`] decides *whether* a
//! change is worth a notification and what it should say, and is pure; the
//! [`Notify`] backends decide *how* to deliver it. Tests exercise the policy
//! without putting banners on anyone's screen.
//!
//! **What does not notify** matters as much as what does. A task moving to
//! `running`, `committed`, or `cancelled` produces nothing: the user either
//! caused it or is already watching. Notifying on those would train them to
//! ignore the ones that matter.

use std::process::Command;

use crate::domain::{BlockedKind, Task, TaskState};

/// How much the notification should insist.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Urgency {
    Normal,
    /// Something broke and will not fix itself.
    Critical,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Notification {
    pub task_id: i64,
    pub title: String,
    pub body: String,
    pub urgency: Urgency,
}

/// Whether a task's new state is worth telling the user about, and what to say.
///
/// `task` is the task *after* the change, so its `blocked_kind` and
/// `failure_reason` are the current ones.
pub fn for_transition(task: &Task) -> Option<Notification> {
    let (title, body, urgency) = match task.state {
        TaskState::AwaitingReview => (
            "Ready for review".to_string(),
            task.title.clone(),
            Urgency::Normal,
        ),

        TaskState::Blocked => {
            let title = match task.blocked_kind {
                Some(BlockedKind::PermissionPrompt) => "Needs permission",
                Some(BlockedKind::Question) => "Needs an answer",
                Some(BlockedKind::Silence) => "Waiting for input",
                // The store forbids this, but a notification is not the place
                // to be strict about it.
                None => "Blocked",
            };
            let body = match &task.blocked_reason {
                Some(reason) => format!("{}: {}", task.title, reason),
                None => task.title.clone(),
            };
            (title.to_string(), body, Urgency::Normal)
        }

        TaskState::Failed => {
            let body = match &task.failure_reason {
                Some(reason) => format!("{}: {}", task.title, reason),
                None => task.title.clone(),
            };
            ("Task failed".to_string(), body, Urgency::Critical)
        }

        // Started by the scheduler, or finished by the user's own hand. Either
        // way they do not need telling. `paused` is the user's own hand too —
        // being told about a thing you just did is noise.
        TaskState::Queued
        | TaskState::Running
        | TaskState::Paused
        | TaskState::Committed
        | TaskState::Cancelled => {
            return None;
        }
    };

    Some(Notification {
        task_id: task.id,
        title: format!("marver — {title}"),
        body,
        urgency,
    })
}

/// Delivers a notification to wherever the user will see it.
pub trait Notify {
    fn send(&self, notification: &Notification) -> Result<(), String>;
}

/// The platform's notification mechanism.
#[derive(Debug, Clone, Default)]
pub struct SystemNotifier;

impl Notify for SystemNotifier {
    #[cfg(target_os = "macos")]
    fn send(&self, notification: &Notification) -> Result<(), String> {
        // Values are passed as `argv` rather than interpolated into the script.
        // A task title is arbitrary user text, and AppleScript built by string
        // concatenation would let a quote in a title break — or rewrite — the
        // script.
        run(
            "osascript",
            &[
                "-e",
                "on run argv",
                "-e",
                "display notification (item 1 of argv) with title (item 2 of argv)",
                "-e",
                "end run",
                &notification.body,
                &notification.title,
            ],
        )
    }

    #[cfg(not(target_os = "macos"))]
    fn send(&self, notification: &Notification) -> Result<(), String> {
        let urgency = match notification.urgency {
            Urgency::Normal => "normal",
            Urgency::Critical => "critical",
        };
        // `--` stops a title beginning with `-` being read as a flag.
        run(
            "notify-send",
            &["-u", urgency, "--", &notification.title, &notification.body],
        )
    }
}

fn run(program: &str, args: &[&str]) -> Result<(), String> {
    let output = Command::new(program)
        .args(args)
        .output()
        .map_err(|err| format!("could not run {program}: {err}"))?;
    if !output.status.success() {
        return Err(format!(
            "{program} failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }
    Ok(())
}

/// Discards everything. For runs where notifications are unwanted.
#[derive(Debug, Clone, Default)]
pub struct SilentNotifier;

impl Notify for SilentNotifier {
    fn send(&self, _: &Notification) -> Result<(), String> {
        Ok(())
    }
}

/// Applies the policy and delivers what it produces.
///
/// A delivery failure is returned rather than propagated as an error: a missing
/// `notify-send` should not fail the state change that triggered it.
pub struct Notifier<N: Notify> {
    backend: N,
    enabled: bool,
}

impl<N: Notify> Notifier<N> {
    pub fn new(backend: N) -> Self {
        Self {
            backend,
            enabled: true,
        }
    }

    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Notify about a task's current state, if it warrants one.
    ///
    /// Returns what was sent, or `None` when the state is not notifiable or
    /// notifications are switched off. A backend failure is reported as `Err`
    /// but is safe to ignore.
    pub fn announce(&self, task: &Task) -> Result<Option<Notification>, String> {
        if !self.enabled {
            return Ok(None);
        }
        let Some(notification) = for_transition(task) else {
            return Ok(None);
        };
        self.backend.send(&notification)?;
        Ok(Some(notification))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::{BlockedInfo, Store, Transition};
    use chrono::{DateTime, Utc};
    use std::cell::RefCell;
    use std::path::Path;

    fn at(secs: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(secs, 0).expect("valid timestamp")
    }

    /// Captures notifications instead of showing them.
    #[derive(Default)]
    struct Recorder {
        sent: RefCell<Vec<Notification>>,
        fail: bool,
    }

    impl Recorder {
        fn failing() -> Self {
            Self {
                sent: RefCell::new(Vec::new()),
                fail: true,
            }
        }
        fn sent(&self) -> Vec<Notification> {
            self.sent.borrow().clone()
        }
    }

    impl Notify for Recorder {
        fn send(&self, notification: &Notification) -> Result<(), String> {
            self.sent.borrow_mut().push(notification.clone());
            if self.fail {
                return Err("no notification daemon".to_string());
            }
            Ok(())
        }
    }

    /// A task walked to `state`, with whatever detail that state requires.
    fn task_in(state: TaskState) -> Task {
        let mut store = Store::open_in_memory().unwrap();
        let task = store
            .create_task(
                "Fix the auth flow",
                "p",
                Path::new("/tmp/tasks"),
                &[],
                at(0),
            )
            .unwrap();
        let id = task.id;

        if state != TaskState::Queued {
            store
                .transition(id, TaskState::Running, Transition::Plain, at(1))
                .unwrap();
        }
        match state {
            TaskState::Queued | TaskState::Running => {}
            TaskState::Blocked => {
                store
                    .transition(
                        id,
                        TaskState::Blocked,
                        Transition::Blocked(BlockedInfo::with_reason(
                            BlockedKind::PermissionPrompt,
                            "edit src/main.rs",
                        )),
                        at(2),
                    )
                    .unwrap();
            }
            TaskState::AwaitingReview => {
                store
                    .transition(id, TaskState::AwaitingReview, Transition::Plain, at(2))
                    .unwrap();
            }
            TaskState::Committed => {
                store
                    .transition(id, TaskState::AwaitingReview, Transition::Plain, at(2))
                    .unwrap();
                store
                    .transition(id, TaskState::Committed, Transition::Plain, at(3))
                    .unwrap();
            }
            TaskState::Failed => {
                store
                    .transition(
                        id,
                        TaskState::Failed,
                        Transition::Failed("the session died".to_string()),
                        at(2),
                    )
                    .unwrap();
            }
            TaskState::Cancelled => {
                store
                    .transition(id, TaskState::Cancelled, Transition::Plain, at(2))
                    .unwrap();
            }
            TaskState::Paused => {
                store
                    .transition(id, TaskState::Paused, Transition::Plain, at(2))
                    .unwrap();
            }
        }
        store.get_task(id).unwrap()
    }

    #[test]
    fn finishing_a_turn_asks_for_review() {
        let n = for_transition(&task_in(TaskState::AwaitingReview)).unwrap();
        assert_eq!(n.title, "marver — Ready for review");
        assert_eq!(n.body, "Fix the auth flow");
        assert_eq!(n.urgency, Urgency::Normal);
    }

    #[test]
    fn a_permission_prompt_says_so_and_names_the_reason() {
        let n = for_transition(&task_in(TaskState::Blocked)).unwrap();
        assert_eq!(n.title, "marver — Needs permission");
        assert_eq!(
            n.body, "Fix the auth flow: edit src/main.rs",
            "the reason is the whole point of the notification"
        );
    }

    #[test]
    fn each_blocked_kind_gets_its_own_wording() {
        let mut task = task_in(TaskState::Blocked);
        for (kind, expected) in [
            (BlockedKind::PermissionPrompt, "marver — Needs permission"),
            (BlockedKind::Question, "marver — Needs an answer"),
            (BlockedKind::Silence, "marver — Waiting for input"),
        ] {
            task.blocked_kind = Some(kind);
            assert_eq!(for_transition(&task).unwrap().title, expected);
        }
    }

    #[test]
    fn a_failure_is_critical_and_explains_itself() {
        let n = for_transition(&task_in(TaskState::Failed)).unwrap();
        assert_eq!(n.title, "marver — Task failed");
        assert_eq!(n.body, "Fix the auth flow: the session died");
        assert_eq!(n.urgency, Urgency::Critical);
    }

    #[test]
    fn states_the_user_caused_are_silent() {
        // Notifying on these would train the user to ignore the ones that
        // actually need them.
        for state in [
            TaskState::Queued,
            TaskState::Running,
            TaskState::Committed,
            TaskState::Cancelled,
        ] {
            assert_eq!(
                for_transition(&task_in(state)),
                None,
                "{state} should not notify"
            );
        }
    }

    #[test]
    fn exactly_three_states_notify() {
        let notifying: Vec<TaskState> = TaskState::ALL
            .iter()
            .copied()
            .filter(|s| for_transition(&task_in(*s)).is_some())
            .collect();
        assert_eq!(
            notifying,
            [
                TaskState::Blocked,
                TaskState::AwaitingReview,
                TaskState::Failed
            ]
        );
    }

    #[test]
    fn the_task_id_travels_with_the_notification() {
        let task = task_in(TaskState::AwaitingReview);
        assert_eq!(for_transition(&task).unwrap().task_id, task.id);
    }

    #[test]
    fn a_blocked_task_without_a_reason_still_notifies() {
        let mut task = task_in(TaskState::Blocked);
        task.blocked_reason = None;
        let n = for_transition(&task).unwrap();
        assert_eq!(n.body, "Fix the auth flow");
    }

    #[test]
    fn announce_delivers_only_notifiable_states() {
        let recorder = Recorder::default();
        let notifier = Notifier::new(recorder);

        assert!(
            notifier
                .announce(&task_in(TaskState::AwaitingReview))
                .unwrap()
                .is_some()
        );
        assert!(
            notifier
                .announce(&task_in(TaskState::Running))
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn disabling_suppresses_everything() {
        let notifier = Notifier::new(Recorder::default()).enabled(false);
        assert!(
            notifier
                .announce(&task_in(TaskState::Failed))
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn a_backend_failure_is_reported_not_swallowed() {
        let notifier = Notifier::new(Recorder::failing());
        let result = notifier.announce(&task_in(TaskState::Failed));
        assert!(result.is_err(), "the caller should be able to see this");
    }

    #[test]
    fn the_silent_backend_accepts_everything() {
        let notifier = Notifier::new(SilentNotifier);
        assert!(
            notifier
                .announce(&task_in(TaskState::Failed))
                .unwrap()
                .is_some(),
            "the policy still runs; only delivery is a no-op"
        );
    }

    /// Puts a real banner on the screen, so it is not part of a normal run.
    ///
    /// Run deliberately with:
    /// `cargo test -- --ignored sends_a_real_notification`
    ///
    /// Worth having: the pure tests cannot catch the body and title arguments
    /// being passed in the wrong order, which is invisible until a human looks
    /// at a banner.
    #[test]
    #[ignore = "shows a desktop notification"]
    fn sends_a_real_notification() {
        let notification = Notification {
            task_id: 1,
            title: "marver — Ready for review".to_string(),
            body: r#"TITLE GOES ABOVE, BODY BELOW — "quotes" and $(whoami)"#.to_string(),
            urgency: Urgency::Normal,
        };
        SystemNotifier.send(&notification).expect("should deliver");
    }

    #[test]
    fn awkward_titles_are_carried_verbatim() {
        // These reach the platform command as argv, never as script text, so
        // nothing here needs escaping — but the policy must not mangle them
        // either.
        let mut task = task_in(TaskState::AwaitingReview);
        task.title = r#"fix "quotes" & $(whoami) '; rm -rf /"#.to_string();
        let n = for_transition(&task).unwrap();
        assert_eq!(n.body, r#"fix "quotes" & $(whoami) '; rm -rf /"#);

        let notifier = Notifier::new(Recorder::default());
        notifier.announce(&task).unwrap();
        let delivered = notifier.backend.sent();
        assert_eq!(delivered.len(), 1);
        assert_eq!(
            delivered[0].body, n.body,
            "the backend must receive the text unmangled"
        );
    }
}