type-bridge-workspace 2.2.2

Validated programmatic workspace configuration for type-bridge
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
//! Validated, programmatic TypeBridge workspace configuration.
//!
//! This public orchestration boundary deliberately stops before schema loading,
//! history, persistence, provider/network I/O, secret resolution, or
//! compiled-runtime construction. Its bounded filesystem observations are the
//! explicitly supplied workspace YAML and custom TLS trust material: callers
//! inject local source services that canonicalize and prove those inputs before
//! an inert, fully validated [`TypeBridgeConfig`] is returned.

#![deny(missing_docs)]

use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::path::{Component, Path, PathBuf};

use sha2::{Digest as _, Sha256};
use type_bridge_contract::capability::{CapabilityId, CapabilitySet};
use type_bridge_contract::fingerprint::SemanticProfileId;
use type_bridge_contract::managed_scope::{
    ManagedScopeBinding, ManagedScopeId, ManagedScopeProfileId,
};
use type_bridge_contract::migration::MigrationAppLabel;
use type_bridge_contract::projection::{BindingTarget, CSymbolPrefix};
use type_bridge_contract::reserved::TYPEBRIDGE_JOURNAL_DATABASE_SUFFIX;
use type_bridge_contract::schema::SourceSpan;
use type_bridge_contract::semantic_profile::SemanticProfile;
use type_bridge_schema::{SchemaSourceKind, SchemaSourceService};
use type_bridge_schema_migration::{MigrationSafetyPolicy, validate_portable_direct_child};
use unicode_casefold::UnicodeCaseFold as _;
use unicode_normalization::UnicodeNormalization as _;

mod authority;
mod backfill_intent;
mod bundle;
mod lock;
mod migration;
mod workspace;
mod workspace_yaml;

pub use authority::{WorkspaceDirectoryAuthority, WorkspaceOutputDirectory};
pub use backfill_intent::{
    MAX_BACKFILL_INTENT_BYTES, TYPEBRIDGE_BACKFILL_INTENT_V1, parse_backfill_intent,
};
pub use bundle::{
    BundleProjectionContext, BundleVerificationContext, MAX_SCHEMA_BUNDLE_BYTES,
    SCHEMA_BUNDLE_FINGERPRINT_CANONICALIZATION, SCHEMA_BUNDLE_FINGERPRINT_DOMAIN,
    SchemaBundleError, SchemaBundleErrorCode, TYPEBRIDGE_SCHEMA_BUNDLE_V1, TypeBridgeRuntime,
    VerifiedSchemaBundle, build_verified_schema_bundle, decode_verified_schema_bundle,
    encode_verified_schema_bundle,
};
pub use lock::{
    MAX_WORKSPACE_LOCK_BYTES, TYPEBRIDGE_WORKSPACE_LOCK_V1, VerifiedWorkspaceLock, WorkspaceLock,
    WorkspaceLockError, WorkspaceLockErrorCode, generate_workspace_lock, verify_workspace_lock,
};
pub use migration::{MigrationDirectoryAuthority, MigrationPlanEntry};
pub use workspace::{TypeBridgeWorkspace, TypeBridgeWorkspaceError, TypeBridgeWorkspaceServices};
pub use workspace_yaml::{
    ConfigOrigin, LocatedConfigSpec, TYPEBRIDGE_WORKSPACE_V1_FORMAT, TypeBridgeConfigSpec,
};

/// The preferred server-semantic profile for newly authored V2 workspaces.
pub const TYPEBRIDGE_WORKSPACE_SEMANTIC_PROFILE_ID: &str = "typedb-3.12.1/v1";
/// Frozen server-semantic profiles accepted for workspace generation.
pub const TYPEBRIDGE_WORKSPACE_SEMANTIC_PROFILE_IDS: &[&str] =
    &["typedb-3.11.5/v1", TYPEBRIDGE_WORKSPACE_SEMANTIC_PROFILE_ID];

const MAX_SYMBOLIC_ID_BYTES: usize = 255;
const MAX_EXTENSION_VERSION_BYTES: usize = 64;
const C_SYMBOL_PREFIX_MAX_BYTES: usize = 63;
const C_SYMBOL_PREFIX_SHORT_MARKER: &str = "tb_";
const C_SYMBOL_PREFIX_DIGEST_MARKER: &str = "tbh_sha256_";
const C_SYMBOL_PREFIX_DIGEST_DOMAIN: &[u8] = b"typebridge.c-symbol-prefix/v1\0";
const BASE32_LOWER_ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";

/// Stable categories returned while validating programmatic workspace policy.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum WorkspaceConfigErrorCode {
    /// A workspace root was not absolute.
    WorkspaceRootNotAbsolute,
    /// A workspace root contained unresolved lexical components.
    WorkspaceRootNotCanonical,
    /// The injected source service could not canonicalize the root.
    WorkspaceRootCanonicalizationFailed,
    /// A path was not a portable, confined workspace-relative path.
    PathNotConfined,
    /// The schema-set path was not a lowercase YAML path.
    InvalidSchemaSetPath,
    /// The schema-authority output was not a lowercase JSON path.
    InvalidSchemaAuthorityOutputPath,
    /// The migration path did not identify a direct V2 history directory.
    InvalidMigrationV2Directory,
    /// A required builder field was absent.
    MissingRequiredField,
    /// A singleton builder field was assigned more than once.
    DuplicateRequiredField,
    /// The selected semantic profile is not the exact workspace profile.
    UnsupportedSemanticProfile,
    /// The exclusive managed-scope profile could not be bound.
    InvalidManagedScope,
    /// Two workspace-owned paths are equal or nested.
    OverlappingWorkspacePath,
    /// One binding output target appeared more than once.
    DuplicateOutputTarget,
    /// A binding target is newer than this workspace implementation.
    UnsupportedBindingTarget,
    /// A symbolic secret slot appeared more than once.
    DuplicateSecretSlot,
    /// One extension handler appeared more than once.
    DuplicateExtensionHandler,
    /// A symbolic identifier was malformed.
    InvalidSymbolicIdentifier,
    /// One environment's managed database aliases another environment's journal.
    EnvironmentDatabaseCollision,
    /// A config origin was absent, escaped its root, or was malformed.
    InvalidConfigOrigin,
    /// Config bytes were not valid UTF-8.
    InvalidWorkspaceEncoding,
    /// The shared lossless YAML parser rejected the document.
    InvalidWorkspaceYaml,
    /// The workspace format discriminator is unsupported.
    UnsupportedWorkspaceFormat,
    /// A closed workspace mapping contained an unknown key.
    UnknownWorkspaceKey,
    /// A required workspace wire field was absent.
    MissingWorkspaceField,
    /// A workspace wire value had the wrong shape or spelling.
    InvalidWorkspaceValue,
    /// A set-like capability requirement appeared more than once.
    DuplicateCapabilityRequirement,
    /// A secret input was a literal rather than a reference.
    SecretLiteralRejected,
    /// An environment secret reference was malformed.
    InvalidSecretReference,
    /// A local secret-reference validator rejected a reference.
    SecretReferenceRejected,
    /// A local extension registry rejected a requirement.
    ExtensionRequirementRejected,
    /// An environment TLS value was not the canonical Boolean spelling.
    InvalidTlsBoolean,
    /// A custom root CA was supplied without explicitly enabling TLS.
    TlsRootCaRequiresTls,
    /// A custom root CA contradicted an explicit disabled TLS policy.
    TlsRootCaWithDisabledTls,
    /// A custom root CA path was not a readable, non-empty confined file.
    InvalidTlsRootCa,
}

/// A structured programmatic workspace validation failure.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkspaceConfigError {
    code: WorkspaceConfigErrorCode,
    detail: Option<String>,
    message: &'static str,
    origin: Option<String>,
    source_span: Option<Box<SourceSpan>>,
}

impl WorkspaceConfigError {
    fn new(code: WorkspaceConfigErrorCode, message: &'static str) -> Self {
        Self {
            code,
            detail: None,
            message,
            origin: None,
            source_span: None,
        }
    }

    fn with_detail(mut self, detail: impl Into<String>) -> Self {
        self.detail = Some(detail.into());
        self
    }

    pub(crate) fn with_source(
        mut self,
        origin: impl Into<String>,
        source_span: SourceSpan,
    ) -> Self {
        self.origin = Some(origin.into());
        self.source_span = Some(Box::new(source_span));
        self
    }

    /// Return the stable error category.
    #[must_use]
    pub const fn code(&self) -> WorkspaceConfigErrorCode {
        self.code
    }

    /// Return optional deterministic error context.
    #[must_use]
    pub fn detail(&self) -> Option<&str> {
        self.detail.as_deref()
    }

    /// Return the immutable diagnostic origin captured during parsing.
    #[must_use]
    pub fn origin(&self) -> Option<&str> {
        self.origin.as_deref()
    }

    /// Return the exact source span for a parsed-config failure, if available.
    #[must_use]
    pub fn source_span(&self) -> Option<&SourceSpan> {
        self.source_span.as_deref()
    }
}

impl fmt::Display for WorkspaceConfigError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.message)?;
        if let Some(detail) = &self.detail {
            write!(formatter, ": {detail}")?;
        }
        Ok(())
    }
}

impl Error for WorkspaceConfigError {}

/// A stable failure reported by an injected, local-only config service.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WorkspaceServiceError {
    code: &'static str,
}

impl WorkspaceServiceError {
    /// Construct a service failure with a stable implementation-owned code.
    #[must_use]
    pub const fn new(code: &'static str) -> Self {
        Self { code }
    }

    /// Return the stable service-owned code.
    #[must_use]
    pub const fn code(self) -> &'static str {
        self.code
    }
}

impl fmt::Display for WorkspaceServiceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.code)
    }
}

impl Error for WorkspaceServiceError {}

/// A narrow local source service for root and custom-CA path validation.
///
/// Config validation never reads schema documents or expands source patterns.
/// When a custom root CA is configured, the service additionally proves its
/// canonical confinement and bounded readability. Full schema source services
/// automatically satisfy this boundary.
pub trait WorkspaceSourceService {
    /// Return the canonical spelling of the supplied workspace root.
    fn canonicalize_workspace_root(&self, root: &Path) -> Result<PathBuf, WorkspaceServiceError>;

    /// Return the canonical physical spelling of one workspace-owned path.
    ///
    /// Implementations that only support virtual programmatic configs may
    /// retain the default rejection. The method is required only when a
    /// custom root CA path is configured.
    fn canonicalize_workspace_path(&self, _path: &Path) -> Result<PathBuf, WorkspaceServiceError> {
        Err(WorkspaceServiceError::new(
            "workspace_path_canonicalization_unavailable",
        ))
    }

    /// Prove that one canonical path is a readable regular file and return
    /// its observed byte length.
    ///
    /// The default rejection keeps existing virtual services source
    /// compatible and is exercised only by custom-root configuration.
    fn readable_workspace_file_len(&self, _path: &Path) -> Result<u64, WorkspaceServiceError> {
        Err(WorkspaceServiceError::new(
            "workspace_file_observation_unavailable",
        ))
    }
}

impl<T> WorkspaceSourceService for T
where
    T: SchemaSourceService + ?Sized,
{
    fn canonicalize_workspace_root(&self, root: &Path) -> Result<PathBuf, WorkspaceServiceError> {
        self.canonicalize(root)
            .map_err(|_| WorkspaceServiceError::new("schema_source_canonicalize_failed"))
    }

    fn canonicalize_workspace_path(&self, path: &Path) -> Result<PathBuf, WorkspaceServiceError> {
        self.canonicalize(path)
            .map_err(|_| WorkspaceServiceError::new("workspace_path_canonicalize_failed"))
    }

    fn readable_workspace_file_len(&self, path: &Path) -> Result<u64, WorkspaceServiceError> {
        let observation = self
            .metadata(path)
            .map_err(|_| WorkspaceServiceError::new("workspace_file_metadata_failed"))?;
        if observation.kind() != SchemaSourceKind::File {
            return Err(WorkspaceServiceError::new("workspace_path_is_not_a_file"));
        }
        let capture = self
            .capture_file(path, 0)
            .map_err(|_| WorkspaceServiceError::new("workspace_file_read_failed"))?;
        if capture.before() != &observation || capture.after() != &observation {
            return Err(WorkspaceServiceError::new(
                "workspace_file_changed_during_validation",
            ));
        }
        Ok(observation.len())
    }
}

/// A validator for symbolic secret references.
///
/// This service intentionally has no method that can resolve or read a secret.
pub trait SecretReferenceService {
    /// Validate that a symbolic reference is accepted by local policy.
    fn validate_reference(&self, reference: &SecretReference) -> Result<(), WorkspaceServiceError>;
}

/// A local registry for projection-only extension requirements.
///
/// Implementations must validate against locally supplied registry state and
/// must not perform network discovery during config construction.
pub trait ExtensionRegistryService {
    /// Validate one exact extension handler/version requirement.
    fn validate_requirement(
        &self,
        requirement: &ExtensionRequirement,
    ) -> Result<(), WorkspaceServiceError>;
}

/// Explicit services used to validate a programmatic config hermetically.
pub struct TypeBridgeConfigServices<'a> {
    extensions: &'a dyn ExtensionRegistryService,
    secrets: &'a dyn SecretReferenceService,
    sources: &'a dyn WorkspaceSourceService,
}

impl<'a> TypeBridgeConfigServices<'a> {
    /// Construct a service set without ambient environment or network state.
    ///
    /// Filesystem access remains explicit through `sources` and is used only
    /// for canonical-root and optional custom-CA validation.
    #[must_use]
    pub const fn new(
        sources: &'a dyn WorkspaceSourceService,
        secrets: &'a dyn SecretReferenceService,
        extensions: &'a dyn ExtensionRegistryService,
    ) -> Self {
        Self {
            extensions,
            secrets,
            sources,
        }
    }
}

/// An explicit absolute workspace root whose canonical spelling is service-verified.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct WorkspaceRoot(PathBuf);

impl WorkspaceRoot {
    /// Validate the lexical portion of an explicit absolute workspace root.
    pub fn new(path: impl Into<PathBuf>) -> Result<Self, WorkspaceConfigError> {
        let path = path.into();
        if !path.is_absolute() {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::WorkspaceRootNotAbsolute,
                "workspace root must be explicit and absolute",
            ));
        }
        if path.to_str().is_none()
            || path
                .components()
                .any(|component| matches!(component, Component::CurDir | Component::ParentDir))
        {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::WorkspaceRootNotCanonical,
                "workspace root must have a portable canonical spelling",
            ));
        }
        Ok(Self(path))
    }

    /// Return the explicit root path.
    #[must_use]
    pub fn as_path(&self) -> &Path {
        &self.0
    }
}

pub(crate) fn confined_relative_path(
    path: impl Into<PathBuf>,
    subject: &'static str,
) -> Result<PathBuf, WorkspaceConfigError> {
    let path = path.into();
    let Some(portable) = path.to_str() else {
        return Err(WorkspaceConfigError::new(
            WorkspaceConfigErrorCode::PathNotConfined,
            "workspace-relative path must be valid UTF-8",
        )
        .with_detail(subject));
    };
    let invalid_spelling = portable.is_empty()
        || portable.contains(['\\', ':', '\0'])
        || portable.bytes().any(|byte| byte.is_ascii_control())
        || portable
            .split('/')
            .any(|segment| segment.is_empty() || matches!(segment, "." | ".."));
    let invalid_components = path.is_absolute()
        || path
            .components()
            .any(|component| !matches!(component, Component::Normal(_)));
    if invalid_spelling || invalid_components {
        return Err(WorkspaceConfigError::new(
            WorkspaceConfigErrorCode::PathNotConfined,
            "workspace-relative path escapes or is not portable",
        )
        .with_detail(subject));
    }
    Ok(path)
}

/// A canonical, workspace-confined custom root CA file.
///
/// Construction resolves a portable workspace-relative path against the
/// canonical workspace root, follows symbolic links, rejects escapes, and
/// proves that the target is a readable non-empty regular file. The lower
/// transport layer re-validates the PEM certificate contents immediately
/// before any network I/O.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkspaceRootCa(PathBuf);

impl WorkspaceRootCa {
    /// Resolve and validate a workspace-relative custom root CA path.
    pub fn new(
        workspace_root: &WorkspaceRoot,
        relative_path: impl Into<PathBuf>,
        sources: &dyn WorkspaceSourceService,
    ) -> Result<Self, WorkspaceConfigError> {
        let relative_path = confined_relative_path(relative_path, "environment.tls-root-ca")?;
        let canonical_root = sources
            .canonicalize_workspace_root(workspace_root.as_path())
            .map_err(|error| {
                WorkspaceConfigError::new(
                    WorkspaceConfigErrorCode::WorkspaceRootCanonicalizationFailed,
                    "custom root CA validation could not canonicalize the workspace root",
                )
                .with_detail(error.code())
            })?;
        if canonical_root != workspace_root.as_path() {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::WorkspaceRootNotCanonical,
                "custom root CA validation requires a canonical workspace root",
            ));
        }

        // Extend component-wise: joining the whole portable relative path
        // onto a Windows verbatim (`\\?\`) root would keep its forward
        // slashes, which verbatim paths exempt from separator normalization.
        let mut candidate = canonical_root.clone();
        candidate.extend(relative_path.components());
        let canonical_path = sources
            .canonicalize_workspace_path(&candidate)
            .map_err(|error| {
                WorkspaceConfigError::new(
                    WorkspaceConfigErrorCode::InvalidTlsRootCa,
                    "custom root CA path cannot be canonicalized",
                )
                .with_detail(error.code())
            })?;
        if canonical_path == canonical_root
            || !canonical_path.starts_with(&canonical_root)
            || canonical_path.to_str().is_none()
        {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::InvalidTlsRootCa,
                "custom root CA path escapes the canonical workspace root",
            ));
        }

        let length = sources
            .readable_workspace_file_len(&canonical_path)
            .map_err(|error| {
                WorkspaceConfigError::new(
                    WorkspaceConfigErrorCode::InvalidTlsRootCa,
                    "custom root CA path must be a readable regular file",
                )
                .with_detail(error.code())
            })?;
        if length == 0 {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::InvalidTlsRootCa,
                "custom root CA file must not be empty",
            ));
        }
        Ok(Self(canonical_path))
    }

    /// Return the canonical absolute root CA path.
    #[must_use]
    pub fn as_path(&self) -> &Path {
        &self.0
    }
}

/// Validated transport policy for one workspace environment.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum WorkspaceTransportPolicy {
    /// Plaintext HTTP and gRPC.
    #[default]
    Disabled,
    /// TLS using operating-system native trust roots.
    NativeRoots,
    /// TLS using one canonical workspace-confined custom root CA file.
    CustomRootCa(WorkspaceRootCa),
}

/// A confined path to one portable schema-set manifest.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct SchemaSetPath(PathBuf);

impl SchemaSetPath {
    /// Validate a confined lowercase `.yaml` schema-set path.
    pub fn new(path: impl Into<PathBuf>) -> Result<Self, WorkspaceConfigError> {
        let path = confined_relative_path(path, "schema_set")?;
        if path.extension().and_then(|extension| extension.to_str()) != Some("yaml") {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::InvalidSchemaSetPath,
                "schema-set path must end in lowercase .yaml",
            ));
        }
        Ok(Self(path))
    }

    /// Return the canonical workspace-relative path.
    #[must_use]
    pub fn as_path(&self) -> &Path {
        &self.0
    }
}

/// A confined direct V2 migration-history directory.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct MigrationV2Directory(PathBuf);

impl MigrationV2Directory {
    /// Validate a confined directory whose final component is exactly `v2`.
    pub fn new(path: impl Into<PathBuf>) -> Result<Self, WorkspaceConfigError> {
        let path = confined_relative_path(path, "migration_v2_directory")?;
        if path.file_name().and_then(|name| name.to_str()) != Some("v2") {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::InvalidMigrationV2Directory,
                "canonical migration directory must identify the V2 history directly",
            ));
        }
        Ok(Self(path))
    }

    /// Return the canonical workspace-relative directory.
    #[must_use]
    pub fn as_path(&self) -> &Path {
        &self.0
    }
}

/// A confined output directory for one shipped binding target.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct OutputDirectory(PathBuf);

impl OutputDirectory {
    /// Validate a confined output directory.
    pub fn new(path: impl Into<PathBuf>) -> Result<Self, WorkspaceConfigError> {
        Ok(Self(confined_relative_path(path, "binding_output")?))
    }

    /// Return the canonical workspace-relative directory.
    #[must_use]
    pub fn as_path(&self) -> &Path {
        &self.0
    }
}

/// A confined portable file path for the generated server schema authority.
///
/// The path remains relative to the workspace root. Generation must resolve
/// its parent through [`WorkspaceOutputDirectory::open_beneath`] and publish
/// its final component through [`WorkspaceOutputDirectory::write_atomic`] so
/// no symbolic-link component can redirect the artifact.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct SchemaAuthorityOutputPath(PathBuf);

impl SchemaAuthorityOutputPath {
    /// Validate a portable workspace-relative lowercase `.json` artifact path.
    pub fn new(path: impl Into<PathBuf>) -> Result<Self, WorkspaceConfigError> {
        let path = confined_relative_path(path, "schema_authority_output")?;
        if path.components().any(|component| {
            let Component::Normal(name) = component else {
                return true;
            };
            validate_portable_direct_child(name).is_err()
        }) {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::PathNotConfined,
                "schema-authority output path is not portable",
            )
            .with_detail("schema_authority_output"));
        }
        if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::InvalidSchemaAuthorityOutputPath,
                "schema-authority output path must end in lowercase .json",
            )
            .with_detail("schema_authority_output"));
        }
        Ok(Self(path))
    }

    /// Return the canonical workspace-relative output path.
    #[must_use]
    pub fn as_path(&self) -> &Path {
        &self.0
    }
}

fn output_field_name(target: BindingTarget) -> Result<&'static str, WorkspaceConfigError> {
    match target {
        BindingTarget::Python => Ok("output.python"),
        BindingTarget::TypeScript => Ok("output.typescript"),
        BindingTarget::Rust => Ok("output.rust"),
        BindingTarget::C => Ok("output.c"),
        _ => Err(unsupported_binding_target(target)),
    }
}

fn unsupported_binding_target(target: BindingTarget) -> WorkspaceConfigError {
    WorkspaceConfigError::new(
        WorkspaceConfigErrorCode::UnsupportedBindingTarget,
        "workspace implementation does not support this binding target",
    )
    .with_detail(target.as_str())
}

/// Derive the stable C global-symbol prefix owned by a migration application.
///
/// Labels whose reversible `tb_` spelling fits in 63 bytes escape `_` as
/// `_u` and `-` as `_h`. Longer spellings use the disjoint
/// `tbh_sha256_` namespace followed by the complete lowercase unpadded RFC
/// 4648 base32 encoding of SHA-256 over
/// `typebridge.c-symbol-prefix/v1\0 || label_length_u64_be || label_bytes`.
/// The digest lane is collision-resistant rather than mathematically
/// injective. The app label is already portable lowercase ASCII, so this
/// transformation is infallible.
#[must_use]
pub fn c_symbol_prefix_for_app_label(app_label: &MigrationAppLabel) -> CSymbolPrefix {
    let mut short =
        String::with_capacity(C_SYMBOL_PREFIX_SHORT_MARKER.len() + app_label.as_str().len());
    short.push_str(C_SYMBOL_PREFIX_SHORT_MARKER);
    for byte in app_label.as_str().bytes() {
        match byte {
            b'_' => short.push_str("_u"),
            b'-' => short.push_str("_h"),
            _ => short.push(char::from(byte)),
        }
    }
    if short.len() <= C_SYMBOL_PREFIX_MAX_BYTES {
        return CSymbolPrefix::new(short)
            .expect("a validated migration app label always yields a valid short C prefix");
    }

    let mut hasher = Sha256::new();
    hasher.update(C_SYMBOL_PREFIX_DIGEST_DOMAIN);
    hasher.update(
        u64::try_from(app_label.as_str().len())
            .expect("migration app-label length fits u64")
            .to_be_bytes(),
    );
    hasher.update(app_label.as_str().as_bytes());
    let digest = hasher.finalize();
    let prefix = format!(
        "{C_SYMBOL_PREFIX_DIGEST_MARKER}{}",
        encode_base32_lower(&digest)
    );
    debug_assert_eq!(prefix.len(), C_SYMBOL_PREFIX_MAX_BYTES);
    CSymbolPrefix::new(prefix)
        .expect("the frozen digest spelling always yields a valid bounded C prefix")
}

fn encode_base32_lower(bytes: &[u8]) -> String {
    let mut encoded = String::with_capacity((bytes.len() * 8).div_ceil(5));
    let mut accumulator = 0_u16;
    let mut retained_bits = 0_u8;
    for &byte in bytes {
        accumulator = (accumulator << 8) | u16::from(byte);
        retained_bits += 8;
        while retained_bits >= 5 {
            retained_bits -= 5;
            let index = usize::from((accumulator >> retained_bits) & 0x1f);
            encoded.push(char::from(BASE32_LOWER_ALPHABET[index]));
            accumulator &= (1_u16 << retained_bits) - 1;
        }
    }
    if retained_bits != 0 {
        let index = usize::from((accumulator << (5 - retained_bits)) & 0x1f);
        encoded.push(char::from(BASE32_LOWER_ALPHABET[index]));
    }
    encoded
}

pub(crate) fn portable_path_collision_key(path: &Path) -> Option<Vec<String>> {
    path.components()
        .map(|component| match component {
            Component::Prefix(prefix) => prefix
                .as_os_str()
                .to_str()
                .map(|value| format!("prefix:{}", value.case_fold().nfc().collect::<String>())),
            Component::RootDir => Some("root:".to_owned()),
            Component::CurDir => Some("cur:".to_owned()),
            Component::ParentDir => Some("parent:".to_owned()),
            Component::Normal(value) => value
                .to_str()
                .map(|value| value.case_fold().nfc().collect::<String>()),
        })
        .collect()
}

pub(crate) fn workspace_paths_overlap(left: &Path, right: &Path) -> bool {
    let (Some(left_key), Some(right_key)) = (
        portable_path_collision_key(left),
        portable_path_collision_key(right),
    ) else {
        return left == right || left.starts_with(right) || right.starts_with(left);
    };
    left_key.starts_with(&right_key) || right_key.starts_with(&left_key)
}

fn valid_namespaced_id(value: &str) -> bool {
    let mut count = 0_usize;
    let valid = value.split('.').all(|segment| {
        count += 1;
        let mut bytes = segment.bytes();
        bytes.next().is_some_and(|byte| byte.is_ascii_lowercase())
            && bytes.all(|byte| {
                byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_')
            })
    });
    valid && count >= 2 && value.len() <= MAX_SYMBOLIC_ID_BYTES
}

/// A deterministic logical slot containing one symbolic secret reference.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct SecretSlot(String);

impl SecretSlot {
    /// Validate a lowercase namespaced secret slot such as `typedb.credential`.
    pub fn new(value: impl Into<String>) -> Result<Self, WorkspaceConfigError> {
        let value = value.into();
        if !valid_namespaced_id(&value) {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::InvalidSymbolicIdentifier,
                "secret slot must be a bounded lowercase namespaced identifier",
            ));
        }
        Ok(Self(value))
    }

    /// Return the canonical slot spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// A retained environment-variable reference, never a resolved secret value.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct SecretReference {
    environment_variable: String,
}

impl SecretReference {
    /// Construct an environment reference without reading the environment.
    pub fn environment(variable: impl Into<String>) -> Result<Self, WorkspaceConfigError> {
        let variable = variable.into();
        let mut bytes = variable.bytes();
        let valid = variable.len() <= MAX_SYMBOLIC_ID_BYTES
            && bytes
                .next()
                .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
            && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_');
        if !valid {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::InvalidSecretReference,
                "environment reference contains an invalid variable name",
            ));
        }
        Ok(Self {
            environment_variable: variable,
        })
    }

    /// Parse the sole shipped symbolic spelling, `env:VARIABLE`.
    ///
    /// Inputs without a symbolic scheme are rejected as literals.
    pub fn parse_symbolic(value: impl AsRef<str>) -> Result<Self, WorkspaceConfigError> {
        let value = value.as_ref();
        let Some(variable) = value.strip_prefix("env:") else {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::SecretLiteralRejected,
                "secret literals are forbidden; use a symbolic reference",
            ));
        };
        Self::environment(variable)
    }

    /// Return the retained environment variable name without resolving it.
    #[must_use]
    pub fn environment_variable(&self) -> &str {
        &self.environment_variable
    }
}

/// One exact local extension handler/version requirement.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ExtensionRequirement {
    handler_id: String,
    version: String,
}

impl ExtensionRequirement {
    /// Validate one namespaced handler ID and bounded version spelling.
    pub fn new(
        handler_id: impl Into<String>,
        version: impl Into<String>,
    ) -> Result<Self, WorkspaceConfigError> {
        let handler_id = handler_id.into();
        let version = version.into();
        let valid_version = !version.is_empty()
            && version.len() <= MAX_EXTENSION_VERSION_BYTES
            && version.bytes().all(|byte| {
                byte.is_ascii_lowercase()
                    || byte.is_ascii_digit()
                    || matches!(byte, b'.' | b'-' | b'_')
            });
        if !valid_namespaced_id(&handler_id) || !valid_version {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::InvalidSymbolicIdentifier,
                "extension requirement has an invalid handler ID or version",
            ));
        }
        Ok(Self {
            handler_id,
            version,
        })
    }

    /// Return the stable extension handler ID.
    #[must_use]
    pub fn handler_id(&self) -> &str {
        &self.handler_id
    }

    /// Return the exact required handler version.
    #[must_use]
    pub fn version(&self) -> &str {
        &self.version
    }
}

/// One named, inert deployment environment.
///
/// Environments carry connection identity and policy only: credentials are
/// symbolic environment references, never committed values, and production
/// application stays opt-in through the explicit `migrate` flag.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkspaceEnvironment {
    database: String,
    http_port: Option<u16>,
    migrate: bool,
    password: SecretReference,
    requirements: CapabilitySet,
    transport_policy: WorkspaceTransportPolicy,
    uri: String,
    username: SecretReference,
}

fn invalid_environment_uri() -> WorkspaceConfigError {
    WorkspaceConfigError::new(
        WorkspaceConfigErrorCode::InvalidWorkspaceValue,
        "environment uri must be a comma-separated list of host:port or [IPv6]:port endpoints without credentials, schemes, or control characters",
    )
}

fn valid_endpoint_port(port: &str) -> bool {
    !port.is_empty()
        && port.bytes().all(|byte| byte.is_ascii_digit())
        && port.parse::<u16>().is_ok_and(|port| port != 0)
}

fn valid_endpoint_host(host: &str) -> bool {
    let host = host.strip_suffix('.').unwrap_or(host);
    !host.is_empty()
        && host.len() <= 253
        && host.split('.').all(|label| {
            !label.is_empty()
                && label.len() <= 63
                && label
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
                && label
                    .as_bytes()
                    .first()
                    .is_some_and(u8::is_ascii_alphanumeric)
                && label
                    .as_bytes()
                    .last()
                    .is_some_and(u8::is_ascii_alphanumeric)
        })
}

fn valid_environment_endpoint(endpoint: &str) -> bool {
    if let Some(bracketed) = endpoint.strip_prefix('[') {
        let Some((address, port)) = bracketed.split_once("]:") else {
            return false;
        };
        !address.is_empty()
            && !port.contains(['[', ']', ':'])
            && address.parse::<Ipv6Addr>().is_ok()
            && valid_endpoint_port(port)
    } else {
        let Some((host, port)) = endpoint.rsplit_once(':') else {
            return false;
        };
        !host.contains(['[', ']', ':']) && valid_endpoint_host(host) && valid_endpoint_port(port)
    }
}

pub(crate) fn validate_environment_uri(uri: &str) -> Result<(), WorkspaceConfigError> {
    if uri.is_empty() || !uri.split(',').all(valid_environment_endpoint) {
        return Err(invalid_environment_uri());
    }
    Ok(())
}

fn normalized_environment_endpoints(uri: &str) -> Result<BTreeSet<String>, WorkspaceConfigError> {
    uri.split(',')
        .map(|endpoint| {
            if let Some(bracketed) = endpoint.strip_prefix('[') {
                let (address, port) = bracketed.split_once("]:")?;
                let address = address.parse::<Ipv6Addr>().ok()?;
                let port = port.parse::<u16>().ok()?;
                Some(format!("[{address}]:{port}"))
            } else {
                let (host, port) = endpoint.rsplit_once(':')?;
                let host = host.strip_suffix('.').unwrap_or(host);
                let host = host
                    .parse::<Ipv4Addr>()
                    .map_or_else(|_| host.to_ascii_lowercase(), |address| address.to_string());
                let port = port.parse::<u16>().ok()?;
                Some(format!("{host}:{port}"))
            }
        })
        .collect::<Option<BTreeSet<_>>>()
        .ok_or_else(invalid_environment_uri)
}

pub(crate) fn validate_environment_database(database: &str) -> Result<(), WorkspaceConfigError> {
    if database.is_empty() {
        return Err(WorkspaceConfigError::new(
            WorkspaceConfigErrorCode::InvalidWorkspaceValue,
            "environment database must be non-empty",
        ));
    }
    Ok(())
}

impl WorkspaceEnvironment {
    fn from_validated(
        uri: String,
        database: String,
        username: SecretReference,
        password: SecretReference,
    ) -> Self {
        Self {
            database,
            http_port: None,
            migrate: false,
            password,
            requirements: CapabilitySet::new(),
            transport_policy: WorkspaceTransportPolicy::Disabled,
            uri,
            username,
        }
    }

    /// Construct one environment with mandatory connection identity.
    ///
    /// The uri is one or more comma-separated TypeDB endpoints: `host:port`
    /// or bracketed `[IPv6]:port`, with every port in `1..=65535`. Userinfo,
    /// schemes, paths, query strings, whitespace, and control characters are
    /// rejected: credentials stay symbolic by construction, so an address
    /// echoed by driver errors or tracing can never leak them.
    pub fn new(
        uri: impl Into<String>,
        database: impl Into<String>,
        username: SecretReference,
        password: SecretReference,
    ) -> Result<Self, WorkspaceConfigError> {
        let uri = uri.into();
        let database = database.into();
        validate_environment_uri(&uri)?;
        validate_environment_database(&database)?;
        Ok(Self::from_validated(uri, database, username, password))
    }

    /// Select an explicit provider HTTP port.
    #[must_use]
    pub fn with_http_port(mut self, port: u16) -> Self {
        self.http_port = Some(port);
        self
    }

    /// Opt this environment into migration application.
    #[must_use]
    pub const fn with_migrate(mut self, migrate: bool) -> Self {
        self.migrate = migrate;
        self
    }

    /// Select the validated transport policy for this environment.
    #[must_use]
    pub fn with_transport_policy(mut self, policy: WorkspaceTransportPolicy) -> Self {
        self.transport_policy = policy;
        self
    }

    /// Add environment-specific capability requirements.
    #[must_use]
    pub fn require_capabilities(
        mut self,
        capabilities: impl IntoIterator<Item = CapabilityId>,
    ) -> Self {
        for capability in capabilities {
            self.requirements.insert(capability);
        }
        self
    }

    /// Return the provider address.
    #[must_use]
    pub fn uri(&self) -> &str {
        &self.uri
    }

    /// Return the managed database name.
    #[must_use]
    pub fn database(&self) -> &str {
        &self.database
    }

    /// Return the explicit provider HTTP port, when configured.
    #[must_use]
    pub const fn http_port(&self) -> Option<u16> {
        self.http_port
    }

    /// Return the symbolic username reference.
    #[must_use]
    pub const fn username(&self) -> &SecretReference {
        &self.username
    }

    /// Return the symbolic password reference.
    #[must_use]
    pub const fn password(&self) -> &SecretReference {
        &self.password
    }

    /// Return whether migration application is opted in.
    #[must_use]
    pub const fn migrate(&self) -> bool {
        self.migrate
    }

    /// Return the validated transport policy.
    #[must_use]
    pub const fn transport_policy(&self) -> &WorkspaceTransportPolicy {
        &self.transport_policy
    }

    /// Return environment-specific capability requirements.
    #[must_use]
    pub const fn requirements(&self) -> &CapabilitySet {
        &self.requirements
    }
}

/// An inert validated workspace policy produced only by its builder.
///
/// This trusted type intentionally implements no deserialization contract.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TypeBridgeConfig {
    app_label: MigrationAppLabel,
    environments: BTreeMap<String, WorkspaceEnvironment>,
    extensions: BTreeSet<ExtensionRequirement>,
    managed_scope: ManagedScopeBinding,
    migration_policy: MigrationSafetyPolicy,
    migration_v2_directory: MigrationV2Directory,
    outputs: BTreeMap<BindingTarget, OutputDirectory>,
    type_names: BTreeMap<BindingTarget, Vec<type_bridge_contract::projection::TypeNameOverride>>,
    required_capabilities: CapabilitySet,
    schema_authority_output: Option<SchemaAuthorityOutputPath>,
    schema_set: SchemaSetPath,
    secret_references: BTreeMap<SecretSlot, SecretReference>,
    semantic_profile: SemanticProfileId,
    workspace_root: WorkspaceRoot,
}

impl TypeBridgeConfig {
    /// Begin typed programmatic construction at one explicit workspace root.
    #[must_use]
    pub fn builder(workspace_root: WorkspaceRoot) -> TypeBridgeConfigBuilder {
        TypeBridgeConfigBuilder::new(workspace_root)
    }

    /// Return the service-verified canonical workspace root.
    #[must_use]
    pub const fn workspace_root(&self) -> &WorkspaceRoot {
        &self.workspace_root
    }

    /// Return the confined schema-set manifest path.
    #[must_use]
    pub const fn schema_set(&self) -> &SchemaSetPath {
        &self.schema_set
    }

    /// Return the schema-set manifest path resolved under the root.
    #[must_use]
    pub fn schema_set_absolute_path(&self) -> PathBuf {
        // Extend component-wise: joining the whole portable relative path
        // onto a Windows verbatim (`\\?\`) root would keep its forward
        // slashes, which verbatim paths exempt from separator normalization.
        let mut path = self.workspace_root.as_path().to_path_buf();
        path.extend(self.schema_set.as_path().components());
        path
    }

    /// Return the validated migration application label.
    #[must_use]
    pub const fn app_label(&self) -> &MigrationAppLabel {
        &self.app_label
    }

    /// Return the durable scope bound to the frozen exclusive profile.
    #[must_use]
    pub const fn managed_scope(&self) -> &ManagedScopeBinding {
        &self.managed_scope
    }

    /// Return the exact server-semantic profile.
    #[must_use]
    pub const fn semantic_profile(&self) -> &SemanticProfileId {
        &self.semantic_profile
    }

    /// Return the confined canonical V2 migration directory.
    #[must_use]
    pub const fn migration_v2_directory(&self) -> &MigrationV2Directory {
        &self.migration_v2_directory
    }

    /// Return every named deployment environment.
    #[must_use]
    pub const fn environments(&self) -> &BTreeMap<String, WorkspaceEnvironment> {
        &self.environments
    }

    /// Return one named deployment environment.
    #[must_use]
    pub fn environment(&self, name: &str) -> Option<&WorkspaceEnvironment> {
        self.environments.get(name)
    }

    /// Return the explicit apply-side migration safety policy.
    ///
    /// The policy can tighten the verifier's classification but never loosen
    /// it: a standing allowance for destructive or opaque work is rejected by
    /// construction, so no configuration spells a permanent `force = true`.
    #[must_use]
    pub const fn migration_policy(&self) -> &MigrationSafetyPolicy {
        &self.migration_policy
    }

    /// Return the V2 migration directory resolved under the root.
    #[must_use]
    pub fn migration_v2_absolute_path(&self) -> PathBuf {
        self.workspace_root
            .as_path()
            .join(self.migration_v2_directory.as_path())
    }

    /// Return additive workspace capability requirements.
    #[must_use]
    pub const fn required_capabilities(&self) -> &CapabilitySet {
        &self.required_capabilities
    }

    /// Return independently configured shipped output targets.
    #[must_use]
    pub const fn outputs(&self) -> &BTreeMap<BindingTarget, OutputDirectory> {
        &self.outputs
    }

    /// Return validated model-name overrides for one binding output.
    #[must_use]
    pub fn type_name_overrides(
        &self,
        target: BindingTarget,
    ) -> &[type_bridge_contract::projection::TypeNameOverride] {
        self.type_names.get(&target).map_or(&[], Vec::as_slice)
    }

    /// Return the configured generated server-authority artifact path.
    #[must_use]
    pub const fn schema_authority_output(&self) -> Option<&SchemaAuthorityOutputPath> {
        self.schema_authority_output.as_ref()
    }

    /// Return retained symbolic references without resolving secret values.
    #[must_use]
    pub const fn secret_references(&self) -> &BTreeMap<SecretSlot, SecretReference> {
        &self.secret_references
    }

    /// Return exact locally validated extension requirements.
    #[must_use]
    pub const fn extensions(&self) -> &BTreeSet<ExtensionRequirement> {
        &self.extensions
    }
}

/// A consuming typed builder for [`TypeBridgeConfig`].
///
/// The builder accepts only validated nested values. `build` performs the
/// remaining cross-field and injected-service checks without loading schema or
/// consulting any provider.
pub struct TypeBridgeConfigBuilder {
    app_label: Option<MigrationAppLabel>,
    environments: Vec<(String, WorkspaceEnvironment)>,
    duplicate_required_fields: BTreeSet<&'static str>,
    extensions: Vec<ExtensionRequirement>,
    managed_scope_id: Option<ManagedScopeId>,
    migration_policy: Option<MigrationSafetyPolicy>,
    migration_v2_directory: Option<MigrationV2Directory>,
    outputs: Vec<(BindingTarget, OutputDirectory)>,
    type_names: Vec<(BindingTarget, type_bridge_contract::id::TypeId, String)>,
    required_capabilities: CapabilitySet,
    schema_authority_output: Option<SchemaAuthorityOutputPath>,
    schema_set: Option<SchemaSetPath>,
    secrets: Vec<(SecretSlot, SecretReference)>,
    semantic_profile: Option<SemanticProfileId>,
    workspace_root: WorkspaceRoot,
}

impl TypeBridgeConfigBuilder {
    fn new(workspace_root: WorkspaceRoot) -> Self {
        Self {
            app_label: None,
            environments: Vec::new(),
            duplicate_required_fields: BTreeSet::new(),
            extensions: Vec::new(),
            managed_scope_id: None,
            migration_policy: None,
            migration_v2_directory: None,
            outputs: Vec::new(),
            type_names: Vec::new(),
            required_capabilities: CapabilitySet::new(),
            schema_authority_output: None,
            schema_set: None,
            secrets: Vec::new(),
            semantic_profile: None,
            workspace_root,
        }
    }

    fn mark_duplicate<T>(
        slot: &mut Option<T>,
        value: T,
        field: &'static str,
        duplicates: &mut BTreeSet<&'static str>,
    ) {
        if slot.replace(value).is_some() {
            duplicates.insert(field);
        }
    }

    /// Select the portable schema-set manifest.
    #[must_use]
    pub fn schema_set(mut self, path: SchemaSetPath) -> Self {
        Self::mark_duplicate(
            &mut self.schema_set,
            path,
            "schema_set",
            &mut self.duplicate_required_fields,
        );
        self
    }

    /// Select the validated migration application label.
    #[must_use]
    pub fn app_label(mut self, app_label: MigrationAppLabel) -> Self {
        Self::mark_duplicate(
            &mut self.app_label,
            app_label,
            "app_label",
            &mut self.duplicate_required_fields,
        );
        self
    }

    /// Bind the durable managed-scope identity to the sole exclusive profile.
    #[must_use]
    pub fn exclusive_managed_scope(mut self, scope_id: ManagedScopeId) -> Self {
        Self::mark_duplicate(
            &mut self.managed_scope_id,
            scope_id,
            "managed_scope",
            &mut self.duplicate_required_fields,
        );
        self
    }

    /// Select the exact server-semantic profile.
    #[must_use]
    pub fn semantic_profile(mut self, profile: SemanticProfileId) -> Self {
        Self::mark_duplicate(
            &mut self.semantic_profile,
            profile,
            "semantic_profile",
            &mut self.duplicate_required_fields,
        );
        self
    }

    /// Select the confined direct V2 migration directory.
    #[must_use]
    pub fn migration_v2_directory(mut self, directory: MigrationV2Directory) -> Self {
        Self::mark_duplicate(
            &mut self.migration_v2_directory,
            directory,
            "migration_v2_directory",
            &mut self.duplicate_required_fields,
        );
        self
    }

    /// Replace the default apply-side migration safety policy.
    ///
    /// [`MigrationSafetyPolicy`] construction already rejects every standing
    /// allowance for destructive or opaque work, so no builder input spells a
    /// permanent `force = true`.
    #[must_use]
    pub fn migration_policy(mut self, policy: MigrationSafetyPolicy) -> Self {
        Self::mark_duplicate(
            &mut self.migration_policy,
            policy,
            "migration_policy",
            &mut self.duplicate_required_fields,
        );
        self
    }

    /// Add one open capability requirement without replacing prior requirements.
    #[must_use]
    pub fn require_capability(mut self, capability: CapabilityId) -> Self {
        self.required_capabilities.insert(capability);
        self
    }

    /// Add capability requirements without replacing prior requirements.
    #[must_use]
    pub fn require_capabilities(
        mut self,
        capabilities: impl IntoIterator<Item = CapabilityId>,
    ) -> Self {
        for capability in capabilities {
            self.required_capabilities.insert(capability);
        }
        self
    }

    /// Add one independently regenerated shipped binding target.
    #[must_use]
    pub fn output(mut self, target: BindingTarget, directory: OutputDirectory) -> Self {
        self.outputs.push((target, directory));
        self
    }

    /// Override a generated model name while retaining its canonical database identity.
    #[must_use]
    pub fn type_name_override(
        mut self,
        target: BindingTarget,
        type_id: type_bridge_contract::id::TypeId,
        name: impl Into<String>,
    ) -> Self {
        self.type_names.push((target, type_id, name.into()));
        self
    }

    /// Select the generated server schema-authority artifact path.
    #[must_use]
    pub fn schema_authority_output(mut self, output: SchemaAuthorityOutputPath) -> Self {
        Self::mark_duplicate(
            &mut self.schema_authority_output,
            output,
            "schema_authority_output",
            &mut self.duplicate_required_fields,
        );
        self
    }

    /// Add one named deployment environment.
    #[must_use]
    pub fn environment(
        mut self,
        name: impl Into<String>,
        environment: WorkspaceEnvironment,
    ) -> Self {
        self.environments.push((name.into(), environment));
        self
    }

    /// Add one retained symbolic secret reference.
    #[must_use]
    pub fn secret(mut self, slot: SecretSlot, reference: SecretReference) -> Self {
        self.secrets.push((slot, reference));
        self
    }

    /// Add one exact local extension requirement.
    #[must_use]
    pub fn require_extension(mut self, requirement: ExtensionRequirement) -> Self {
        self.extensions.push(requirement);
        self
    }

    /// Validate the complete config using only the explicitly injected services.
    pub fn build(
        self,
        services: &TypeBridgeConfigServices<'_>,
    ) -> Result<TypeBridgeConfig, WorkspaceConfigError> {
        if let Some(field) = self.duplicate_required_fields.iter().next() {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::DuplicateRequiredField,
                "a singleton workspace field was assigned more than once",
            )
            .with_detail(*field));
        }

        fn required<T>(value: Option<T>, field: &'static str) -> Result<T, WorkspaceConfigError> {
            value.ok_or_else(|| {
                WorkspaceConfigError::new(
                    WorkspaceConfigErrorCode::MissingRequiredField,
                    "required workspace field is missing",
                )
                .with_detail(field)
            })
        }
        let schema_set = required(self.schema_set, "schema_set")?;
        let app_label = required(self.app_label, "app_label")?;
        let managed_scope_id = required(self.managed_scope_id, "managed_scope")?;
        let semantic_profile = required(self.semantic_profile, "semantic_profile")?;
        let migration_v2_directory =
            required(self.migration_v2_directory, "migration_v2_directory")?;
        let schema_authority_output = self.schema_authority_output;

        if !TYPEBRIDGE_WORKSPACE_SEMANTIC_PROFILE_IDS.contains(&semantic_profile.as_str())
            || SemanticProfile::resolve(&semantic_profile).is_err()
        {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::UnsupportedSemanticProfile,
                "workspace requires a frozen TypeDB 3.11.5 or 3.12.1 semantic profile",
            )
            .with_detail(semantic_profile.as_str()));
        }

        let canonical_root = services
            .sources
            .canonicalize_workspace_root(self.workspace_root.as_path())
            .map_err(|error| {
                WorkspaceConfigError::new(
                    WorkspaceConfigErrorCode::WorkspaceRootCanonicalizationFailed,
                    "injected source service could not canonicalize workspace root",
                )
                .with_detail(error.code())
            })?;
        if canonical_root != self.workspace_root.as_path() {
            return Err(WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::WorkspaceRootNotCanonical,
                "explicit workspace root differs from its canonical spelling",
            ));
        }

        let managed_scope = ManagedScopeBinding::exclusive(managed_scope_id).map_err(|_| {
            WorkspaceConfigError::new(
                WorkspaceConfigErrorCode::InvalidManagedScope,
                "managed scope could not bind to the exclusive profile",
            )
        })?;
        debug_assert_eq!(
            managed_scope.profile().id(),
            &ManagedScopeProfileId::exclusive()
        );

        let mut outputs = BTreeMap::new();
        for (target, directory) in self.outputs {
            output_field_name(target)?;
            if outputs.insert(target, directory).is_some() {
                return Err(WorkspaceConfigError::new(
                    WorkspaceConfigErrorCode::DuplicateOutputTarget,
                    "binding output target is configured more than once",
                ));
            }
        }

        let mut name_configs = BTreeMap::new();
        for (target, type_id, name) in self.type_names {
            use type_bridge_contract::projection::{CSymbolPrefix, ProjectionConfig};
            if !outputs.contains_key(&target) {
                return Err(WorkspaceConfigError::new(
                    WorkspaceConfigErrorCode::InvalidWorkspaceValue,
                    "type-name overrides require a configured binding output",
                ));
            }
            let config = name_configs
                .remove(&target)
                .unwrap_or_else(|| match target {
                    BindingTarget::Python => ProjectionConfig::python(),
                    BindingTarget::TypeScript => ProjectionConfig::typescript(),
                    BindingTarget::Rust => ProjectionConfig::rust(),
                    // Only names are retained; CLI generation owns the actual C prefix.
                    _ => ProjectionConfig::c(CSymbolPrefix::new("tb").expect("static C prefix")),
                });
            let config = config
                .with_type_name_override(type_id, name)
                .map_err(|error| {
                    WorkspaceConfigError::new(
                        WorkspaceConfigErrorCode::InvalidWorkspaceValue,
                        "invalid binding type-name override",
                    )
                    .with_detail(error.to_string())
                })?;
            name_configs.insert(target, config);
        }
        let type_names = name_configs
            .into_iter()
            .map(|(target, config)| (target, config.type_name_overrides().to_vec()))
            .collect();

        let mut workspace_paths: Vec<(&'static str, &Path)> = vec![
            ("schema_set", schema_set.as_path()),
            ("migration_v2_directory", migration_v2_directory.as_path()),
        ];
        for (target, directory) in &outputs {
            workspace_paths.push((output_field_name(*target)?, directory.as_path()));
        }
        if let Some(output) = &schema_authority_output {
            workspace_paths.push(("artifact.schema_authority", output.as_path()));
        }
        for left_index in 0..workspace_paths.len() {
            for right_index in (left_index + 1)..workspace_paths.len() {
                let (left_name, left_path) = workspace_paths[left_index];
                let (right_name, right_path) = workspace_paths[right_index];
                if workspace_paths_overlap(left_path, right_path) {
                    return Err(WorkspaceConfigError::new(
                        WorkspaceConfigErrorCode::OverlappingWorkspacePath,
                        "workspace-owned paths must be pairwise disjoint",
                    )
                    .with_detail(format!("{left_name},{right_name}")));
                }
            }
        }

        let mut environments = BTreeMap::new();
        for (name, environment) in self.environments {
            if name.is_empty()
                || name.len() > MAX_SYMBOLIC_ID_BYTES
                || !name.bytes().all(|byte| {
                    byte.is_ascii_lowercase()
                        || byte.is_ascii_digit()
                        || matches!(byte, b'-' | b'_')
                })
            {
                return Err(WorkspaceConfigError::new(
                    WorkspaceConfigErrorCode::InvalidSymbolicIdentifier,
                    "environment names must be bounded lowercase identifiers",
                )
                .with_detail(name));
            }
            for reference in [environment.username(), environment.password()] {
                services
                    .secrets
                    .validate_reference(reference)
                    .map_err(|error| {
                        WorkspaceConfigError::new(
                            WorkspaceConfigErrorCode::SecretReferenceRejected,
                            "local secret-reference service rejected an environment credential",
                        )
                        .with_detail(error.code())
                    })?;
            }
            if environments.insert(name, environment).is_some() {
                return Err(WorkspaceConfigError::new(
                    WorkspaceConfigErrorCode::DuplicateRequiredField,
                    "environment name is configured more than once",
                ));
            }
        }

        let environment_namespaces = environments
            .iter()
            .map(|(name, environment)| {
                normalized_environment_endpoints(environment.uri())
                    .map(|endpoints| (name, environment, endpoints))
            })
            .collect::<Result<Vec<_>, _>>()?;
        for left_index in 0..environment_namespaces.len() {
            for right_index in (left_index + 1)..environment_namespaces.len() {
                let (left_name, left, left_endpoints) = &environment_namespaces[left_index];
                let (right_name, right, right_endpoints) = &environment_namespaces[right_index];
                if left_endpoints.is_disjoint(right_endpoints) {
                    continue;
                }
                let left_journal =
                    format!("{}{TYPEBRIDGE_JOURNAL_DATABASE_SUFFIX}", left.database());
                let right_journal =
                    format!("{}{TYPEBRIDGE_JOURNAL_DATABASE_SUFFIX}", right.database());
                if left_journal == right.database() || right_journal == left.database() {
                    return Err(WorkspaceConfigError::new(
                        WorkspaceConfigErrorCode::EnvironmentDatabaseCollision,
                        "one environment's managed database aliases another environment's reserved migration journal on overlapping TypeDB endpoint sets",
                    )
                    .with_detail(format!("{left_name},{right_name}")));
                }
            }
        }

        if let Some(output) = &schema_authority_output {
            let mut output_absolute = self.workspace_root.as_path().to_path_buf();
            output_absolute.extend(output.as_path().components());
            for (name, environment) in &environments {
                if let WorkspaceTransportPolicy::CustomRootCa(root_ca) =
                    environment.transport_policy()
                    && workspace_paths_overlap(&output_absolute, root_ca.as_path())
                {
                    return Err(WorkspaceConfigError::new(
                        WorkspaceConfigErrorCode::OverlappingWorkspacePath,
                        "schema-authority output cannot overlap custom trust material",
                    )
                    .with_detail(format!(
                        "artifact.schema_authority,environment.{name}.tls_root_ca"
                    )));
                }
            }
        }

        let mut secret_references = BTreeMap::new();
        for (slot, reference) in self.secrets {
            if secret_references.insert(slot, reference).is_some() {
                return Err(WorkspaceConfigError::new(
                    WorkspaceConfigErrorCode::DuplicateSecretSlot,
                    "symbolic secret slot is configured more than once",
                ));
            }
        }

        let mut extensions_by_handler = BTreeMap::new();
        for requirement in self.extensions {
            if extensions_by_handler
                .insert(requirement.handler_id.clone(), requirement)
                .is_some()
            {
                return Err(WorkspaceConfigError::new(
                    WorkspaceConfigErrorCode::DuplicateExtensionHandler,
                    "extension handler is required more than once",
                ));
            }
        }
        let extensions = extensions_by_handler.into_values().collect::<BTreeSet<_>>();

        for reference in secret_references.values() {
            services
                .secrets
                .validate_reference(reference)
                .map_err(|error| {
                    WorkspaceConfigError::new(
                        WorkspaceConfigErrorCode::SecretReferenceRejected,
                        "local secret-reference service rejected a symbolic reference",
                    )
                    .with_detail(error.code())
                })?;
        }
        for requirement in &extensions {
            services
                .extensions
                .validate_requirement(requirement)
                .map_err(|error| {
                    WorkspaceConfigError::new(
                        WorkspaceConfigErrorCode::ExtensionRequirementRejected,
                        "local extension registry rejected a handler requirement",
                    )
                    .with_detail(error.code())
                })?;
        }

        Ok(TypeBridgeConfig {
            app_label,
            environments,
            extensions,
            managed_scope,
            migration_policy: self
                .migration_policy
                .unwrap_or_else(MigrationSafetyPolicy::default_policy),
            migration_v2_directory,
            outputs,
            type_names,
            required_capabilities: self.required_capabilities,
            schema_authority_output,
            schema_set,
            secret_references,
            semantic_profile,
            workspace_root: self.workspace_root,
        })
    }
}