kazam 1.13.2

Local infrastructure for coding agents: context, visibility, durable execution. One Rust binary, no cloud.
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
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
//! Strict semantic/structural validation for kazam page YAML.
//!
//! serde deserialization catches type errors and missing required fields.
//! This layer catches everything serde can't:
//!   - Component-specific rules (card_grid needs at least one card, etc.)
//!   - Enum value validation (valid theme names, shell types, color names)
//!   - Structural rules (deck pages need slides, non-deck pages need components)
//!   - Cross-references (nav hrefs should point to existing pages)
//!   - Freshness field format validation
//!
//! All validation errors are returned as structured [`ValidationError`] values.
//! The caller decides whether to surface them as JSON or pretty-printed text.

use std::collections::HashSet;
use std::path::Path;

use crate::types::{Component, Page, Shell, SiteConfig, Slide};

// ── Error type ────────────────────────────────────────

#[derive(serde::Serialize)]
pub struct ValidationError {
    /// Source file that contains the error.
    pub file: String,
    /// YAML keypath, e.g. `components[2].cards[0].title`.
    pub path: String,
    /// Short category: `"missing_field"`, `"invalid_value"`, `"structural"`,
    /// `"cross_reference"`, `"format"`.
    pub error_type: String,
    /// Human-readable explanation.
    pub message: String,
    /// Optional hint to help an agent self-correct.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suggestion: Option<String>,
}

impl ValidationError {
    fn new(
        file: impl Into<String>,
        path: impl Into<String>,
        error_type: impl Into<String>,
        message: impl Into<String>,
        suggestion: Option<String>,
    ) -> Self {
        ValidationError {
            file: file.into(),
            path: path.into(),
            error_type: error_type.into(),
            message: message.into(),
            suggestion,
        }
    }
}

// ── Public entry points ───────────────────────────────

/// Validate a single parsed [`Page`] against semantic rules.
/// `file` is included in every error for traceability.
pub fn validate_page(file: &str, page: &Page) -> Vec<ValidationError> {
    let mut errors = Vec::new();
    validate_shell_structure(file, page, &mut errors);
    if let Some(components) = &page.components {
        validate_components(file, "components", components, &mut errors);
    }
    if let Some(slides) = &page.slides {
        for (i, slide) in slides.iter().enumerate() {
            let path = format!("slides[{}].components", i);
            validate_components(file, &path, &slide.components, &mut errors);
        }
        if matches!(page.shell, Shell::Deck) {
            validate_slide_density(file, slides, &mut errors);
        }
    }
    if let Some(fv) = &page.freshness {
        if let Some(freshness) = fv.as_full() {
            validate_freshness(file, "freshness", freshness, &mut errors);
        }
    }
    validate_pack(file, page, &mut errors);
    errors
}

/// Pack pages (`pack:` present) must actually be installable: at least one
/// non-empty markdown component reachable the way `kazam install` collects
/// them (top level or nested in sections), and only known target names.
fn validate_pack(file: &str, page: &Page, errors: &mut Vec<ValidationError>) {
    let Some(pack) = &page.pack else { return };

    const VALID_TARGETS: [&str; 7] = [
        "claude", "cursor", "agents", "windsurf", "copilot", "gemini", "aider",
    ];
    for (i, target) in pack.targets.iter().enumerate() {
        if !VALID_TARGETS.contains(&target.as_str()) {
            errors.push(ValidationError::new(
                file,
                format!("pack.targets[{}]", i),
                "invalid_value",
                format!("unknown pack target \"{}\"", target),
                Some(format!(
                    "Valid targets: {}. Omit targets: to write all.",
                    VALID_TARGETS.join(", ")
                )),
            ));
        }
    }

    fn has_installable_markdown(components: &[Component]) -> bool {
        components.iter().any(|c| match c {
            Component::Markdown { body } => !body.trim().is_empty(),
            Component::Section { components, .. } => has_installable_markdown(components),
            _ => false,
        })
    }

    let ok = page
        .components
        .as_deref()
        .is_some_and(has_installable_markdown);
    if !ok {
        errors.push(ValidationError::new(
            file,
            "pack",
            "structural",
            "pack pages need at least one non-empty markdown component — that's what `kazam install` compiles into tool config files",
            Some("Add a markdown component (top level or inside a section) with the pack's rules, or remove the pack: block.".into()),
        ));
    }

    use crate::types::{MatchMode, PackHook};
    for (i, hook) in pack.hooks.iter().enumerate() {
        let path = format!("pack.hooks[{}]", i);
        match hook {
            PackHook::BlockOnMatch { patterns, mode, .. } => {
                if patterns.is_empty() {
                    errors.push(ValidationError::new(
                        file,
                        &path,
                        "structural",
                        "block_on_match needs at least one pattern",
                        None,
                    ));
                }
                if *mode == MatchMode::Regex {
                    errors.push(ValidationError::new(
                        file,
                        &path,
                        "invalid_value",
                        "regex match mode is not supported yet; use substring or word patterns",
                        None,
                    ));
                }
            }
            PackHook::Allowlist { allow, .. } if allow.is_empty() => {
                errors.push(ValidationError::new(
                    file,
                    &path,
                    "structural",
                    "allowlist needs at least one allowed value",
                    None,
                ));
            }
            _ => {}
        }
    }
}

/// Validate a single YAML file. Parses it as a [`Page`] and runs semantic
/// checks. No cross-reference or site config validation (those need the full
/// directory). Useful for pre-write validation in curata's API layer.
pub fn validate_single_file(path: &Path) -> Vec<ValidationError> {
    let file_str = path.display().to_string();

    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            return vec![ValidationError::new(
                &file_str,
                "",
                "format",
                format!("Could not read file: {}", e),
                None,
            )];
        }
    };

    let page: Page = match serde_yaml::from_str(&content) {
        Ok(p) => p,
        Err(e) => {
            return vec![ValidationError::new(
                &file_str,
                "",
                "format",
                format!("YAML parse error: {}", e),
                Some("Check YAML syntax and required fields (title:, shell:).".into()),
            )];
        }
    };

    validate_page(&file_str, &page)
}

/// Validate a site directory. Parses every `.yaml` file (skipping `kazam.yaml`
/// and `404.yaml`), validates each page, and checks nav cross-references.
pub fn validate_dir(dir: &Path) -> Vec<ValidationError> {
    use std::fs;
    use walkdir::WalkDir;

    let mut errors = Vec::new();

    // Load site config for cross-reference checks.
    let config_path = dir.join("kazam.yaml");
    let config: SiteConfig = if config_path.exists() {
        match fs::read_to_string(&config_path)
            .ok()
            .and_then(|s| serde_yaml::from_str(&s).ok())
        {
            Some(c) => c,
            None => {
                errors.push(ValidationError::new(
                    config_path.display().to_string(),
                    "",
                    "format",
                    "kazam.yaml could not be parsed",
                    Some("Check YAML syntax and required fields (name:).".into()),
                ));
                SiteConfig::default()
            }
        }
    } else {
        SiteConfig::default()
    };

    // Collect all page hrefs (stem-relative, html extension) so we can check
    // nav cross-references. We convert `foo/bar.yaml` → `foo/bar.html`.
    let mut known_pages: HashSet<String> = HashSet::new();

    // First pass: collect pages, parse, validate individually.
    for entry in WalkDir::new(dir)
        .follow_links(true)
        .into_iter()
        .filter_entry(|e| {
            if e.depth() > 0 {
                if let Some(name) = e.file_name().to_str() {
                    if name.starts_with('.') || name == "_site" || name == "prompts" {
                        return false;
                    }
                }
            }
            true
        })
        .flatten()
    {
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        if path.extension().map(|e| e != "yaml").unwrap_or(true) {
            continue;
        }
        let fname = path.file_name().unwrap_or_default();
        if fname == "kazam.yaml" || fname == "404.yaml" {
            continue;
        }

        let rel = match path.strip_prefix(dir) {
            Ok(r) => r,
            Err(_) => continue,
        };

        // Record as a known page (html path).
        let html_path = rel
            .with_extension("html")
            .to_string_lossy()
            .replace('\\', "/");
        known_pages.insert(html_path);

        let file_str = rel.to_string_lossy().to_string();

        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(e) => {
                errors.push(ValidationError::new(
                    &file_str,
                    "",
                    "format",
                    format!("Could not read file: {}", e),
                    None,
                ));
                continue;
            }
        };

        let page: Page = match serde_yaml::from_str(&content) {
            Ok(p) => p,
            Err(e) => {
                errors.push(ValidationError::new(
                    &file_str,
                    "",
                    "format",
                    format!("YAML parse error: {}", e),
                    Some("Check YAML syntax and required fields (title:, shell:).".into()),
                ));
                continue;
            }
        };

        errors.extend(validate_page(&file_str, &page));
    }

    // Second pass: nav cross-references.
    if let Some(nav) = &config.nav {
        validate_nav_links("kazam.yaml", "nav", nav, &known_pages, &mut errors);
    }

    // Validate site config theme value.
    validate_site_config("kazam.yaml", &config, &mut errors);

    errors
}

// ── Site config validation ────────────────────────────

fn validate_site_config(file: &str, config: &SiteConfig, errors: &mut Vec<ValidationError>) {
    // Valid theme names.
    const VALID_THEMES: &[&str] = &[
        "dark", "light", "red", "orange", "yellow", "green", "teal", "blue", "violet",
    ];
    if let Some(theme) = &config.theme {
        if !VALID_THEMES.contains(&theme.as_str()) {
            errors.push(ValidationError::new(
                file,
                "theme",
                "invalid_value",
                format!(
                    "Unknown theme {:?}. Valid themes: {}",
                    theme,
                    VALID_THEMES.join(", ")
                ),
                Some(format!("Set theme to one of: {}", VALID_THEMES.join(", "))),
            ));
        }
    }
}

// ── Shell / structure validation ──────────────────────

fn validate_shell_structure(file: &str, page: &Page, errors: &mut Vec<ValidationError>) {
    match page.shell {
        Shell::Deck => {
            // Deck pages must have slides.
            if page.slides.as_ref().map(|s| s.is_empty()).unwrap_or(true) {
                errors.push(ValidationError::new(
                    file,
                    "slides",
                    "structural",
                    "shell: deck pages must have at least one slide under slides:",
                    Some(
                        "Add a slides: list with at least one item (label: + components:).".into(),
                    ),
                ));
            }
            // Deck pages should not have top-level components.
            if page
                .components
                .as_ref()
                .map(|c| !c.is_empty())
                .unwrap_or(false)
            {
                errors.push(ValidationError::new(
                    file,
                    "components",
                    "structural",
                    "shell: deck pages use slides:, not top-level components:",
                    Some("Move components into slides[N].components:.".into()),
                ));
            }
        }
        Shell::Hub => {
            // Hub pages render components like standard pages and need a
            // hub: block for the masthead.
            if page
                .components
                .as_ref()
                .map(|c| c.is_empty())
                .unwrap_or(true)
            {
                errors.push(ValidationError::new(
                    file,
                    "components",
                    "structural",
                    "shell: hub pages must have at least one component under components:",
                    Some("Add a components: list.".into()),
                ));
            }
            if page.hub.is_none() {
                errors.push(ValidationError::new(
                    file,
                    "hub",
                    "structural",
                    "shell: hub pages need a hub: block (name + pages) for the masthead",
                    Some("Add hub: with name: and a pages: list of {label, href}.".into()),
                ));
            }
        }
        Shell::Standard | Shell::Document => {
            // Non-deck pages must have components.
            if page
                .components
                .as_ref()
                .map(|c| c.is_empty())
                .unwrap_or(true)
            {
                errors.push(ValidationError::new(
                    file,
                    "components",
                    "structural",
                    "page must have at least one component under components:",
                    Some("Add a components: list. Start with - type: header, title: ...".into()),
                ));
            }
            // Non-deck pages should not have slides.
            if page.slides.as_ref().map(|s| !s.is_empty()).unwrap_or(false) {
                errors.push(ValidationError::new(
                    file,
                    "slides",
                    "structural",
                    "slides: is only used by shell: deck pages",
                    Some("Remove slides: or change shell to deck.".into()),
                ));
            }
        }
    }
}

// ── Slide density validation ─────────────────────────

const SLIDE_DENSITY_LIMIT: u32 = 9;

fn component_height_cost(c: &Component) -> u32 {
    match c {
        Component::Header { subtitle, .. } => {
            if subtitle.is_some() {
                2
            } else {
                1
            }
        }
        Component::Callout { .. } => 2,
        Component::Blockquote { .. } => 2,
        Component::StatGrid { stats, .. } => 2 + (stats.len() as u32 / 5),
        Component::CardGrid { cards, .. } => 1 + cards.len() as u32,
        Component::SelectableGrid { cards, .. } => 2 + (cards.len() as u32 / 3),
        Component::Steps { items, .. } => 1 + items.len() as u32,
        Component::Table { rows, .. } => 2 + rows.len() as u32,
        Component::Pipeline { .. } => 5,
        Component::SplitCompare { .. } => 4,
        Component::Chart { .. } => 4,
        Component::Radar { .. } => 4,
        Component::Sankey { .. } => 4,
        Component::Graph { .. } => 4,
        Component::Architecture { .. } => 4,
        Component::Quadrant { .. } => 4,
        Component::OrgChart { .. } => 5,
        Component::Venn { .. } => 3,
        Component::Timeline { items, .. } => 1 + items.len() as u32,
        Component::EventTimeline { events, .. } => 2 + events.len() as u32,
        Component::DefinitionList { items, .. } => 1 + items.len() as u32,
        Component::Accordion { items, .. } => 1 + items.len() as u32,
        Component::BeforeAfter { items, .. } => 2 + items.len() as u32,
        Component::Columns { columns, .. } => columns
            .iter()
            .map(|col| col.iter().map(component_height_cost).sum::<u32>())
            .max()
            .unwrap_or(0),
        Component::Section { components, .. } => {
            1 + components.iter().map(component_height_cost).sum::<u32>()
        }
        Component::Tabs { tabs, .. } => 2 + tabs.len().min(1) as u32,
        Component::Markdown { body, .. } => 1 + (body.lines().count() as u32 / 4),
        Component::Code { code, .. } => 2 + (code.lines().count() as u32 / 3),
        Component::Image { .. } | Component::Embed { .. } => 4,
        Component::Gauge { items, .. } => 2 + items.len() as u32,
        Component::RuleList { items, .. } => 1 + items.len() as u32,
        Component::Tree { .. } => 4,
        Component::PriorityQueue { items, .. } => 2 + items.len() as u32,
        _ => 1,
    }
}

fn validate_slide_density(file: &str, slides: &[Slide], errors: &mut Vec<ValidationError>) {
    for (i, slide) in slides.iter().enumerate() {
        let mut cost: u32 = slide.components.iter().map(component_height_cost).sum();
        // The slide header (eyebrow + title + optional subtitle) is not a
        // component but still consumes vertical space; count it toward density.
        if slide.title.is_some() || slide.eyebrow.is_some() {
            cost += if slide.subtitle.is_some() { 2 } else { 1 };
        }
        if cost > SLIDE_DENSITY_LIMIT {
            errors.push(ValidationError::new(
                file,
                format!("slides[{}]", i),
                "density",
                format!(
                    "Slide {:?} has ~{} content units (limit {}). Content will likely overflow the viewport.",
                    slide.label, cost, SLIDE_DENSITY_LIMIT
                ),
                Some("Split into two slides, or remove components to fit one screen.".into()),
            ));
        }
    }
}

// ── Component validation ──────────────────────────────

fn validate_components(
    file: &str,
    path_prefix: &str,
    components: &[Component],
    errors: &mut Vec<ValidationError>,
) {
    for (i, component) in components.iter().enumerate() {
        let path = format!("{}[{}]", path_prefix, i);
        validate_component(file, &path, component, errors);
    }
}

fn validate_component(
    file: &str,
    path: &str,
    component: &Component,
    errors: &mut Vec<ValidationError>,
) {
    match component {
        Component::CardGrid { cards, .. } => {
            if cards.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.cards", path),
                    "missing_field",
                    "card_grid requires at least one card in cards:",
                    Some("Add at least one card with title: and optional description:.".into()),
                ));
            }
        }

        Component::SelectableGrid { cards, .. } => {
            if cards.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.cards", path),
                    "missing_field",
                    "selectable_grid requires at least one card in cards:",
                    Some("Add at least one card with title:.".into()),
                ));
            }
        }

        Component::Table { columns, rows, .. } => {
            if columns.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.columns", path),
                    "missing_field",
                    "table requires at least one column in columns:",
                    Some("Add columns with key: and label:.".into()),
                ));
            }
            if rows.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.rows", path),
                    "missing_field",
                    "table requires at least one row in rows:",
                    Some("Add at least one row object matching the column keys.".into()),
                ));
            }
            // Validate that each row contains all column keys.
            for (ri, row) in rows.iter().enumerate() {
                for col in columns.iter() {
                    if !row.contains_key(col.key.as_str()) {
                        errors.push(ValidationError::new(
                            file,
                            format!("{}.rows[{}]", path, ri),
                            "missing_field",
                            format!("row is missing column key {:?}", col.key),
                            Some(format!("Add {}: <value> to this row.", col.key)),
                        ));
                    }
                }
            }
        }

        Component::Chart { data, series, .. } => {
            let has_data = data.as_ref().map(|d| !d.is_empty()).unwrap_or(false);
            let has_series = series.as_ref().map(|s| !s.is_empty()).unwrap_or(false);
            if !has_data && !has_series {
                errors.push(ValidationError::new(
                    file,
                    path,
                    "missing_field",
                    "chart requires either data: (single-series) or series: (multi-series)",
                    Some("Add data: [{label: X, value: N}] for a simple chart, or series: for multi-series.".into()),
                ));
            }
            if has_data && has_series {
                errors.push(ValidationError::new(
                    file,
                    path,
                    "structural",
                    "chart cannot have both data: and series: — pick one",
                    Some("Use data: for single-series charts, series: for multi-series.".into()),
                ));
            }
        }

        Component::Timeline { items } => {
            if items.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.items", path),
                    "missing_field",
                    "timeline requires at least one item",
                    Some("Add items with name: and status: (completed/active/upcoming).".into()),
                ));
            }
        }

        Component::StatGrid { stats, .. } => {
            if stats.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.stats", path),
                    "missing_field",
                    "stat_grid requires at least one stat",
                    Some("Add stats with label: and value:.".into()),
                ));
            }
        }

        Component::BeforeAfter { items, .. } => {
            if items.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.items", path),
                    "missing_field",
                    "before_after requires at least one item",
                    Some("Add items with title:, before:, and after:.".into()),
                ));
            }
        }

        Component::Steps { items, .. } => {
            if items.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.items", path),
                    "missing_field",
                    "steps requires at least one item",
                    Some("Add items with title: and optional detail:.".into()),
                ));
            }
        }

        Component::Tabs { tabs } => {
            if tabs.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.tabs", path),
                    "missing_field",
                    "tabs requires at least one tab",
                    Some("Add tabs with label: and components:.".into()),
                ));
            }
            for (ti, tab) in tabs.iter().enumerate() {
                if tab.components.is_empty() {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.tabs[{}].components", path, ti),
                        "missing_field",
                        format!("tab {:?} has no components", tab.label),
                        Some("Add at least one component inside this tab.".into()),
                    ));
                } else {
                    validate_components(
                        file,
                        &format!("{}.tabs[{}].components", path, ti),
                        &tab.components,
                        errors,
                    );
                }
            }
        }

        Component::Section { components, .. } => {
            // A section can be a pure heading/anchor with no nested components — valid.
            if !components.is_empty() {
                validate_components(file, &format!("{}.components", path), components, errors);
            }
        }

        Component::Columns { columns, .. } => {
            if columns.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.columns", path),
                    "missing_field",
                    "columns requires at least one column",
                    Some("Add columns as a list of component lists.".into()),
                ));
            }
            for (ci, col_components) in columns.iter().enumerate() {
                if col_components.is_empty() {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.columns[{}]", path, ci),
                        "missing_field",
                        format!("column {} has no components", ci),
                        Some("Add at least one component to each column.".into()),
                    ));
                } else {
                    validate_components(
                        file,
                        &format!("{}.columns[{}]", path, ci),
                        col_components,
                        errors,
                    );
                }
            }
        }

        Component::Accordion { items } => {
            if items.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.items", path),
                    "missing_field",
                    "accordion requires at least one item",
                    Some("Add items with title: and components:.".into()),
                ));
            }
            for (ai, item) in items.iter().enumerate() {
                if item.components.is_empty() {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.items[{}].components", path, ai),
                        "missing_field",
                        format!("accordion item {:?} has no components", item.title),
                        Some("Add at least one component inside this accordion item.".into()),
                    ));
                } else {
                    validate_components(
                        file,
                        &format!("{}.items[{}].components", path, ai),
                        &item.components,
                        errors,
                    );
                }
            }
        }

        Component::EventTimeline { events, .. } => {
            if events.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.events", path),
                    "missing_field",
                    "event_timeline requires at least one event",
                    Some("Add events with date: and title:.".into()),
                ));
            }
            // Validate date formats.
            for (ei, event) in events.iter().enumerate() {
                if crate::freshness::parse_iso_date(&event.date).is_none() {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.events[{}].date", path, ei),
                        "format",
                        format!("invalid date {:?} — must be YYYY-MM-DD", event.date),
                        Some("Use ISO date format: 2026-01-15".into()),
                    ));
                }
            }
        }

        Component::PriorityQueue { items, .. } => {
            if items.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.items", path),
                    "missing_field",
                    "priority_queue requires at least one item",
                    Some("Add items with label: and optional due:.".into()),
                ));
            }
        }

        Component::Tree { nodes, .. } => {
            if nodes.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.nodes", path),
                    "missing_field",
                    "tree requires at least one node",
                    Some("Add nodes with label: and optional children:.".into()),
                ));
            }
        }

        Component::Venn { sets, .. } => {
            if sets.len() < 2 {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.sets", path),
                    "structural",
                    format!("venn requires at least 2 sets, found {}", sets.len()),
                    Some("Add at least two sets with label:.".into()),
                ));
            }
        }

        Component::Kbd { keys } => {
            if keys.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.keys", path),
                    "missing_field",
                    "kbd requires at least one key",
                    Some("Add keys: [\"Ctrl\", \"C\"] for example.".into()),
                ));
            }
        }

        Component::Breadcrumb { items } => {
            if items.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.items", path),
                    "missing_field",
                    "breadcrumb requires at least one item",
                    Some("Add items with label: and optional href:.".into()),
                ));
            }
        }

        Component::ButtonGroup { .. } => {
            // An empty button_group is valid — buttons may be conditionally populated.
        }

        Component::DefinitionList { items } => {
            if items.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.items", path),
                    "missing_field",
                    "definition_list requires at least one item",
                    Some("Add items with term: and definition:.".into()),
                ));
            }
        }

        Component::AvatarGroup { avatars, .. } => {
            if avatars.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.avatars", path),
                    "missing_field",
                    "avatar_group requires at least one avatar",
                    Some("Add avatars with name:.".into()),
                ));
            }
        }

        Component::Meta { fields } => {
            if fields.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.fields", path),
                    "missing_field",
                    "meta requires at least one field",
                    Some("Add fields with key: and value:.".into()),
                ));
            }
        }

        Component::ProgressBar { value, .. } => {
            if *value > 100 {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.value", path),
                    "invalid_value",
                    format!("progress_bar value {} exceeds 100", value),
                    Some("Set value to a number between 0 and 100.".into()),
                ));
            }
        }

        // Components with no extra validation needed beyond serde.
        Component::Header { .. }
        | Component::Markdown { .. }
        | Component::Callout { .. }
        | Component::Code { .. }
        | Component::Image { .. }
        | Component::Badge { .. }
        | Component::Tag { .. }
        | Component::Divider { .. }
        | Component::Status { .. }
        | Component::Blockquote { .. }
        | Component::Avatar { .. }
        | Component::EmptyState { .. }
        | Component::Icon { .. }
        | Component::Embed { .. }
        | Component::Resources { .. }
        | Component::HeroBanner { .. }
        | Component::RoleMap { .. }
        | Component::SplitCompare { .. } => {}

        Component::Sankey { flows, .. } => {
            if flows.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.flows", path),
                    "missing_field",
                    "sankey requires at least one flow",
                    Some("Add flows with source:, target:, and value:.".into()),
                ));
            }
            for (i, f) in flows.iter().enumerate() {
                if f.value <= 0.0 {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.flows[{}].value", path, i),
                        "structural",
                        "sankey flow value must be > 0",
                        None,
                    ));
                }
                if f.source == f.target {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.flows[{}]", path, i),
                        "structural",
                        "sankey flow source and target must differ",
                        None,
                    ));
                }
            }
        }

        Component::Radar { axes, curves, .. } => {
            if axes.len() < 3 {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.axes", path),
                    "structural",
                    "radar requires at least 3 axes",
                    Some("Add at least 3 axis labels.".into()),
                ));
            }
            if curves.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.curves", path),
                    "missing_field",
                    "radar requires at least one curve",
                    Some("Add curves with label: and values: [].".into()),
                ));
            }
            for (i, c) in curves.iter().enumerate() {
                if c.values.len() != axes.len() {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.curves[{}].values", path, i),
                        "structural",
                        format!(
                            "curve values length ({}) must match axes count ({})",
                            c.values.len(),
                            axes.len()
                        ),
                        None,
                    ));
                }
            }
        }

        Component::Quadrant {
            quadrants, points, ..
        } => {
            if quadrants.len() != 4 {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.quadrants", path),
                    "structural",
                    format!(
                        "quadrant requires exactly 4 labels, got {}",
                        quadrants.len()
                    ),
                    Some("Provide 4 labels: Q1 (top-right), Q2 (top-left), Q3 (bottom-left), Q4 (bottom-right).".into()),
                ));
            }
            if points.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.points", path),
                    "missing_field",
                    "quadrant requires at least one point",
                    Some("Add points with label:, x: (0-1), y: (0-1).".into()),
                ));
            }
        }

        Component::Architecture {
            nodes, connections, ..
        } => {
            if nodes.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.nodes", path),
                    "missing_field",
                    "architecture requires at least one node",
                    Some("Add nodes with id: and label:.".into()),
                ));
            }
            let ids: Vec<&str> = nodes.iter().map(|n| n.id.as_str()).collect();
            for (i, c) in connections.iter().enumerate() {
                if !ids.contains(&c.from.as_str()) {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.connections[{}].from", path, i),
                        "structural",
                        format!("connection references unknown node id {:?}", c.from),
                        None,
                    ));
                }
                if !ids.contains(&c.to.as_str()) {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.connections[{}].to", path, i),
                        "structural",
                        format!("connection references unknown node id {:?}", c.to),
                        None,
                    ));
                }
                if c.from == c.to {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.connections[{}]", path, i),
                        "structural",
                        "connection from and to must differ",
                        None,
                    ));
                }
            }
        }
        Component::Pipeline {
            inputs,
            stages,
            outputs,
            ..
        } => {
            if stages.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.stages", path),
                    "missing_field",
                    "pipeline requires at least one stage",
                    Some("Add stages with label: and capabilities:.".into()),
                ));
            }
            if inputs.is_empty() && outputs.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    path.to_string(),
                    "structural",
                    "pipeline needs at least one input or output",
                    None,
                ));
            }
        }
        Component::Graph {
            nodes,
            edges,
            groups,
            ..
        } => {
            if nodes.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.nodes", path),
                    "missing_field",
                    "graph requires at least one node",
                    Some("Add nodes with id: and label:.".into()),
                ));
            }
            let node_ids: std::collections::HashSet<&str> =
                nodes.iter().map(|n| n.id.as_str()).collect();
            for (i, edge) in edges.iter().enumerate() {
                if !node_ids.contains(edge.from.as_str()) {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.edges[{}].from", path, i),
                        "cross_reference",
                        format!("edge references non-existent node '{}'", edge.from),
                        None,
                    ));
                }
                if !node_ids.contains(edge.to.as_str()) {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.edges[{}].to", path, i),
                        "cross_reference",
                        format!("edge references non-existent node '{}'", edge.to),
                        None,
                    ));
                }
            }
            for (i, grp) in groups.iter().enumerate() {
                if let Some(parent) = &grp.parent {
                    if !groups.iter().any(|g| g.id == *parent) {
                        errors.push(ValidationError::new(
                            file,
                            format!("{}.groups[{}].parent", path, i),
                            "cross_reference",
                            format!("group parent '{}' not found", parent),
                            None,
                        ));
                    }
                }
            }
        }
        Component::OrgChart { people, .. } => {
            if people.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.people", path),
                    "missing_field",
                    "org_chart requires at least one person",
                    Some("Add people with id:, name:, and optional reports:.".into()),
                ));
            }
        }

        Component::Aside { body } => {
            if body.trim().is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.body", path),
                    "missing_field",
                    "aside requires a non-empty body",
                    Some("Add body: with the aside content.".into()),
                ));
            }
        }

        Component::RuleList { items } => {
            if items.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.items", path),
                    "missing_field",
                    "rule_list requires at least one item",
                    Some("Add items with label: and body:.".into()),
                ));
            }
            for (i, item) in items.iter().enumerate() {
                if item.label.trim().is_empty() {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.items[{}].label", path, i),
                        "missing_field",
                        "rule_list item requires a non-empty label",
                        Some("Add label: to this item.".into()),
                    ));
                }
                if item.body.trim().is_empty() {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.items[{}].body", path, i),
                        "missing_field",
                        "rule_list item requires a non-empty body",
                        Some("Add body: to this item.".into()),
                    ));
                }
            }
        }

        Component::Gauge { items, max, .. } => {
            if items.is_empty() {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.items", path),
                    "missing_field",
                    "gauge requires at least one item",
                    Some("Add items with label: and value:.".into()),
                ));
            }
            if *max <= 0.0 {
                errors.push(ValidationError::new(
                    file,
                    format!("{}.max", path),
                    "invalid_value",
                    format!("gauge max must be > 0, got {}", max),
                    Some("Set max to a positive number.".into()),
                ));
            }
        }
    }
}

// ── Freshness validation ──────────────────────────────

fn validate_freshness(
    file: &str,
    path: &str,
    freshness: &crate::types::Freshness,
    errors: &mut Vec<ValidationError>,
) {
    if let Some(updated) = &freshness.updated {
        if crate::freshness::parse_iso_date(updated).is_none() {
            errors.push(ValidationError::new(
                file,
                format!("{}.updated", path),
                "format",
                format!("invalid date {:?} — must be YYYY-MM-DD", updated),
                Some("Use ISO date format: 2026-01-15".into()),
            ));
        }
    }
    if let Some(review_every) = &freshness.review_every {
        if crate::freshness::parse_duration_days(review_every).is_none() {
            errors.push(ValidationError::new(
                file,
                format!("{}.review_every", path),
                "format",
                format!(
                    "invalid duration {:?} — accepts Nd/Nw/Nm/Ny or weekly/monthly/quarterly/yearly",
                    review_every
                ),
                Some("Examples: 30d, 4w, 3m, 1y, weekly, monthly, quarterly, yearly".into()),
            ));
        }
    }
}

// ── Nav cross-reference validation ────────────────────

fn validate_nav_links(
    file: &str,
    path: &str,
    nav: &[crate::types::NavLink],
    known_pages: &HashSet<String>,
    errors: &mut Vec<ValidationError>,
) {
    for (i, link) in nav.iter().enumerate() {
        let link_path = format!("{}[{}]", path, i);
        if let Some(href) = &link.href {
            // Only check local hrefs (not external URLs).
            if !href.starts_with("http://")
                && !href.starts_with("https://")
                && !href.starts_with('#')
                && !href.starts_with("mailto:")
            {
                // Normalize: strip leading slash, ensure .html extension.
                let normalized = normalize_href(href);
                if !known_pages.contains(&normalized) {
                    errors.push(ValidationError::new(
                        file,
                        format!("{}.href", link_path),
                        "cross_reference",
                        format!("nav href {:?} does not match any known page ({})", href, normalized),
                        Some(format!(
                            "Create a page at the matching .yaml path, or fix the href. Known pages: {}",
                            {
                                let mut sorted: Vec<&String> = known_pages.iter().collect();
                                sorted.sort();
                                sorted.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")
                            }
                        )),
                    ));
                }
            }
        }
        // Recurse into children.
        if let Some(children) = &link.children {
            validate_nav_links(
                file,
                &format!("{}[{}].children", path, i),
                children,
                known_pages,
                errors,
            );
        }
    }
}

/// Normalize an href to a canonical `path/to/page.html` form for matching
/// against `known_pages`. Strips leading `/`, adds `.html` if missing.
fn normalize_href(href: &str) -> String {
    let href = href.trim_start_matches('/');
    if href.ends_with(".html") {
        href.to_string()
    } else if href.ends_with(".yaml") {
        format!("{}.html", href.trim_end_matches(".yaml"))
    } else if href.is_empty() || href.ends_with('/') {
        format!("{}index.html", href)
    } else {
        format!("{}.html", href)
    }
}

// ── Pretty printing ───────────────────────────────────

/// Print validation errors to stderr in a human-readable, colored format.
pub fn print_pretty(errors: &[ValidationError]) {
    if errors.is_empty() {
        eprintln!("\u{2713} No validation errors found.");
        return;
    }
    // Group by file.
    let mut by_file: std::collections::BTreeMap<&str, Vec<&ValidationError>> =
        std::collections::BTreeMap::new();
    for e in errors {
        by_file.entry(&e.file).or_default().push(e);
    }
    for (file, errs) in &by_file {
        eprintln!("\n\u{2718} {} ({} error(s))", file, errs.len());
        for e in errs {
            eprintln!("    [{:^16}] {}", e.error_type, e.message);
            if !e.path.is_empty() {
                eprintln!("    {:>18} {}", "at:", e.path);
            }
            if let Some(hint) = &e.suggestion {
                eprintln!("    {:>18} {}", "hint:", hint);
            }
        }
    }
}

// ── Tests ─────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{Component, Freshness, Page, Shell};

    fn make_page(shell: Shell, components: Option<Vec<Component>>) -> Page {
        Page {
            title: "Test Page".into(),
            shell,
            eyebrow: None,
            subtitle: None,
            components,
            slides: None,
            unlisted: false,
            texture: None,
            glow: None,
            print_flow: None,
            hub: None,
            freshness: None,
            search_terms: Vec::new(),
            owner: None,
            references: Vec::new(),
            personas: Vec::new(),
            archived: false,
            draft: false,
            nav_layout: None,
            nav: None,
            pack: None,
        }
    }

    fn pack_meta(targets: &[&str]) -> crate::types::PackMeta {
        crate::types::PackMeta {
            targets: targets.iter().map(|s| s.to_string()).collect(),
            hooks: Vec::new(),
        }
    }

    #[test]
    fn pack_with_markdown_passes() {
        let mut page = make_page(
            Shell::Standard,
            Some(vec![Component::Markdown {
                body: "rules".into(),
            }]),
        );
        page.pack = Some(pack_meta(&[]));
        assert!(validate_page("p.yaml", &page).is_empty());
    }

    #[test]
    fn pack_with_markdown_in_section_passes() {
        let mut page = make_page(
            Shell::Standard,
            Some(vec![Component::Section {
                heading: Some("Rules".into()),
                eyebrow: None,
                components: vec![Component::Markdown {
                    body: "rules".into(),
                }],
                align: Default::default(),
                id: None,
            }]),
        );
        page.pack = Some(pack_meta(&["claude", "cursor"]));
        assert!(validate_page("p.yaml", &page).is_empty());
    }

    #[test]
    fn pack_without_markdown_fails_structural() {
        let mut page = make_page(Shell::Standard, Some(vec![header_component()]));
        page.pack = Some(pack_meta(&[]));
        let errors = validate_page("p.yaml", &page);
        assert!(errors
            .iter()
            .any(|e| e.error_type == "structural" && e.path == "pack"));
    }

    #[test]
    fn pack_with_empty_markdown_fails_structural() {
        let mut page = make_page(
            Shell::Standard,
            Some(vec![Component::Markdown { body: "   ".into() }]),
        );
        page.pack = Some(pack_meta(&[]));
        let errors = validate_page("p.yaml", &page);
        assert!(errors
            .iter()
            .any(|e| e.error_type == "structural" && e.path == "pack"));
    }

    #[test]
    fn pack_with_unknown_target_fails() {
        let mut page = make_page(
            Shell::Standard,
            Some(vec![Component::Markdown {
                body: "rules".into(),
            }]),
        );
        page.pack = Some(pack_meta(&["claude", "notatool"]));
        let errors = validate_page("p.yaml", &page);
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].path, "pack.targets[1]");
        assert_eq!(errors[0].error_type, "invalid_value");
    }

    fn header_component() -> Component {
        Component::Header {
            title: "Hello".into(),
            subtitle: None,
            eyebrow: None,
            align: Default::default(),
            id: None,
        }
    }

    // ── Valid page passes validation ──────────────────

    #[test]
    fn valid_standard_page_passes() {
        let page = make_page(Shell::Standard, Some(vec![header_component()]));
        let errors = validate_page("test.yaml", &page);
        assert!(
            errors.is_empty(),
            "expected no errors, got: {:?}",
            errors.iter().map(|e| &e.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn valid_deck_page_passes() {
        use crate::types::Slide;
        let page = Page {
            title: "Deck".into(),
            shell: Shell::Deck,
            eyebrow: None,
            subtitle: None,
            components: None,
            slides: Some(vec![Slide {
                label: "Slide 1".into(),
                components: vec![header_component()],
                title: None,
                eyebrow: None,
                subtitle: None,
                align: None,
                valign: None,
                cover: false,
                hide_label: false,
            }]),
            unlisted: false,
            texture: None,
            glow: None,
            print_flow: None,
            hub: None,
            freshness: None,
            search_terms: Vec::new(),
            owner: None,
            references: Vec::new(),
            personas: Vec::new(),
            archived: false,
            draft: false,
            nav_layout: None,
            nav: None,
            pack: None,
        };
        let errors = validate_page("deck.yaml", &page);
        assert!(
            errors.is_empty(),
            "expected no errors, got: {:?}",
            errors.iter().map(|e| &e.message).collect::<Vec<_>>()
        );
    }

    // ── Structural rules enforced ─────────────────────

    #[test]
    fn standard_page_without_components_fails() {
        let page = make_page(Shell::Standard, None);
        let errors = validate_page("test.yaml", &page);
        assert!(
            errors.iter().any(|e| e.error_type == "structural"),
            "expected structural error"
        );
    }

    #[test]
    fn deck_page_without_slides_fails() {
        let page = make_page(Shell::Deck, None);
        let errors = validate_page("test.yaml", &page);
        assert!(
            errors
                .iter()
                .any(|e| e.error_type == "structural" && e.path == "slides"),
            "expected structural error on slides"
        );
    }

    // ── Missing required fields caught ────────────────

    #[test]
    fn card_grid_with_empty_cards_fails() {
        use crate::types::Connector;
        let page = make_page(
            Shell::Standard,
            Some(vec![Component::CardGrid {
                cards: vec![],
                min_width: None,
                connector: Connector::None,
            }]),
        );
        let errors = validate_page("test.yaml", &page);
        assert!(
            errors
                .iter()
                .any(|e| e.path.contains("cards") && e.error_type == "missing_field"),
            "expected missing_field on cards"
        );
    }

    #[test]
    fn table_requires_columns_and_rows() {
        let page = make_page(
            Shell::Standard,
            Some(vec![Component::Table {
                columns: vec![],
                rows: vec![],
                filterable: false,
                summary: None,
            }]),
        );
        let errors = validate_page("test.yaml", &page);
        assert!(errors.iter().any(|e| e.path.contains("columns")));
        assert!(errors.iter().any(|e| e.path.contains("rows")));
    }

    // ── Component-specific rules ──────────────────────

    #[test]
    fn chart_needs_data_or_series() {
        use crate::types::ChartKind;
        let page = make_page(
            Shell::Standard,
            Some(vec![Component::Chart {
                kind: ChartKind::Bar,
                title: None,
                height: None,
                x_label: None,
                y_label: None,
                orientation: Default::default(),
                data: None,
                series: None,
            }]),
        );
        let errors = validate_page("test.yaml", &page);
        assert!(
            errors.iter().any(|e| e.error_type == "missing_field"),
            "expected missing_field for chart without data or series"
        );
    }

    #[test]
    fn chart_cannot_have_both_data_and_series() {
        use crate::types::{ChartKind, ChartPoint, ChartSeries};
        let page = make_page(
            Shell::Standard,
            Some(vec![Component::Chart {
                kind: ChartKind::Bar,
                title: None,
                height: None,
                x_label: None,
                y_label: None,
                orientation: Default::default(),
                data: Some(vec![ChartPoint {
                    label: "A".into(),
                    value: 1.0,
                    color: None,
                }]),
                series: Some(vec![ChartSeries {
                    label: "S".into(),
                    color: None,
                    points: vec![ChartPoint {
                        label: "A".into(),
                        value: 1.0,
                        color: None,
                    }],
                }]),
            }]),
        );
        let errors = validate_page("test.yaml", &page);
        assert!(
            errors.iter().any(|e| e.error_type == "structural"),
            "expected structural error for chart with both data and series"
        );
    }

    #[test]
    fn progress_bar_over_100_fails() {
        let page = make_page(
            Shell::Standard,
            Some(vec![Component::ProgressBar {
                value: 150,
                label: None,
                color: Default::default(),
                detail: None,
                target: None,
                thresholds: std::collections::HashMap::new(),
            }]),
        );
        let errors = validate_page("test.yaml", &page);
        assert!(
            errors.iter().any(|e| e.error_type == "invalid_value"),
            "expected invalid_value for progress_bar > 100"
        );
    }

    // ── Freshness format validation ───────────────────

    #[test]
    fn freshness_bad_date_fails() {
        let mut page = make_page(Shell::Standard, Some(vec![header_component()]));
        page.freshness = Some(crate::types::FreshnessValue::Full(Freshness {
            updated: Some("not-a-date".into()),
            review_every: None,
            owner: None,
            sources_of_truth: None,
            expires: None,
            refresh: None,
        }));
        let errors = validate_page("test.yaml", &page);
        assert!(
            errors
                .iter()
                .any(|e| e.error_type == "format" && e.path.contains("updated")),
            "expected format error on freshness.updated"
        );
    }

    #[test]
    fn freshness_bad_duration_fails() {
        let mut page = make_page(Shell::Standard, Some(vec![header_component()]));
        page.freshness = Some(crate::types::FreshnessValue::Full(Freshness {
            updated: None,
            review_every: Some("once in a while".into()),
            owner: None,
            sources_of_truth: None,
            expires: None,
            refresh: None,
        }));
        let errors = validate_page("test.yaml", &page);
        assert!(
            errors
                .iter()
                .any(|e| e.error_type == "format" && e.path.contains("review_every")),
            "expected format error on freshness.review_every"
        );
    }

    #[test]
    fn freshness_valid_values_pass() {
        let mut page = make_page(Shell::Standard, Some(vec![header_component()]));
        page.freshness = Some(crate::types::FreshnessValue::Full(Freshness {
            updated: Some("2026-01-15".into()),
            review_every: Some("quarterly".into()),
            owner: Some("team@example.com".into()),
            sources_of_truth: None,
            expires: None,
            refresh: None,
        }));
        let errors = validate_page("test.yaml", &page);
        assert!(errors.is_empty(), "expected no errors for valid freshness");
    }

    // ── Error JSON format ─────────────────────────────

    #[test]
    fn error_serializes_to_json_correctly() {
        let err = ValidationError {
            file: "foo.yaml".into(),
            path: "components[0].cards".into(),
            error_type: "missing_field".into(),
            message: "needs at least one card".into(),
            suggestion: Some("add a card".into()),
        };
        let json = serde_json::to_string(&err).unwrap();
        assert!(json.contains("\"file\":\"foo.yaml\""));
        assert!(json.contains("\"path\":\"components[0].cards\""));
        assert!(json.contains("\"error_type\":\"missing_field\""));
        assert!(json.contains("\"suggestion\":\"add a card\""));
    }

    #[test]
    fn error_without_suggestion_omits_field() {
        let err = ValidationError {
            file: "foo.yaml".into(),
            path: "".into(),
            error_type: "structural".into(),
            message: "something wrong".into(),
            suggestion: None,
        };
        let json = serde_json::to_string(&err).unwrap();
        assert!(!json.contains("suggestion"));
    }

    // ── Nav href normalization ────────────────────────

    #[test]
    fn normalize_href_various_forms() {
        assert_eq!(normalize_href("index.html"), "index.html");
        assert_eq!(normalize_href("/index.html"), "index.html");
        assert_eq!(normalize_href("foo/bar"), "foo/bar.html");
        assert_eq!(normalize_href("foo/bar.yaml"), "foo/bar.html");
        assert_eq!(normalize_href(""), "index.html");
        assert_eq!(normalize_href("/"), "index.html");
    }
}