shep 0.15.0

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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! The pane itself: what it is over, and what it reads off that target.
//!
//! One `FieldSet`, the values the target currently holds, and a `Viewport`
//! over the rows. Everything here answers a question; the answers to
//! keystrokes live in the modules beside it, and the rows themselves and the
//! cursor's walk through them in [`super::walk`].

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::Arc;

use serde_json::{Map, Value};
use shep_core::config::{ApplyGroup, apply_group, reaches_running};
use shep_core::protocol::SheepConfigView;

use super::super::edits::{EditKey, Edits};
use super::super::field::{
    Field, FieldKind, FieldSet, Flattened, Outline, flatten_values, flattened,
};
use super::super::viewport::Viewport;
use super::entries::{EntryBody, EntryRows};
use super::entry_remove::Reshape;
use super::fields::{entries_text, render_json, resolved_by_kind, resolved_display, sheep_fields};
use super::sheep_dog::SheepDogTable;

// Link-only (IR-32): the unit grammars a row's resolved display goes
// through, the field kind a locked row reports, and the group order this
// type's own field indexes into.
#[cfg(doc)]
use super::super::field::ValueKind;
use super::dogs::dog_names;
use super::{DogsPane, EnvTyping, ListPane, Lock, PaneEdit, PaneRow, PaneTarget, PaneTyping};
#[cfg(doc)]
use shep_core::config::GROUP_ORDER;
#[cfg(doc)]
use shep_core::values::{MemSize, UpDuration};

/// The state of an open pane.
///
/// `Debug` is manual and redacted (IR-41): `values` is a sheep's config with
/// `env` already stripped by [`SheepConfigView::new`], but `args` and `cwd`
/// are still in it and routinely carry a token or a home directory.
/// `env_keys` is a key set, which is itself worth keeping out of a log, and
/// the same reasoning [`SheepConfigView`]'s own `Debug` gives applies here
/// unchanged: this type is a copy of that one's payload.
#[derive(Clone)]
pub struct ConfigPane {
    pub(super) target: PaneTarget,
    pub(super) fields: FieldSet,
    pub(super) values: Map<String, Value>,
    pub(super) env_keys: Vec<String>,
    pub(super) overridden: Vec<String>,
    /// Field names parked until the next respawn, as the shepherd reported
    /// them. Nothing to do with [`Self::edits`], which is this pane's own
    /// set of unwritten changes; the two words come from opposite ends and
    /// the collision is the shepherd's.
    pub(super) pending: Vec<String>,
    /// Index into [`GROUP_ORDER`]: which group's fields the field list
    /// draws. Meaningless for a dog pane, whose fields carry no group and
    /// so are visible under any of them; see [`Self::rows`].
    pub(super) group: usize,
    pub(super) view: Viewport,
    /// The open text editor, or [`None`].
    pub(super) typing: Option<PaneTyping>,
    /// Everything the operator has changed and nothing has written yet.
    /// Emptied by [`Self::close`], which is the only door out.
    pub(super) edits: Edits,
    /// The open env editor, or [`None`]. Never open at the same time as
    /// [`Self::list`]: each opens on a row of its own kind, and `Escape`
    /// closes whichever is up before the pane.
    pub(super) env_typing: Option<EnvTyping>,
    /// The open list sub-screen. Never open at the same time as
    /// [`Self::env_typing`]: each opens on a row of its own kind, and
    /// `Escape` closes whichever is up before the pane. `Box`, like
    /// [`Self::dogs`]: one is open at a time, and inline it would put a
    /// whole sub-screen in every move of the pane.
    pub(super) list: Option<Box<ListPane>>,
    /// The open dogs sub-screen, over a sheep's `dogs` row. Never open at
    /// the same time as [`Self::list`] or an editor: it opens only on a
    /// field list with nothing else up.
    pub(super) dogs: Option<Box<DogsPane>>,
    /// The dog's `[<name>]` table as TOML text, and [`None`] for a sheep.
    ///
    /// Kept beside the parsed `values` rather than instead of them, because
    /// the two answer different questions: `values` is what the rows render,
    /// and this is what a write edits. `Request::SetDogConfig` replaces the
    /// whole section, so an edit that re-rendered it from `values` would
    /// throw away every comment the operator wrote. See
    /// [`Self::edited_section_with`].
    pub(super) section: Option<String>,
    /// A dog's table on a sheep, whole, and where each dotted row lives in
    /// it. [`None`] for every other target. See [`Self::sheep_dog`].
    pub(super) dog_table: Option<Box<SheepDogTable>>,
    /// Each dotted row key of a dog pane to the real property path it was
    /// built from. Empty for any other target.
    ///
    /// The rows are [`flattened`]'s, so a key is dotted for a nested table
    /// and quoted for a property literally named with a dot. The write walks
    /// this map rather than the key: see [`Self::edited_section_with`].
    /// Shared, so the pane stays small enough to sit in `Body` unboxed.
    pub(super) section_paths: Arc<BTreeMap<String, Vec<String>>>,
    /// The tables a dog pane's rows nest in. Empty for a sheep. Shared, so
    /// the pane stays small enough to sit in `Body` unboxed.
    pub(super) outline: Arc<Outline>,
    /// The rows under each array or map of tables. Empty for a sheep.
    pub(super) entries: Arc<EntryRows>,
    /// The tables currently drawn open, by their dotted path. See
    /// [`Self::rows`].
    pub(super) open: BTreeSet<String>,
    /// What each entry removal or addition replaced in the set, newest last,
    /// so `u` can hand it back. See [`Self::file_whole`]. Shared, like
    /// [`Self::entries`], so the pane stays small enough to sit in `Body`.
    pub(super) reshapes: Arc<Vec<Reshape>>,
    /// The rows under each union of a dog's table on a sheep, as editor
    /// fields keyed by the name their edits file under. Empty for any other
    /// target. See [`super::union`].
    pub(super) arms: Arc<BTreeMap<String, Field>>,
}

impl core::fmt::Debug for ConfigPane {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "ConfigPane {{ target: {:?}, fields: {}, env_keys: {}, cursor: {} }}",
            self.target,
            self.fields.len(),
            self.env_keys.len(),
            self.view.cursor()
        )
    }
}

impl ConfigPane {
    /// A pane over one sheep's config, read off the Flockfile schema.
    ///
    /// The schema is the field list: it already carries every property's
    /// type, default and group, so the pane reads the same document `shep
    /// init` scaffolds from rather than keeping a second list of 40 names
    /// in step with it.
    #[must_use]
    pub fn sheep(view: SheepConfigView) -> Self {
        let (fields, values) = sheep_fields(&view.config);
        Self {
            target: PaneTarget::Sheep { name: view.name },
            fields,
            values,
            env_keys: view.env_keys,
            overridden: view.overridden,
            pending: view.pending,
            group: 0,
            view: Viewport::new(),
            typing: None,
            edits: Edits::default(),
            env_typing: None,
            list: None,
            dogs: None,
            section: None,
            dog_table: None,
            reshapes: Arc::default(),
            arms: Arc::default(),
            section_paths: Arc::default(),
            outline: Arc::new(Outline::default()),
            entries: Arc::default(),
            open: BTreeSet::new(),
        }
    }

    /// A pane over one dog's `[<name>]` section.
    ///
    /// `schema` is the dog's own answer to the schema flag, probed at
    /// open rather than read from anywhere; `section` is the table as
    /// `Request::DogConfig` rendered it, empty when `dogs.toml` has none.
    ///
    /// In schema order, with no group headers: a dog's schema carries no
    /// `init.group`. A nested table is a row that opens and closes, with its
    /// keys under it, as it is on that dog's table over a sheep; see
    /// [`Self::rows`]. A [`FieldKind::List`] row opens the list sub-screen,
    /// as a sheep's `args` does. A [`FieldKind::Map`] row, and a list
    /// [`flattened`] closed to [`FieldKind::Opaque`], is marked not editable
    /// and draws [`Lock::NoWidget`].
    #[must_use]
    pub fn dog(
        name: String,
        adopted_path: Option<PathBuf>,
        schema: Value,
        section: String,
    ) -> Self {
        let Flattened {
            fields,
            paths,
            outline,
            shapes,
        } = flattened(&schema);
        let fields = FieldSet::from_fields(
            fields
                .fields()
                .iter()
                .cloned()
                .map(|mut field| {
                    if field.kind == FieldKind::Map {
                        field.editable = false;
                    }
                    field
                })
                .collect(),
            &[],
        );
        let table: Map<String, Value> = section
            .parse::<toml::Table>()
            .ok()
            .and_then(|table| serde_json::to_value(table).ok())
            .and_then(|value| value.as_object().cloned())
            .unwrap_or_default();
        let values = flatten_values(&table, &paths);
        let entries = EntryRows::build(&fields, &paths, &values, shapes);
        Self {
            target: PaneTarget::Dog { name, adopted_path },
            fields,
            values,
            env_keys: Vec::new(),
            overridden: Vec::new(),
            pending: Vec::new(),
            group: 0,
            view: Viewport::new(),
            typing: None,
            edits: Edits::default(),
            env_typing: None,
            list: None,
            dogs: None,
            section: Some(section),
            dog_table: None,
            reshapes: Arc::default(),
            arms: Arc::default(),
            section_paths: Arc::new(paths),
            open: outline.top_level_paths(),
            outline: Arc::new(outline),
            entries: Arc::new(entries),
        }
    }

    /// Whether `section` is the text this dog pane last took from the
    /// shepherd, comments included. False for any other target.
    #[must_use]
    pub(in crate::lookout) fn holds_section(&self, section: &str) -> bool {
        self.section.as_deref() == Some(section)
    }

    /// The key under the cursor, and why the pane will not edit it, when it
    /// will not. [`None`] both for a row that edits and for no row at all.
    ///
    /// The one place a caller asks "may I edit what is selected", so a
    /// refusal is raised for the right one of [`Lock`]'s two reasons rather
    /// than for a generic third.
    #[must_use]
    pub fn cursor_lock(&self) -> Option<(&str, Lock)> {
        let field = match self.cursor()? {
            PaneRow::Field(index) => self.fields.fields().get(index)?,
            PaneRow::Entry(index) => match &self.entries.row(index)?.body {
                EntryBody::Leaf { field, .. } => field,
                EntryBody::Node { .. } | EntryBody::New { .. } => return None,
            },
            PaneRow::Choice { field, .. } => self.fields.fields().get(field)?,
            PaneRow::Arm { field, .. } => self.fields.fields().get(field)?,
            PaneRow::Table(_) | PaneRow::Env(_) | PaneRow::AddEnv => return None,
        };
        if let Some(arm) = self.arm_field(self.cursor()?) {
            return self.lock(&arm.key).map(|lock| (field.key.as_str(), lock));
        }
        self.lock(&field.key).map(|lock| (field.key.as_str(), lock))
    }

    /// The field under the cursor, for a row that holds a value: a config
    /// field, or a field inside an entry, whose key is its full path.
    pub(in crate::lookout) fn cursor_field(&self) -> Option<&Field> {
        match self.cursor()? {
            PaneRow::Field(index) => self.fields.fields().get(index),
            PaneRow::Entry(index) => match &self.entries.row(index)?.body {
                EntryBody::Leaf { field, .. } => Some(field),
                EntryBody::Node { .. } | EntryBody::New { .. } => None,
            },
            PaneRow::Arm { .. } => self.arm_field(self.cursor()?),
            PaneRow::Table(_) | PaneRow::Choice { .. } | PaneRow::Env(_) | PaneRow::AddEnv => None,
        }
    }

    /// The field filed under `key`: one of [`Self::fields`], or a field
    /// inside an entry.
    pub(super) fn field_of(&self, key: &str) -> Option<&Field> {
        self.fields
            .by_key(key)
            .or_else(|| self.entries.leaf(key).map(|leaf| leaf.field))
            .or_else(|| self.arm_field_of(key))
    }

    /// What the target holds for `key`, or [`None`] for a key it holds
    /// nothing for. A field inside an entry reads [`Value::Null`] when the
    /// entry lacks it.
    pub(super) fn stored_of(&self, key: &str) -> Option<&Value> {
        self.values
            .get(key)
            .or_else(|| self.entries.leaf(key).map(|leaf| leaf.stored))
            .or_else(|| self.arm_value(key))
    }

    /// The kind of widget the row under the cursor wants, or [`None`] for
    /// no row at all, or for one on an env row, which has no [`FieldKind`].
    #[must_use]
    pub fn cursor_kind(&self) -> Option<&FieldKind> {
        match self.cursor()? {
            PaneRow::Field(index) => self.fields.fields().get(index).map(|field| &field.kind),
            PaneRow::Entry(index) => match &self.entries.row(index)?.body {
                EntryBody::Leaf { field, .. } => Some(&field.kind),
                EntryBody::Node { .. } | EntryBody::New { .. } => None,
            },
            PaneRow::Arm { .. } => self.arm_field(self.cursor()?).map(|field| &field.kind),
            PaneRow::Table(_) | PaneRow::Choice { .. } | PaneRow::Env(_) | PaneRow::AddEnv => None,
        }
    }

    /// What is being edited.
    #[must_use]
    pub fn target(&self) -> &PaneTarget {
        &self.target
    }

    /// The form.
    #[must_use]
    pub fn fields(&self) -> &FieldSet {
        &self.fields
    }

    /// The current value of `key`, rendered for a cell.
    ///
    /// A scalar shows bare, an absent or `null` value shows `(unset)`, and
    /// anything else shows compact JSON. On a dog's pane an array or map of
    /// tables shows how many entries it holds and nothing of them, since an
    /// entry can hold a secret. A sheep's `env` is the one field
    /// whose value this pane never holds, since the shepherd strips it on
    /// the way out, so it shows its key count instead, and the sub-screen
    /// shows the names. A sheep's `dogs` shows dog names and no value: a
    /// table's secrets are marked only by a schema this pane does not hold.
    ///
    /// That special case is gated on the target, not on the key alone: a
    /// dog's schema is somebody else's, and one declaring a field named
    /// `env` reads its own section, not [`Self::env_keys`], which
    /// [`Self::dog`] always leaves empty.
    ///
    /// This is the parseable form: what [`Self::begin_typing`] seeds an
    /// editor with. [`Self::display_value`] is the one a row draws, and the
    /// two disagree exactly for a [`ValueKind`] field, where a seed has to
    /// stay something the daemon's own grammar still accepts.
    #[must_use]
    pub fn value(&self, key: &str) -> String {
        if key == "env" && matches!(self.target, PaneTarget::Sheep { .. }) {
            return match self.env_keys.len() {
                1 => "1 key".to_owned(),
                count => format!("{count} keys"),
            };
        }
        if key == "dogs" && matches!(self.target, PaneTarget::Sheep { .. }) {
            return dog_names(self.values.get("dogs"));
        }
        if !matches!(self.target, PaneTarget::Sheep { .. })
            && let Some(FieldKind::Entries(_)) = self.fields.by_key(key).map(|field| &field.kind)
        {
            return entries_text(self.values.get(key));
        }
        if let Some(text) = self.union_text(key).or_else(|| self.arm_text(key)) {
            return text;
        }
        if let Some(text) = self.checklist_text(key, self.values.get(key)) {
            return text;
        }
        if let Some(EntryBody::Leaf { text, .. }) = self.entries.leaf_body(key) {
            return text.clone();
        }
        self.values
            .get(key)
            .map_or_else(|| render_json(&Value::Null), render_json)
    }

    /// The value a filed edit holds for `key`, rendered the way
    /// [`Self::value`] renders a stored one, or [`None`] when nothing is
    /// filed for it. Only ever answers for a config field: an env edit has
    /// no field key to be filed under.
    #[must_use]
    pub fn edited_value(&self, key: &str) -> Option<String> {
        let PaneEdit::Set { value, .. } = self.edits.get(&EditKey::Field(key.to_owned()))?.edit()
        else {
            return None;
        };
        if let Some(text) = self.union_text(key) {
            return Some(text);
        }
        let raw = if self.entries_field(key).is_some() {
            entries_text(Some(value.as_value()))
        } else {
            self.checklist_text(key, Some(value.as_value()))
                .unwrap_or_else(|| render_json(value.as_value()))
        };
        Some(self.resolved(key, &raw))
    }

    /// [`Self::value`], resolved through its own grammar for a
    /// [`MemSize`]/[`UpDuration`] field: what a row draws instead of the
    /// digits an operator would otherwise have to already know the
    /// convention for.
    #[must_use]
    pub fn display_value(&self, key: &str) -> String {
        self.resolved(key, &self.value(key))
    }

    fn resolved(&self, key: &str, raw: &str) -> String {
        match (self.entries.leaf(key), self.arm_field_of(key)) {
            (Some(leaf), _) => resolved_by_kind(leaf.field.value_kind, raw),
            (None, Some(arm)) => resolved_by_kind(arm.value_kind, raw),
            (None, None) => resolved_display(&self.fields, key, raw),
        }
    }

    /// What changing `key` costs.
    ///
    /// [`None`] is not reachable for a sheep and is not dead weight either:
    /// a dog decides for itself what a published change reloads, so the
    /// answer for one is "the pane does not know", and every caller already
    /// renders that as an empty cost cell rather than as a guess.
    #[must_use]
    pub fn cost(&self, key: &str) -> Option<ApplyGroup> {
        match self.target {
            PaneTarget::Sheep { .. } => Some(apply_group(key)),
            // The dog decides, not shep. Said once at the foot of the pane
            // rather than guessed per row.
            PaneTarget::Dog { .. } | PaneTarget::SheepDog { .. } => None,
        }
    }

    /// Why the pane will not edit `key`, or [`None`] when it will.
    ///
    /// [`Lock::Refused`] outranks [`Lock::NoWidget`]: a Structural field
    /// that also happened to have no widget is still refused by shep, which
    /// is the fact that survives the pane gaining every widget it lacks. A
    /// sheep's `dogs` is [`Lock::SubScreen`] ahead of its own missing
    /// widget, since Enter there does open something.
    #[must_use]
    pub fn lock(&self, key: &str) -> Option<Lock> {
        if self.cost(key) == Some(ApplyGroup::Structural) {
            return Some(Lock::Refused);
        }
        if key == "dogs" && matches!(self.target, PaneTarget::Sheep { .. }) {
            return Some(Lock::SubScreen);
        }
        if let Some(place) = self.place(key) {
            return self.lock(place.union()).or_else(|| {
                self.arm_field_of(key)
                    .is_none_or(|field| !field.editable)
                    .then_some(Lock::NoWidget)
            });
        }
        if let Some(leaf) = self.entries.leaf(key) {
            let edits_here = matches!(self.target, PaneTarget::Dog { .. })
                && matches!(
                    leaf.field.kind,
                    FieldKind::Bool
                        | FieldKind::Integer
                        | FieldKind::Number
                        | FieldKind::Text
                        | FieldKind::Choice(_)
                        | FieldKind::Suggested(_)
                );
            return (!edits_here || !leaf.field.editable).then_some(Lock::NoWidget);
        }
        match self.fields.by_key(key) {
            Some(field) if !field.editable => Some(Lock::NoWidget),
            Some(field)
                if matches!(field.kind, FieldKind::Union(_))
                    && !matches!(self.target, PaneTarget::SheepDog { .. }) =>
            {
                Some(Lock::NoWidget)
            }
            _ => None,
        }
    }

    /// Whether an operator has overridden `key`.
    #[must_use]
    pub fn is_overridden(&self, key: &str) -> bool {
        self.overridden.iter().any(|name| name == key)
    }

    /// Whether `key` is parked until the next respawn.
    #[must_use]
    pub fn is_pending(&self, key: &str) -> bool {
        self.pending.iter().any(|name| name == key)
    }

    /// How many fields wait for a reload or a restart.
    ///
    /// Every one of them is already written to the override store, so this
    /// counts what the running process has not taken yet, never what an
    /// operator could lose.
    #[must_use]
    pub fn parked_count(&self) -> usize {
        self.pending.len()
    }

    /// The filed edits a respawn is what applies, by field name, in the
    /// set's own key order.
    ///
    /// An env key counts: `env` is `ApplyGroup::NeedsRespawn` and every
    /// value is baked into the child at exec.
    #[must_use]
    pub(in crate::lookout) fn unsent_fields_needing_a_respawn(&self) -> Vec<String> {
        self.edits
            .iter()
            .filter_map(|(key, _)| match key {
                EditKey::Field(name) if !reaches_running(name) => Some(name.clone()),
                EditKey::Env(name) => Some(format!("env {name}")),
                EditKey::Field(_) => None,
            })
            .collect()
    }

    /// How many filed edits the running sheep already takes without a
    /// respawn: the complement of [`Self::unsent_fields_needing_a_respawn`]
    /// within the same set. An env key never counts, for the same reason it
    /// always counts on the other side: `env` is `ApplyGroup::NeedsRespawn`.
    ///
    /// What the close dialog's "everything else you changed is already
    /// live" sentence draws on: a filed set holding only fields a respawn
    /// applies has nothing else to say that about.
    #[must_use]
    pub(in crate::lookout) fn live_edit_count(&self) -> usize {
        self.edits
            .iter()
            .filter(|(key, _)| matches!(key, EditKey::Field(name) if reaches_running(name)))
            .count()
    }

    /// Whether a reload of this sheep overlaps its replacement or runs
    /// serially. Always [`ReloadKind::Overlap`] for a dog, which has no
    /// such fields to read.
    #[must_use]
    pub fn reload_kind(&self) -> ReloadKind {
        let flag = |key: &str| {
            self.values
                .get(key)
                .and_then(Value::as_bool)
                .unwrap_or(false)
        };
        let has_probe = self
            .values
            .get("readiness_probe")
            .is_some_and(|probe| !probe.is_null());
        reload_mode(flag("wait_ready"), has_probe, flag("reuse_port"))
    }

    /// Adopts a previous pane's pending set, so a refresh does not
    /// silently drop changes the operator has not written yet.
    ///
    /// The set is the operator's and the values are the shepherd's: a
    /// re-read replaces every value on screen and keeps every edit filed
    /// over them.
    ///
    /// An open editor is deliberately not carried: its buffer was seeded
    /// from a value this refresh may have just changed, so keeping it
    /// would put the operator halfway through editing something that is no
    /// longer there. `App::release_text_mode_if_unowned` is what puts the
    /// keyboard back when that happens.
    pub(in crate::lookout) fn adopt_edits(&mut self, previous: Edits) {
        self.edits = previous;
    }
}

/// Which of the daemon's two reloads an app takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReloadKind {
    /// The replacement is spawned alongside the instance it replaces.
    Overlap,
    /// The instance being replaced is drained first, so the app is down for
    /// the length of the drain.
    Serial,
}

/// Whether a reload of this app overlaps or runs serially.
///
/// The daemon decides through `ReadinessSource::of`, which answers for
/// `wait_ready` before it reads `readiness_probe`, so an app with both
/// overlaps.
pub(super) const fn reload_mode(wait_ready: bool, has_probe: bool, reuse_port: bool) -> ReloadKind {
    if !wait_ready && has_probe && !reuse_port {
        ReloadKind::Serial
    } else {
        ReloadKind::Overlap
    }
}