zebflow 0.11.14

Reactive web automation platform — pipelines, templates, and real-time collaboration in a single binary.
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
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
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
//! Permanent project configuration contract.
//!
//! The structures in this module own the repository format. Runtime services
//! continue to use [`ZebflowJson`], with explicit conversions at the boundary,
//! so ordinary Rust refactoring cannot silently change `repo/zebflow.yaml`.

use std::collections::{BTreeMap, HashMap};

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::contracts::{ContractError, ContractKind, ContractMetadata, PlatformContract};
use crate::infra::execution::backend::ExecutionProfileKind;
use crate::infra::execution::placement::{
    ProjectRuntimeMode, ProjectRuntimeProfile, ResourceProfile, RuntimeResourceSpec,
};
use crate::platform::model::{
    DEFAULT_ALLOWED_FILE_EXTENSIONS, ProjectBootstrapPlan, ZebflowJson, ZebflowJsonAssistant,
    ZebflowJsonConfigs, ZebflowJsonData, ZebflowJsonDistribution, ZebflowJsonDistributionHub,
    ZebflowJsonFiles, ZebflowJsonGit, ZebflowJsonGitRemote, ZebflowJsonInitialDataDir,
    ZebflowJsonLayout, ZebflowJsonLocks, ZebflowJsonLogging, ZebflowJsonMetadata,
    ZebflowJsonPipelines, ZebflowJsonRwe, ZebflowJsonRweLibraryEntry, ZebflowJsonUploads,
    slug_segment,
};
use crate::zebfs::FileBackend;

/// Canonical repository filename for project configuration.
pub const PROJECT_CONFIGURATION_FILE: &str = "zebflow.yaml";
/// Previous repository filename accepted only by the explicit migration path.
pub const LEGACY_PROJECT_CONFIGURATION_FILE: &str = "zebflow.json";
/// Recovery copy stem retained by the explicit JSON-to-YAML migration,
/// combined with the migration date (`project-directory.md` §5) into
/// `data/recovery/zebflow-config-{date}.json`.
pub const PROJECT_CONFIGURATION_BACKUP_FILE: &str = "zebflow-config";

/// Canonical `zebflow.yaml` contract.
pub struct ProjectConfigurationContract;

impl PlatformContract for ProjectConfigurationContract {
    type Spec = ProjectConfigurationSpec;
    const KIND: ContractKind = ContractKind::ProjectConfiguration;

    fn validate(metadata: &ContractMetadata, spec: &Self::Spec) -> Result<(), ContractError> {
        if metadata.name != slug_segment(&metadata.name) {
            return Err(ContractError::invalid(
                "metadata.name must be a canonical project slug",
            ));
        }
        if metadata.version.is_some()
            || metadata.digest.is_some()
            || !metadata.annotations.is_empty()
        {
            return Err(ContractError::invalid(
                "ProjectConfiguration metadata contains only name",
            ));
        }
        spec.validate()
    }
}

/// Portable, non-secret project configuration stored under the contract envelope.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectConfigurationSpec {
    #[serde(default)]
    pub profile: ProjectProfileSpec,
    /// Repository layout. Unlike the other sections this one is omitted when it
    /// is empty, so a project that never declared a layout is not rewritten to
    /// carry an empty section it did not author.
    #[serde(default, skip_serializing_if = "is_default")]
    pub layout: ProjectLayoutSpec,
    #[serde(default)]
    pub rwe: ProjectRweSpec,
    #[serde(default)]
    pub pipelines: ProjectPipelinesSpec,
    #[serde(default)]
    pub runtime: ProjectRuntimeSpec,
    #[serde(default)]
    pub bootstrap: ProjectBootstrapSpec,
    #[serde(default)]
    pub git: ProjectGitSpec,
    #[serde(default)]
    pub assistant: ProjectAssistantSpec,
    #[serde(default)]
    pub locks: ProjectLocksSpec,
    /// Reserved for future project-wide data behavior. It never contains records.
    #[serde(default)]
    pub data: ProjectDataSpec,
    #[serde(default)]
    pub files: ProjectFilesSpec,
    #[serde(default)]
    pub distribution: ProjectDistributionSpec,
}

impl ProjectConfigurationSpec {
    fn validate(&self) -> Result<(), ContractError> {
        self.layout.validate()?;
        validate_text("spec.profile.title", &self.profile.title, 256, false)?;
        validate_text(
            "spec.profile.description",
            &self.profile.description,
            16_384,
            true,
        )?;
        for url in &self.rwe.allow_list {
            validate_http_pattern("spec.rwe.allow_list", url)?;
        }
        if self
            .rwe
            .allow_list
            .iter()
            .collect::<std::collections::BTreeSet<_>>()
            .len()
            != self.rwe.allow_list.len()
        {
            return Err(ContractError::invalid(
                "spec.rwe.allow_list must contain unique entries",
            ));
        }
        if let Some(base) = &self.rwe.deployment_asset_base {
            validate_http_or_root_path("spec.rwe.deployment_asset_base", base)?;
        }
        for (name, library) in &self.rwe.libraries {
            if !name.starts_with("zeb/") || !is_safe_logical_name(name, true) {
                return Err(ContractError::invalid(format!(
                    "spec.rwe.libraries key '{name}' must use the zeb/<name> form"
                )));
            }
            validate_text("spec.rwe.libraries.*.version", &library.version, 128, false)?;
            if library.version.trim().is_empty() {
                return Err(ContractError::invalid(
                    "spec.rwe.libraries.*.version must not be empty",
                ));
            }
            // `hub` joined `offline`/`online` when the local hub gained
            // `rwe_library` packages: a hub-installed library is requested by
            // configuration and resolved against its installed copy.
            if !matches!(library.source.as_str(), "offline" | "online" | "hub") {
                return Err(ContractError::invalid(
                    "spec.rwe.libraries.*.source must be offline, online, or hub",
                ));
            }
        }
        if let Some(capture) = &self.pipelines.logging.trace_capture {
            capture.validate().map_err(|message| {
                ContractError::invalid(format!("spec.pipelines.logging.trace_capture: {message}"))
            })?;
        }
        if let Some(value) = self.pipelines.logging.max_invocations
            && !(1..=1000).contains(&value)
        {
            return Err(ContractError::invalid(
                "spec.pipelines.logging.max_invocations must be between 1 and 1000",
            ));
        }
        if let Some(value) = self.pipelines.logging.max_error_groups
            && !(1..=10_000).contains(&value)
        {
            return Err(ContractError::invalid(
                "spec.pipelines.logging.max_error_groups must be between 1 and 10000",
            ));
        }
        if let Some(value) = self.pipelines.logging.occurrence_ring
            && !(1..=100_000).contains(&value)
        {
            return Err(ContractError::invalid(
                "spec.pipelines.logging.occurrence_ring must be between 1 and 100000",
            ));
        }
        if let Some(value) = self.pipelines.node_timeout_secs
            && !(5..=3600).contains(&value)
        {
            return Err(ContractError::invalid(
                "spec.pipelines.node_timeout_secs must be between 5 and 3600",
            ));
        }

        if let Some(backend) = self.files.backend.as_deref() {
            FileBackend::parse(backend).map_err(|err| {
                ContractError::invalid(format!("spec.files.backend {}", err.message))
            })?;
        }

        validate_optional_mb(
            "spec.files.uploads.max_asset_size_mb",
            self.files.uploads.max_asset_size_mb,
            5,
        )?;
        validate_optional_mb(
            "spec.files.uploads.webhook_body_max_mb",
            self.files.uploads.webhook_body_max_mb,
            100,
        )?;
        validate_optional_mb(
            "spec.files.uploads.max_file_size_mb",
            self.files.uploads.max_file_size_mb,
            5,
        )?;

        if self.runtime.min_replicas == 0 {
            return Err(ContractError::invalid(
                "spec.runtime.min_replicas must be greater than zero",
            ));
        }
        if let Some(max) = self.runtime.max_replicas
            && max < self.runtime.min_replicas
        {
            return Err(ContractError::invalid(
                "spec.runtime.max_replicas must be greater than or equal to min_replicas",
            ));
        }
        let mut runtime_tags = std::collections::BTreeSet::new();
        for tag in &self.runtime.required_tags {
            if !is_safe_logical_name(tag, false) || !runtime_tags.insert(tag) {
                return Err(ContractError::invalid(
                    "spec.runtime.required_tags must contain unique logical names",
                ));
            }
        }
        match (
            self.runtime.resource_profile,
            self.runtime.custom_resources.as_ref(),
        ) {
            (ProjectResourceProfileSpec::Custom, None) => {
                return Err(ContractError::invalid(
                    "spec.runtime.custom_resources is required for the custom resource profile",
                ));
            }
            (ProjectResourceProfileSpec::Custom, Some(resources)) => {
                resources.validate()?;
            }
            (_, Some(_)) => {
                return Err(ContractError::invalid(
                    "spec.runtime.custom_resources is only allowed for the custom resource profile",
                ));
            }
            (_, None) => {}
        }

        validate_unique_paths("spec.bootstrap.activate", &self.bootstrap.activate, true)?;
        validate_git(&self.git.remote)?;
        for (path, value) in [
            (
                "spec.assistant.high_model_credential",
                self.assistant.high_model_credential.as_deref(),
            ),
            (
                "spec.assistant.general_model_credential",
                self.assistant.general_model_credential.as_deref(),
            ),
        ] {
            if let Some(value) = value {
                validate_identifier(path, value)?;
            }
        }
        validate_optional_range(
            "spec.assistant.max_steps",
            self.assistant.max_steps,
            1,
            1000,
        )?;
        validate_optional_range(
            "spec.assistant.max_replans",
            self.assistant.max_replans,
            0,
            64,
        )?;
        validate_optional_range(
            "spec.assistant.chat_history_pairs",
            self.assistant.chat_history_pairs,
            0,
            50,
        )?;
        validate_unique_paths("spec.locks.templates", &self.locks.templates, false)?;
        if !self.distribution.hub.entry_url.is_empty() {
            validate_http_or_root_path(
                "spec.distribution.hub.entry_url",
                &self.distribution.hub.entry_url,
            )?;
        }
        Ok(())
    }
}

fn validate_text(
    path: &str,
    value: &str,
    maximum: usize,
    allow_newlines: bool,
) -> Result<(), ContractError> {
    if value.len() > maximum
        || value.chars().any(|character| {
            character == '\0'
                || (character.is_control()
                    && (!allow_newlines || !matches!(character, '\n' | '\r' | '\t')))
        })
    {
        return Err(ContractError::invalid(format!(
            "{path} must be at most {maximum} bytes and contain no unsupported control characters"
        )));
    }
    Ok(())
}

fn validate_identifier(path: &str, value: &str) -> Result<(), ContractError> {
    if value.is_empty()
        || value.len() > 128
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
    {
        return Err(ContractError::invalid(format!(
            "{path} must contain only letters, numbers, dot, underscore, and hyphen"
        )));
    }
    Ok(())
}

fn is_safe_logical_name(value: &str, allow_slash: bool) -> bool {
    !value.is_empty()
        && value.len() <= 256
        && value.bytes().all(|byte| {
            byte.is_ascii_alphanumeric()
                || matches!(byte, b'-' | b'_' | b'.')
                || (allow_slash && byte == b'/')
        })
        && !value
            .split('/')
            .any(|segment| segment.is_empty() || segment == "." || segment == "..")
}

fn validate_http_pattern(path: &str, value: &str) -> Result<(), ContractError> {
    if value.len() > 2048
        || value.chars().any(char::is_control)
        || !(value.starts_with("https://") || value.starts_with("http://"))
        || value.split_once("://").is_some_and(|(_, rest)| {
            rest.split('/')
                .next()
                .is_some_and(|authority| authority.contains('@'))
        })
    {
        return Err(ContractError::invalid(format!(
            "{path} entries must be HTTP(S) patterns without embedded credentials"
        )));
    }
    Ok(())
}

fn validate_http_or_root_path(path: &str, value: &str) -> Result<(), ContractError> {
    if value.starts_with('/') {
        if value.starts_with("//") || value.contains("..") || value.chars().any(char::is_control) {
            return Err(ContractError::invalid(format!(
                "{path} must be a normalized root-relative path"
            )));
        }
        return Ok(());
    }
    let url = reqwest::Url::parse(value)
        .map_err(|_| ContractError::invalid(format!("{path} must be HTTP(S) or root-relative")))?;
    if !matches!(url.scheme(), "http" | "https")
        || !url.username().is_empty()
        || url.password().is_some()
    {
        return Err(ContractError::invalid(format!(
            "{path} must be HTTP(S) without embedded credentials"
        )));
    }
    Ok(())
}

fn validate_git(remote: &ProjectGitRemoteSpec) -> Result<(), ContractError> {
    let empty =
        remote.credential_id.is_empty() && remote.repo_url.is_empty() && remote.branch.is_empty();
    if empty {
        return Ok(());
    }
    if remote.repo_url.is_empty() || remote.branch.is_empty() {
        return Err(ContractError::invalid(
            "spec.git.remote.repo_url and branch are required together",
        ));
    }
    if !remote.credential_id.is_empty() {
        validate_identifier("spec.git.remote.credential_id", &remote.credential_id)?;
    }
    validate_git_url(&remote.repo_url)?;
    validate_git_branch(&remote.branch)
}

fn validate_git_url(value: &str) -> Result<(), ContractError> {
    if value.len() > 2048 || value.chars().any(char::is_control) {
        return Err(ContractError::invalid(
            "spec.git.remote.repo_url is invalid",
        ));
    }
    if value.starts_with("git@") {
        if value.contains(':') && !value.contains(char::is_whitespace) {
            return Ok(());
        }
    }
    let url = reqwest::Url::parse(value)
        .map_err(|_| ContractError::invalid("spec.git.remote.repo_url is invalid"))?;
    let invalid_credentials =
        url.password().is_some() || (url.scheme() == "https" && !url.username().is_empty());
    // `file://` is a bare repository on this machine or a mounted volume — the
    // remote a test and an air-gapped instance use. It carries no credentials.
    if !matches!(url.scheme(), "https" | "ssh" | "file") || invalid_credentials {
        return Err(ContractError::invalid(
            "spec.git.remote.repo_url must use HTTPS, SSH or file:// without embedded credentials",
        ));
    }
    Ok(())
}

fn validate_git_branch(value: &str) -> Result<(), ContractError> {
    if !is_git_branch_name(value) {
        return Err(ContractError::invalid(
            "spec.git.remote.branch is not a valid Git branch name",
        ));
    }
    Ok(())
}

/// Whether `value` may be handed to git as a branch name. Beyond git's own
/// ref rules, a leading `-` is refused: git reads such an argument as an
/// option, and `--upload-pack=<program>` runs a program. Every caller that
/// takes a branch from a request checks it here before git sees it.
pub fn is_git_branch_name(value: &str) -> bool {
    let invalid = value.is_empty()
        || value.len() > 255
        || value.starts_with('-')
        || value.starts_with('.')
        || value.ends_with('.')
        || value.ends_with('/')
        || value.ends_with(".lock")
        || value.contains("..")
        || value.contains("@{")
        || value
            .chars()
            .any(|character| character.is_control() || " ~^:?*[\\".contains(character));
    !invalid
}

fn validate_optional_range(
    path: &str,
    value: Option<u32>,
    minimum: u32,
    maximum: u32,
) -> Result<(), ContractError> {
    if value.is_some_and(|value| value < minimum || value > maximum) {
        return Err(ContractError::invalid(format!(
            "{path} must be between {minimum} and {maximum}"
        )));
    }
    Ok(())
}

fn validate_unique_paths(
    path: &str,
    values: &[String],
    allow_glob: bool,
) -> Result<(), ContractError> {
    let mut seen = std::collections::BTreeSet::new();
    for value in values {
        let invalid_character = value.chars().any(|character| {
            character.is_control()
                || character == '\\'
                || (!allow_glob && matches!(character, '*' | '?' | '[' | ']'))
        });
        if value.is_empty()
            || value.len() > 1024
            || value.starts_with('/')
            || value
                .split('/')
                .any(|segment| segment == "." || segment == "..")
            || invalid_character
            || !seen.insert(value)
        {
            return Err(ContractError::invalid(format!(
                "{path} must contain unique, project-relative paths"
            )));
        }
    }
    Ok(())
}

/// Decodes the known pre-contract `zebflow.json` shape for explicit migration.
/// Normal project configuration reads never call this function.
pub fn decode_legacy_project_configuration(
    bytes: &[u8],
) -> Result<ProjectConfigurationSpec, ContractError> {
    let legacy: LegacyProjectConfiguration =
        serde_json::from_slice(bytes).map_err(ContractError::Json)?;
    if legacy.version != "1.0" {
        return Err(ContractError::invalid(format!(
            "unsupported legacy project configuration version '{}'",
            legacy.version
        )));
    }
    if !legacy.configs.pipelines.nodes.is_empty() {
        return Err(ContractError::invalid(
            "legacy configs.pipelines.nodes must be empty before migration",
        ));
    }
    let LegacyProjectConfigs {
        rwe,
        pipelines,
        runtime,
        bootstrap,
        git,
        assistant,
        locks,
        data,
        files,
    } = legacy.configs;
    let hub = match (legacy.distribution.marketplace, legacy.distribution.hub) {
        (Some(_), Some(_)) => {
            return Err(ContractError::invalid(
                "legacy distribution cannot contain both marketplace and hub",
            ));
        }
        (Some(value), None) | (None, Some(value)) => value,
        (None, None) => ZebflowJsonDistributionHub::default(),
    };
    let spec: ProjectConfigurationSpec = ZebflowJson {
        metadata: legacy.metadata,
        configs: ZebflowJsonConfigs {
            // The legacy shape has no layout section, so a migrated project
            // declares nothing and keeps the directories it already used.
            layout: ZebflowJsonLayout::default(),
            rwe,
            pipelines: ZebflowJsonPipelines {
                logging: pipelines.logging,
                node_timeout_secs: pipelines.node_timeout_secs,
            },
            runtime,
            bootstrap,
            git,
            assistant,
            locks,
            data,
            files,
        },
        distribution: ZebflowJsonDistribution { hub },
    }
    .into();
    spec.validate()?;
    Ok(spec)
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct LegacyProjectConfiguration {
    version: String,
    #[serde(default)]
    metadata: ZebflowJsonMetadata,
    #[serde(default)]
    configs: LegacyProjectConfigs,
    #[serde(default)]
    distribution: LegacyProjectDistribution,
}

#[derive(Debug, Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct LegacyProjectConfigs {
    #[serde(default)]
    rwe: ZebflowJsonRwe,
    #[serde(default)]
    pipelines: LegacyProjectPipelines,
    #[serde(default)]
    runtime: ProjectRuntimeProfile,
    #[serde(default)]
    bootstrap: ProjectBootstrapPlan,
    #[serde(default)]
    git: ZebflowJsonGit,
    #[serde(default)]
    assistant: ZebflowJsonAssistant,
    #[serde(default)]
    locks: ZebflowJsonLocks,
    #[serde(default)]
    data: ZebflowJsonData,
    #[serde(default)]
    files: ZebflowJsonFiles,
}

#[derive(Debug, Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct LegacyProjectPipelines {
    #[serde(default)]
    logging: ZebflowJsonLogging,
    #[serde(default)]
    node_timeout_secs: Option<u64>,
    #[serde(default)]
    nodes: HashMap<String, Value>,
}

#[derive(Debug, Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct LegacyProjectDistribution {
    #[serde(default)]
    marketplace: Option<ZebflowJsonDistributionHub>,
    #[serde(default)]
    hub: Option<ZebflowJsonDistributionHub>,
}

fn validate_optional_mb(path: &str, value: Option<u32>, minimum: u32) -> Result<(), ContractError> {
    if let Some(value) = value
        && !(minimum..=1024).contains(&value)
    {
        return Err(ContractError::invalid(format!(
            "{path} must be between {minimum} and 1024"
        )));
    }
    Ok(())
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectProfileSpec {
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub title: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub description: String,
}

/// Declared repository layout.
///
/// Every entry is optional. An absent entry resolves to the platform default in
/// [`ZebflowJsonLayout::resolve`], which is what keeps a project written before
/// this section existed on exactly the directories it already used.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectLayoutSpec {
    /// Source root: pipelines, pages, styles, and shared components. It is also
    /// the RWE template root, which is one directory today and not two.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r#static: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub docs: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    /// Directory holding the portable SQLite schema export.
    ///
    /// This is a separate entry from `schema` because the two exports are
    /// different documents produced by different engines, and a project may
    /// carry one without the other.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sqlite_schema: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node_interfaces: Option<String>,
    /// Prefixes an install replays as initial data, each bound to one engine.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub initial_data: Option<Vec<ProjectInitialDataDirSpec>>,
    /// File extensions this project accepts inside `repo/`, without a dot.
    ///
    /// This is the one layout entry that is not a directory, and it belongs
    /// here for the same reason the directories do: it answers "what is this
    /// project's repository allowed to contain", and every consumer that has to
    /// agree on that already resolves through the same layout.
    ///
    /// Declaring it narrows the platform set. It cannot widen it -- an entry
    /// the platform does not allow is refused by name rather than ignored,
    /// because the install refusal built on this set is not overridable and a
    /// project that could widen it would be overriding it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allowed_extensions: Option<Vec<String>>,
}

/// One initial-data prefix and the database engine that would replay it.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectInitialDataDirSpec {
    pub path: String,
    pub engine: String,
}

/// Engine tokens the installer dispatches on. A prefix bound to anything else
/// would name a replay path that no code performs.
const INITIAL_DATA_ENGINES: &[&str] = &["sekejap", "sqlite"];

impl ProjectLayoutSpec {
    fn validate(&self) -> Result<(), ContractError> {
        for (path, value) in [
            ("spec.layout.source", self.source.as_deref()),
            ("spec.layout.r#static", self.r#static.as_deref()),
            ("spec.layout.docs", self.docs.as_deref()),
            ("spec.layout.schema", self.schema.as_deref()),
            ("spec.layout.sqlite_schema", self.sqlite_schema.as_deref()),
            (
                "spec.layout.node_interfaces",
                self.node_interfaces.as_deref(),
            ),
        ] {
            if let Some(value) = value {
                validate_layout_dir(path, value)?;
            }
        }
        self.validate_allowed_extensions()?;
        let Some(entries) = &self.initial_data else {
            return Ok(());
        };
        let mut seen = std::collections::BTreeSet::new();
        for entry in entries {
            validate_layout_dir("spec.layout.initial_data.*.path", &entry.path)?;
            if !INITIAL_DATA_ENGINES.contains(&entry.engine.as_str()) {
                return Err(ContractError::invalid(format!(
                    "spec.layout.initial_data.*.engine must be one of {}",
                    INITIAL_DATA_ENGINES.join(", ")
                )));
            }
            if !seen.insert(&entry.path) {
                return Err(ContractError::invalid(
                    "spec.layout.initial_data paths must be unique",
                ));
            }
        }
        Ok(())
    }

    /// Accepts a declared subset of the platform's extension set, refusing
    /// anything else by name.
    ///
    /// An unknown entry is refused rather than dropped so that a project cannot
    /// believe it accepts a file type no install would ever write, and a
    /// platform entry cannot be widened past what the install gate enforces.
    fn validate_allowed_extensions(&self) -> Result<(), ContractError> {
        let Some(declared) = &self.allowed_extensions else {
            return Ok(());
        };
        if declared.is_empty() {
            return Err(ContractError::invalid(
                "spec.layout.allowed_extensions must name at least one extension",
            ));
        }
        let mut seen = std::collections::BTreeSet::new();
        for entry in declared {
            if !DEFAULT_ALLOWED_FILE_EXTENSIONS.contains(&entry.as_str()) {
                return Err(ContractError::invalid(format!(
                    "spec.layout.allowed_extensions entry '{entry}' is not one of the \
                     extensions this platform accepts; the list may narrow the platform \
                     set and may not widen it"
                )));
            }
            if !seen.insert(entry) {
                return Err(ContractError::invalid(
                    "spec.layout.allowed_extensions entries must be unique",
                ));
            }
        }
        Ok(())
    }
}

/// Accepts one normalized, project-relative directory.
///
/// Layout entries name directories that other paths are built on top of, so a
/// trailing slash or a traversal segment here would be inherited by every path
/// derived from it rather than failing at the one place it was written.
///
/// `HubPackage` records the layout a publisher's paths were produced by and
/// validates it through this same rule, because a package layout an install
/// would translate against has to be exactly as safe as one a project declares.
/// One layout directory: a normalized, project-relative path, or empty.
///
/// Empty names the repository root, and is how a project says a kind is not
/// gathered under a directory of its own — a pipeline, a page and a README
/// side by side at the top of the repository. It is the default for
/// `spec.layout.source`, so a project that declares nothing is a project with
/// no imposed folders at all.
pub(crate) fn validate_layout_dir(path: &str, value: &str) -> Result<(), ContractError> {
    if value.is_empty() {
        return Ok(());
    }
    let invalid = value.len() > 1024
        || value.starts_with('/')
        || value.ends_with('/')
        || value
            .split('/')
            .any(|segment| segment.is_empty() || segment == "." || segment == "..")
        || value.chars().any(|character| {
            character.is_control()
                || character == '\\'
                || matches!(character, '*' | '?' | '[' | ']')
        });
    if invalid {
        return Err(ContractError::invalid(format!(
            "{path} must be a normalized, project-relative directory"
        )));
    }
    Ok(())
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectRweSpec {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allow_list: Vec<String>,
    #[serde(default, skip_serializing_if = "is_false")]
    pub minify_html: bool,
    #[serde(default = "default_true", skip_serializing_if = "is_true")]
    pub strict_mode: bool,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub libraries: BTreeMap<String, ProjectRweLibrarySpec>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deployment_asset_base: Option<String>,
}

impl Default for ProjectRweSpec {
    fn default() -> Self {
        Self {
            allow_list: Vec::new(),
            minify_html: false,
            strict_mode: true,
            libraries: BTreeMap::new(),
            deployment_asset_base: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectRweLibrarySpec {
    pub version: String,
    pub source: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectPipelinesSpec {
    #[serde(default, skip_serializing_if = "is_default")]
    pub logging: ProjectPipelineLoggingSpec,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node_timeout_secs: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectPipelineLoggingSpec {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_invocations: Option<u32>,
    /// Distinct error groups kept per project; 1–10000, default 200.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_error_groups: Option<u32>,
    /// Occurrences remembered per error group; 1–100000, default 500.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub occurrence_ring: Option<u32>,
    /// Default capture bounds for node input/output previews. Pipelines may
    /// override individual fields; execution payloads are never compacted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trace_capture: Option<crate::pipeline::trace_capture::TraceCaptureSettings>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProjectRuntimeModeSpec {
    #[default]
    Shared,
    Pinned,
    Dedicated,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProjectExecutionSpec {
    #[default]
    Resident,
    DockerJob,
    K8sJob,
    SparkSubmit,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ProjectResourceProfileSpec {
    Tiny,
    #[default]
    Small,
    Medium,
    Large,
    Custom,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectRuntimeSpec {
    #[serde(default, skip_serializing_if = "is_default")]
    pub mode: ProjectRuntimeModeSpec,
    #[serde(default, skip_serializing_if = "is_default")]
    pub execution: ProjectExecutionSpec,
    #[serde(default, skip_serializing_if = "is_default")]
    pub resource_profile: ProjectResourceProfileSpec,
    #[serde(default = "default_min_replicas", skip_serializing_if = "is_one")]
    pub min_replicas: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_replicas: Option<u32>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_tags: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub custom_resources: Option<ProjectRuntimeResourceSpec>,
}

impl Default for ProjectRuntimeSpec {
    fn default() -> Self {
        Self {
            mode: ProjectRuntimeModeSpec::Shared,
            execution: ProjectExecutionSpec::Resident,
            resource_profile: ProjectResourceProfileSpec::Small,
            min_replicas: 1,
            max_replicas: None,
            required_tags: Vec::new(),
            custom_resources: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectRuntimeResourceSpec {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cpu_request_millis: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory_request_mb: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cpu_limit_millis: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory_limit_mb: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ephemeral_disk_mb: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accelerator_count: Option<u16>,
}

impl ProjectRuntimeResourceSpec {
    fn validate(&self) -> Result<(), ContractError> {
        if [
            self.cpu_request_millis,
            self.memory_request_mb,
            self.cpu_limit_millis,
            self.memory_limit_mb,
            self.ephemeral_disk_mb,
        ]
        .into_iter()
        .flatten()
        .any(|value| value == 0)
            || self.accelerator_count.is_some_and(|value| value == 0)
        {
            return Err(ContractError::invalid(
                "spec.runtime.custom_resources values must be greater than zero",
            ));
        }
        if let (Some(request), Some(limit)) = (self.cpu_request_millis, self.cpu_limit_millis)
            && request > limit
        {
            return Err(ContractError::invalid(
                "spec.runtime.custom_resources.cpu_request_millis must not exceed cpu_limit_millis",
            ));
        }
        if let (Some(request), Some(limit)) = (self.memory_request_mb, self.memory_limit_mb)
            && request > limit
        {
            return Err(ContractError::invalid(
                "spec.runtime.custom_resources.memory_request_mb must not exceed memory_limit_mb",
            ));
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectBootstrapSpec {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub activate: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectGitSpec {
    #[serde(default, skip_serializing_if = "is_default")]
    pub remote: ProjectGitRemoteSpec,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectGitRemoteSpec {
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub credential_id: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub repo_url: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub branch: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectAssistantSpec {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub high_model_credential: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub general_model_credential: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_steps: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_replans: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chat_history_pairs: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectLocksSpec {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub templates: Vec<String>,
}

/// Reserved v1 section for future data policy settings.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectDataSpec {}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectFilesSpec {
    /// The native store this project's files live in.
    ///
    /// This answers "where does this project keep its files", and it is the
    /// same word a FileRef carries in `backend`. It does not answer "which
    /// outside bucket may a pipeline read" -- an external S3 or MinIO bucket a
    /// pipeline talks to is a connection with a credential, chosen per
    /// pipeline, and bytes fetched from one still land in the native store.
    ///
    /// Optional. An absent entry resolves to [`FileBackend::default`], so a
    /// project that declares nothing keeps the store it always used and is not
    /// rewritten to carry a section it did not author.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backend: Option<String>,
    #[serde(default, skip_serializing_if = "is_default")]
    pub uploads: ProjectUploadSpec,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectUploadSpec {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_asset_size_mb: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub webhook_body_max_mb: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_file_size_mb: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectDistributionSpec {
    #[serde(default)]
    pub hub: ProjectHubDistributionSpec,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ProjectHubDistributionSpec {
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub entry_url: String,
    #[serde(default, skip_serializing_if = "is_false")]
    pub as_app: bool,
    #[serde(default, skip_serializing_if = "is_false")]
    pub producer_enabled: bool,
}

impl From<ZebflowJson> for ProjectConfigurationSpec {
    fn from(value: ZebflowJson) -> Self {
        let default_uploads = ZebflowJsonUploads::default();
        Self {
            profile: ProjectProfileSpec {
                title: value.metadata.title,
                description: value.metadata.description,
            },
            layout: ProjectLayoutSpec {
                source: value.configs.layout.source,
                r#static: value.configs.layout.r#static,
                docs: value.configs.layout.docs,
                schema: value.configs.layout.schema,
                sqlite_schema: value.configs.layout.sqlite_schema,
                node_interfaces: value.configs.layout.node_interfaces,
                initial_data: value.configs.layout.initial_data.map(|entries| {
                    entries
                        .into_iter()
                        .map(|entry| ProjectInitialDataDirSpec {
                            path: entry.path,
                            engine: entry.engine,
                        })
                        .collect()
                }),
                allowed_extensions: value.configs.layout.allowed_extensions,
            },
            rwe: ProjectRweSpec {
                allow_list: value.configs.rwe.allow_list,
                minify_html: value.configs.rwe.minify_html,
                strict_mode: value.configs.rwe.strict_mode,
                libraries: value
                    .configs
                    .rwe
                    .libraries
                    .into_iter()
                    .map(|(name, item)| {
                        (
                            name,
                            ProjectRweLibrarySpec {
                                version: item.version,
                                source: item.source,
                            },
                        )
                    })
                    .collect(),
                deployment_asset_base: value.configs.rwe.deployment_asset_base,
            },
            pipelines: ProjectPipelinesSpec {
                logging: ProjectPipelineLoggingSpec {
                    max_invocations: value.configs.pipelines.logging.max_invocations,
                    max_error_groups: value.configs.pipelines.logging.max_error_groups,
                    occurrence_ring: value.configs.pipelines.logging.occurrence_ring,
                    trace_capture: value.configs.pipelines.logging.trace_capture,
                },
                node_timeout_secs: value.configs.pipelines.node_timeout_secs,
            },
            runtime: value.configs.runtime.into(),
            bootstrap: ProjectBootstrapSpec {
                activate: value.configs.bootstrap.activate,
            },
            git: ProjectGitSpec {
                remote: ProjectGitRemoteSpec {
                    credential_id: value.configs.git.remote.credential_id,
                    repo_url: value.configs.git.remote.repo_url,
                    branch: value.configs.git.remote.branch,
                },
            },
            assistant: ProjectAssistantSpec {
                high_model_credential: value.configs.assistant.high_model_credential,
                general_model_credential: value.configs.assistant.general_model_credential,
                max_steps: value.configs.assistant.max_steps,
                max_replans: value.configs.assistant.max_replans,
                chat_history_pairs: value.configs.assistant.chat_history_pairs,
                enabled: value.configs.assistant.enabled,
            },
            locks: ProjectLocksSpec {
                templates: value.configs.locks.templates,
            },
            data: ProjectDataSpec {},
            files: ProjectFilesSpec {
                backend: value.configs.files.backend,
                uploads: ProjectUploadSpec {
                    max_asset_size_mb: (value.configs.files.uploads.max_asset_size_mb
                        != default_uploads.max_asset_size_mb)
                        .then_some(value.configs.files.uploads.max_asset_size_mb),
                    webhook_body_max_mb: (value.configs.files.uploads.webhook_body_max_mb
                        != default_uploads.webhook_body_max_mb)
                        .then_some(value.configs.files.uploads.webhook_body_max_mb),
                    max_file_size_mb: value.configs.files.uploads.max_file_size_mb,
                },
            },
            distribution: ProjectDistributionSpec {
                hub: ProjectHubDistributionSpec {
                    entry_url: value.distribution.hub.entry_url,
                    as_app: value.distribution.hub.as_app,
                    producer_enabled: value.distribution.hub.producer_enabled,
                },
            },
        }
    }
}

impl From<ProjectConfigurationSpec> for ZebflowJson {
    fn from(value: ProjectConfigurationSpec) -> Self {
        let default_uploads = ZebflowJsonUploads::default();
        Self {
            metadata: ZebflowJsonMetadata {
                title: value.profile.title,
                description: value.profile.description,
            },
            configs: ZebflowJsonConfigs {
                layout: ZebflowJsonLayout {
                    source: value.layout.source,
                    r#static: value.layout.r#static,
                    docs: value.layout.docs,
                    schema: value.layout.schema,
                    sqlite_schema: value.layout.sqlite_schema,
                    node_interfaces: value.layout.node_interfaces,
                    initial_data: value.layout.initial_data.map(|entries| {
                        entries
                            .into_iter()
                            .map(|entry| ZebflowJsonInitialDataDir {
                                path: entry.path,
                                engine: entry.engine,
                            })
                            .collect()
                    }),
                    allowed_extensions: value.layout.allowed_extensions,
                },
                rwe: ZebflowJsonRwe {
                    allow_list: value.rwe.allow_list,
                    minify_html: value.rwe.minify_html,
                    strict_mode: value.rwe.strict_mode,
                    libraries: value
                        .rwe
                        .libraries
                        .into_iter()
                        .map(|(name, item)| {
                            (
                                name,
                                ZebflowJsonRweLibraryEntry {
                                    version: item.version,
                                    source: item.source,
                                },
                            )
                        })
                        .collect(),
                    deployment_asset_base: value.rwe.deployment_asset_base,
                },
                pipelines: ZebflowJsonPipelines {
                    logging: ZebflowJsonLogging {
                        max_invocations: value.pipelines.logging.max_invocations,
                        max_error_groups: value.pipelines.logging.max_error_groups,
                        occurrence_ring: value.pipelines.logging.occurrence_ring,
                        trace_capture: value.pipelines.logging.trace_capture,
                    },
                    node_timeout_secs: value.pipelines.node_timeout_secs,
                },
                runtime: value.runtime.into(),
                bootstrap: ProjectBootstrapPlan {
                    activate: value.bootstrap.activate,
                },
                git: ZebflowJsonGit {
                    remote: ZebflowJsonGitRemote {
                        credential_id: value.git.remote.credential_id,
                        repo_url: value.git.remote.repo_url,
                        branch: value.git.remote.branch,
                    },
                },
                assistant: ZebflowJsonAssistant {
                    high_model_credential: value.assistant.high_model_credential,
                    general_model_credential: value.assistant.general_model_credential,
                    max_steps: value.assistant.max_steps,
                    max_replans: value.assistant.max_replans,
                    chat_history_pairs: value.assistant.chat_history_pairs,
                    enabled: value.assistant.enabled,
                },
                locks: ZebflowJsonLocks {
                    templates: value.locks.templates,
                },
                data: ZebflowJsonData {},
                files: ZebflowJsonFiles {
                    backend: value.files.backend,
                    uploads: ZebflowJsonUploads {
                        max_asset_size_mb: value
                            .files
                            .uploads
                            .max_asset_size_mb
                            .unwrap_or(default_uploads.max_asset_size_mb),
                        webhook_body_max_mb: value
                            .files
                            .uploads
                            .webhook_body_max_mb
                            .unwrap_or(default_uploads.webhook_body_max_mb),
                        max_file_size_mb: value.files.uploads.max_file_size_mb,
                    },
                },
            },
            distribution: ZebflowJsonDistribution {
                hub: ZebflowJsonDistributionHub {
                    entry_url: value.distribution.hub.entry_url,
                    as_app: value.distribution.hub.as_app,
                    producer_enabled: value.distribution.hub.producer_enabled,
                },
            },
        }
    }
}

impl From<ProjectRuntimeProfile> for ProjectRuntimeSpec {
    fn from(value: ProjectRuntimeProfile) -> Self {
        Self {
            mode: match value.mode {
                ProjectRuntimeMode::Shared => ProjectRuntimeModeSpec::Shared,
                ProjectRuntimeMode::Pinned => ProjectRuntimeModeSpec::Pinned,
                ProjectRuntimeMode::Dedicated => ProjectRuntimeModeSpec::Dedicated,
            },
            execution: match value.execution {
                ExecutionProfileKind::Resident => ProjectExecutionSpec::Resident,
                ExecutionProfileKind::DockerJob => ProjectExecutionSpec::DockerJob,
                ExecutionProfileKind::K8sJob => ProjectExecutionSpec::K8sJob,
                ExecutionProfileKind::SparkSubmit => ProjectExecutionSpec::SparkSubmit,
            },
            resource_profile: match value.resource_profile {
                ResourceProfile::Tiny => ProjectResourceProfileSpec::Tiny,
                ResourceProfile::Small => ProjectResourceProfileSpec::Small,
                ResourceProfile::Medium => ProjectResourceProfileSpec::Medium,
                ResourceProfile::Large => ProjectResourceProfileSpec::Large,
                ResourceProfile::Custom => ProjectResourceProfileSpec::Custom,
            },
            min_replicas: value.min_replicas,
            max_replicas: value.max_replicas,
            required_tags: value.required_tags,
            custom_resources: value.custom_resources.map(Into::into),
        }
    }
}

impl From<ProjectRuntimeSpec> for ProjectRuntimeProfile {
    fn from(value: ProjectRuntimeSpec) -> Self {
        Self {
            mode: match value.mode {
                ProjectRuntimeModeSpec::Shared => ProjectRuntimeMode::Shared,
                ProjectRuntimeModeSpec::Pinned => ProjectRuntimeMode::Pinned,
                ProjectRuntimeModeSpec::Dedicated => ProjectRuntimeMode::Dedicated,
            },
            execution: match value.execution {
                ProjectExecutionSpec::Resident => ExecutionProfileKind::Resident,
                ProjectExecutionSpec::DockerJob => ExecutionProfileKind::DockerJob,
                ProjectExecutionSpec::K8sJob => ExecutionProfileKind::K8sJob,
                ProjectExecutionSpec::SparkSubmit => ExecutionProfileKind::SparkSubmit,
            },
            resource_profile: match value.resource_profile {
                ProjectResourceProfileSpec::Tiny => ResourceProfile::Tiny,
                ProjectResourceProfileSpec::Small => ResourceProfile::Small,
                ProjectResourceProfileSpec::Medium => ResourceProfile::Medium,
                ProjectResourceProfileSpec::Large => ResourceProfile::Large,
                ProjectResourceProfileSpec::Custom => ResourceProfile::Custom,
            },
            min_replicas: value.min_replicas,
            max_replicas: value.max_replicas,
            required_tags: value.required_tags,
            custom_resources: value.custom_resources.map(Into::into),
        }
    }
}

impl From<RuntimeResourceSpec> for ProjectRuntimeResourceSpec {
    fn from(value: RuntimeResourceSpec) -> Self {
        Self {
            cpu_request_millis: value.cpu_request_millis,
            memory_request_mb: value.memory_request_mb,
            cpu_limit_millis: value.cpu_limit_millis,
            memory_limit_mb: value.memory_limit_mb,
            ephemeral_disk_mb: value.ephemeral_disk_mb,
            accelerator_count: value.accelerator_count,
        }
    }
}

impl From<ProjectRuntimeResourceSpec> for RuntimeResourceSpec {
    fn from(value: ProjectRuntimeResourceSpec) -> Self {
        Self {
            cpu_request_millis: value.cpu_request_millis,
            memory_request_mb: value.memory_request_mb,
            cpu_limit_millis: value.cpu_limit_millis,
            memory_limit_mb: value.memory_limit_mb,
            ephemeral_disk_mb: value.ephemeral_disk_mb,
            accelerator_count: value.accelerator_count,
        }
    }
}

const fn default_true() -> bool {
    true
}

const fn default_min_replicas() -> u32 {
    1
}

fn is_false(value: &bool) -> bool {
    !*value
}

fn is_true(value: &bool) -> bool {
    *value
}

fn is_one(value: &u32) -> bool {
    *value == 1
}

fn is_default<T: Default + PartialEq>(value: &T) -> bool {
    *value == T::default()
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;
    use crate::contracts::{
        ContractMetadata, decode_contract_value, decode_contract_yaml, encode_contract,
        encode_contract_yaml,
    };
    use crate::platform::model::ResolvedProjectLayout;

    #[test]
    fn trace_capture_defaults_survive_runtime_and_yaml_roundtrip() {
        let mut spec = ProjectConfigurationSpec::default();
        let capture = crate::pipeline::trace_capture::TraceCaptureSettings {
            level: Some(crate::pipeline::trace_capture::CaptureLevel::Full),
            array_sample_count: Some(1),
            max_string_chars: Some(1024),
            max_depth: Some(4),
            max_node_bytes: Some(4096),
            max_run_bytes: Some(16384),
        };
        spec.pipelines.logging.trace_capture = Some(capture.clone());
        let runtime: ZebflowJson = spec.into();
        let restored: ProjectConfigurationSpec = runtime.into();
        assert_eq!(
            restored.pipelines.logging.trace_capture,
            Some(capture.clone())
        );
        let bytes = encode_contract_yaml::<ProjectConfigurationContract>(
            ContractMetadata::named("project"),
            restored,
        )
        .unwrap();
        let decoded = decode_contract_yaml::<ProjectConfigurationContract>(&bytes).unwrap();
        assert_eq!(decoded.spec.pipelines.logging.trace_capture, Some(capture));
    }

    #[test]
    fn trace_capture_defaults_reject_invalid_limits() {
        let mut spec = ProjectConfigurationSpec::default();
        spec.pipelines.logging.trace_capture =
            Some(crate::pipeline::trace_capture::TraceCaptureSettings {
                max_node_bytes: Some(0),
                ..Default::default()
            });
        assert!(
            encode_contract::<ProjectConfigurationContract>(
                ContractMetadata::named("project"),
                spec,
            )
            .is_err()
        );
    }

    const COMPLETE_V1: &[u8] =
        include_bytes!("../../../tests/fixtures/contracts/project-configuration/v1-complete.yaml");
    const COMPLETE_LEGACY_V1: &[u8] = include_bytes!(
        "../../../tests/fixtures/contracts/project-configuration/legacy-1.0-complete.json"
    );
    const DECLARED_LAYOUT_V1: &[u8] =
        include_bytes!("../../../tests/fixtures/contracts/project-configuration/v1-layout.yaml");

    fn declared_layout() -> ProjectLayoutSpec {
        ProjectLayoutSpec {
            source: Some("src".to_string()),
            r#static: Some("src/static".to_string()),
            docs: Some("documentation".to_string()),
            schema: Some("db/schema".to_string()),
            sqlite_schema: Some("db/sqlite".to_string()),
            node_interfaces: Some("vendor/nodes".to_string()),
            initial_data: Some(vec![ProjectInitialDataDirSpec {
                path: "db/seeds".to_string(),
                engine: "sekejap".to_string(),
            }]),
            allowed_extensions: Some(
                ["tsx", "ts", "css", "json", "md"]
                    .into_iter()
                    .map(str::to_string)
                    .collect(),
            ),
        }
    }

    #[test]
    fn an_undeclared_layout_resolves_to_the_hardcoded_platform_directories() {
        let document = decode_contract_yaml::<ProjectConfigurationContract>(COMPLETE_V1).unwrap();
        assert_eq!(document.spec.layout, ProjectLayoutSpec::default());

        let layout = ZebflowJson::from(document.spec).layout();
        // Undeclared means the repository itself: no imposed folders.
        assert_eq!(layout.source, "");
        assert_eq!(layout.r#static, "static");
        assert_eq!(layout.docs, "docs");
        assert_eq!(layout.schema, "schemas/sekejap");
        assert_eq!(layout.sqlite_schema, "schemas/sqlite");
        assert_eq!(layout.node_interfaces, "nodes");
        assert_eq!(
            layout
                .initial_data
                .iter()
                .map(|entry| (entry.path.as_str(), entry.engine.as_str()))
                .collect::<Vec<_>>(),
            [
                ("initial-data/sekejap", "sekejap"),
                ("initial-data/sqlite", "sqlite"),
                ("init/sekejap", "sekejap"),
                ("init/sqlite", "sqlite"),
                ("seeds/sekejap", "sekejap"),
                ("seeds/sqlite", "sqlite"),
            ]
        );
        assert_eq!(layout, ResolvedProjectLayout::platform_default());
    }

    #[test]
    fn declared_layout_fixture_roundtrips_byte_for_byte() {
        let document =
            decode_contract_yaml::<ProjectConfigurationContract>(DECLARED_LAYOUT_V1).unwrap();
        assert_eq!(document.spec.layout, declared_layout());
        assert_eq!(
            encode_contract_yaml::<ProjectConfigurationContract>(document.metadata, document.spec)
                .unwrap(),
            DECLARED_LAYOUT_V1
        );
    }

    #[test]
    fn a_declared_layout_survives_the_runtime_model_roundtrip() {
        let expected = ProjectConfigurationSpec {
            layout: declared_layout(),
            ..ProjectConfigurationSpec::default()
        };
        let runtime: ZebflowJson = expected.clone().into();
        assert_eq!(runtime.layout().source, "src");
        // Undeclared entries still resolve to the platform default.
        assert_eq!(runtime.layout().r#static, "src/static");
        assert_eq!(ProjectConfigurationSpec::from(runtime), expected);
    }

    #[test]
    fn unusable_layout_directories_and_engines_are_rejected() {
        let seed = |path: &str, engine: &str| ProjectInitialDataDirSpec {
            path: path.to_string(),
            engine: engine.to_string(),
        };
        for layout in [
            ProjectLayoutSpec {
                source: Some("/pipelines".to_string()),
                ..ProjectLayoutSpec::default()
            },
            ProjectLayoutSpec {
                source: Some("pipelines/".to_string()),
                ..ProjectLayoutSpec::default()
            },
            ProjectLayoutSpec {
                source: Some("../pipelines".to_string()),
                ..ProjectLayoutSpec::default()
            },
            ProjectLayoutSpec {
                r#static: Some("pipelines/*".to_string()),
                ..ProjectLayoutSpec::default()
            },
            ProjectLayoutSpec {
                initial_data: Some(vec![seed("seeds/mysql", "mysql")]),
                ..ProjectLayoutSpec::default()
            },
            ProjectLayoutSpec {
                initial_data: Some(vec![
                    seed("seeds/sekejap", "sekejap"),
                    seed("seeds/sekejap", "sqlite"),
                ]),
                ..ProjectLayoutSpec::default()
            },
        ] {
            assert!(
                encode_contract::<ProjectConfigurationContract>(
                    ContractMetadata::named("project"),
                    ProjectConfigurationSpec {
                        layout,
                        ..ProjectConfigurationSpec::default()
                    },
                )
                .is_err()
            );
        }
    }

    /// The extension list narrows the platform set and cannot widen it. A
    /// widening entry is refused by name rather than dropped, because a project
    /// that silently kept an extension no install would ever write would
    /// believe it accepted a file type the gate refuses.
    #[test]
    fn an_extension_list_may_narrow_the_platform_set_and_may_not_widen_it() {
        let with = |extensions: &[&str]| ProjectConfigurationSpec {
            layout: ProjectLayoutSpec {
                allowed_extensions: Some(
                    extensions.iter().map(|value| value.to_string()).collect(),
                ),
                ..ProjectLayoutSpec::default()
            },
            ..ProjectConfigurationSpec::default()
        };
        let encoded = |spec: ProjectConfigurationSpec| {
            encode_contract::<ProjectConfigurationContract>(
                ContractMetadata::named("project"),
                spec,
            )
        };

        encoded(with(&["tsx", "json"])).expect("a subset of the platform set is a narrowing");
        for refused in [
            vec!["tsx", "sh"],
            vec!["tsx", ".tsx"],
            vec!["tsx", "TSX"],
            vec!["tsx", "tsx"],
            vec![],
        ] {
            assert!(
                encoded(with(&refused)).is_err(),
                "accepted {refused:?}, which is not a narrowing of the platform set"
            );
        }
    }

    /// A project that declares nothing inherits the platform set whole, which
    /// is what keeps the install gate on for every project written before this
    /// entry existed.
    #[test]
    fn an_undeclared_extension_list_resolves_to_the_platform_set() {
        let layout = ProjectLayoutSpec::default();
        assert_eq!(layout.allowed_extensions, None);
        assert_eq!(
            ZebflowJson::from(ProjectConfigurationSpec {
                layout,
                ..ProjectConfigurationSpec::default()
            })
            .layout()
            .allowed_extensions,
            DEFAULT_ALLOWED_FILE_EXTENSIONS
                .iter()
                .map(|value| (*value).to_string())
                .collect::<Vec<_>>()
        );
    }

    /// A project that declares nothing keeps the store it always used, and is
    /// not rewritten to carry an entry it did not author.
    #[test]
    fn an_undeclared_backend_resolves_to_the_local_store() {
        let spec = ProjectConfigurationSpec::default();
        assert_eq!(spec.files.backend, None);

        let runtime = ZebflowJson::from(spec);
        assert_eq!(runtime.configs.files.backend, None);
        assert_eq!(
            runtime.configs.files.effective_backend().unwrap(),
            FileBackend::Zebfs
        );

        let encoded = encode_contract_yaml::<ProjectConfigurationContract>(
            ContractMetadata::named("project"),
            ProjectConfigurationSpec::from(runtime),
        )
        .unwrap();
        assert!(
            !String::from_utf8(encoded).unwrap().contains("backend"),
            "an absent declaration must stay absent on rewrite"
        );
    }

    /// The declaration and the FileRef field name the same store, so the same
    /// word has to be accepted here that a stored FileRef already carries.
    #[test]
    fn a_declared_backend_survives_the_runtime_model_roundtrip() {
        let expected = ProjectConfigurationSpec {
            files: ProjectFilesSpec {
                backend: Some(crate::pipeline::nodes::shared::file_ref::BACKEND_ZEBFS.to_string()),
                ..ProjectFilesSpec::default()
            },
            ..ProjectConfigurationSpec::default()
        };
        let runtime: ZebflowJson = expected.clone().into();
        assert_eq!(
            runtime.configs.files.effective_backend().unwrap(),
            FileBackend::Zebfs
        );
        assert_eq!(ProjectConfigurationSpec::from(runtime), expected);
    }

    /// An unknown backend is refused by name with the accepted list, rather
    /// than defaulted -- a project whose bytes went to a store it did not
    /// declare is worse than a project that will not start.
    #[test]
    fn an_unknown_backend_is_refused_by_name() {
        let with = |backend: &str| ProjectConfigurationSpec {
            files: ProjectFilesSpec {
                backend: Some(backend.to_string()),
                ..ProjectFilesSpec::default()
            },
            ..ProjectConfigurationSpec::default()
        };
        encode_contract::<ProjectConfigurationContract>(
            ContractMetadata::named("project"),
            with("zebfs"),
        )
        .expect("the local backend is accepted by its declared name");

        for refused in ["ftp", "local", "ZebFS", "", "minio"] {
            let error = encode_contract::<ProjectConfigurationContract>(
                ContractMetadata::named("project"),
                with(refused),
            )
            .expect_err("only a backend this build can open is accepted");
            let message = error.to_string();
            assert!(message.contains("spec.files.backend"), "{message}");
            assert!(message.contains(&format!("'{refused}'")), "{message}");
            assert!(message.contains("accepted: zebfs"), "{message}");
        }
    }

    #[test]
    fn default_document_uses_the_permanent_section_layout() {
        let encoded = encode_contract::<ProjectConfigurationContract>(
            ContractMetadata::named("project-development"),
            ProjectConfigurationSpec::default(),
        )
        .unwrap();
        let value: serde_json::Value = serde_json::from_slice(&encoded).unwrap();

        assert_eq!(value["apiVersion"], "zebflow.com/v1");
        assert_eq!(value["kind"], "ProjectConfiguration");
        assert_eq!(value["spec"]["data"], json!({}));
        assert_eq!(value["spec"]["distribution"]["hub"], json!({}));
        assert!(value["spec"].get("configs").is_none());
        assert!(value["spec"].get("settings").is_none());
    }

    #[test]
    fn complete_v1_fixture_is_canonical_and_roundtrips_byte_for_byte() {
        let document = decode_contract_yaml::<ProjectConfigurationContract>(COMPLETE_V1).unwrap();
        assert_eq!(document.metadata.name, "project-development");
        assert_eq!(document.spec.runtime.min_replicas, 2);
        assert_eq!(document.spec.files.uploads.webhook_body_max_mb, Some(512));
        assert_eq!(
            encode_contract_yaml::<ProjectConfigurationContract>(document.metadata, document.spec,)
                .unwrap(),
            COMPLETE_V1
        );
    }

    #[test]
    fn unknown_and_invalid_settings_are_rejected() {
        let unknown = json!({
            "apiVersion": "zebflow.com/v1",
            "kind": "ProjectConfiguration",
            "metadata": {"name": "project"},
            "spec": {"data": {"records": []}}
        });
        assert!(decode_contract_value::<ProjectConfigurationContract>(unknown).is_err());

        let invalid = json!({
            "apiVersion": "zebflow.com/v1",
            "kind": "ProjectConfiguration",
            "metadata": {"name": "project"},
            "spec": {"pipelines": {"node_timeout_secs": 1}}
        });
        assert!(decode_contract_value::<ProjectConfigurationContract>(invalid).is_err());
    }

    #[test]
    fn disk_and_runtime_models_roundtrip() {
        let document = decode_contract_yaml::<ProjectConfigurationContract>(COMPLETE_V1).unwrap();
        let expected = document.spec;
        let runtime: ZebflowJson = expected.clone().into();
        let restored = ProjectConfigurationSpec::from(runtime);
        assert_eq!(restored, expected);
    }

    #[test]
    fn runtime_defaults_match_frozen_contract_defaults() {
        let runtime = ZebflowJson::default();
        let runtime_spec = ProjectConfigurationSpec::from(runtime);
        assert_eq!(runtime_spec, ProjectConfigurationSpec::default());
    }

    #[test]
    fn assistant_limits_match_the_settings_interface() {
        let mut spec = ProjectConfigurationSpec::default();
        spec.assistant.max_steps = Some(1);
        spec.assistant.max_replans = Some(0);
        spec.assistant.chat_history_pairs = Some(0);
        assert!(
            encode_contract::<ProjectConfigurationContract>(
                ContractMetadata::named("project"),
                spec.clone(),
            )
            .is_ok()
        );

        spec.assistant.max_replans = Some(65);
        assert!(
            encode_contract::<ProjectConfigurationContract>(
                ContractMetadata::named("project"),
                spec,
            )
            .is_err()
        );
    }

    #[test]
    fn explicit_legacy_decoder_maps_data_and_marketplace() {
        let legacy = br#"{
            "version":"1.0",
            "metadata":{"title":"Legacy","description":""},
            "configs":{"data":{},"pipelines":{"nodes":{}}},
            "distribution":{"marketplace":{"as_app":true}}
        }"#;
        let migrated = decode_legacy_project_configuration(legacy).unwrap();
        assert_eq!(migrated.profile.title, "Legacy");
        assert!(migrated.distribution.hub.as_app);
        assert_eq!(migrated.data, ProjectDataSpec {});
    }

    #[test]
    fn complete_legacy_fixture_preserves_every_owned_section() {
        let migrated = decode_legacy_project_configuration(COMPLETE_LEGACY_V1).unwrap();
        assert_eq!(migrated.profile.title, "Legacy Project");
        assert_eq!(migrated.rwe.libraries["zeb/deckgl"].version, "bridge-0.1");
        assert_eq!(migrated.runtime.min_replicas, 2);
        assert_eq!(migrated.runtime.max_replicas, Some(4));
        assert_eq!(migrated.bootstrap.activate, ["pipelines/main.zf.json"]);
        assert_eq!(migrated.files.uploads.webhook_body_max_mb, Some(512));
        assert!(migrated.distribution.hub.as_app);
    }

    #[test]
    fn project_metadata_is_identity_only() {
        for metadata in [
            ContractMetadata {
                version: Some("1.0.0".to_string()),
                ..ContractMetadata::named("project")
            },
            ContractMetadata {
                digest: Some(format!("sha256:{}", "0".repeat(64))),
                ..ContractMetadata::named("project")
            },
            ContractMetadata {
                annotations: [("owner".to_string(), "team".to_string())]
                    .into_iter()
                    .collect(),
                ..ContractMetadata::named("project")
            },
        ] {
            assert!(
                encode_contract::<ProjectConfigurationContract>(
                    metadata,
                    ProjectConfigurationSpec::default()
                )
                .is_err()
            );
        }
    }

    #[test]
    fn secret_bearing_urls_and_ambiguous_lists_are_rejected() {
        let mut spec = ProjectConfigurationSpec::default();
        spec.git.remote.repo_url = "https://token@git.example.com/project.git".to_string();
        spec.git.remote.branch = "main".to_string();
        assert!(
            encode_contract::<ProjectConfigurationContract>(
                ContractMetadata::named("project"),
                spec
            )
            .is_err()
        );

        for branch in ["--upload-pack=touch /tmp/x", "-b", "main..x", ".hidden"] {
            let mut spec = ProjectConfigurationSpec::default();
            spec.git.remote.repo_url = "https://git.example.com/project.git".to_string();
            spec.git.remote.branch = branch.to_string();
            assert!(
                encode_contract::<ProjectConfigurationContract>(
                    ContractMetadata::named("project"),
                    spec
                )
                .is_err(),
                "branch {branch:?} must be refused"
            );
        }
        assert!(is_git_branch_name("feature/a-b"));

        let mut spec = ProjectConfigurationSpec::default();
        spec.rwe.allow_list = vec![
            "https://cdn.example.com/*".to_string(),
            "https://cdn.example.com/*".to_string(),
        ];
        assert!(
            encode_contract::<ProjectConfigurationContract>(
                ContractMetadata::named("project"),
                spec
            )
            .is_err()
        );

        let mut spec = ProjectConfigurationSpec::default();
        spec.rwe.libraries.insert(
            "zeb/deckgl".to_string(),
            ProjectRweLibrarySpec {
                version: " ".to_string(),
                source: "offline".to_string(),
            },
        );
        assert!(
            encode_contract::<ProjectConfigurationContract>(
                ContractMetadata::named("project"),
                spec
            )
            .is_err()
        );
    }
}