shep 0.25.2

The shep binary: a process manager that keeps a flock of long-running processes alive on macOS, Linux and Windows, with logs, watch and cron restarts, and webhook alerts
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
use super::super::*;

impl App {
    /// The operator's `Enter` on the settings screen. On a section it folds;
    /// on a typed key or a map entry with nothing pending it opens
    /// [`Pending::Typing`] and switches [`InputMode::Text`] on; on an armed
    /// candidate it sends and moves to [`Pending::Sent`].
    ///
    /// Both acting cases go through [`Self::authorize_write`], the editor
    /// included, so the refusal arrives before a whole socket path is typed.
    pub(super) fn confirm_setting(&mut self) -> Effect {
        let Some(settings) = self.settings_mut() else {
            return Effect::None;
        };
        if settings.pending.is_none() && settings.toggle_fold() {
            return Effect::None;
        }
        if settings.pending.is_none() && settings.env_editor_at_cursor().is_some() {
            self.open_env_editor();
            return Effect::None;
        }
        let opens_editor = settings.pending.is_none() && settings.editor_at_cursor().is_some();
        if !opens_editor && !settings.is_armed() {
            return Effect::None;
        }
        let Some(authority) = self.authorize_write() else {
            return Effect::None;
        };
        let Some(settings) = self.settings_mut() else {
            return Effect::None;
        };
        if opens_editor {
            let Some((target, seed)) = settings.editor_at_cursor() else {
                return Effect::None;
            };
            let buffer = TextBox::from(seed.as_str());
            settings.pending = Some(Pending::Typing { target, buffer });
            self.mode = InputMode::Text;
            return Effect::None;
        }
        // Minted before the borrow below, and spent on either arm that
        // sends: past the gate above, the pending edit is armed.
        let ticket = self.take_write_ticket();
        let Some(settings) = self.settings_mut() else {
            return Effect::None;
        };
        match settings.pending.take() {
            Some(Pending::Armed { edit, text, .. }) => {
                settings.pending = Some(Pending::Sent { text, ticket });
                Effect::WriteSetting {
                    edit,
                    ticket,
                    authority,
                }
            }
            Some(Pending::DogArmed { edit, text, .. }) => {
                settings.pending = Some(Pending::Sent { text, ticket });
                Effect::WriteDog {
                    edit,
                    ticket,
                    authority,
                }
            }
            Some(Pending::DogTuneArmed { tune, text, .. }) => {
                settings.pending = Some(Pending::Sent { text, ticket });
                Effect::WriteDogTune {
                    tune,
                    ticket,
                    authority,
                }
            }
            // Not an `Effect`: a dog's section goes to the shepherd, which is
            // the only thing that can write `dogs.toml` for a dog, so this is
            // the same `Sent::SetDogSection` a dog pane's close raises.
            Some(Pending::DogSectionArmed {
                name, toml, text, ..
            }) => {
                settings.pending = Some(Pending::Sent { text, ticket });
                Effect::Send(Sent::SetDogSection {
                    name,
                    ticket,
                    toml,
                    authority,
                })
            }
            // Not a socket request: the entry lives in `shep.toml`, which the
            // event loop writes, as it does for a dog pane's close.
            Some(Pending::DogEnvArmed {
                name, edits, text, ..
            }) => {
                settings.pending = Some(Pending::Sent { text, ticket });
                Effect::WriteDogEnv {
                    write: DogEnvWrite {
                        name,
                        edits,
                        ticket,
                        authority,
                    },
                    then: Vec::new(),
                }
            }
            other => {
                settings.pending = other;
                Effect::None
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lookout::view::fixtures;

    #[test]
    fn the_daemon_confirm_names_both_layers_lookout_cannot_see() {
        let mut app = fixtures::app_in_settings_on("daemon.log_level");
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let text = app.settings().unwrap().pending().unwrap().text.to_string();
        assert!(text.contains("shep daemon reload"), "got: {text}");
        assert!(text.contains("SHEP_LOG_LEVEL"), "got: {text}");
        assert!(text.contains("--log-level"), "got: {text}");
    }

    #[test]
    fn the_whistle_confirm_names_a_whistle_restart_and_not_a_reload() {
        let mut app = fixtures::app_in_settings_on("whistle.allow_control");
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let text = app.settings().unwrap().pending().unwrap().text.to_string();
        assert!(text.contains("shep whistle restarted"), "got: {text}");
        assert!(
            !text.contains("daemon reload"),
            "a whistle key needs no reload: {text}"
        );
    }

    #[test]
    fn the_style_confirm_promises_nothing_beyond_the_next_command() {
        let mut app = fixtures::app_in_settings_on("style.level");
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let text = app.settings().unwrap().pending().unwrap().text.to_string();
        assert!(text.contains("the next command reads it"), "got: {text}");
    }

    /// `style::resolve` is flag over env over config, so with `$SHEP_STYLE` or
    /// `--style` in play the write lands and nothing changes.
    #[test]
    fn a_shadowed_style_confirm_names_the_layer_that_keeps_winning() {
        for (source, layer) in [
            (StyleSource::Env, "$SHEP_STYLE"),
            (StyleSource::Flag, "--style"),
        ] {
            let mut app = fixtures::app_in_settings_with_shadowed_style(source);
            let _ = app.update(Msg::Key(KeyPress::Cycle));
            let text = app.settings().unwrap().pending().unwrap().text.to_string();
            assert!(text.contains(layer), "{source} must name itself: {text}");
            assert!(
                text.contains("keeps winning"),
                "{source} must say what it does: {text}"
            );
            assert!(
                !text.contains("the next command reads it"),
                "{source}: the next command reads {source}, not the file: {text}"
            );
        }
    }

    #[test]
    fn enter_sends_the_armed_edit() {
        let mut app = fixtures::app_in_settings_on("daemon.log_level");
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let effect = app.update(Msg::Key(KeyPress::Confirm));
        let Effect::WriteSetting { edit, .. } = effect else {
            panic!("Enter must send");
        };
        assert!(matches!(edit, SettingEdit::Set { .. }));
        assert_eq!(edit.key(), "daemon.log_level");
        assert!(app.settings().unwrap().pending().unwrap().sent);
    }

    #[test]
    fn a_written_edit_updates_the_row_and_its_source() {
        let mut app = fixtures::app_in_settings_on("daemon.log_level");
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let Effect::WriteSetting { edit, ticket, .. } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send");
        };
        let SettingEdit::Set {
            value: candidate, ..
        } = edit.clone()
        else {
            panic!("cycling only ever arms Set");
        };

        let effect = app.update(Msg::SettingWritten {
            edit,
            ticket,
            result: Ok(()),
        });
        assert_eq!(
            effect,
            Effect::LoadSettings,
            "a landed write re-reads rather than hand-folding the row"
        );
        assert!(app.settings().unwrap().pending().is_none());

        // The re-read, which `run_ui` drives through `load_settings`.
        let mut updated = fixtures::settings_snapshot();
        updated.document["daemon"]["log_level"] = serde_json::json!(candidate);
        let _ = app.update(Msg::Settings {
            result: Ok(updated.clone()),
        });

        assert_eq!(app.settings().unwrap().snapshot(), &updated);
    }

    #[test]
    fn an_unset_write_returns_the_row_to_the_default() {
        let mut app = fixtures::app_in_settings_on("daemon.max_cron_sleep");
        let _ = app.update(Msg::Key(KeyPress::Confirm));
        for _ in 0..8 {
            let _ = app.update(Msg::Key(KeyPress::TextBackspace));
        }
        let _ = app.update(Msg::Key(KeyPress::TextApply));
        let Effect::WriteSetting { edit, ticket, .. } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send");
        };
        assert_eq!(edit, fixtures::setting_unset("daemon.max_cron_sleep"));

        let effect = app.update(Msg::SettingWritten {
            edit,
            ticket,
            result: Ok(()),
        });
        assert_eq!(effect, Effect::LoadSettings);

        let mut updated = fixtures::settings_snapshot();
        updated.document["daemon"]
            .as_object_mut()
            .unwrap()
            .remove("max_cron_sleep");
        let _ = app.update(Msg::Settings {
            result: Ok(updated.clone()),
        });

        assert_eq!(app.settings().unwrap().snapshot(), &updated);
    }

    /// A refused write reopens the text editor, and the overlay must not
    /// survive to hide it: `on_key` checks text mode ahead of `keymap_open`,
    /// so a still-open overlay would swallow every key meant for it.
    ///
    /// Reachable because `is_armed` covers `Pending::Armed` and
    /// `Pending::DogArmed` and not `Pending::Sent`, so `h` with a write in
    /// flight opens the overlay, and the reply then restores text mode.
    #[test]
    fn a_refused_write_closes_the_overlay_before_reopening_the_editor() {
        let mut app = fixtures::app_in_settings_on("daemon.max_cron_sleep");
        let _ = app.update(Msg::Key(KeyPress::Confirm));
        let _ = app.update(Msg::Key(KeyPress::TextApply));
        let Effect::WriteSetting { edit, ticket, .. } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send");
        };

        let _ = app.update(Msg::Key(KeyPress::Help));
        assert!(
            app.keymap_open(),
            "a write in flight is not armed, so `h` must open the overlay"
        );

        let _ = app.update(Msg::SettingWritten {
            edit,
            ticket,
            result: Err("refused".to_string()),
        });

        // Both halves, because `!(a && b)` holds when either is false and
        // this one would pass vacuously if the buffer restoration broke:
        // `typed_text_of` no longer matching means neither line runs and the
        // assertion is satisfied by an editor that never reopened.
        assert!(
            !app.keymap_open(),
            "the overlay is still up while text mode owns the keyboard"
        );
        assert_eq!(
            app.mode,
            InputMode::Text,
            "the editor must reopen, so the operator gets their typed text back"
        );
        assert!(
            matches!(
                app.settings().unwrap().pending,
                Some(Pending::Typing { .. })
            ),
            "the refused write's buffer is what the editor reopens with"
        );
    }

    /// Pins `Msg::Settings`'s `opening` check.
    #[test]
    fn the_cursor_survives_a_landed_writes_reload() {
        let mut app = fixtures::app_in_settings_on("daemon.max_cron_sleep");
        let before = app.settings().unwrap().cursor();
        let _ = app.update(Msg::Key(KeyPress::Confirm));
        let _ = app.update(Msg::Key(KeyPress::TextApply));
        let Effect::WriteSetting { edit, ticket, .. } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send");
        };
        let _ = app.update(Msg::SettingWritten {
            edit,
            ticket,
            result: Ok(()),
        });
        let _ = app.update(Msg::Settings {
            result: Ok(fixtures::settings_snapshot()),
        });
        assert_eq!(app.settings().unwrap().cursor(), before);
    }

    #[test]
    fn the_cursor_survives_a_refresh() {
        let mut app = fixtures::app_in_settings_on("daemon.max_cron_sleep");
        let before = app.settings().unwrap().cursor();
        assert_eq!(
            app.update(Msg::Key(KeyPress::Refresh)),
            Effect::LoadSettings
        );
        let _ = app.update(Msg::Settings {
            result: Ok(fixtures::settings_snapshot()),
        });
        assert_eq!(app.settings().unwrap().cursor(), before);
    }

    #[test]
    fn a_refused_write_says_why_and_leaves_the_row_alone() {
        let mut app = fixtures::app_in_settings_on("daemon.log_level");
        let before = app.settings().unwrap().snapshot().clone();
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let Effect::WriteSetting { edit, ticket, .. } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send");
        };
        let _ = app.update(Msg::SettingWritten {
            edit,
            ticket,
            result: Err("max_cron_sleep is 500ms, below the 1s floor".into()),
        });

        assert_eq!(app.settings().unwrap().snapshot(), &before);
        let notice = app.notice().unwrap();
        assert!(notice.is_grave());
        assert!(notice.to_string().contains("below the 1s floor"));
    }

    /// Two writes can be in flight at once: `Pending::Sent` eats no key, so
    /// `space` arms a second edit over the first and `Enter` sends it. The
    /// first write's answer must not resolve the second, which is the edit
    /// the screen is actually showing a prompt for.
    #[test]
    fn a_superseded_reply_does_not_resolve_the_edit_that_replaced_it() {
        let mut app = fixtures::app_in_settings_on("daemon.log_level");
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let Effect::WriteSetting {
            edit: first,
            ticket: first_ticket,
            ..
        } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send the first edit");
        };

        fixtures::select_setting(&mut app, "whistle.allow_control");
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let Effect::WriteSetting {
            edit: second,
            ticket: second_ticket,
            ..
        } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send the second edit too");
        };
        assert_ne!(first_ticket, second_ticket, "two writes are two tickets");

        let effect = app.update(Msg::SettingWritten {
            edit: first,
            ticket: first_ticket,
            result: Ok(()),
        });
        assert_eq!(
            effect,
            Effect::None,
            "a re-read here rebuilds the screen and throws the live edit away"
        );
        assert!(
            app.settings().unwrap().pending().is_some_and(|p| p.sent),
            "the second edit is still in flight and still says so"
        );

        let effect = app.update(Msg::SettingWritten {
            edit: second,
            ticket: second_ticket,
            result: Ok(()),
        });
        assert_eq!(effect, Effect::LoadSettings, "its own reply re-reads");
        assert!(app.settings().unwrap().pending().is_none());
    }

    /// The worst of the two: a refusal reopens the editor for a free-text
    /// field, so a superseded one used to replace a live `Pending::Sent`
    /// with a text editor. The live write's own answer then cleared it and
    /// left `InputMode::Text` behind with nothing to type into, which is
    /// the state `a_refused_settings_write_landing_over_a_dog_pane_does_not_arm_text_mode`
    /// exists to keep out by the other door.
    #[test]
    fn a_superseded_refusal_does_not_reopen_the_editor_over_a_live_edit() {
        let mut app = fixtures::app_in_settings_on("daemon.socket");
        let _ = app.update(Msg::Key(KeyPress::Confirm));
        let _ = app.update(Msg::Key(KeyPress::TextApply));
        let Effect::WriteSetting {
            edit: socket,
            ticket: socket_ticket,
            ..
        } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send the socket edit");
        };

        fixtures::select_setting(&mut app, "daemon.log_level");
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let Effect::WriteSetting {
            edit: level,
            ticket: level_ticket,
            ..
        } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send the log level edit too");
        };

        let _ = app.update(Msg::SettingWritten {
            edit: socket,
            ticket: socket_ticket,
            result: Err("the socket path is too long".into()),
        });
        assert_eq!(
            app.mode(),
            InputMode::Normal,
            "no editor was opened, so no text mode is owed one"
        );
        assert!(app.settings().unwrap().typing().is_none());
        assert!(
            app.settings().unwrap().pending().is_some_and(|p| p.sent),
            "the log level edit is still in flight"
        );
        assert!(
            app.notice().unwrap().to_string().contains("too long"),
            "the refusal is still reported"
        );

        let _ = app.update(Msg::SettingWritten {
            edit: level,
            ticket: level_ticket,
            result: Ok(()),
        });
        assert_eq!(app.mode(), InputMode::Normal);
        assert!(app.settings().unwrap().pending().is_none());
    }

    /// A dog's ticket has to survive two hops: the file half answers as
    /// `Msg::DogWritten`, which raises `Sent::Dog`, and only the shepherd's
    /// answer to that clears the prompt. An edit armed in between owns the
    /// prompt by then.
    #[test]
    fn a_superseded_dog_reply_does_not_resolve_the_edit_that_replaced_it() {
        let mut app = fixtures::app_in_settings_on_dog("metrics");
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let Effect::WriteDog { edit, ticket, .. } = app.update(Msg::Key(KeyPress::Confirm)) else {
            panic!("Enter must send the file half");
        };
        let Effect::Send(dog) = app.update(Msg::DogWritten {
            edit,
            ticket,
            result: Ok(DogEntry {
                source: DogSource::BuiltIn {
                    grants: None,
                    events: Vec::new(),
                },
                env: BTreeMap::default(),
            }),
        }) else {
            panic!("a landed file half must raise the daemon half");
        };

        fixtures::select_setting(&mut app, "daemon.log_level");
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let Effect::WriteSetting { ticket: scalar, .. } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send the scalar edit");
        };
        assert_ne!(ticket, scalar, "the toggle and the scalar are two writes");

        let info = ProcessInfo::builder(50, "metrics", ProcStatus::Online)
            .pid(Some(50_000))
            .dog(Some(DogSource::BuiltIn {
                grants: None,
                events: Vec::new(),
            }))
            .build();
        let effect = app.update(Msg::Replied {
            sent: dog,
            result: Ok(Response::DogStarted(info)),
        });
        assert_eq!(effect, Effect::None, "the live edit survives a re-read");
        assert!(
            app.settings().unwrap().pending().is_some_and(|p| p.sent),
            "the scalar edit is still in flight and still says so"
        );
        assert_eq!(
            app.notice().map(ToString::to_string).as_deref(),
            Some("enable metrics: the shepherd started it"),
            "the toggle still reports what the shepherd did"
        );
    }

    /// The door a refuse-to-arm guard could not close: `Escape` leaves the
    /// screen without cancelling the write, and reopening it builds a fresh
    /// `Settings` with nothing pending. The abandoned write's answer must
    /// still not touch whatever the reopened screen has armed since.
    #[test]
    fn a_reply_for_a_write_the_screen_walked_away_from_touches_nothing() {
        let mut app = fixtures::app_in_settings_on("daemon.socket");
        let _ = app.update(Msg::Key(KeyPress::Confirm));
        let _ = app.update(Msg::Key(KeyPress::TextApply));
        let Effect::WriteSetting {
            edit: socket,
            ticket: socket_ticket,
            ..
        } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send the socket edit");
        };

        let _ = app.update(Msg::Key(KeyPress::Escape));
        assert!(app.settings().is_none(), "Escape leaves the screen");
        let _ = app.update(Msg::Key(KeyPress::Settings));
        let _ = app.update(Msg::Settings {
            result: Ok(fixtures::settings_snapshot()),
        });
        fixtures::select_setting(&mut app, "daemon.log_level");
        let _ = app.update(Msg::Key(KeyPress::Cycle));
        let Effect::WriteSetting { ticket: level, .. } = app.update(Msg::Key(KeyPress::Confirm))
        else {
            panic!("Enter must send the reopened screen's edit");
        };
        assert_ne!(socket_ticket, level, "a reopened screen mints its own");

        let _ = app.update(Msg::SettingWritten {
            edit: socket,
            ticket: socket_ticket,
            result: Err("the socket path is too long".into()),
        });
        assert_eq!(app.mode(), InputMode::Normal);
        assert!(app.settings().unwrap().typing().is_none());
        assert!(
            app.settings().unwrap().pending().is_some_and(|p| p.sent),
            "the reopened screen's own edit is untouched"
        );
    }
}