shep-core 0.6.4

Types, Flockfile parsing, and the wire protocol shared by the shep process manager's daemon, client, and CLI
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
//! Flockfile: discovery and multi-format parsing
//!
//! One document shape across formats: a list of app tables under the `app`
//! key (`[[app]]` in TOML). Parsing is strict serde, no code execution;
//! `.js` configs are the CLI's job (it shells out to node and feeds the
//! resulting JSON through [`FlockFormat::Json`]).

use core::fmt;

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

#[cfg(feature = "schema")]
use schemars::Schema;

use serde::{Deserialize, Serialize};

use crate::config::AppConfig;

/// A parsed Flockfile: the declared flock
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Flockfile {
    /// App entries in declaration order
    pub apps: Vec<AppConfig>,
}

/// One app as the document declared it: the validated config, plus the
/// keys the document literally wrote.
///
/// The key set cannot be recovered from [`AppConfig`] afterwards:
/// `#[serde(default)]` gives every field a value, so a document naming
/// four keys deserializes identically to one naming forty.
/// [`Flockfile::parse_declared`] carries the claim out for a later merge
/// that keys on what a template declares, not on its values.
///
/// `Serialize`/`Deserialize` since this type travels inside a wire
/// request, keyed on the same claim. Derived `Debug` is safe: `config`
/// redacts its own `env`, and `declared_env` holds only key names.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeclaredApp {
    /// The app, validated the same way [`Flockfile::parse`] validates one
    pub config: AppConfig,
    /// Top-level keys this app's table wrote, whatever their values
    pub declared: BTreeSet<String>,
    /// Keys inside this app's `env` table. Empty when `env` was not declared.
    pub declared_env: BTreeSet<String>,
}

// Application entries are locked to the `app` key: a typo'd key must fail
// loudly. `$schema` and `dog` are the two keys explicitly let in beside
// it; a future schema key is added the same explicit way, so older
// binaries reject newer Flockfiles by design rather than ignore them.
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
// `rename` sets `schema_name`, which schemars uses as the root schema's
// `title`. The type is called `RawFlockfile` because it is the
// pre-validation twin of `Flockfile`; the document an operator writes is a
// Flockfile, and that is what the title has to say.
#[cfg_attr(feature = "schema", schemars(rename = "Flockfile"))]
#[serde(deny_unknown_fields)]
struct RawFlockfile {
    /// The editor's schema hint, read and discarded.
    ///
    /// This is the "future schema key" the comment above anticipated, added
    /// HERE explicitly rather than by relaxing `deny_unknown_fields`: a
    /// typo'd key must still fail loudly, and exactly one more key is now
    /// legal. shep does not validate against the named schema and makes no
    /// promise about it — it is a hint for the operator's editor, which is
    /// the only consumer that ever reads it.
    ///
    /// TOML Flockfiles do not need it: taplo's `#:schema <url>` directive is
    /// a comment, invisible to serde. JSON and JSON5 have no comment an
    /// editor agrees to look in, which is why this field exists at all.
    #[serde(default, rename = "$schema")]
    schema: Option<String>,
    /// A dog's own per-app configuration, read and discarded.
    ///
    /// Added the same way `$schema` was, explicitly rather than by relaxing
    /// `deny_unknown_fields`, so a typo'd key still fails loudly and exactly
    /// one more key is legal.
    ///
    /// It exists because the alternative is a Flockfile no daemon will accept.
    /// A dog that needs per-app configuration has nowhere to put it: shep-deploy
    /// wants a build command for the app it deploys, which belongs beside that
    /// app's declaration and nowhere else, and a Flockfile carrying one was
    /// refused outright by `shep start`. Measured 2026-08-28 against shep
    /// 0.1.8: an operator following shep-deploy's own README could not register
    /// their app at all. `unknown field `build`, expected `$schema` or `app``.
    ///
    /// It must BE a table. shep does not read what is inside it, does not
    /// validate it, and makes no promise about it. Those are two different
    /// claims and only the second one is a promise not to care: the dog that
    /// owns a key under this table is the only thing that understands it, and
    /// shep refusing a document because it does not recognise another
    /// program's config is a coupling neither side wants.
    ///
    /// Nested under one key rather than allowing loose top-level keys, so
    /// exactly one name is reserved and a typo anywhere else still fails.
    ///
    /// A map of ignored values rather than `IgnoredAny`, which would have
    /// accepted `dog = 5` and `dog = ["a"]` as happily as a table. Not reading
    /// what a dog wrote is the point; not caring whether it wrote a table at
    /// all is a different thing, and it would have made the one key this file
    /// adds the one key where a typo does not fail loudly.
    #[serde(default)]
    #[cfg_attr(
        feature = "schema",
        schemars(with = "Option<BTreeMap<String, serde_json::Value>>")
    )]
    dog: Option<BTreeMap<String, serde::de::IgnoredAny>>,
    #[serde(default, rename = "app")]
    apps: Vec<AppConfig>,
}

/// The committed Flockfile JSON Schema.
///
/// `include_str!` makes the file a compile-time input: deleting it fails
/// the build, and changing `AppConfig` fails
/// `the_committed_schema_is_current` with the command that fixes it.
///
/// Lives inside this package, not the repository root: `cargo package`
/// packs only files under the package directory, and a root-relative
/// `include_str!` would fail every `cargo install shep`.
///
/// `#[allow(dead_code)]`: its only reader is `#[cfg(test)]`, so a plain
/// `cargo build`/`clippy` sees no reader and would otherwise flag it dead.
#[cfg(feature = "schema")]
pub const COMMITTED: &str = include_str!("../../assets/flockfile.schema.json");

/// How to regenerate the committed copy. Named in the drift test's own
/// failure message, so a red test is self-service.
///
/// Same `#[allow(dead_code)]` reasoning as [`COMMITTED`] just above: its one
/// reader is that same test.
#[cfg(feature = "schema")]
#[allow(dead_code)]
const REGENERATE: &str =
    "cargo run --bin shep -- schema > crates/shep-core/assets/flockfile.schema.json";

/// Renders the Flockfile JSON Schema: the document grammar, pretty-printed
/// with a trailing newline so the committed file is a well-formed text file.
///
/// Generated from `RawFlockfile`, the type serde actually deserializes a
/// Flockfile into, so the schema and the parser cannot drift.
/// `AppConfig` supplies the per-app half and lands in `$defs`.
///
/// Describes the deserializer, not the normalizer:
/// `AppConfig::kill_signal` stays a plain string here even though
/// `config::normalize` accepts only four spellings, since the schema's
/// job is what serde parses, not what a later validation step accepts.
#[cfg(feature = "schema")]
#[track_caller]
#[must_use]
pub fn flockfile_schema_string() -> String {
    let schema = flockfile_schema_json();
    let mut rendered =
        serde_json::to_string_pretty(&schema).expect("a schemars Schema always serializes");
    rendered.push('\n');
    rendered
}

/// Returns the Flockfile JSON Schema.
///
/// Generated from `RawFlockfile`, the type serde actually deserializes a
/// Flockfile into, so the schema and the parser cannot drift. Describes
/// the deserializer, not the normalizer: `AppConfig::kill_signal` stays a
/// plain string here even though `config::normalize` accepts only four
/// spellings.
///
/// # Panics
/// Never in practice: schemars produces a `serde_json::Value` tree, which
/// `to_string_pretty` cannot fail on. `#[track_caller]` so a future
/// fallible change reports the caller.
#[cfg(feature = "schema")]
#[track_caller]
#[must_use]
pub fn flockfile_schema_json() -> Schema {
    schemars::schema_for!(RawFlockfile)
}

/// Input format of a Flockfile
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlockFormat {
    /// `Flockfile.toml`: `[[app]]` tables
    Toml,
    /// `.yaml`/`.yml`
    Yaml,
    /// Strict JSON
    Json,
    /// JSON5 (comments, trailing commas)
    Json5,
}

impl FlockFormat {
    /// Maps a file extension to its format (`None` = unsupported, e.g. `.js`)
    #[must_use]
    pub fn from_path(path: &Path) -> Option<Self> {
        match path.extension()?.to_str()? {
            "toml" => Some(Self::Toml),
            "yaml" | "yml" => Some(Self::Yaml),
            "json" => Some(Self::Json),
            "json5" => Some(Self::Json5),
            _ => None,
        }
    }
}

impl Flockfile {
    /// Parses Flockfile source text in the given format.
    ///
    /// # Errors
    /// - Format variants ([`FlockfileError::Toml`] etc.): backend parse
    ///   failure, carrying the backend's message. Json5 additionally rejects
    ///   sources nested past a depth of 64 before reaching the backend
    ///   parser, whose recursive-descent stack-overflows on deep input
    ///   rather than returning an error.
    /// - [`FlockfileError::NoApps`]: parsed fine but declared no apps.
    /// - [`FlockfileError::UnknownKeys`]: named a key no field claims.
    pub fn parse(source: &str, format: FlockFormat) -> Result<Self, FlockfileError> {
        let raw = parse_raw_denying_unknown(source, format)?;
        let RawFlockfile {
            schema: _schema,
            // Discarded by name. Whatever a dog wrote under `[dog]` is that
            // dog's to read out of the file itself; shep only had to stop
            // refusing the document for containing it.
            dog: _dog,
            apps,
        } = raw;
        if apps.is_empty() {
            return Err(FlockfileError::NoApps);
        }
        Ok(Self { apps })
    }

    /// Parses `text` and reports, per app, which keys the document wrote.
    ///
    /// Runs the same per-format parse and validation [`Flockfile::parse`]
    /// does, then separately deserializes the same source into a
    /// [`serde_json::Value`] and reads each app table's keys off it:
    /// `AppConfig`'s `#[serde(default)]` erases which keys a document
    /// actually named, which is exactly what the value pass recovers.
    ///
    /// # Errors
    /// Every error [`Flockfile::parse`] returns, for the same inputs.
    pub fn parse_declared(
        text: &str,
        format: FlockFormat,
    ) -> Result<Vec<DeclaredApp>, FlockfileError> {
        // Same reasoning as `Flockfile::parse`: this reads a Flockfile off
        // disk (the reload/muster path in shep-cli), not a value off the
        // wire, so a typo here must still be loud.
        let raw = parse_raw_denying_unknown(text, format)?;
        let RawFlockfile {
            schema: _schema,
            dog: _dog,
            apps,
        } = raw;
        if apps.is_empty() {
            return Err(FlockfileError::NoApps);
        }

        // A document that reached this point already parsed successfully
        // into `RawFlockfile` above, so the same source deserializing into a
        // generic `Value` cannot fail for a reason the `RawFlockfile` pass
        // would not already have caught.
        let value = parse_into::<serde_json::Value>(text, format)?;
        let tables: Vec<Option<&serde_json::Map<String, serde_json::Value>>> = value
            .get("app")
            .and_then(serde_json::Value::as_array)
            .map(|apps| apps.iter().map(serde_json::Value::as_object).collect())
            .unwrap_or_default();

        Ok(apps
            .into_iter()
            .enumerate()
            .map(|(index, config)| {
                let table = tables.get(index).copied().flatten();
                let declared = table
                    .map(|t| t.keys().cloned().collect())
                    .unwrap_or_default();
                let declared_env = table
                    .and_then(|t| t.get("env"))
                    .and_then(serde_json::Value::as_object)
                    .map(|e| e.keys().cloned().collect())
                    .unwrap_or_default();
                DeclaredApp {
                    config,
                    declared,
                    declared_env,
                }
            })
            .collect())
    }
}

// Shared by `Flockfile::parse` and `parse_declared`: both read a Flockfile
// off disk (never a value off the wire), so both refuse a typo the same
// way. `deny_unknown_fields` used to live on `AppConfig` itself, which made
// every new Flockfile field a protocol event: the same type rides the
// wire, where an unknown field means a newer peer rather than a typo. The
// denial belongs here instead.
fn parse_raw_denying_unknown(
    source: &str,
    format: FlockFormat,
) -> Result<RawFlockfile, FlockfileError> {
    let mut unknown = Vec::new();
    let raw: RawFlockfile = parse_into_ignoring(source, format, |path| {
        // `dog` is a map of `IgnoredAny` by design (see its doc comment):
        // shep does not read or validate what a dog wrote there, so
        // serde_ignored's callback for a key inside it is not a typo, it
        // is the field doing exactly what it is for.
        if !path.starts_with("dog.") {
            unknown.push(path.to_string());
        }
    })?;
    if !unknown.is_empty() {
        return Err(FlockfileError::UnknownKeys { keys: unknown });
    }
    Ok(raw)
}

// Its one caller deserializes into `serde_json::Value`, which claims every
// key, so `parse_into_ignoring`'s callback never fires here; delegating
// costs nothing behaviorally and drops a second four-arm format dispatch.
fn parse_into<T: serde::de::DeserializeOwned>(
    source: &str,
    format: FlockFormat,
) -> Result<T, FlockfileError> {
    parse_into_ignoring(source, format, |_| {})
}

// The one four-arm format dispatch, shared by `parse_into` (an empty
// `on_ignored`) and `parse_raw_denying_unknown` (a real one). Each format's
// `Deserializer` routes through `serde_ignored::deserialize`, calling
// `on_ignored` once per key the target type did not claim, recursing into
// nested structs (a Flockfile's `readiness_probe`/`liveness_probe` tables
// included). The real callback is used only by `Flockfile::parse` and
// `parse_declared`: those are the two places a document really is a
// hand-written file, where an unrecognized key means a typo. Everywhere else
// the same `AppConfig`/`ProbeConfig` shape rides the wire, where it means a
// newer peer instead, which is why the two types dropped
// `deny_unknown_fields` rather than this function replacing it everywhere.
fn parse_into_ignoring<T: serde::de::DeserializeOwned>(
    source: &str,
    format: FlockFormat,
    mut on_ignored: impl FnMut(&str),
) -> Result<T, FlockfileError> {
    match format {
        FlockFormat::Toml => serde_ignored::deserialize(toml::Deserializer::new(source), |path| {
            on_ignored(&path.to_string());
        })
        .map_err(|e| FlockfileError::Toml(e.to_string())),
        FlockFormat::Yaml => serde_saphyr::with_deserializer_from_str(source, |de| {
            serde_ignored::deserialize(de, |path| on_ignored(&path.to_string()))
        })
        .map_err(|e| FlockfileError::Yaml(e.to_string())),
        FlockFormat::Json => {
            let mut de = serde_json::Deserializer::from_str(source);
            let value = serde_ignored::deserialize(&mut de, |path| on_ignored(&path.to_string()))
                .map_err(|e| FlockfileError::Json(e.to_string()))?;
            // `serde_json::from_str` checks this too, to catch trailing
            // garbage after a value that otherwise parsed fine.
            de.end().map_err(|e| FlockfileError::Json(e.to_string()))?;
            Ok(value)
        }
        FlockFormat::Json5 => {
            if json5_nesting_depth(source) > MAX_JSON5_NESTING_DEPTH {
                return Err(FlockfileError::Json5(
                    "nesting depth exceeds 64".to_string(),
                ));
            }
            let mut de = json5::Deserializer::from_str(source)
                .map_err(|e| FlockfileError::Json5(e.to_string()))?;
            serde_ignored::deserialize(&mut de, |path| on_ignored(&path.to_string()))
                .map_err(|e| FlockfileError::Json5(e.to_string()))
        }
    }
}

// json5's recursive-descent parser stack-overflows (SIGABRT, uncatchable)
// around ~4500 levels of nesting. 64 is far beyond the deepest legitimate
// Flockfile nesting (4) and comfortably clear of the crash threshold.
const MAX_JSON5_NESTING_DEPTH: u32 = 64;

// Scans for the maximum concurrently-open `[`/`{` depth, skipping quoted
// strings and `//`/`/* */` comments so bracket-like characters inside
// them don't distort the count. Fails closed: an unterminated string or
// comment returns `u32::MAX`, which always exceeds the depth cap.
fn json5_nesting_depth(source: &str) -> u32 {
    let mut depth: u32 = 0;
    let mut max_depth: u32 = 0;
    let mut in_string: Option<char> = None;
    let mut chars = source.chars().peekable();
    while let Some(c) = chars.next() {
        if let Some(quote) = in_string {
            match c {
                '\\' => {
                    chars.next(); // skip the escaped character
                }
                q if q == quote => in_string = None,
                _ => {}
            }
            continue;
        }
        match c {
            '/' if chars.peek() == Some(&'/') => {
                chars.next(); // consume the second '/'
                for c2 in chars.by_ref() {
                    if c2 == '\n' {
                        break;
                    }
                }
            }
            '/' if chars.peek() == Some(&'*') => {
                chars.next(); // consume the '*'
                let mut prev = '\0';
                let mut closed = false;
                for c2 in chars.by_ref() {
                    if prev == '*' && c2 == '/' {
                        closed = true;
                        break;
                    }
                    prev = c2;
                }
                if !closed {
                    return u32::MAX; // unterminated block comment
                }
            }
            '"' | '\'' => in_string = Some(c),
            '[' | '{' => {
                depth = depth.saturating_add(1);
                max_depth = max_depth.max(depth);
            }
            ']' | '}' => depth = depth.saturating_sub(1),
            _ => {}
        }
    }
    if in_string.is_some() {
        return u32::MAX; // unterminated string
    }
    max_depth
}

const DISCOVERY_ORDER: [&str; 10] = [
    "Flockfile.toml",
    "Flockfile.yaml",
    "Flockfile.yml",
    "Flockfile.json",
    "Flockfile.json5",
    "flockfile.toml",
    "flockfile.yaml",
    "flockfile.yml",
    "flockfile.json",
    "flockfile.json5",
];

/// Finds the Flockfile in a directory (spec §5 ten-name order)
#[must_use]
pub fn discover(dir: &Path) -> Option<PathBuf> {
    DISCOVERY_ORDER
        .iter()
        .map(|name| dir.join(name))
        .find(|p| p.is_file())
}

/// Error type returned from [`Flockfile::parse`].
///
/// `#[non_exhaustive]`: an out-of-tree consumer could otherwise match
/// this exhaustively and a new variant would break them silently. Growth
/// is anticipated per backend, not per format: `.js` Flockfiles never
/// appear here, since shep-core never executes anything. The node bridge
/// lives in shep-cli, which feeds its output back through
/// [`FlockFormat::Json`].
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FlockfileError {
    /// TOML backend rejected the source (carries its message)
    Toml(String),
    /// YAML backend rejected the source
    Yaml(String),
    /// JSON backend rejected the source
    Json(String),
    /// JSON5 backend rejected the source
    Json5(String),
    /// The document parsed but declared no apps
    NoApps,
    /// The document named one or more keys no field claims.
    ///
    /// A Flockfile is hand-written, unlike the same [`AppConfig`]/
    /// [`ProbeConfig`](crate::config::ProbeConfig) shape riding the wire,
    /// where an unknown field means a newer peer rather than a typo.
    /// `keys` names every offending key (dotted path for a nested one, e.g.
    /// `app.0.readiness_probe.<the misspelled key>`) so one refusal lists
    /// every typo instead of one refusal per run.
    UnknownKeys {
        /// Every key the document named that no field claimed.
        keys: Vec<String>,
    },
}

impl fmt::Display for FlockfileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Toml(m) => write!(f, "invalid TOML Flockfile: {m}"),
            Self::Yaml(m) => write!(f, "invalid YAML Flockfile: {m}"),
            Self::Json(m) => write!(f, "invalid JSON Flockfile: {m}"),
            Self::Json5(m) => write!(f, "invalid JSON5 Flockfile: {m}"),
            Self::NoApps => f.write_str("Flockfile declares no apps"),
            Self::UnknownKeys { keys } => {
                write!(f, "Flockfile names unrecognized key")?;
                if keys.len() != 1 {
                    f.write_str("s")?;
                }
                write!(f, ": {}", keys.join(", "))
            }
        }
    }
}

impl core::error::Error for FlockfileError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn toml_array_of_tables() {
        let src = r#"
[[app]]
name = "web"
script = "./srv"

[[app]]
name = "worker"
script = "python3"
args = ["job.py"]
"#;
        let flock = Flockfile::parse(src, FlockFormat::Toml).unwrap();
        assert_eq!(flock.apps.len(), 2);
        assert_eq!(flock.apps[1].name, "worker");
    }

    #[test]
    fn json_and_json5_and_yaml() {
        let json = r#"{ "app": [{ "name": "web", "script": "./srv" }] }"#;
        assert_eq!(
            Flockfile::parse(json, FlockFormat::Json)
                .unwrap()
                .apps
                .len(),
            1
        );

        let json5 = r#"{ app: [{ name: "web", script: "./srv" }], /* comment */ }"#;
        assert_eq!(
            Flockfile::parse(json5, FlockFormat::Json5)
                .unwrap()
                .apps
                .len(),
            1
        );

        let yaml = "app:\n  - name: web\n    script: ./srv\n";
        assert_eq!(
            Flockfile::parse(yaml, FlockFormat::Yaml)
                .unwrap()
                .apps
                .len(),
            1
        );
    }

    #[test]
    fn empty_app_list_is_an_error() {
        assert_eq!(
            Flockfile::parse("app: []\n", FlockFormat::Yaml).unwrap_err(),
            FlockfileError::NoApps
        );
    }

    #[test]
    fn parse_errors_carry_the_backend_message() {
        match Flockfile::parse("not toml [[", FlockFormat::Toml).unwrap_err() {
            FlockfileError::Toml(msg) => assert!(!msg.is_empty()),
            other => panic!("expected Toml error, got {other:?}"),
        }
    }

    #[test]
    fn format_from_path() {
        use std::path::Path;
        assert_eq!(
            FlockFormat::from_path(Path::new("Flockfile.toml")),
            Some(FlockFormat::Toml)
        );
        assert_eq!(
            FlockFormat::from_path(Path::new("f.yml")),
            Some(FlockFormat::Yaml)
        );
        assert_eq!(
            FlockFormat::from_path(Path::new("f.json5")),
            Some(FlockFormat::Json5)
        );
        assert_eq!(FlockFormat::from_path(Path::new("f.js")), None);
    }

    #[test]
    fn discover_prefers_toml_then_capitalized() {
        // tempdir gives RAII cleanup instead of a manual remove_dir_all, so
        // a failing assertion above can't leak the directory.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("flockfile.json"), "{}").unwrap();
        std::fs::write(dir.path().join("Flockfile.yaml"), "").unwrap();
        assert_eq!(
            discover(dir.path()),
            Some(dir.path().join("Flockfile.yaml"))
        );
        std::fs::write(dir.path().join("Flockfile.toml"), "").unwrap();
        assert_eq!(
            discover(dir.path()),
            Some(dir.path().join("Flockfile.toml"))
        );
    }

    /// fails if a `.js` name is ever added to the discovery order. Reading
    /// one runs node on it, and discovery is the path with no operator in
    /// the loop, so it must never reach node.
    #[test]
    fn discovery_never_names_a_js_file_and_stays_ten_names() {
        assert_eq!(DISCOVERY_ORDER.len(), 10);
        for name in DISCOVERY_ORDER {
            assert!(
                !name.ends_with(".js"),
                "{name} would let `shep start` execute a repo's JavaScript"
            );
            assert!(FlockFormat::from_path(Path::new(name)).is_some());
        }
    }

    #[test]
    fn yaml_deep_nesting_is_rejected_without_crashing() {
        // 5000-deep flow-style nesting must return Err from serde-saphyr,
        // never overflow the stack.
        let deep = "[".repeat(5000);
        let result = Flockfile::parse(&deep, FlockFormat::Yaml);
        assert!(matches!(result, Err(FlockfileError::Yaml(_))));
    }

    #[test]
    fn yaml_alias_bomb_is_bounded() {
        // Billion-laughs shape: each level aliases the previous twice. The
        // backend must reject it or resolve it bounded; completing
        // quickly is the assertion.
        let mut bomb = String::from("a: &a [\"x\",\"x\"]\n");
        for i in 1..9 {
            bomb.push_str(&format!(
                "{c}: &{c} [*{p},*{p}]\n",
                c = (b'a' + i) as char,
                p = (b'a' + i - 1) as char
            ));
        }
        let result = Flockfile::parse(&bomb, FlockFormat::Yaml);
        assert!(result.is_err(), "alias bomb must not produce a valid flock");
    }

    #[test]
    fn json5_beyond_max_nesting_depth_is_rejected_without_crashing() {
        // json5 stack-overflows (SIGABRT) around ~4500 levels, so the depth
        // guard must reject this before calling into it. 5000 unclosed `[`
        // is nonsense JSON5, but the guard runs before any real parsing.
        let src = "[".repeat(5000);
        assert_eq!(
            Flockfile::parse(&src, FlockFormat::Json5).unwrap_err(),
            FlockfileError::Json5("nesting depth exceeds 64".to_string())
        );
    }

    #[test]
    fn json5_nesting_depth_counts_concurrently_open_brackets() {
        let nested = format!("{}{}", "[".repeat(10), "]".repeat(10));
        assert_eq!(json5_nesting_depth(&nested), 10);
    }

    #[test]
    fn json5_nesting_depth_ignores_brackets_inside_strings() {
        let src = r#"{ "a": "[[[[[[[[[[", "b": "esc\"aped [ too" }"#;
        assert_eq!(json5_nesting_depth(src), 1); // only the outer `{`
    }

    #[test]
    fn json5_legitimately_nested_doc_still_parses() {
        // A probe object nested inside an app object inside the app array
        // inside the root object: depth 4, the deepest a real Flockfile
        // schema allows, well under the depth-64 guard.
        let src = r#"{
            app: [{
                name: "web",
                script: "./srv",
                readiness_probe: { kind: "http", target: "http://localhost/x" },
            }],
        }"#;
        let flock = Flockfile::parse(src, FlockFormat::Json5).unwrap();
        assert_eq!(flock.apps.len(), 1);
    }

    #[test]
    fn json5_line_comment_apostrophe_does_not_hide_deep_nesting() {
        // Regression: a `'` inside a `//` comment must not flip the scanner
        // into string mode and make it ignore every bracket that follows,
        // letting an over-deep document slip past the guard.
        let src = format!("// don't nest\n{}", "[".repeat(5000));
        assert_eq!(
            Flockfile::parse(&src, FlockFormat::Json5).unwrap_err(),
            FlockfileError::Json5("nesting depth exceeds 64".to_string())
        );
    }

    #[test]
    fn json5_block_comment_apostrophe_does_not_hide_deep_nesting() {
        let src = format!("/* it's fine */\n{}", "[".repeat(5000));
        assert_eq!(
            Flockfile::parse(&src, FlockFormat::Json5).unwrap_err(),
            FlockfileError::Json5("nesting depth exceeds 64".to_string())
        );
    }

    #[test]
    fn json5_benign_comment_does_not_undercount_a_real_document() {
        // Same depth-4 document as `json5_legitimately_nested_doc_still_parses`,
        // plus a comment (apostrophe included) that must be skipped cleanly
        // rather than throwing off the count.
        let src = r#"{
            /* it's the app list */
            app: [{
                name: "web",
                script: "./srv",
                readiness_probe: { kind: "http", target: "http://localhost/x" },
            }],
        }"#;
        let flock = Flockfile::parse(src, FlockFormat::Json5).unwrap();
        assert_eq!(flock.apps.len(), 1);
    }

    /// Resolves a `$ref` into `$defs`, one hop, and returns the subschema.
    /// Everything with a `schema_name` is referenced rather than inlined, so
    /// an assertion that does not follow the ref is asserting about a
    /// `{"$ref": …}` object and passes or fails for the wrong reason.
    #[cfg(feature = "schema")]
    fn resolved<'a>(
        root: &'a serde_json::Value,
        node: &'a serde_json::Value,
    ) -> &'a serde_json::Value {
        match node.get("$ref").and_then(serde_json::Value::as_str) {
            Some(r) => {
                let name = r
                    .strip_prefix("#/$defs/")
                    .expect("every $ref in this schema points into $defs");
                &root["$defs"][name]
            }
            None => node,
        }
    }

    /// fails whenever the Flockfile grammar changes and the committed schema
    /// does not. That includes a doc-comment edit: schemars reads `///` into
    /// `description`, which becomes hover text in the operator's editor, so
    /// a docs-only change is a real schema change, and regenerating is the
    /// correct response, not a sign anything broke.
    #[cfg(feature = "schema")]
    #[test]
    fn the_committed_schema_is_current() {
        assert_eq!(
            flockfile_schema_string(),
            COMMITTED,
            "crates/shep-core/assets/flockfile.schema.json is stale. Regenerate it:\n    {REGENERATE}\n\
             A doc-comment edit on AppConfig counts; schemars puts doc comments \
             into `description`."
        );
    }

    /// fails if the artefact goes back to describing one app. The document is
    /// `{"app": [ … ]}`; a schema whose own `required` names `name` and
    /// `script` is an AppConfig schema under a Flockfile filename, and every
    /// real Flockfile would fail against it.
    #[cfg(feature = "schema")]
    #[test]
    fn the_schema_describes_a_document_not_one_app() {
        let schema: serde_json::Value = serde_json::from_str(&flockfile_schema_string()).unwrap();
        assert!(schema["properties"]["app"].is_object(), "{schema}");
        assert_eq!(schema["properties"]["app"]["type"], "array", "{schema}");
        assert!(
            schema["properties"]["name"].is_null(),
            "root must not be an app: {schema}"
        );
        assert!(schema["$defs"]["AppConfig"].is_object(), "{schema}");
    }

    /// fails if the schema starts describing `normalize`'s grammar instead of
    /// serde's. The four signal names belong to a validation step elsewhere;
    /// a schema that listed them would be describing something it cannot see.
    #[cfg(feature = "schema")]
    #[test]
    fn kill_signal_stays_an_unconstrained_string() {
        let schema: serde_json::Value = serde_json::from_str(&flockfile_schema_string()).unwrap();
        let field = resolved(
            &schema,
            &schema["$defs"]["AppConfig"]["properties"]["kill_signal"],
        );
        let types = field["type"]
            .as_array()
            .unwrap_or_else(|| panic!("kill_signal must carry a type array: {field}"));
        assert!(
            types.iter().any(|t| t == "string"),
            "kill_signal must accept a string: {field}"
        );
        assert!(
            field.get("enum").is_none(),
            "kill_signal must not become an enum of the four signal names: {field}"
        );
        assert!(
            field.get("pattern").is_none(),
            "kill_signal must not become pattern-constrained: {field}"
        );
    }

    /// fails if MemSize or UpDuration reverts to a derive and starts
    /// describing its inner integer. Follows the `$ref`: the fields are
    /// references into `$defs`, not inline schemas.
    #[cfg(feature = "schema")]
    #[test]
    fn duration_and_memory_fields_are_string_shaped() {
        let schema: serde_json::Value = serde_json::from_str(&flockfile_schema_string()).unwrap();
        let app = &schema["$defs"]["AppConfig"]["properties"];

        // `min_uptime: UpDuration` (not `Option`) is a bare `$ref`.
        let min_uptime = resolved(&schema, &app["min_uptime"]);
        assert_eq!(min_uptime["type"], "string", "{min_uptime}");
        assert_eq!(min_uptime["pattern"], r"^\d+(ms|h|m|s)?$", "{min_uptime}");

        // `max_memory: Option<MemSize>` is a `$ref` under `anyOf` beside `"null"`.
        let any_of = app["max_memory"]["anyOf"]
            .as_array()
            .unwrap_or_else(|| panic!("max_memory must be anyOf: {}", app["max_memory"]));
        let ref_node = any_of
            .iter()
            .find(|v| v.get("$ref").is_some())
            .unwrap_or_else(|| panic!("max_memory's anyOf must carry a $ref: {any_of:?}"));
        let max_memory = resolved(&schema, ref_node);
        assert_eq!(max_memory["type"], "string", "{max_memory}");
        assert_eq!(max_memory["pattern"], r"^\d+(G|M|K)?$", "{max_memory}");
    }

    /// fails if a Flockfile carrying a dog's own configuration is refused.
    ///
    /// A dog with per-app configuration has nowhere else to put it: it
    /// belongs beside the app's declaration, in the repository the dog
    /// deploys.
    ///
    /// The contents are not validated: shep does not know what a dog's
    /// keys mean, and refusing a document for not recognising another
    /// program's config is a coupling neither side wants.
    #[test]
    fn a_dog_table_is_accepted_and_ignored() {
        let src = r#"
[dog.deploy]
command = "npm run build"
artifacts = ["dist/app.js"]

[dog.some-other-dog]
anything = { nested = true, count = 3 }

[[app]]
name = "web"
script = "./srv"
"#;
        let flock =
            Flockfile::parse(src, FlockFormat::Toml).expect("a dog's table is not an error");
        assert_eq!(flock.apps.len(), 1);
        assert_eq!(flock.apps[0].name, "web");
    }

    /// fails if `dog` accepts something that is not a table.
    ///
    /// Not reading what a dog wrote does not mean not caring whether it
    /// wrote a table: that would make this the one key where a typo does
    /// not fail loudly.
    #[test]
    fn a_dog_that_is_not_a_table_is_refused() {
        for value in ["5", "\"nope\"", "[1, 2]", "true"] {
            let src = format!("dog = {value}\n\n[[app]]\nname = \"web\"\nscript = \"./srv\"\n");
            assert!(
                Flockfile::parse(&src, FlockFormat::Toml).is_err(),
                "`dog = {value}` is not a table and must be refused"
            );
        }
    }

    /// fails if a typo anywhere else stops failing loudly.
    ///
    /// Exactly one more key is legal, which is the whole reason the table is
    /// nested under one name rather than allowing loose top-level keys.
    #[test]
    fn a_key_that_is_not_dog_still_fails() {
        let src = r#"
[build]
command = "npm run build"

[[app]]
name = "web"
script = "./srv"
"#;
        let err = Flockfile::parse(src, FlockFormat::Toml)
            .expect_err("an unknown top-level key must still be refused");
        assert!(
            format!("{err}").contains("build"),
            "the refusal must name the key: {err}"
        );
    }

    #[test]
    fn a_schema_key_is_accepted_and_ignored() {
        let src = r#"{ "$schema": "./flockfile.schema.json",
                       "app": [{ "name": "web", "script": "./srv" }] }"#;
        let flock = Flockfile::parse(src, FlockFormat::Json).unwrap();
        assert_eq!(flock.apps.len(), 1);
    }

    /// fails if the new field is implemented by relaxing
    /// `deny_unknown_fields` instead of naming one more key, which would
    /// silently accept every typo the document lock exists to catch.
    #[test]
    fn one_more_key_is_legal_and_no_others_are() {
        let src = r#"{ "schema": "x", "app": [{ "name": "w", "script": "./s" }] }"#;
        assert!(
            matches!(
                Flockfile::parse(src, FlockFormat::Json),
                Err(FlockfileError::Json(_))
            ),
            "bare `schema` (no $) must still be an unknown field"
        );
    }

    #[test]
    fn a_toml_flockfile_takes_the_key_too() {
        let src = "\"$schema\" = \"./flockfile.schema.json\"\n\
                   [[app]]\nname = \"web\"\nscript = \"./srv\"\n";
        assert_eq!(
            Flockfile::parse(src, FlockFormat::Toml).unwrap().apps.len(),
            1
        );
    }

    /// fails if the declared key set is inferred from values rather than read
    /// from the document. `autorestart = true` is also the default, so a
    /// parser that reports "fields that differ from Default" would miss it,
    /// and a later file load would then overwrite an operator who had
    /// turned it off.
    #[test]
    fn declared_reports_keys_the_document_wrote_even_at_their_default() {
        let text = r#"
[[app]]
name = "web"
script = "./srv"
autorestart = true
"#;
        let apps = Flockfile::parse_declared(text, FlockFormat::Toml).unwrap();
        assert_eq!(apps.len(), 1);
        let declared = &apps[0].declared;
        assert!(declared.contains("autorestart"), "declared: {declared:?}");
        assert!(declared.contains("name"));
        assert!(declared.contains("script"));
        assert!(
            !declared.contains("max_memory"),
            "a key nobody wrote is not declared"
        );
        assert_eq!(declared.len(), 3);
    }

    /// fails if env keys are not reported separately. `env` is the only map
    /// of user-supplied keys in `AppConfig`, so the merge treats it one
    /// level deeper than every other field.
    #[test]
    fn declared_env_reports_the_keys_inside_the_env_table() {
        let text = r#"
[[app]]
name = "web"
script = "./srv"
env = { DB_HOST = "", NODE_ENV = "production" }
"#;
        let apps = Flockfile::parse_declared(text, FlockFormat::Toml).unwrap();
        assert_eq!(
            apps[0].declared_env.iter().collect::<Vec<_>>(),
            vec!["DB_HOST", "NODE_ENV"]
        );
        assert!(apps[0].declared.contains("env"));
    }

    /// A typo in a Flockfile must still be loud. This is the whole reason
    /// `deny_unknown_fields` was there.
    #[test]
    fn a_misspelled_flockfile_key_is_refused_and_named() {
        let err = Flockfile::parse(
            "[[app]]\nname = \"web\"\nscript = \"./srv\"\nmax_restrts = 5\n",
            FlockFormat::Toml,
        )
        .expect_err("a typo must be refused");
        let FlockfileError::UnknownKeys { keys } = err else {
            panic!("expected UnknownKeys, got {err:?}");
        };
        assert!(
            keys.iter().any(|k| k.contains("max_restrts")),
            "got {keys:?}"
        );
    }

    /// Nesting is why this uses serde_ignored rather than a key list.
    ///
    /// `kind`/`target` are supplied alongside the typo: both are required by
    /// `ProbeConfig` with no default, and omitting them would surface a
    /// missing-field error instead of the unknown-key one this test means to
    /// exercise.
    #[test]
    fn a_misspelled_key_inside_a_probe_is_also_named() {
        let err = Flockfile::parse(
            "[[app]]\nname = \"web\"\nscript = \"./srv\"\n[app.readiness_probe]\nkind = \"http\"\ntarget = \"http://localhost/x\"\ntimeuot = \"5s\"\n",
            FlockFormat::Toml,
        )
        .expect_err("a nested typo must be refused");
        let FlockfileError::UnknownKeys { keys } = err else {
            panic!("expected UnknownKeys, got {err:?}");
        };
        // The variant alone would pass on any path at all, including one
        // from a different app. Nesting is the reason this parse goes
        // through `serde_ignored` rather than a flat key list, so the
        // path is the thing worth asserting.
        assert!(
            keys.iter()
                .any(|key| key.contains("readiness_probe") && key.contains("timeuot")),
            "the nested path should name both the probe and the key: {keys:?}"
        );
    }

    /// The design goal is one refusal naming every typo, not one refusal
    /// per run. Two misspelled keys in one document must both show up in
    /// the single [`FlockfileError::UnknownKeys`] this produces.
    #[test]
    fn two_misspelled_keys_are_both_named_in_one_error() {
        let err = Flockfile::parse(
            "[[app]]\nname = \"web\"\nscript = \"./srv\"\nmax_restrts = 5\ninstences = 2\n",
            FlockFormat::Toml,
        )
        .expect_err("both typos must be refused");
        let FlockfileError::UnknownKeys { keys } = err else {
            panic!("expected UnknownKeys, got {err:?}");
        };
        assert!(
            keys.iter().any(|k| k.contains("max_restrts")),
            "got {keys:?}"
        );
        assert!(keys.iter().any(|k| k.contains("instences")), "got {keys:?}");
    }

    /// fails if a format other than TOML loses the unknown-key refusal.
    /// `parse_into_ignoring` dispatches over all four; a regression here
    /// means a format bypassed `serde_ignored` on the way through.
    #[test]
    fn a_misspelled_key_is_refused_in_every_parse_format() {
        let cases: [(FlockFormat, &str); 4] = [
            (
                FlockFormat::Toml,
                "[[app]]\nname = \"web\"\nscript = \"./srv\"\nmax_restrts = 5\n",
            ),
            (
                FlockFormat::Yaml,
                "app:\n  - name: web\n    script: ./srv\n    max_restrts: 5\n",
            ),
            (
                FlockFormat::Json,
                r#"{"app":[{"name":"web","script":"./srv","max_restrts":5}]}"#,
            ),
            (
                FlockFormat::Json5,
                "{ app: [{ name: \"web\", script: \"./srv\", max_restrts: 5 }] }",
            ),
        ];
        for (format, text) in cases {
            let err = Flockfile::parse(text, format).expect_err("a typo must be refused");
            assert!(
                matches!(err, FlockfileError::UnknownKeys { .. }),
                "{format:?}: got {err:?}"
            );
        }
    }

    /// fails if a format other than TOML loses the key set. All four go
    /// through one generic intermediate, so a regression here means the
    /// intermediate was bypassed for a format.
    #[test]
    fn declared_survives_every_parse_format() {
        let cases: [(FlockFormat, &str); 4] = [
            (
                FlockFormat::Toml,
                "[[app]]\nname = \"web\"\nscript = \"./srv\"\nautorestart = true\n",
            ),
            (
                FlockFormat::Yaml,
                "app:\n  - name: web\n    script: ./srv\n    autorestart: true\n",
            ),
            (
                FlockFormat::Json,
                r#"{"app":[{"name":"web","script":"./srv","autorestart":true}]}"#,
            ),
            (
                FlockFormat::Json5,
                "{ app: [{ name: \"web\", script: \"./srv\", autorestart: true }] }",
            ),
        ];
        for (format, text) in cases {
            let apps = Flockfile::parse_declared(text, format)
                .unwrap_or_else(|e| panic!("{format:?} failed to parse: {e}"));
            assert!(
                apps[0].declared.contains("autorestart"),
                "{format:?}: declared {:?}",
                apps[0].declared
            );
        }
    }
}