shep-daemon 0.8.0

The supervision engine behind shep: process spawning, restart policy, the log plane, watch and cron restarts, and the RPC server
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
//! Spawn assembly: pure functions that build [`SpawnSpec`] from app config.
//!
//! The assembler takes a validated `ResolvedApp` and produces a fully-resolved
//! [`SpawnSpec`] ready for [`ProcessRunner::spawn`](crate::runner::ProcessRunner::spawn).
//! No I/O here: the defaults, the process env, the paths, the credentials and
//! the secret store are all read by the daemon before the assembler is called.
//!
//! Two builders, and only one of them may be spawned. [`assemble`] resolves
//! every `{{secret:...}}` and refuses the spec when one will not; the private
//! `describe` is for the callers that read a spec's log paths or build its
//! prober without ever starting a process.
//!
//! Public for its two out-of-crate readers and nothing else: `tests/real_runner.rs`
//! calls [`assemble`] to build a spec it then spawns for real, and
//! [`instance_slots`]'s doc example is compiled as its own crate.

use core::convert::Infallible;
use core::fmt;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use shep_core::config::ResolvedApp;
use shep_core::config::template::{self, RenderError};
use shep_core::paths::ShepPaths;
use shep_core::secrets::SecretView;

use crate::privilege::Credentials;
use crate::runner::SpawnSpec;

/// Finds the `count` lowest-free instance slot numbers from an existing set.
///
/// Used to allocate instance slots for clustered apps. Assumes `existing` is
/// sorted; returns a new vector of `count` distinct slots, smallest first,
/// none of which appear in `existing`.
///
/// # Examples
///
/// ```
/// use shep_daemon::assemble::instance_slots;
///
/// assert_eq!(instance_slots(&[], 3), vec![0, 1, 2]);
/// assert_eq!(instance_slots(&[0, 2], 2), vec![1, 3]);
/// ```
#[must_use]
pub fn instance_slots(existing: &[u32], count: u32) -> Vec<u32> {
    let mut result = Vec::with_capacity(count as usize);
    let mut candidate = 0u32;

    for _ in 0..count {
        while existing.contains(&candidate) || result.contains(&candidate) {
            candidate += 1;
        }
        result.push(candidate);
        candidate += 1;
    }

    result
}

/// The env every spawned child starts from, before the app's own `env` map
/// is folded on top (app config always wins on conflict), plus `PATH`:
/// without one, a bare program or interpreter name can never be found by
/// exec, so it's seeded unconditionally rather than left to `keys`.
///
/// [`build`] calls this with the platform-selected [`INHERITED`] and a
/// `std::env::var` reader; a test can pass [`INHERITED_WINDOWS`] and a fake
/// reader instead, on any host, without touching real process env.
/// Mutating that from a test is unsound under a parallel test binary, and
/// `std::env::set_var` is itself `unsafe` since edition 2024.
fn inherited_env(
    keys: &[&str],
    env_reader: &dyn Fn(&str) -> Option<String>,
) -> BTreeMap<String, String> {
    let mut env = BTreeMap::new();
    // An empty PATH ("PATH=") is treated as absent: `Some("")` would
    // otherwise slip through `unwrap_or_else`, and an empty PATH resolves a
    // bare program against the cwd instead of searching.
    let path = env_reader("PATH")
        .filter(|value| !value.is_empty())
        .unwrap_or_else(|| DEFAULT_PATH.to_string());
    env.insert("PATH".to_string(), path);
    for key in keys {
        if let Some(value) = env_reader(key) {
            env.insert((*key).to_string(), value);
        }
    }
    env
}

/// The `PATH` a child gets when the daemon itself has none.
#[cfg(unix)]
const DEFAULT_PATH: &str = "/usr/local/bin:/usr/bin:/bin";
/// The `PATH` a child gets when the daemon itself has none.
///
/// Not expanded via `%SystemRoot%`: these literal paths are correct on
/// every standard Windows install and need no variable to resolve.
#[cfg(windows)]
const DEFAULT_PATH: &str = r"C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem";

/// Variables inherited from the daemon's own environment, on top of `PATH`.
const INHERITED_UNIX: &[&str] = &["HOME", "USER", "LANG", "TZ"];

/// Variables inherited from the daemon's own environment, on top of `PATH`.
///
/// Longer than the unix list because Windows children need it: many Win32
/// APIs read `%SystemRoot%` directly, and `PATHEXT`/`COMSPEC` let a child
/// resolve and run `.cmd` files at all. `TEMP`/`TMP` and the
/// `USERPROFILE`/`APPDATA`/`LOCALAPPDATA` trio are where most runtimes keep
/// per-user state. Still a closed allowlist, not inherit-everything.
///
/// `PYTHONUTF8`/`PYTHONIOENCODING` are here for one specific failure: a
/// non-console stdio handle (a pipe, which is what every spawned child gets)
/// makes CPython up to 3.14 fall back to the legacy ANSI code page for
/// `sys.stdout`/`sys.stderr` on Windows, and any non-ASCII byte an app prints
/// then raises `UnicodeEncodeError`. CPython 3.15 turns UTF-8 mode on by
/// default (PEP 686), so these two matter for an older interpreter and for
/// anything that sets `PYTHONUTF8=0`. Neither has a unix equivalent to piggyback
/// on. `LANG` is what decides a child's stdio encoding there and
/// [`INHERITED_UNIX`] forwards it, which is not the same as setting one: a
/// daemon started with no `LANG`, or with one naming a non-UTF-8 locale,
/// hands that to its children. Windows has no variable in that role to
/// forward at all. Setting either in the daemon's own environment now
/// reaches every spawned app; an app can still set them itself, per-app, in
/// its Flockfile `env`.
const INHERITED_WINDOWS: &[&str] = &[
    "SystemRoot",
    "windir",
    "SystemDrive",
    "COMSPEC",
    "PATHEXT",
    "TEMP",
    "TMP",
    "USERPROFILE",
    "HOMEDRIVE",
    "HOMEPATH",
    "APPDATA",
    "LOCALAPPDATA",
    "PROCESSOR_ARCHITECTURE",
    "NUMBER_OF_PROCESSORS",
    "OS",
    "LANG",
    "TZ",
    "PYTHONUTF8",
    "PYTHONIOENCODING",
];

/// The list [`build`] actually reads on this build. Picked with `cfg!`
/// rather than `#[cfg(...)]` gating [`INHERITED_UNIX`]/[`INHERITED_WINDOWS`]
/// themselves: both stay referenced on every target this way, so a test can
/// run either platform's list (and [`inherited_env`]'s filtering) on any
/// host, the same way this crate's unit-file renderers are pinned by text
/// on a Mac without a systemd host, and `-D warnings` never calls the other
/// platform's list dead code.
const INHERITED: &[&str] = if cfg!(windows) {
    INHERITED_WINDOWS
} else {
    INHERITED_UNIX
};

/// Which of an app's fields carried a `{{secret:...}}` that would not
/// resolve, and why.
///
/// Redacted by construction (IR-41): `field` is an env key or a field's own
/// name, and [`RenderError`] quotes only the reference, the namespace and
/// the environment. Neither half can hold a secret's value.
#[non_exhaustive]
#[derive(Debug)]
pub enum AssembleError {
    /// A template in `field` could not be rendered.
    Template {
        /// The env key it was in, or the field's own name (`args`,
        /// `out_file`, `err_file`).
        field: String,
        /// Why.
        source: RenderError,
    },
}

impl AssembleError {
    /// Whether waiting could make this spec assemble.
    ///
    /// `true` only for a namespace no provider dog has pushed to yet; see
    /// [`RenderError::is_retriable`]. A caller that calls every refusal
    /// retriable turns a key nobody has set into a crash loop.
    #[must_use]
    pub fn is_retriable(&self) -> bool {
        match self {
            Self::Template { source, .. } => source.is_retriable(),
        }
    }
}

impl fmt::Display for AssembleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Template { field, source } => write!(f, "`{field}`: {source}"),
        }
    }
}

impl core::error::Error for AssembleError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Template { source, .. } => Some(source),
        }
    }
}

/// Assembles a [`SpawnSpec`] from a validated app config and instance slot.
///
/// `credentials` and `secrets` are both resolved by the caller, since a
/// passwd lookup and a store read are real I/O and this function otherwise
/// stays pure. `interpreter = None` or `Some("none")` runs the script
/// directly; `Some(path)` runs `path` with `[script, ...args]`.
///
/// Explicit `out_file`/`err_file` win over the default log path and render
/// `{{instance}}`, `{{name}}` and `{{SHEP_HOME}}` the way `env` and `args`
/// do; normalize refuses a `{{secret:...}}` in either, and a path that
/// collides across instances unless `merge_logs` asked for it. A relative one
/// is anchored at the app's `cwd`, which a `{{SHEP_HOME}}` path never is: it
/// renders absolute, so the anchor leaves it alone.
/// `SpawnSpec::stdin` carries `config.stdin` straight through: unlike
/// `channel`, nothing else turns it on.
///
/// The spec a child is spawned from, and the only one that may be: every
/// `{{secret:...}}` in it resolved. The crate-private `describe` is for a
/// caller reading a spec it will not spawn.
///
/// # Errors
///
/// - [`AssembleError::Template`]: an `env` value or an arg names a secret
///   this view cannot resolve. [`AssembleError::is_retriable`] says whether
///   waiting would help. A log path cannot reach here: normalize refuses a
///   secret in one.
pub fn assemble(
    app: &ResolvedApp,
    instance: u32,
    paths: &ShepPaths,
    credentials: Option<Credentials>,
    secrets: &SecretView,
) -> Result<SpawnSpec, AssembleError> {
    let name = app.config().name.clone();
    build(
        app,
        instance,
        paths,
        credentials,
        secrets.environment(),
        |value, field| {
            template::render(value, &name, instance, Some(&paths.home), secrets).map_err(|source| {
                AssembleError::Template {
                    field: field.to_string(),
                    source,
                }
            })
        },
        InheritedEnv {
            keys: INHERITED,
            reader: &|key: &str| std::env::var(key).ok(),
        },
    )
}

/// [`assemble`] for a caller reading a spec rather than spawning one: a
/// value holding a `{{secret:...}}` this view cannot resolve keeps its
/// references as written instead of refusing.
///
/// Never spawn this sheep's own program from what this returns. Its callers
/// name a sheep's log files, preflight the program exec will find, or build
/// a prober, and a refusal there would cost an operator the sheep itself:
/// `shep add` exists to register a template whose secrets nobody has filled
/// in yet, and an adoption that refused one would strand a running flock.
///
/// A prober is the caller that does spawn something. `OsProber` runs an
/// exec probe's own command in this spec's `cwd` with this spec's `env`, so
/// a value that fell back reaches that command as the reference itself:
/// `PW={{secret:KEY}}`, not the value and not an empty string. Only a sheep
/// that already spawned is armed with a probe, so the fallback is reachable
/// there just while the store has stopped answering something it answered
/// at the spawn.
///
/// The whole value falls back, not the one reference in it that missed, so a
/// caller cannot read a half-resolved value as a resolved one.
#[must_use]
pub(crate) fn describe(
    app: &ResolvedApp,
    instance: u32,
    paths: &ShepPaths,
    credentials: Option<Credentials>,
    secrets: &SecretView,
) -> SpawnSpec {
    let name = app.config().name.clone();
    let built: Result<SpawnSpec, Infallible> = build(
        app,
        instance,
        paths,
        credentials,
        secrets.environment(),
        |value, _| {
            Ok(
                template::render(value, &name, instance, Some(&paths.home), secrets)
                    .unwrap_or_else(|_| {
                        template::render_positional(value, &name, instance, Some(&paths.home))
                    }),
            )
        },
        InheritedEnv {
            keys: INHERITED,
            reader: &|key: &str| std::env::var(key).ok(),
        },
    );
    match built {
        Ok(spec) => spec,
        Err(never) => match never {},
    }
}

/// [`inherited_env`]'s two arguments bundled into one: a key list plus a
/// reader, so [`build`] takes one parameter for this instead of two, and a
/// test can substitute both without touching real process env.
struct InheritedEnv<'a> {
    keys: &'a [&'a str],
    reader: &'a dyn Fn(&str) -> Option<String>,
}

/// [`assemble`] and [`describe`] over one body: `render` is handed each
/// templated value with the field name to blame, and decides what an
/// unresolvable `{{secret:...}}` costs. Both callers in this module pass
/// [`INHERITED`] and a `std::env::var` closure as `inherited`.
///
/// # Errors
///
/// Whatever `render` returns, at the first value it refuses.
fn build<E>(
    app: &ResolvedApp,
    instance: u32,
    paths: &ShepPaths,
    credentials: Option<Credentials>,
    environment: &str,
    mut render: impl FnMut(&str, &str) -> Result<String, E>,
    inherited: InheritedEnv<'_>,
) -> Result<SpawnSpec, E> {
    let config = app.config();
    let name = config.name.clone();

    // Args carry the same grammar as `env`, rendered once here before the
    // interpreter logic below decides where they land.
    let mut rendered_args = Vec::with_capacity(config.args.len());
    for value in &config.args {
        rendered_args.push(render(value, "args")?);
    }

    let (program, args) = match &config.interpreter {
        None => (config.script.clone(), rendered_args),
        Some(interp) if interp == "none" => (config.script.clone(), rendered_args),
        Some(interp) => {
            let mut interp_args = vec![config.script.clone()];
            interp_args.extend(rendered_args);
            (interp.clone(), interp_args)
        }
    };

    // Anything not seeded here is invisible to the child: tokio_runner.rs
    // calls env_clear() then envs(&spec.env). Each value renders through the
    // grammar as it is inserted.
    let mut env = inherited_env(inherited.keys, inherited.reader);
    for (key, value) in &config.env {
        let value = render(value, key)?;
        env.insert(key.clone(), value);
    }
    // Fixed names, always injected: an app that wants the slot under its
    // own var can template it, e.g. `MY_VAR = "{{instance}}"`. After the
    // app's own map, and refused by normalize, so neither can be shadowed.
    env.insert("SHEP_INSTANCE".to_string(), instance.to_string());
    env.insert("SHEP_NAME".to_string(), name.clone());
    env.insert("SHEP_ENVIRONMENT".to_string(), environment.to_string());

    let cwd = config.cwd.as_ref().map(PathBuf::from);

    let log_stem = if config.merge_logs {
        format!("{}-", name)
    } else {
        format!("{}-{}-", name, instance)
    };

    let out_file = match &config.out_file {
        Some(explicit) => anchor_log_path(render(explicit, "out_file")?, cwd.as_deref()),
        None => paths.logs.join(format!("{}out.log", log_stem)),
    };

    let err_file = match &config.err_file {
        Some(explicit) => anchor_log_path(render(explicit, "err_file")?, cwd.as_deref()),
        None => paths.logs.join(format!("{}err.log", log_stem)),
    };

    // Also implied by wait_ready or shutdown_with_message: widening this
    // must keep every term, or dropping one silently stops opening fd 3 for
    // an app that relied on it implying the channel.
    let channel = config.channel || config.wait_ready || config.shutdown_with_message;

    Ok(SpawnSpec {
        name,
        program,
        args,
        cwd,
        env,
        out_file,
        err_file,
        channel,
        stdin: config.stdin,
        credentials,
    })
}

/// Anchors an explicit log path at the sheep's `cwd` when it is relative.
///
/// The shepherd opens these files itself, so a bare relative path resolves
/// against the shepherd's directory rather than the sheep's: the same config
/// names one file under the shepherd a handover started from and another
/// under its successor, and `shep bleats` reads a third under the CLI's.
///
/// A sheep with no `cwd` already runs in the shepherd's own directory.
fn anchor_log_path(rendered: String, cwd: Option<&Path>) -> PathBuf {
    let path = PathBuf::from(rendered);
    match cwd {
        Some(cwd) if path.is_relative() => cwd.join(path),
        _ => path,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use shep_core::config::{AppConfig, normalize};

    fn test_paths() -> ShepPaths {
        ShepPaths {
            home: PathBuf::from("/home/ada/.shep"),
            daemon_config: PathBuf::from("/home/ada/.shep/shep.toml"),
            dogs_config: PathBuf::from("/home/ada/.shep/dogs.toml"),
            snapshot: PathBuf::from("/home/ada/.shep/flock.json"),
            logs: PathBuf::from("/home/ada/.shep/logs"),
            pids: PathBuf::from("/home/ada/.shep/pids"),
            run: PathBuf::from("/home/ada/.shep/run"),
            socket: PathBuf::from("/home/ada/.shep/run/shep.sock"),
            barks: PathBuf::from("/home/ada/.shep/barks.jsonl"),
            kv: PathBuf::from("/home/ada/.shep/kv.json"),
            overrides: PathBuf::from("/home/ada/.shep/overrides.json"),
            secrets: PathBuf::from("/home/ada/.shep/secrets.json"),
            secrets_cache: PathBuf::from("/home/ada/.shep/secrets-cache.json"),
        }
    }

    /// A view holding nothing, in the environment a host defaults to.
    fn no_secrets() -> SecretView {
        SecretView::empty("production".to_string())
    }

    /// A view holding exactly `key` in `environment`, and nothing else.
    fn view_with(environment: &str, key: &str, value: &str) -> SecretView {
        SecretView::new(
            environment.to_string(),
            BTreeMap::from([(
                key.to_string(),
                BTreeMap::from([(environment.to_string(), value.to_string())]),
            )]),
            shep_core::secrets::ProviderCache::default(),
        )
    }

    #[test]
    fn slots_empty_request() {
        let result = instance_slots(&[], 3);
        assert_eq!(result, vec![0, 1, 2]);
    }

    #[test]
    fn slots_skip_occupied() {
        let result = instance_slots(&[0, 2], 2);
        assert_eq!(result, vec![1, 3]);
    }

    #[test]
    fn every_child_learns_its_slot_and_its_name() {
        let app = normalize(AppConfig {
            name: "worker".to_string(),
            script: "bin/worker".to_string(),
            ..Default::default()
        })
        .unwrap();
        let spec = assemble(&app, 3, &test_paths(), None, &no_secrets()).unwrap();
        assert_eq!(spec.env.get("SHEP_INSTANCE").map(String::as_str), Some("3"));
        assert_eq!(
            spec.env.get("SHEP_NAME").map(String::as_str),
            Some("worker")
        );
    }

    #[test]
    fn interpreter_none_runs_script_directly() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "/opt/bin/server".to_string(),
            args: vec!["--port".to_string(), "8080".to_string()],
            interpreter: None,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert_eq!(spec.program, "/opt/bin/server");
        assert_eq!(spec.args, vec!["--port", "8080"]);
    }

    #[test]
    fn interpreter_explicit_none_runs_script_directly() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "server.py".to_string(),
            args: vec!["--verbose".to_string()],
            interpreter: Some("none".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert_eq!(spec.program, "server.py");
        assert_eq!(spec.args, vec!["--verbose"]);
    }

    #[test]
    fn interpreter_path_prepends_script() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app.js".to_string(),
            args: vec!["--debug".to_string(), "true".to_string()],
            interpreter: Some("node".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert_eq!(spec.program, "node");
        assert_eq!(spec.args, vec!["app.js", "--debug", "true"]);
    }

    #[test]
    fn merge_logs_false_uses_instance_suffix() {
        let app_config = AppConfig {
            name: "web".to_string(),
            script: "app".to_string(),
            args: vec![],
            merge_logs: false,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 2, &paths, None, &no_secrets()).unwrap();

        assert_eq!(
            spec.out_file,
            PathBuf::from("/home/ada/.shep/logs/web-2-out.log")
        );
        assert_eq!(
            spec.err_file,
            PathBuf::from("/home/ada/.shep/logs/web-2-err.log")
        );
    }

    #[test]
    fn merge_logs_true_omits_instance_suffix() {
        let app_config = AppConfig {
            name: "api".to_string(),
            script: "api".to_string(),
            args: vec![],
            merge_logs: true,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 1, &paths, None, &no_secrets()).unwrap();

        assert_eq!(
            spec.out_file,
            PathBuf::from("/home/ada/.shep/logs/api-out.log")
        );
        assert_eq!(
            spec.err_file,
            PathBuf::from("/home/ada/.shep/logs/api-err.log")
        );
    }

    #[test]
    fn explicit_out_file_wins() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            merge_logs: false,
            out_file: Some("/var/log/myapp.log".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert_eq!(spec.out_file, PathBuf::from("/var/log/myapp.log"));
        assert_eq!(
            spec.err_file,
            PathBuf::from("/home/ada/.shep/logs/app-0-err.log")
        );
    }

    #[test]
    fn a_relative_log_path_is_anchored_at_the_app_cwd() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            cwd: Some("/srv/app".to_string()),
            out_file: Some("logs/out.log".to_string()),
            err_file: Some("logs/{{name}}-err.log".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert_eq!(spec.out_file, PathBuf::from("/srv/app/logs/out.log"));
        assert_eq!(spec.err_file, PathBuf::from("/srv/app/logs/app-err.log"));
    }

    #[test]
    fn an_absolute_log_path_ignores_the_app_cwd() {
        // A leading separator is not absolute on Windows, so the literal
        // has to carry a drive letter there to be the case under test.
        let absolute = if cfg!(windows) {
            r"C:\var\log\myapp.log"
        } else {
            "/var/log/myapp.log"
        };
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            cwd: Some("/srv/app".to_string()),
            out_file: Some(absolute.to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert_eq!(spec.out_file, PathBuf::from(absolute));
    }

    /// A sheep with no `cwd` runs where the shepherd does, so a relative
    /// path already resolves there and gains nothing from an anchor.
    #[test]
    fn a_relative_log_path_without_a_cwd_is_left_alone() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            cwd: None,
            out_file: Some("logs/out.log".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert_eq!(spec.out_file, PathBuf::from("logs/out.log"));
    }

    /// The default log path is `$SHEP_HOME/logs`, which no `cwd` moves.
    #[test]
    fn a_defaulted_log_path_ignores_the_app_cwd() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            cwd: Some("/srv/app".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert_eq!(
            spec.out_file,
            PathBuf::from("/home/ada/.shep/logs/app-0-out.log")
        );
    }

    /// `{{SHEP_HOME}}` renders absolute, so the cwd anchor leaves it alone.
    /// The ordering is what makes that true: `build` renders first and
    /// anchors second. Inverted, the token would still be in the string at
    /// the anchor, read as a relative path, and land the sheep's logs under
    /// its own working directory.
    #[test]
    fn a_shep_home_log_path_is_not_anchored_at_the_app_cwd() {
        // A leading separator is not absolute on Windows, so the home has to
        // carry a drive letter there for this to be the case under test.
        let home = if cfg!(windows) {
            r"C:\shep"
        } else {
            "/home/ada/.shep"
        };
        let mut paths = test_paths();
        paths.home = PathBuf::from(home);

        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            cwd: Some("/srv/app".to_string()),
            out_file: Some("{{SHEP_HOME}}/logs/{{name}}-out.log".to_string()),
            err_file: Some("{{SHEP_HOME}}/logs/{{name}}-err.log".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        let logs = PathBuf::from(home).join("logs");
        assert_eq!(spec.out_file, logs.join("app-out.log"));
        assert_eq!(spec.err_file, logs.join("app-err.log"));
    }

    /// The token reads the shepherd's own home rather than a fixed default,
    /// so two daemons under different `$SHEP_HOME`s write to different files
    /// from one Flockfile.
    #[test]
    fn a_shep_home_log_path_follows_the_shepherd_it_is_assembled_for() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            out_file: Some("{{SHEP_HOME}}/logs/out.log".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();

        let mut elsewhere = test_paths();
        elsewhere.home = PathBuf::from(if cfg!(windows) {
            r"C:\srv\shep"
        } else {
            "/srv/shep"
        });

        let here_paths = test_paths();
        let here = assemble(&app, 0, &here_paths, None, &no_secrets()).unwrap();
        let there = assemble(&app, 0, &elsewhere, None, &no_secrets()).unwrap();

        // Both sides read their own `paths.home` rather than a literal. The
        // `there` half already had to, since its home carries a drive letter
        // on Windows, and spelling `here`'s out again was the one place in
        // this test that could go stale against the fixture.
        assert_eq!(here.out_file, here_paths.home.join("logs").join("out.log"));
        assert_eq!(there.out_file, elsewhere.home.join("logs").join("out.log"));
        assert_ne!(
            here.out_file, there.out_file,
            "one config, two shepherds, two files"
        );
    }

    // fails if the gate drops the `channel` term from the disjunction
    #[test]
    fn channel_enabled_by_its_own_field() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            channel: true,
            wait_ready: false,
            shutdown_with_message: false,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert!(spec.channel);
    }

    // fails if the gate drops the `wait_ready` term from the disjunction
    #[test]
    fn channel_enabled_by_wait_ready() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            channel: false,
            wait_ready: true,
            shutdown_with_message: false,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert!(spec.channel);
    }

    // fails if the gate drops the `shutdown_with_message` term from the
    // disjunction
    #[test]
    fn channel_enabled_by_shutdown_with_message() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            channel: false,
            wait_ready: false,
            shutdown_with_message: true,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert!(spec.channel);
    }

    // Catches a stuck-open gate (e.g. `|| true`), since all three flags are
    // false here, unlike the three positive tests above.
    #[test]
    fn channel_disabled_when_all_three_flags_are_false() {
        let app_config = AppConfig {
            name: "app".to_string(),
            script: "app".to_string(),
            args: vec![],
            channel: false,
            wait_ready: false,
            shutdown_with_message: false,
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let paths = test_paths();

        let spec = assemble(&app, 0, &paths, None, &no_secrets()).unwrap();

        assert!(!spec.channel);
    }

    #[test]
    fn assembled_env_always_carries_a_path() {
        // tokio_runner.rs's env_clear() + envs(&spec.env) means this map IS
        // the child's whole env: no PATH here, and a bare interpreter name
        // (node, python3, sh, ...) can never be found by exec.
        let app_config = AppConfig {
            name: "web".to_string(),
            script: "app.js".to_string(),
            args: vec![],
            interpreter: Some("node".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let spec = assemble(&app, 0, &test_paths(), None, &no_secrets()).unwrap();
        let path = spec
            .env
            .get("PATH")
            .expect("PATH must survive env_clear()+envs(&spec.env)");
        assert!(
            !path.is_empty(),
            "an empty PATH is exactly the ENOENT failure mode"
        );
    }

    // Goes through `build`, the function `assemble`/`describe` actually call,
    // rather than asserting on `INHERITED_WINDOWS.contains(...)` directly: a
    // list-membership assert would stay green even if `build` stopped
    // reading its `inherited` argument at all. Passes `INHERITED_WINDOWS`
    // explicitly so this runs on any host rather than only in CI's Windows
    // job, the same way this crate's other unit-file renderers are pinned
    // by text without needing the OS they render for.
    #[test]
    fn windows_stdio_encoding_vars_reach_spec_env() {
        let app_config = AppConfig {
            name: "web".to_string(),
            script: "app.js".to_string(),
            interpreter: Some("none".to_string()),
            ..Default::default()
        };
        let app = normalize(app_config).unwrap();
        let fake_env = |key: &str| match key {
            "PYTHONUTF8" => Some("1".to_string()),
            "PYTHONIOENCODING" => Some("utf-8".to_string()),
            _ => None,
        };

        let spec = build::<Infallible>(
            &app,
            0,
            &test_paths(),
            None,
            "production",
            |value, _field| Ok(value.to_string()),
            InheritedEnv {
                keys: INHERITED_WINDOWS,
                reader: &fake_env,
            },
        )
        .expect("no template in this app can fail to render");

        assert_eq!(spec.env.get("PYTHONUTF8").map(String::as_str), Some("1"));
        assert_eq!(
            spec.env.get("PYTHONIOENCODING").map(String::as_str),
            Some("utf-8")
        );
    }

    #[test]
    fn an_explicit_app_path_overrides_the_seeded_default() {
        let mut app_config = AppConfig {
            name: "web".to_string(),
            script: "app.js".to_string(),
            args: vec![],
            interpreter: Some("node".to_string()),
            ..Default::default()
        };
        app_config
            .env
            .insert("PATH".to_string(), "/opt/custom/bin".to_string());
        let app = normalize(app_config).unwrap();
        let spec = assemble(&app, 0, &test_paths(), None, &no_secrets()).unwrap();
        assert_eq!(
            spec.env.get("PATH").map(String::as_str),
            Some("/opt/custom/bin")
        );
    }

    /// The one field on the way to the runner whose default is "closed":
    /// a regression here would silently give an opted-in app `/dev/null`.
    #[test]
    fn the_stdin_flag_reaches_the_spawn_spec() {
        let mut app = AppConfig::minimal("repl", "./repl");
        app.stdin = true;
        let spec = assemble(
            &normalize(app).unwrap(),
            0,
            &test_paths(),
            None,
            &no_secrets(),
        )
        .unwrap();
        assert!(spec.stdin);
    }

    #[test]
    fn templates_render_per_instance_in_env_and_args() {
        let mut config = AppConfig {
            name: "z-worker".to_string(),
            script: "bin/worker".to_string(),
            instances: 4,
            args: vec!["--metrics-port".to_string(), "91{{instance}}".to_string()],
            ..Default::default()
        };
        config
            .env
            .insert("Z_WORKER_ID".to_string(), "z-{{instance}}".to_string());
        config.env.insert(
            "Z_DEVICE_ID".to_string(),
            "{{name}}-{{instance}}d".to_string(),
        );

        let app = normalize(config).unwrap();
        let spec = assemble(&app, 2, &test_paths(), None, &no_secrets()).unwrap();

        assert_eq!(spec.env.get("Z_WORKER_ID").map(String::as_str), Some("z-2"));
        assert_eq!(
            spec.env.get("Z_DEVICE_ID").map(String::as_str),
            Some("z-worker-2d")
        );
        assert!(spec.args.contains(&"912".to_string()), "{:?}", spec.args);
    }

    #[test]
    fn a_templated_log_path_renders_per_instance() {
        let app = normalize(AppConfig {
            name: "web".to_string(),
            script: "./srv".to_string(),
            instances: 3,
            out_file: Some("/var/log/web-{{instance}}.log".to_string()),
            ..Default::default()
        })
        .unwrap();
        let spec = assemble(&app, 2, &test_paths(), None, &no_secrets()).unwrap();
        assert_eq!(spec.out_file, PathBuf::from("/var/log/web-2.log"));
    }

    /// Unlike `channel` (implied by `wait_ready`/`shutdown_with_message`),
    /// nothing implies `stdin`.
    #[test]
    fn nothing_else_turns_stdin_on() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.channel = true;
        app.wait_ready = true;
        app.shutdown_with_message = true;
        let spec = assemble(
            &normalize(app).unwrap(),
            0,
            &test_paths(),
            None,
            &no_secrets(),
        )
        .unwrap();
        assert!(spec.channel, "the fixture should still open a channel");
        assert!(!spec.stdin);
    }

    #[test]
    fn a_resolved_secret_reaches_the_child_env() {
        let mut config = AppConfig::minimal("web", "./srv");
        config
            .env
            .insert("PW".into(), "{{secret:DB_PASSWORD}}".into());
        let app = normalize(config).unwrap();
        let spec = assemble(
            &app,
            0,
            &test_paths(),
            None,
            &view_with("production", "DB_PASSWORD", "hunter2"),
        )
        .unwrap();
        assert_eq!(spec.env.get("PW").map(String::as_str), Some("hunter2"));
    }

    #[test]
    fn shep_environment_is_injected_and_matches_the_view() {
        let app = normalize(AppConfig::minimal("web", "./srv")).unwrap();
        let spec = assemble(
            &app,
            0,
            &test_paths(),
            None,
            &SecretView::empty("staging".into()),
        )
        .unwrap();
        assert_eq!(
            spec.env.get("SHEP_ENVIRONMENT").map(String::as_str),
            Some("staging")
        );
    }

    #[test]
    fn a_missing_key_refuses_the_spawn_and_names_the_field() {
        let mut config = AppConfig::minimal("web", "./srv");
        config.env.insert("PW".into(), "{{secret:ABSENT}}".into());
        let app = normalize(config).unwrap();
        let err = assemble(
            &app,
            0,
            &test_paths(),
            None,
            &SecretView::empty("production".into()),
        )
        .unwrap_err();
        assert!(!err.is_retriable());
        // Exact strings for both renderings (IR-41): the type is meant to
        // carry a field name and a reference and never a value, and a
        // substring check cannot see a field it was never told about.
        assert_eq!(
            err.to_string(),
            "`PW`: `{{secret:ABSENT}}` has no value in the `production` environment"
        );
        assert_eq!(
            format!("{err:?}"),
            "Template { field: \"PW\", source: Unresolved { reference: \"{{secret:ABSENT}}\", \
             environment: \"production\" } }"
        );
        let rendered = err.to_string();
        assert!(
            !rendered.contains('\u{2014}') && !rendered.contains('\u{2013}'),
            "no em or en dash in copy a user reads: {rendered}"
        );
    }

    #[test]
    fn an_unready_namespace_refuses_retriably() {
        let mut config = AppConfig::minimal("web", "./srv");
        config.env.insert("PW".into(), "{{secret:vault/K}}".into());
        let app = normalize(config).unwrap();
        let err = assemble(
            &app,
            0,
            &test_paths(),
            None,
            &SecretView::empty("production".into()),
        )
        .unwrap_err();
        assert!(err.is_retriable());
    }

    /// Args carry the same grammar `env` does. A log path does not, and
    /// `normalize` is what refuses one there; see
    /// `a_secret_in_a_log_path_is_refused` in shep-core.
    #[test]
    fn a_secret_resolves_in_args() {
        let mut config = AppConfig::minimal("web", "./srv");
        config.args = vec!["--token={{secret:K}}".into()];
        let app = normalize(config).unwrap();
        let spec = assemble(
            &app,
            0,
            &test_paths(),
            None,
            &view_with("production", "K", "v"),
        )
        .unwrap();
        assert_eq!(spec.args, vec!["--token=v".to_string()]);
    }

    #[test]
    fn an_app_cannot_set_shep_environment_by_hand() {
        let mut config = AppConfig::minimal("web", "./srv");
        config
            .env
            .insert("SHEP_ENVIRONMENT".into(), "sneaky".into());
        // normalize refuses it, the same way it refuses SHEP_NAME.
        assert!(normalize(config).is_err());
    }

    /// The half of the store a namespace reads is refused apart from the
    /// operator's own, since only one of the two clears itself.
    #[test]
    fn the_two_refusal_shapes_stay_apart() {
        let mut absent = AppConfig::minimal("a", "./srv");
        absent.env.insert("K".into(), "{{secret:NOPE}}".into());
        let mut unready = AppConfig::minimal("b", "./srv");
        unready.env.insert("K".into(), "{{secret:ns/NOPE}}".into());
        let view = SecretView::empty("production".to_string());
        let of = |config| {
            assemble(&normalize(config).unwrap(), 0, &test_paths(), None, &view)
                .unwrap_err()
                .is_retriable()
        };
        assert!(!of(absent), "a key nobody set waits on a person");
        assert!(of(unready), "a namespace no dog pushed to clears itself");
    }

    /// `describe` is what registration, adoption and every prober site read,
    /// and each of those has a live sheep to lose if a store read refuses.
    #[test]
    fn describe_keeps_an_unresolvable_reference_rather_than_refusing() {
        let mut config = AppConfig::minimal("web", "./srv");
        config.env.insert("PW".into(), "{{secret:ABSENT}}".into());
        config.out_file = Some("/tmp/{{name}}.log".into());
        config.merge_logs = true;
        let app = normalize(config).unwrap();
        let spec = describe(
            &app,
            0,
            &test_paths(),
            None,
            &SecretView::empty("staging".into()),
        );
        assert_eq!(
            spec.env.get("PW").map(String::as_str),
            Some("{{secret:ABSENT}}")
        );
        assert_eq!(spec.out_file, PathBuf::from("/tmp/web.log"));
        assert_eq!(
            spec.env.get("SHEP_ENVIRONMENT").map(String::as_str),
            Some("staging"),
            "a described spec still names its environment"
        );
    }

    /// A value that resolves is identical either way, so the two builders
    /// cannot drift on anything but a refusal.
    #[test]
    fn describe_matches_assemble_when_every_reference_resolves() {
        let mut config = AppConfig::minimal("web", "./srv");
        config.env.insert("PW".into(), "{{secret:K}}".into());
        let app = normalize(config).unwrap();
        let view = view_with("production", "K", "v");
        let assembled = assemble(&app, 2, &test_paths(), None, &view).unwrap();
        let described = describe(&app, 2, &test_paths(), None, &view);
        assert_eq!(assembled.env, described.env);
        assert_eq!(assembled.out_file, described.out_file);
        assert_eq!(assembled.args, described.args);
    }
}