nodex-core 0.2.2

Universal graph-based document tool — core library
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
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;

use crate::error::{Error, Result};

/// Root configuration deserialized from `nodex.toml`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
    #[serde(default)]
    pub scope: ScopeConfig,
    #[serde(default)]
    pub kinds: KindsConfig,
    #[serde(default)]
    pub statuses: StatusesConfig,
    #[serde(default)]
    pub identity: IdentityConfig,
    #[serde(default)]
    pub schema: SchemaConfig,
    #[serde(default)]
    pub rules: RulesConfig,
    #[serde(default)]
    pub parser: ParserConfig,
    #[serde(default)]
    pub detection: DetectionConfig,
    #[serde(default)]
    pub output: OutputConfig,
    #[serde(default)]
    pub report: ReportConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScopeConfig {
    #[serde(default)]
    pub include: Vec<String>,
    #[serde(default)]
    pub exclude: Vec<String>,
    #[serde(default)]
    pub conditional_exclude: Vec<ConditionalExclude>,
}

impl Default for ScopeConfig {
    fn default() -> Self {
        Self {
            include: vec!["**/*.md".to_string()],
            exclude: vec![],
            conditional_exclude: vec![],
        }
    }
}

/// When a file matching `parent_glob` satisfies `condition` (today the
/// only supported condition is `status_terminal`), every other file in
/// the parent's directory is dropped from scan scope. The parent itself
/// stays in scope so it still parses into the graph.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConditionalExclude {
    pub parent_glob: String,
    #[serde(default = "default_condition")]
    pub condition: String,
}

fn default_condition() -> String {
    "status_terminal".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KindsConfig {
    #[serde(default = "default_kinds")]
    pub allowed: Vec<String>,
}

impl Default for KindsConfig {
    fn default() -> Self {
        Self {
            allowed: default_kinds(),
        }
    }
}

fn default_kinds() -> Vec<String> {
    ["generic", "guide", "readme"]
        .iter()
        .map(|s| s.to_string())
        .collect()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatusesConfig {
    #[serde(default = "default_statuses")]
    pub allowed: Vec<String>,
    #[serde(default = "default_terminal")]
    pub terminal: Vec<String>,
}

impl Default for StatusesConfig {
    fn default() -> Self {
        Self {
            allowed: default_statuses(),
            terminal: default_terminal(),
        }
    }
}

fn default_statuses() -> Vec<String> {
    [
        "active",
        "superseded",
        "archived",
        "deprecated",
        "abandoned",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect()
}

fn default_terminal() -> Vec<String> {
    ["superseded", "archived", "deprecated", "abandoned"]
        .iter()
        .map(|s| s.to_string())
        .collect()
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IdentityConfig {
    #[serde(default)]
    pub kind_rules: Vec<KindRule>,
    #[serde(default)]
    pub id_rules: Vec<IdRule>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KindRule {
    pub glob: String,
    pub kind: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IdRule {
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub glob: Option<String>,
    pub template: String,
}

/// Document-schema constraints.
///
/// Top-level entries (`required`, `types`, `enums`, `cross_field`)
/// apply to **every** document. Per-kind tightening is expressed in
/// `overrides`; rules combine the global set with the first matching
/// override so kinds inherit a project-wide baseline without ceremony.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaConfig {
    #[serde(default = "default_required")]
    pub required: Vec<String>,
    #[serde(default)]
    pub types: BTreeMap<String, FieldType>,
    #[serde(default)]
    pub enums: BTreeMap<String, Vec<String>>,
    #[serde(default)]
    pub cross_field: Vec<CrossFieldSpec>,
    #[serde(default)]
    pub overrides: Vec<SchemaOverride>,
}

impl Default for SchemaConfig {
    fn default() -> Self {
        Self {
            required: default_required(),
            types: BTreeMap::new(),
            enums: BTreeMap::new(),
            cross_field: vec![],
            overrides: vec![],
        }
    }
}

fn default_required() -> Vec<String> {
    ["id", "title", "kind", "status"]
        .iter()
        .map(|s| s.to_string())
        .collect()
}

/// Per-kind schema constraints.
///
/// Every field except `kinds` and `required` defaults to an empty
/// collection, and each corresponding rule short-circuits when empty.
/// Projects that never configure these keep today's behaviour verbatim.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaOverride {
    pub kinds: Vec<String>,
    pub required: Vec<String>,
    #[serde(default)]
    pub types: BTreeMap<String, FieldType>,
    #[serde(default)]
    pub enums: BTreeMap<String, Vec<String>>,
    #[serde(default)]
    pub cross_field: Vec<CrossFieldSpec>,
}

/// Accepted frontmatter field types. Covers the scalars that actually
/// appear in document frontmatter. Add a variant when a real need arises —
/// the `match` statement in the validator will force every consumer to
/// acknowledge the new type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FieldType {
    String,
    Integer,
    Bool,
    Date,
}

/// Conditional field requirement: "when LHS predicate holds, `require` must be present".
///
/// v1 parser accepts only `"<field>=<value>"` equality. Extending to new
/// predicates (e.g. `in`, `matches`) happens by versioning the `when`
/// string into a richer type, without invalidating existing configs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrossFieldSpec {
    pub when: String,
    pub require: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RulesConfig {
    #[serde(default)]
    pub naming: Vec<NamingRule>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NamingRule {
    pub glob: String,
    pub pattern: String,
    #[serde(default)]
    pub sequential: bool,
    #[serde(default)]
    pub unique: bool,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ParserConfig {
    #[serde(default)]
    pub link_patterns: Vec<LinkPattern>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinkPattern {
    pub pattern: String,
    pub relation: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectionConfig {
    #[serde(default = "default_stale_days")]
    pub stale_days: u32,
    #[serde(default = "default_orphan_grace_days")]
    pub orphan_grace_days: u32,
    /// Kinds whose nodes are skipped by orphan detection regardless of incoming-edge count.
    ///
    /// Use for kinds that are leaf-by-design (entry-point skills, package READMEs, runbook
    /// procedures, architecture overviews) where a missing inbound edge is the expected
    /// shape rather than a defect. Per-node `orphan_ok: true` remains available for the
    /// per-instance opt-out within tracked kinds.
    #[serde(default)]
    pub orphan_ok_kinds: Vec<String>,
}

impl Default for DetectionConfig {
    fn default() -> Self {
        Self {
            stale_days: default_stale_days(),
            orphan_grace_days: default_orphan_grace_days(),
            orphan_ok_kinds: Vec::new(),
        }
    }
}

fn default_stale_days() -> u32 {
    180
}

fn default_orphan_grace_days() -> u32 {
    14
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputConfig {
    #[serde(default = "default_output_dir")]
    pub dir: String,
}

impl Default for OutputConfig {
    fn default() -> Self {
        Self {
            dir: default_output_dir(),
        }
    }
}

fn default_output_dir() -> String {
    "_index".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportConfig {
    #[serde(default = "default_report_title")]
    pub title: String,
    #[serde(default = "default_god_node_display_limit")]
    pub god_node_display_limit: usize,
    #[serde(default = "default_display_limit")]
    pub orphan_display_limit: usize,
    #[serde(default = "default_display_limit")]
    pub stale_display_limit: usize,
}

impl Default for ReportConfig {
    fn default() -> Self {
        Self {
            title: default_report_title(),
            god_node_display_limit: default_god_node_display_limit(),
            orphan_display_limit: default_display_limit(),
            stale_display_limit: default_display_limit(),
        }
    }
}

fn default_report_title() -> String {
    "Document Graph".to_string()
}

fn default_god_node_display_limit() -> usize {
    10
}

fn default_display_limit() -> usize {
    20
}

impl Config {
    /// Load config from a `nodex.toml` file. Returns default config if not found.
    ///
    /// Config is validated for internal consistency before it is returned,
    /// so downstream code can assume that `enums` / `cross_field` references
    /// are well-formed.
    pub fn load(root: &Path) -> Result<Self> {
        let path = root.join("nodex.toml");
        if !path.exists() {
            return Ok(Self::default());
        }
        let content = std::fs::read_to_string(&path).map_err(|e| Error::Io {
            path: path.clone(),
            source: e,
        })?;
        let config: Self =
            toml::from_str(&content).map_err(|e| Error::Config(format!("{path:?}: {e}")))?;
        config.validate()?;
        Ok(config)
    }

    /// Validate internal consistency. Called automatically by `load()`.
    ///
    /// Rejects definitions that would otherwise only surface as
    /// confusing runtime behaviour:
    /// - `enums` on collection-valued built-in fields (`tags`,
    ///   `supersedes`, `implements`, `related`) — these cannot be
    ///   validated against a scalar set, so silent ignore would trap
    ///   users who typed the obvious syntax and saw no effect.
    /// - `enums.status` / `enums.kind` values that are not in the
    ///   corresponding global `allowed` list.
    /// - `cross_field.when` expressions that don't parse.
    /// - `cross_field.when`'s LHS and `cross_field.require` referring
    ///   to a field name that is not a built-in scalar and is not
    ///   declared in the override's `types` / `enums` / `required`.
    pub fn validate(&self) -> Result<()> {
        // Refuse structurally-broken configs: empty `kinds.allowed`
        // means every document would be kind-less (inference falls
        // back to "generic") yet no kind would ever be valid — either
        // the user is mis-configured or they meant "accept all kinds"
        // (which is the default when the key is omitted entirely).
        if self.kinds.allowed.is_empty() {
            return Err(Error::Config(
                "kinds.allowed must not be empty; omit the key to accept the defaults, \
                 or list every kind your project uses"
                    .to_string(),
            ));
        }

        // Same rationale as `kinds.allowed`: an empty `statuses.allowed`
        // would make every status value invalid and break scaffolding,
        // which picks the first allowed status for the initial value.
        if self.statuses.allowed.is_empty() {
            return Err(Error::Config(
                "statuses.allowed must not be empty; omit the key to accept the defaults, \
                 or list every status your project uses"
                    .to_string(),
            ));
        }

        // `nodex lifecycle <action>` writes a fixed target status per
        // action (supersede → "superseded", archive → "archived", …).
        // If the project's `statuses.allowed` omits any of those, a
        // lifecycle transition would silently produce a document that
        // then fails enum validation. Surface the mismatch at load time
        // instead, with a message pointing at the exact missing values.
        let missing: Vec<&str> = crate::lifecycle::LIFECYCLE_TARGET_STATUSES
            .iter()
            .copied()
            .filter(|s| !self.statuses.allowed.iter().any(|a| a == s))
            .collect();
        if !missing.is_empty() {
            return Err(Error::Config(format!(
                "statuses.allowed is missing lifecycle target status(es): {missing:?}; \
                 add them to `statuses.allowed` or omit the key to accept the defaults"
            )));
        }

        // `FALLBACK_KIND` is what `parser::identity::infer_kind`
        // assigns when no `identity.kind_rules` glob matches a
        // document's path, and what `migrate` injects when scaffolding
        // frontmatter onto a bare file. Leaving this out of
        // `kinds.allowed` was the exact defect that let `migrate` /
        // `parse_document` write documents their own config then
        // rejected. Require its presence at load; projects that want
        // every document strongly classified can still write
        // exhaustive `kind_rules`, in which case the fallback simply
        // never fires.
        if !self
            .kinds
            .allowed
            .iter()
            .any(|k| k == crate::parser::identity::FALLBACK_KIND)
        {
            return Err(Error::Config(format!(
                "kinds.allowed is missing the fallback kind {:?}; \
                 either include it, or omit `kinds.allowed` to accept the defaults",
                crate::parser::identity::FALLBACK_KIND
            )));
        }

        // Every `detection.orphan_ok_kinds` entry must reference a kind
        // the project actually accepts. Otherwise a typo ("skll" instead
        // of "skill") loads cleanly and the runtime exempts nothing —
        // the silent-skip pattern the config-driven rule explicitly
        // forbids. Same shape as the `enums.status` / `enums.kind`
        // subset-of-global-allowed checks below.
        for k in &self.detection.orphan_ok_kinds {
            if !self.kinds.allowed.iter().any(|a| a == k) {
                return Err(Error::Config(format!(
                    "detection.orphan_ok_kinds contains {k:?} which is not in \
                     kinds.allowed; add it to kinds.allowed or remove the exemption"
                )));
            }
        }

        // `output.dir` is joined to the project root whenever build /
        // report / cache writes their artefacts, so a value like
        // `"../escape"` or `"/etc/out"` would silently write files
        // outside the project. `path_guard::reject_traversal` already
        // enforces this invariant for user-supplied paths on rename /
        // scaffold / migrate; extend it to the config surface.
        if !self.output.dir.is_empty() {
            crate::path_guard::reject_traversal(std::path::Path::new(&self.output.dir)).map_err(
                |_| {
                    Error::Config(format!(
                        "output.dir {:?} escapes the project root; \
                         use a relative path without `..` or a leading `/`",
                        self.output.dir
                    ))
                },
            )?;
        }

        self.validate_block(
            "schema",
            &self.schema.required,
            &self.schema.types,
            &self.schema.enums,
            &self.schema.cross_field,
        )?;

        // Validate naming rules at load time rather than silently
        // skipping invalid patterns at check time — a typo in a glob
        // or regex would otherwise validate zero files forever.
        for (idx, nr) in self.rules.naming.iter().enumerate() {
            if globset::Glob::new(&nr.glob).is_err() {
                return Err(Error::Config(format!(
                    "rules.naming[{idx}].glob {:?} is not a valid glob",
                    nr.glob
                )));
            }
            if regex::Regex::new(&nr.pattern).is_err() {
                return Err(Error::Config(format!(
                    "rules.naming[{idx}].pattern {:?} is not a valid regex",
                    nr.pattern
                )));
            }
        }

        for (idx, ov) in self.schema.overrides.iter().enumerate() {
            let ctx = format!("schema.overrides[{idx}] (kinds={:?})", ov.kinds);
            self.validate_block(&ctx, &ov.required, &ov.types, &ov.enums, &ov.cross_field)?;
            // Reject cross_field entries that duplicate a global entry.
            // `cross_field_for` accumulates global + override — if a
            // user copy-pastes the same rule into both slots, every
            // matching node would get two violations. Fail loud at
            // load time rather than debug silently.
            for cf in &ov.cross_field {
                if self
                    .schema
                    .cross_field
                    .iter()
                    .any(|g| g.when == cf.when && g.require == cf.require)
                {
                    return Err(Error::Config(format!(
                        "{ctx}: cross_field {{ when={:?}, require={:?} }} \
                         is already declared in [schema].cross_field — \
                         remove the override copy or change its predicate",
                        cf.when, cf.require
                    )));
                }
            }
        }
        Ok(())
    }

    /// Validate one schema block (the global [schema] or one override).
    /// Extracted so both share the same rules.
    fn validate_block(
        &self,
        ctx: &str,
        required: &[String],
        types: &BTreeMap<String, FieldType>,
        enums: &BTreeMap<String, Vec<String>>,
        cross_field: &[CrossFieldSpec],
    ) -> Result<()> {
        for (field, allowed) in enums {
            if is_collection_builtin(field) {
                return Err(Error::Config(format!(
                    "{ctx}: enums.{field} — collection-valued built-in \
                     fields cannot have a scalar enum constraint"
                )));
            }
            let global = match field.as_str() {
                "status" => Some((&self.statuses.allowed, "statuses.allowed")),
                "kind" => Some((&self.kinds.allowed, "kinds.allowed")),
                _ => None,
            };
            if let Some((global, key)) = global {
                for value in allowed {
                    if !global.contains(value) {
                        return Err(Error::Config(format!(
                            "{ctx}: enums.{field} contains {value:?} \
                             which is not in {key}"
                        )));
                    }
                }
            }

            // A narrowing enum on `status` — whether at the global
            // `[schema]` level or inside a `[[schema.overrides]]` block —
            // must still cover the four lifecycle target statuses.
            // Otherwise `nodex lifecycle <action>` on a matching document
            // would write a status value that immediately fails its own
            // enum validation, producing a config the tool can mutate
            // only by violating itself.
            if field == "status" {
                let missing: Vec<&str> = crate::lifecycle::LIFECYCLE_TARGET_STATUSES
                    .iter()
                    .copied()
                    .filter(|s| !allowed.iter().any(|a| a == s))
                    .collect();
                if !missing.is_empty() {
                    return Err(Error::Config(format!(
                        "{ctx}: enums.status narrows below the lifecycle target set; \
                         missing {missing:?}. Either include all four \
                         (superseded, archived, deprecated, abandoned) or drop \
                         the enum constraint on status"
                    )));
                }
            }

            // If the same field also declares a non-string `types`
            // constraint, every enum value has to parse as that type.
            // Otherwise `scaffold`'s default ("first allowed enum
            // value") writes a document that immediately fails
            // `field_type` on the next `check` — observed with
            // `types = { priority = "integer" }` combined with
            // `enums = { priority = ["low", "medium", "high"] }`.
            if let Some(ty) = types.get(field)
                && let Some(bad) = allowed.iter().find(|v| !value_matches_field_type(v, *ty))
            {
                return Err(Error::Config(format!(
                    "{ctx}: enums.{field} value {bad:?} is not a valid \
                     {ty:?}; either drop the enum or widen types.{field}"
                )));
            }
        }

        for cf in cross_field {
            let predicate = parse_when(&cf.when).map_err(|e| {
                Error::Config(format!("{ctx}: cross_field.when {:?}: {e}", cf.when))
            })?;
            let WhenPredicate::Equals { field, .. } = &predicate;
            ensure_field_known(field, required, types, enums, ctx, "cross_field.when")?;
            ensure_field_known(
                &cf.require,
                required,
                types,
                enums,
                ctx,
                "cross_field.require",
            )?;
        }
        Ok(())
    }

    /// Merged view: return every field-type constraint that applies to
    /// a given kind (global + first matching override). Scaffold and
    /// rules use this so every declared constraint is honoured once.
    pub fn types_for(&self, kind: &str) -> BTreeMap<String, FieldType> {
        let mut out = self.schema.types.clone();
        if let Some(ov) = self.schema_override_for(kind) {
            for (k, v) in &ov.types {
                out.insert(k.clone(), *v);
            }
        }
        out
    }

    /// Merged view: every enum constraint that applies to a given kind.
    pub fn enums_for(&self, kind: &str) -> BTreeMap<String, Vec<String>> {
        let mut out = self.schema.enums.clone();
        if let Some(ov) = self.schema_override_for(kind) {
            for (k, v) in &ov.enums {
                out.insert(k.clone(), v.clone());
            }
        }
        out
    }

    /// Merged view: every cross-field constraint that applies to a
    /// given kind. Global and override entries accumulate; an override
    /// never silently drops a global rule.
    pub fn cross_field_for(&self, kind: &str) -> Vec<CrossFieldSpec> {
        let mut out = self.schema.cross_field.clone();
        if let Some(ov) = self.schema_override_for(kind) {
            out.extend_from_slice(&ov.cross_field);
        }
        out
    }

    /// Check whether a status string is terminal.
    pub fn is_terminal(&self, status: &str) -> bool {
        self.statuses.terminal.iter().any(|t| t == status)
    }

    /// Whether nodes of the given kind are exempt from orphan detection.
    ///
    /// Driven by `detection.orphan_ok_kinds`. Pairs with the per-instance
    /// `node.orphan_ok` opt-out so callers can express both "this entire
    /// kind is leaf-by-design" and "this specific document is exceptional".
    /// Named to mirror the field and the per-node flag, paralleling
    /// `is_terminal` ↔ `statuses.terminal`.
    pub fn is_orphan_ok_kind(&self, kind: &str) -> bool {
        self.detection.orphan_ok_kinds.iter().any(|k| k == kind)
    }

    /// Get required fields for a given kind. Falls back to the global
    /// `schema.required` list when no override matches.
    pub fn required_for(&self, kind: &str) -> &[String] {
        for ov in &self.schema.overrides {
            if ov.kinds.iter().any(|k| k == kind) {
                return &ov.required;
            }
        }
        &self.schema.required
    }

    /// Find the schema override that applies to a given kind, if any.
    pub fn schema_override_for(&self, kind: &str) -> Option<&SchemaOverride> {
        self.schema
            .overrides
            .iter()
            .find(|ov| ov.kinds.iter().any(|k| k == kind))
    }

    /// The status value that tool-level actions (`scaffold`, `migrate`)
    /// should write when they create a new document of a given kind.
    ///
    /// Walks from the narrowest declaration to the broadest: per-kind
    /// override's `enums.status`, then the global `schema.enums.status`,
    /// then `statuses.allowed`. The first hit's `first()` wins.
    /// `Config::validate` guarantees each of these is either absent or
    /// non-empty, and that any `enums.status` covers the four lifecycle
    /// targets — so the result is always in-vocabulary and the invariant
    /// holding migrate / scaffold together with `check` never breaks.
    pub fn initial_status_for(&self, kind: &str) -> &str {
        if let Some(ov) = self.schema_override_for(kind)
            && let Some(allowed) = ov.enums.get("status")
            && let Some(first) = allowed.first()
        {
            return first.as_str();
        }
        if let Some(allowed) = self.schema.enums.get("status")
            && let Some(first) = allowed.first()
        {
            return first.as_str();
        }
        self.statuses
            .allowed
            .first()
            .map(String::as_str)
            .expect("statuses.allowed non-empty — enforced by Config::validate")
    }
}

/// Parsed `cross_field.when` predicate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WhenPredicate {
    /// `<field>=<value>` — match when the given field equals the value exactly.
    Equals { field: String, value: String },
}

/// Every built-in scalar field on `Node`. Kept here (not on `Node`) so
/// config validation sees the canonical list without pulling in the
/// whole model module. Collections (`tags`, `supersedes`, etc.) are
/// intentionally excluded — they cannot be members of a scalar enum.
pub const BUILTIN_SCALAR_FIELDS: &[&str] = &[
    "id",
    "title",
    "kind",
    "status",
    "created",
    "updated",
    "reviewed",
    "owner",
    "superseded_by",
];

/// Collection-valued built-in fields. Enum/type constraints on these
/// must be rejected — there is no single scalar value to check.
pub const BUILTIN_COLLECTION_FIELDS: &[&str] = &["tags", "supersedes", "implements", "related"];

/// True when `field` is one of the built-in `Node` fields of any kind.
pub fn is_builtin_node_field(field: &str) -> bool {
    BUILTIN_SCALAR_FIELDS.contains(&field) || BUILTIN_COLLECTION_FIELDS.contains(&field)
}

/// True when `field` is a built-in collection-valued field.
pub fn is_collection_builtin(field: &str) -> bool {
    BUILTIN_COLLECTION_FIELDS.contains(&field)
}

/// True when the raw frontmatter-style string `value` is a valid
/// member of the declared `FieldType`. Used by `Config::validate` to
/// reject configs that pair a typed field with an enum containing
/// values that can never satisfy the type.
fn value_matches_field_type(value: &str, ty: FieldType) -> bool {
    match ty {
        FieldType::String => true,
        FieldType::Integer => value.parse::<i64>().is_ok(),
        FieldType::Bool => matches!(value, "true" | "false"),
        FieldType::Date => chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d").is_ok(),
    }
}

/// Reject field names in `cross_field.when` / `cross_field.require`
/// that are not built-in and not explicitly declared in the current
/// schema block. Keeps typos from turning into silently-skipped checks.
fn ensure_field_known(
    field: &str,
    required: &[String],
    types: &BTreeMap<String, FieldType>,
    enums: &BTreeMap<String, Vec<String>>,
    ctx: &str,
    slot: &str,
) -> Result<()> {
    if is_builtin_node_field(field)
        || required.iter().any(|r| r == field)
        || types.contains_key(field)
        || enums.contains_key(field)
    {
        return Ok(());
    }
    Err(Error::Config(format!(
        "{ctx}: {slot} references unknown field {field:?}; declare it \
         in required / types / enums or use a built-in name"
    )))
}

/// Parse a `cross_field.when` expression. v1 accepts only `field=value`.
///
/// Rejects `==` and any form where the value starts with `=`, so a typo
/// can never silently turn into a predicate that matches nothing. Also
/// rejects empty LHS / RHS and expressions with multiple top-level `=`.
pub fn parse_when(raw: &str) -> std::result::Result<WhenPredicate, String> {
    let trimmed = raw.trim();
    let parts: Vec<&str> = trimmed.splitn(3, '=').collect();
    if parts.len() != 2 {
        return Err(format!(
            "expected exactly one '=' in <field>=<value>; values with \
             embedded '=' are not supported in v1 (got {raw:?})"
        ));
    }
    let field = parts[0].trim();
    let value = parts[1].trim();
    if field.is_empty() || value.is_empty() {
        return Err("expected non-empty <field>=<value>".to_string());
    }
    if value.starts_with('=') {
        return Err("value must not start with '=' (use a single '=' separator)".to_string());
    }
    Ok(WhenPredicate::Equals {
        field: field.to_string(),
        value: value.to_string(),
    })
}

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

    #[test]
    fn parse_when_accepts_simple_equality() {
        let p = parse_when("status=superseded").unwrap();
        assert_eq!(
            p,
            WhenPredicate::Equals {
                field: "status".into(),
                value: "superseded".into()
            }
        );
    }

    #[test]
    fn parse_when_trims_whitespace() {
        let p = parse_when("  status  =  superseded  ").unwrap();
        let WhenPredicate::Equals { field, value } = p;
        assert_eq!(field, "status");
        assert_eq!(value, "superseded");
    }

    #[test]
    fn parse_when_rejects_double_equals() {
        assert!(parse_when("status==foo").is_err());
    }

    #[test]
    fn parse_when_rejects_empty_sides() {
        assert!(parse_when("=foo").is_err());
        assert!(parse_when("field=").is_err());
        assert!(parse_when("").is_err());
    }

    #[test]
    fn parse_when_rejects_triple_equals() {
        assert!(parse_when("a=b=c").is_err());
    }

    fn override_with(kind: &str, mut ov: SchemaOverride) -> Config {
        ov.kinds = vec![kind.into()];
        Config {
            schema: SchemaConfig {
                overrides: vec![ov],
                ..Default::default()
            },
            ..Config::default()
        }
    }

    #[test]
    fn validate_rejects_enum_on_collection_field() {
        let config = override_with(
            "adr",
            SchemaOverride {
                kinds: vec![],
                required: vec![],
                types: BTreeMap::new(),
                enums: [("tags".to_string(), vec!["foo".into()])]
                    .into_iter()
                    .collect(),
                cross_field: vec![],
            },
        );
        let err = config.validate().unwrap_err();
        match err {
            Error::Config(msg) => assert!(msg.contains("collection-valued"), "{msg}"),
            _ => panic!("expected Config error"),
        }
    }

    #[test]
    fn validate_rejects_enum_value_outside_global_allowed() {
        // `statuses.allowed` must cover the four lifecycle target
        // statuses (superseded / archived / deprecated / abandoned);
        // include them so this test isolates the "enum value outside
        // allowed" check rather than tripping the lifecycle-coverage
        // check first.
        let config = Config {
            statuses: StatusesConfig {
                allowed: vec![
                    "active".into(),
                    "superseded".into(),
                    "archived".into(),
                    "deprecated".into(),
                    "abandoned".into(),
                ],
                terminal: vec![],
            },
            schema: SchemaConfig {
                overrides: vec![SchemaOverride {
                    kinds: vec!["adr".into()],
                    required: vec![],
                    types: BTreeMap::new(),
                    enums: [("status".to_string(), vec!["active".into(), "bogus".into()])]
                        .into_iter()
                        .collect(),
                    cross_field: vec![],
                }],
                ..Default::default()
            },
            ..Config::default()
        };
        let err = config.validate().unwrap_err();
        match err {
            Error::Config(msg) => {
                assert!(msg.contains("bogus"));
                assert!(msg.contains("statuses.allowed"));
            }
            _ => panic!("expected Config error"),
        }
    }

    #[test]
    fn validate_rejects_cross_field_unknown_field() {
        let config = override_with(
            "adr",
            SchemaOverride {
                kinds: vec![],
                required: vec![],
                types: BTreeMap::new(),
                enums: BTreeMap::new(),
                cross_field: vec![CrossFieldSpec {
                    when: "statuz=superseded".into(),
                    require: "superseded_by".into(),
                }],
            },
        );
        let err = config.validate().unwrap_err();
        match err {
            Error::Config(msg) => assert!(msg.contains("unknown field"), "{msg}"),
            _ => panic!("expected Config error"),
        }
    }

    #[test]
    fn validate_error_includes_override_context() {
        let config = Config {
            schema: SchemaConfig {
                overrides: vec![SchemaOverride {
                    kinds: vec!["adr".into(), "guide".into()],
                    required: vec![],
                    types: BTreeMap::new(),
                    enums: [("tags".to_string(), vec!["x".into()])]
                        .into_iter()
                        .collect(),
                    cross_field: vec![],
                }],
                ..Default::default()
            },
            ..Config::default()
        };
        let err = config.validate().unwrap_err();
        match err {
            Error::Config(msg) => {
                assert!(msg.contains("overrides[0]"));
                assert!(msg.contains("\"adr\""));
            }
            _ => panic!("expected Config error"),
        }
    }

    #[test]
    fn validate_accepts_empty_schema() {
        Config::default().validate().unwrap();
    }

    #[test]
    fn validate_rejects_statuses_allowed_missing_lifecycle_target() {
        // Omitting "archived" would let `nodex lifecycle archive` write
        // a status value the rest of the project's config treats as
        // invalid. The config must fail fast at load time.
        let config = Config {
            statuses: StatusesConfig {
                allowed: vec![
                    "active".into(),
                    "superseded".into(),
                    "deprecated".into(),
                    "abandoned".into(),
                ],
                terminal: vec!["superseded".into()],
            },
            ..Config::default()
        };
        let err = config.validate().unwrap_err();
        match err {
            Error::Config(msg) => {
                assert!(msg.contains("archived"), "message was: {msg}");
                assert!(msg.contains("lifecycle"), "message was: {msg}");
            }
            _ => panic!("expected Config error"),
        }
    }

    #[test]
    fn validate_rejects_override_status_enum_missing_lifecycle_target() {
        // An override enum that narrows `status` below the four
        // lifecycle targets would let `nodex lifecycle archive` on a
        // matching kind write a status the config's own enum then
        // rejects — the tool mutating itself into invalidity. Refuse
        // at load.
        let config = Config {
            schema: SchemaConfig {
                overrides: vec![SchemaOverride {
                    kinds: vec!["adr".into()],
                    required: vec![],
                    types: BTreeMap::new(),
                    enums: [(
                        "status".to_string(),
                        vec!["active".into(), "superseded".into()],
                    )]
                    .into_iter()
                    .collect(),
                    cross_field: vec![],
                }],
                ..Default::default()
            },
            ..Config::default()
        };
        let err = config.validate().unwrap_err();
        match err {
            Error::Config(msg) => {
                assert!(msg.contains("archived"), "message was: {msg}");
                assert!(msg.contains("lifecycle"), "message was: {msg}");
            }
            _ => panic!("expected Config error"),
        }
    }

    #[test]
    fn validate_rejects_output_dir_escaping_root() {
        // `output.dir` is joined to the project root for every
        // build / report / cache write. A traversal value would
        // silently write `_index/*` outside the project root (seen:
        // `../escape` leaked `graph.json` / `cache.json` /
        // `backlinks.json` into the parent directory). Refuse at load.
        for bad in ["../escape", "/etc/nodex", "docs/../../out"] {
            let config = Config {
                output: OutputConfig {
                    dir: bad.to_string(),
                },
                ..Config::default()
            };
            match config.validate() {
                Err(Error::Config(msg)) => assert!(
                    msg.contains("output.dir") && msg.contains("escapes"),
                    "for {bad:?} got unexpected message: {msg}"
                ),
                other => panic!("value {bad:?} should have been rejected, got {other:?}"),
            }
        }
    }

    #[test]
    fn validate_rejects_kinds_allowed_missing_fallback_kind() {
        // `migrate` / `parse_document` assign the fallback kind
        // ("generic") to any document whose path isn't covered by an
        // `identity.kind_rules` glob. If the user's `kinds.allowed`
        // omits it, that assignment immediately fails FieldEnumRule —
        // the tool writing a document its own config rejects. Refuse
        // at load.
        let config = Config {
            kinds: KindsConfig {
                allowed: vec!["adr".into()],
            },
            ..Config::default()
        };
        let err = config.validate().unwrap_err();
        match err {
            Error::Config(msg) => {
                assert!(msg.contains("generic"), "message was: {msg}");
                assert!(msg.contains("fallback"), "message was: {msg}");
            }
            _ => panic!("expected Config error"),
        }
    }

    #[test]
    fn validate_rejects_enum_value_failing_its_declared_type() {
        // `types = { priority = "integer" }` paired with
        // `enums = { priority = ["low", "medium", "high"] }` was an
        // accepted config that made `scaffold` emit an immediately-
        // invalid document (first enum value written, then FieldTypeRule
        // flagged it). Both constraints can legally coexist, but each
        // enum value must parse as the declared type.
        let config = Config {
            schema: SchemaConfig {
                overrides: vec![SchemaOverride {
                    kinds: vec!["adr".into()],
                    required: vec![],
                    types: [("priority".to_string(), FieldType::Integer)]
                        .into_iter()
                        .collect(),
                    enums: [(
                        "priority".to_string(),
                        vec!["low".into(), "medium".into(), "high".into()],
                    )]
                    .into_iter()
                    .collect(),
                    cross_field: vec![],
                }],
                ..Default::default()
            },
            ..Config::default()
        };
        let err = config.validate().unwrap_err();
        match err {
            Error::Config(msg) => {
                assert!(msg.contains("priority"), "message was: {msg}");
                assert!(msg.contains("\"low\""), "message was: {msg}");
            }
            _ => panic!("expected Config error"),
        }
    }

    #[test]
    fn global_cross_field_applies_without_override() {
        let config = Config {
            schema: SchemaConfig {
                cross_field: vec![CrossFieldSpec {
                    when: "status=superseded".into(),
                    require: "superseded_by".into(),
                }],
                ..Default::default()
            },
            ..Config::default()
        };
        config.validate().unwrap();
        let collected = config.cross_field_for("adr");
        assert_eq!(collected.len(), 1);
        assert_eq!(collected[0].require, "superseded_by");
    }

    #[test]
    fn validate_rejects_cross_field_duplicate_across_global_and_override() {
        let config = Config {
            schema: SchemaConfig {
                cross_field: vec![CrossFieldSpec {
                    when: "status=superseded".into(),
                    require: "superseded_by".into(),
                }],
                overrides: vec![SchemaOverride {
                    kinds: vec!["adr".into()],
                    required: vec![],
                    types: BTreeMap::new(),
                    enums: BTreeMap::new(),
                    cross_field: vec![CrossFieldSpec {
                        when: "status=superseded".into(),
                        require: "superseded_by".into(),
                    }],
                }],
                ..Default::default()
            },
            ..Config::default()
        };
        let err = config.validate().unwrap_err();
        match err {
            Error::Config(msg) => {
                assert!(msg.contains("already declared in [schema].cross_field"));
            }
            _ => panic!("expected Config error"),
        }
    }

    #[test]
    fn validate_rejects_orphan_ok_kind_outside_kinds_allowed() {
        // Listing a kind in `detection.orphan_ok_kinds` that isn't in
        // `kinds.allowed` would let the user think they had exempted
        // a kind from orphan detection while the runtime silently
        // exempts nothing. Refuse at load.
        let config = Config {
            kinds: KindsConfig {
                allowed: vec!["generic".into(), "guide".into(), "readme".into()],
            },
            detection: DetectionConfig {
                orphan_ok_kinds: vec!["skll".into()],
                ..DetectionConfig::default()
            },
            ..Config::default()
        };
        let err = config.validate().unwrap_err();
        match err {
            Error::Config(msg) => {
                assert!(msg.contains("orphan_ok_kinds"), "message was: {msg}");
                assert!(msg.contains("\"skll\""), "message was: {msg}");
                assert!(msg.contains("kinds.allowed"), "message was: {msg}");
            }
            _ => panic!("expected Config error"),
        }
    }

    #[test]
    fn is_orphan_ok_kind_matches_configured_entries() {
        let config = Config {
            kinds: KindsConfig {
                allowed: vec!["generic".into(), "skill".into()],
            },
            detection: DetectionConfig {
                orphan_ok_kinds: vec!["skill".into()],
                ..DetectionConfig::default()
            },
            ..Config::default()
        };
        config.validate().unwrap();
        assert!(config.is_orphan_ok_kind("skill"));
        assert!(!config.is_orphan_ok_kind("generic"));
    }

    #[test]
    fn parse_when_error_mentions_quoting_unsupported() {
        let err = parse_when("status==foo").unwrap_err();
        assert!(err.contains("embedded '='") || err.contains("exactly one"));
    }
}