shep 0.20.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
//! A dog's config pane, and the TOML section behind it.

use shep_core::protocol::{DogSource, ProcessInfo, Response};
use shep_core::status::ProcStatus;

use crate::lookout::app::{App, Control, Effect, KeyPress, Msg, Sent};
use crate::lookout::pane::{EntryBody, PaneRow};

use super::flock::{app_with, flock_of};
use super::palette::plain;
use super::sheep_pane::{resolved, select_field};

/// The bark dog's `[bark]` section as `Request::DogConfig` would answer it:
/// a comment, two scalars, and a sink holding a webhook credential.
///
/// The comment is load-bearing rather than decoration: a write goes out as
/// the WHOLE section, so a pane that re-rendered it from the parsed values
/// would delete this line on the operator's own keystroke.
pub fn dog_section() -> String {
    "# how often\npoll = \"60s\"\nhistory_bytes = 4096\n\n[sinks.ops]\nkind = \"slack\"\nurl = \"https://hooks.example/x\"\n"
        .to_string()
}

/// A dashboard with the bark dog's config pane open, opened the way the event
/// loop opens it from the flock: `e` on the dog's own row, then the schema its
/// binary answered with, then the shepherd's section. The control gate is open,
/// so the pane can write.
pub fn app_in_dog_pane() -> App {
    let bark = ProcessInfo::builder(91, "bark", ProcStatus::Online)
        .pid(Some(91_000))
        .dog(Some(DogSource::BuiltIn { grants: None }))
        .build();
    let mut app = app_with(vec![bark], plain());
    app.set_control_for_tests(Control::Allowed);
    app.update(Msg::Key(KeyPress::Edit));
    app.update(Msg::DogPane {
        name: "bark".to_string(),
        adopted_path: None,
        env_keys: Vec::new(),
        result: Ok(crate::dog::builtin_schema("bark").expect("bark is a built-in")),
    });
    app.update(Msg::Replied {
        sent: Sent::DogSection {
            name: "bark".to_string(),
        },
        result: Ok(Response::DogSection {
            toml: dog_section().into(),
        }),
    });
    app
}

/// An adopted channel dog's pane opened through its flock row.
///
/// The adopted path enables env rows. A bare path entry supplies no env keys,
/// so the pane must offer the row that adds the first key.
pub fn app_in_adopted_channel_dog_pane_from_row() -> App {
    let kelpie = ProcessInfo::builder(91, "kelpie", ProcStatus::Online)
        .pid(Some(91_000))
        .dog(Some(DogSource::Adopted {
            grants: None,
            path: "/usr/local/bin/shep-kelpie".to_string(),
            channel: true,
        }))
        .build();
    let mut app = app_with(vec![kelpie], plain());
    app.set_control_for_tests(Control::Allowed);
    let effect = app.update(Msg::Key(KeyPress::Edit));
    let Effect::LoadDogPane { name, adopted_path } = effect else {
        panic!("`e` on a dog row opens a dog pane, got {effect:?}");
    };
    assert_eq!(
        adopted_path.as_deref(),
        Some(std::path::Path::new("/usr/local/bin/shep-kelpie")),
        "the pane probes the binary the row names"
    );
    app.update(Msg::DogPane {
        name,
        adopted_path,
        env_keys: Vec::new(),
        result: Ok(env_dog_schema()),
    });
    app.update(Msg::Replied {
        sent: Sent::DogSection {
            name: "kelpie".to_string(),
        },
        result: Ok(Response::DogSection {
            toml: "ratio = 1.5\n".to_owned().into(),
        }),
    });
    app
}

/// A dog whose schema nests `models.worker` two tables down through a
/// `$ref` chain, with a credential beside a plain field in the inner one.
pub fn nested_dog_schema() -> serde_json::Value {
    serde_json::json!({
        "$ref": "#/$defs/Settings",
        "$defs": {
            "Settings": {
                "type": "object",
                "properties": {
                    "name": { "type": "string" },
                    "models": { "$ref": "#/$defs/Models" },
                },
            },
            "Models": {
                "type": "object",
                "properties": { "worker": { "$ref": "#/$defs/Worker" } },
            },
            "Worker": {
                "type": "object",
                "properties": {
                    "model": { "type": "string" },
                    "token": { "type": "string", "x-shep-secret": true },
                },
            },
        },
    })
}

/// The `[jobs]` section that schema opens on, in the header form of its
/// nested table.
pub fn nested_dog_section() -> String {
    "# which model to run\nname = \"small\"\n\n[models.worker]\n# the credential\ntoken = \"sk-live-51Hx9Qa\"\nmodel = \"gpt\"\n"
        .to_string()
}

/// A dashboard with the `jobs` dog's config pane open, over
/// [`nested_dog_section`], so a dotted row is what an edit walks. Opened the
/// way the event loop opens one: the schema probe, then the shepherd's
/// section. The control gate is open.
pub fn app_in_dog_pane_with_a_nested_table() -> App {
    let mut app = app_with(flock_of(3, 0), plain());
    app.set_control_for_tests(Control::Allowed);
    app.update(Msg::DogPane {
        name: "jobs".to_string(),
        adopted_path: None,
        env_keys: Vec::new(),
        result: Ok(nested_dog_schema()),
    });
    app.update(Msg::Replied {
        sent: Sent::DogSection {
            name: "jobs".to_string(),
        },
        result: Ok(Response::DogSection {
            toml: nested_dog_section().into(),
        }),
    });
    app
}

/// A paddock-shaped dog: a `clients` array whose entries carry a secret
/// `key` beside a `name` or an `id`, a list of their own `peers`, a `models`
/// map, and a scalar.
pub fn entries_dog_schema() -> serde_json::Value {
    serde_json::json!({
        "type": "object",
        "properties": {
            "clients": { "type": "array", "items": { "$ref": "#/$defs/Client" } },
            "models": {
                "type": "object",
                "additionalProperties": { "$ref": "#/$defs/Model" },
            },
            "retries": { "type": "integer" },
        },
        "$defs": {
            "Client": {
                "type": "object",
                "properties": {
                    "id": { "type": "string" },
                    "key": { "type": "string", "x-shep-secret": true },
                    "name": { "type": "string" },
                    "peers": { "type": "array", "items": { "$ref": "#/$defs/Client" } },
                    "timeout": { "type": "integer" },
                },
            },
            "Model": {
                "type": "object",
                "properties": {
                    "context": { "type": "integer" },
                    "provider": { "type": "string" },
                },
            },
        },
    })
}

/// [`entries_dog_schema`] with defaults on the items: a new client is
/// enabled, with a secret `key` of `change-me`, and a new model has a
/// `context` of 4096. No `name`, `id`, or `provider`.
pub fn entries_dog_defaults_schema() -> serde_json::Value {
    let mut schema = entries_dog_schema();
    let defs = &mut schema["$defs"];
    defs["Client"]["properties"]["enabled"] =
        serde_json::json!({ "type": "boolean", "default": true });
    defs["Client"]["properties"]["key"]["default"] = serde_json::json!("change-me");
    defs["Model"]["properties"]["context"]["default"] = serde_json::json!(4096);
    schema
}

/// The `[paddock]` section [`entries_dog_schema`] opens on: three clients,
/// each holding a credential, and two models.
pub fn entries_dog_section() -> String {
    concat!(
        "retries = 3\n\n",
        "[[clients]]\nname = \"alpha\"\nkey = \"hunter2\"\ntimeout = 30\n\n",
        "[[clients]]\nid = \"b-2\"\nkey = \"hunter3\"\n\n",
        "[[clients]]\nkey = \"hunter4\"\n\n",
        "[models.large]\nprovider = \"remote\"\n\n",
        "[models.small]\nprovider = \"local\"\ncontext = 4096\n",
    )
    .to_string()
}

/// A dashboard with the `paddock` dog's config pane open over
/// [`entries_dog_section`], every entries row still closed. Opened the way
/// the event loop opens one. The control gate is open.
pub fn app_in_dog_pane_with_entries() -> App {
    let mut app = app_in_read_only_dog_pane_with_entries();
    app.set_control_for_tests(Control::Allowed);
    app
}

/// [`app_in_dog_pane_with_entries`] over [`entries_dog_defaults_schema`], so a
/// new entry holds the defaults it declares.
pub fn app_in_dog_pane_with_entry_defaults() -> App {
    let mut app = app_with(flock_of(3, 0), plain());
    app.set_control_for_tests(Control::Allowed);
    app.update(Msg::DogPane {
        name: "paddock".to_string(),
        adopted_path: None,
        env_keys: Vec::new(),
        result: Ok(entries_dog_defaults_schema()),
    });
    app.update(Msg::Replied {
        sent: Sent::DogSection {
            name: "paddock".to_string(),
        },
        result: Ok(Response::DogSection {
            toml: entries_dog_section().into(),
        }),
    });
    app
}

/// [`app_in_dog_pane_with_entries`] on a lookout that may not write.
pub fn app_in_read_only_dog_pane_with_entries() -> App {
    let mut app = app_with(flock_of(3, 0), plain());
    app.update(Msg::DogPane {
        name: "paddock".to_string(),
        adopted_path: None,
        env_keys: Vec::new(),
        result: Ok(entries_dog_schema()),
    });
    app.update(Msg::Replied {
        sent: Sent::DogSection {
            name: "paddock".to_string(),
        },
        result: Ok(Response::DogSection {
            toml: entries_dog_section().into(),
        }),
    });
    app
}

/// An adopted dog's schema: one scalar, so the pane's own rows are short
/// enough for an env test to walk.
fn env_dog_schema() -> serde_json::Value {
    serde_json::json!({
        "type": "object",
        "properties": { "ratio": { "type": "number" } },
    })
}

/// A dashboard with an adopted dog's config pane open, with the two `env`
/// keys its `shep.toml` entry sets carried in, the way
/// [`Effect::LoadDogPane`](crate::lookout::app::Effect::LoadDogPane) reads
/// them. The control gate is open, so its env rows are editable.
pub fn app_in_adopted_dog_pane_with_env() -> App {
    let mut app = app_with(flock_of(3, 0), plain());
    app.set_control_for_tests(Control::Allowed);
    app.update(Msg::DogPane {
        name: "kelpie".to_string(),
        adopted_path: Some(std::path::PathBuf::from("/usr/local/bin/shep-kelpie")),
        env_keys: vec!["PADDOCK_KEY".to_string(), "RUST_LOG".to_string()],
        result: Ok(env_dog_schema()),
    });
    app.update(Msg::Replied {
        sent: Sent::DogSection {
            name: "kelpie".to_string(),
        },
        result: Ok(Response::DogSection {
            toml: "ratio = 1.5\n".to_owned().into(),
        }),
    });
    app
}

/// An adopted dog's pane, with one `env` key carried in, whose `dogs.toml`
/// section holds text where its schema has a table. No field edit of that
/// section can be written back, which is the refusal a close has to report
/// beside the `env` edit it filed in the same keystroke.
pub fn app_in_adopted_dog_pane_with_an_unwriteable_section() -> App {
    let mut app = app_with(flock_of(3, 0), plain());
    app.set_control_for_tests(Control::Allowed);
    app.update(Msg::DogPane {
        name: "kelpie".to_string(),
        adopted_path: Some(std::path::PathBuf::from("/usr/local/bin/shep-kelpie")),
        env_keys: vec!["PADDOCK_KEY".to_string()],
        result: Ok(serde_json::json!({
            "type": "object",
            "properties": { "models": { "$ref": "#/$defs/Models" } },
            "$defs": {
                "Models": {
                    "type": "object",
                    "properties": { "model": { "type": "string" } },
                },
            },
        })),
    });
    app.update(Msg::Replied {
        sent: Sent::DogSection {
            name: "kelpie".to_string(),
        },
        result: Ok(Response::DogSection {
            toml: "models = \"old\"\n".to_owned().into(),
        }),
    });
    app
}

/// Walks the open dog pane's cursor onto the row that opens and closes at
/// the open-set key `path`: a nested table, an array or map of tables, or
/// one of their entries. A field inside an entry is found by its row key.
///
/// Panics if no such row is drawn, which is a fixture bug rather than a
/// failure the test is about.
#[track_caller]
pub fn select_node(app: &mut App, path: &str) {
    let pane = app.config_pane().expect("the pane is open");
    let index = pane
        .rows()
        .iter()
        .position(|row| {
            resolved(pane, row).is_some_and(|(pane, row)| match row {
                PaneRow::Field(index) => pane.fields().fields()[index].key == path,
                PaneRow::Table(index) => pane.table_path(index) == Some(path),
                PaneRow::Entry(index) => {
                    pane.entry_row(index)
                        .is_some_and(|entry| match &entry.body {
                            EntryBody::Node { path: at, .. } => at == path,
                            EntryBody::Leaf { field, .. } => field.key == path,
                            EntryBody::New { field } => {
                                format!("{}[+]", pane.fields().fields()[*field].key) == path
                            }
                        })
                }
                PaneRow::Choice { .. }
                | PaneRow::Arm { .. }
                | PaneRow::Env(_)
                | PaneRow::AddEnv
                | PaneRow::Dog(_)
                | PaneRow::Under { .. } => false,
            })
        })
        .unwrap_or_else(|| panic!("no node {path} is drawn"));
    app.update(Msg::Key(KeyPress::SelectFirst));
    for _ in 0..index {
        app.update(Msg::Key(KeyPress::SelectDown));
    }
}

/// A dog whose schema holds a string list with an item pattern, an integer
/// list, a secret list and a map.
pub fn list_dog_schema() -> serde_json::Value {
    serde_json::json!({
        "type": "object",
        "properties": {
            "hosts": {
                "type": "array",
                "items": { "type": "string", "minLength": 3, "pattern": "^[a-z.]+$" },
            },
            "keys": {
                "type": "array",
                "items": { "type": "string" },
                "x-shep-secret": true,
            },
            "labels": { "type": "object", "additionalProperties": { "type": "string" } },
            "ports": { "type": "array", "items": { "type": "integer" } },
        },
    })
}

/// The `[watch]` section [`list_dog_schema`] opens on: a comment above each
/// list, so a write that re-rendered the section would lose them.
pub fn list_dog_section() -> String {
    "# who to ping\nhosts = [\"a.example\", \"b.example\"]\n# the api keys\nkeys = [\"sk-live-51Hx9Qa\"]\nports = [80, 443]\n"
        .to_string()
}

/// A dashboard with the `watch` dog's config pane open over
/// [`list_dog_section`], opened the way the event loop opens one. The
/// control gate is open.
pub fn app_in_dog_pane_with_lists() -> App {
    app_in_dog_pane_over_lists(list_dog_section())
}

/// [`app_in_dog_pane_with_lists`] over a `[watch]` section of the caller's
/// own, for a hand-written one the schema would not have produced.
pub fn app_in_dog_pane_over_lists(section: String) -> App {
    let mut app = app_with(flock_of(3, 0), plain());
    app.set_control_for_tests(Control::Allowed);
    app.update(Msg::DogPane {
        name: "watch".to_string(),
        adopted_path: None,
        env_keys: Vec::new(),
        result: Ok(list_dog_schema()),
    });
    app.update(Msg::Replied {
        sent: Sent::DogSection {
            name: "watch".to_string(),
        },
        result: Ok(Response::DogSection {
            toml: section.into(),
        }),
    });
    app
}

/// [`app_in_dog_pane`] with two edits filed, driven by real key presses:
/// `poll` typed, then `history_bytes` typed.
///
/// Two, and not one, because a batch of one cannot tell a loop from a
/// `take(1)`. What `closing_a_dog_pane_sends_one_write_for_two_edits`
/// needs: proof that a dog's batch is one `Sent::SetDogSection`, not two.
pub fn app_in_dog_pane_with_two_edits() -> App {
    let mut app = app_in_dog_pane();
    for (key, typed) in [("poll", "45s"), ("history_bytes", "8192")] {
        select_field(&mut app, key);
        app.update(Msg::Key(KeyPress::Confirm));
        for _ in 0..64 {
            app.update(Msg::Key(KeyPress::TextBackspace));
        }
        for character in typed.chars() {
            app.update(Msg::Key(KeyPress::TextChar(character)));
        }
        app.update(Msg::Key(KeyPress::TextApply));
    }
    assert_eq!(
        app.config_pane().expect("the pane is open").edits().len(),
        2,
        "the fixture files two edits"
    );
    app
}